]> git.scottworley.com Git - reliable-chat/blob - server/server.go
0c40784ed7b4efb657bd55b798c58f0366991a2b
[reliable-chat] / server / server.go
1 /* reliable-chat - multipath chat
2 * Copyright (C) 2012 Scott Worley <sworley@chkno.net>
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation, either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package main
19
20 import "container/list"
21 import "encoding/json"
22 import "expvar"
23 import "flag"
24 import "log"
25 import "net/http"
26 import "strconv"
27 import "time"
28
29 var port = flag.Int("port", 21059, "Port to listen on")
30 var localaddress = flag.String("localaddress", "", "Local address to bind to")
31 var max_messages = flag.Int("maxmessages", 1000, "Maximum number of messages to retain")
32
33 var speak_count = expvar.NewInt("speak_count")
34 var fetch_count = expvar.NewInt("fetch_count")
35 var fetch_wait_count = expvar.NewInt("fetch_wait_count")
36 var fetch_wake_count = expvar.NewInt("fetch_wake_count")
37 var drop_due_to_limit_count = expvar.NewInt("drop_due_to_limit_count")
38
39 type Message struct {
40 Time time.Time
41 ID string
42 Text string
43 }
44
45 type StoreRequest struct {
46 StartTime time.Time
47 Messages chan<- []Message
48 }
49
50 type Store struct {
51 Add chan *Message
52 Get chan *StoreRequest
53 }
54
55 // TODO: Monotonic clock
56
57 func manage_store(store Store) {
58 messages := list.New()
59 message_count := 0
60 waiting := list.New()
61 main:
62 for {
63 select {
64 case new_message, ok := <-store.Add:
65 if !ok {
66 break main
67 }
68 speak_count.Add(1)
69 for waiter := waiting.Front(); waiter != nil; waiter = waiter.Next() {
70 waiter.Value.(*StoreRequest).Messages <- []Message{*new_message}
71 close(waiter.Value.(*StoreRequest).Messages)
72 fetch_wake_count.Add(1)
73 }
74 waiting.Init()
75 messages.PushBack(new_message)
76 if message_count < *max_messages {
77 message_count++
78 } else {
79 messages.Remove(messages.Front())
80 drop_due_to_limit_count.Add(1)
81 }
82 case request, ok := <-store.Get:
83 if !ok {
84 break main
85 }
86 fetch_count.Add(1)
87 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
88 waiting.PushBack(request)
89 fetch_wait_count.Add(1)
90 } else {
91 start := messages.Back()
92 response_size := 1
93 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
94 start = messages.Front()
95 response_size = message_count
96 } else {
97 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
98 start = start.Prev()
99 response_size++
100 }
101 }
102 response_messages := make([]Message, 0, response_size)
103 for m := start; m != nil; m = m.Next() {
104 response_messages = append(response_messages, *m.Value.(*Message))
105 }
106 request.Messages <- response_messages
107 }
108 }
109 }
110 }
111
112 func start_store() Store {
113 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
114 go manage_store(store)
115 return store
116 }
117
118 const robots_txt = `User-agent: *
119 Disallow: /
120 `
121
122 func start_server(store Store) {
123 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
124 var since time.Time
125 url_since := r.FormValue("since")
126 if url_since != "" {
127 err := json.Unmarshal([]byte(url_since), &since)
128 if err != nil {
129 log.Print("fetch: parse since: ", err)
130 w.WriteHeader(http.StatusBadRequest)
131 w.Write([]byte("Could not parse since as date"))
132 return
133 }
134 }
135 messages_from_store := make(chan []Message, 1)
136 store.Get <- &StoreRequest{since, messages_from_store}
137
138 json_encoded, err := json.Marshal(<-messages_from_store)
139 if err != nil {
140 log.Print("json encode: ", err)
141 w.WriteHeader(http.StatusInternalServerError)
142 return
143 }
144 w.Header().Add("Content-Type", "application/json")
145 w.Header().Add("Access-Control-Allow-Origin", "*")
146 w.Write(json_encoded)
147 })
148
149 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
150 store.Add <- &Message{
151 time.Now(),
152 r.FormValue("id"),
153 r.FormValue("text")}
154 })
155
156 http.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
157 w.Write([]byte(robots_txt))
158 })
159
160 log.Fatal(http.ListenAndServe(*localaddress+":"+strconv.Itoa(*port), nil))
161 }
162
163 func main() {
164 flag.Parse()
165 store := start_store()
166 start_server(store)
167 }