]> git.scottworley.com Git - reliable-chat/blame - server/server.go
Optionally specify an address to bind to
[reliable-chat] / server / server.go
CommitLineData
520c21fd
SW
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
92d1d6ac
SW
18package main
19
20import "container/list"
21import "encoding/json"
03513e5c 22import "expvar"
24a546cf 23import "flag"
92d1d6ac
SW
24import "log"
25import "net/http"
24a546cf 26import "strconv"
92d1d6ac
SW
27import "time"
28
24a546cf 29var port = flag.Int("port", 21059, "Port to listen on")
270d2ae5 30var localaddress = flag.String("localaddress", "", "Local address to bind to")
24a546cf 31
a69e0831 32var frame_count = expvar.NewInt("frame_count")
03513e5c
SW
33var speak_count = expvar.NewInt("speak_count")
34var fetch_count = expvar.NewInt("fetch_count")
35var fetch_wait_count = expvar.NewInt("fetch_wait_count")
36var fetch_wake_count = expvar.NewInt("fetch_wake_count")
37
92d1d6ac
SW
38type Message struct {
39 Time time.Time
b199796a 40 ID string
92d1d6ac
SW
41 Text string
42}
43
92d1d6ac
SW
44type StoreRequest struct {
45 StartTime time.Time
46 Messages chan<- []Message
47}
48
49type Store struct {
fa5e7c1b
SW
50 Add chan *Message
51 Get chan *StoreRequest
92d1d6ac
SW
52}
53
54// TODO: Monotonic clock
55
56func manage_store(store Store) {
57 messages := list.New()
58 message_count := 0
59 max_messages := 1000
60 waiting := list.New()
c282d878 61main:
92d1d6ac
SW
62 for {
63 select {
c282d878
SW
64 case new_message, ok := <-store.Add:
65 if !ok {
66 break main
67 }
03513e5c 68 speak_count.Add(1)
92d1d6ac 69 for waiter := waiting.Front(); waiter != nil; waiter = waiter.Next() {
fa5e7c1b
SW
70 waiter.Value.(*StoreRequest).Messages <- []Message{*new_message}
71 close(waiter.Value.(*StoreRequest).Messages)
03513e5c 72 fetch_wake_count.Add(1)
92d1d6ac
SW
73 }
74 waiting.Init()
03513e5c 75 messages.PushBack(new_message)
92d1d6ac
SW
76 if message_count < max_messages {
77 message_count++
78 } else {
79 messages.Remove(messages.Front())
80 }
c282d878
SW
81 case request, ok := <-store.Get:
82 if !ok {
83 break main
84 }
03513e5c 85 fetch_count.Add(1)
fa5e7c1b 86 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
92d1d6ac 87 waiting.PushBack(request)
03513e5c 88 fetch_wait_count.Add(1)
92d1d6ac
SW
89 } else {
90 start := messages.Back()
91 response_size := 1
fa5e7c1b 92 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
92d1d6ac
SW
93 start = messages.Front()
94 response_size = message_count
95 } else {
fa5e7c1b 96 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
92d1d6ac
SW
97 start = start.Prev()
98 response_size++
99 }
100 }
101 response_messages := make([]Message, 0, response_size)
102 for m := start; m != nil; m = m.Next() {
fa5e7c1b 103 response_messages = append(response_messages, *m.Value.(*Message))
92d1d6ac
SW
104 }
105 request.Messages <- response_messages
106 }
107 }
108 }
109}
110
111func start_store() Store {
fa5e7c1b 112 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
92d1d6ac
SW
113 go manage_store(store)
114 return store
115}
116
f0e385c7
SW
117const frame_html = `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
118 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
119
120<html xmlns="http://www.w3.org/1999/xhtml">
121<head>
122 <script type="text/javascript"><!--//--><![CDATA[//><!--
123 var since;
4565c41c 124 window.parent.postMessage('[{"Time":"2000-01-01T00:00:00.000000-00:00","ID":"/frame deprecation warning","Text":"*** You are using an old version of the client. Please upgrade."}]', "*");
f0e385c7
SW
125 function go() {
126 var delay = 10000;
127 var xhr = new XMLHttpRequest();
128 xhr.onreadystatechange = function() {
129 if (this.readyState == this.DONE) {
130 if (this.status == 200) {
131 var rtxt = this.responseText;
132 if (rtxt != null) {
133 var r = JSON.parse(rtxt);
134 if (r != null) {
135 window.parent.postMessage(rtxt, "*");
136 delay = 40;
137 if (r.length >= 1 && "Time" in r[r.length-1]) {
138 since = r[r.length-1]["Time"];
139 }
140 }
141 }
142 }
143 window.setTimeout(go, delay);
144 }
145 }
146 var uri = "/fetch";
147 if (since) {
148 uri += '?since="' + since + '"';
149 }
150 xhr.open("GET", uri);
151 xhr.send();
152 }
153 //--><!]]></script>
154</head>
155<body onload="go()">
156</body>
157</html>
158`
159
e3e35bbe
SW
160const robots_txt = `User-agent: *
161Disallow: /
162`
163
92d1d6ac
SW
164func start_server(store Store) {
165 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
87ac1d98
SW
166 var since time.Time
167 url_since := r.FormValue("since")
168 if url_since != "" {
169 err := json.Unmarshal([]byte(url_since), &since)
170 if err != nil {
171 log.Print("fetch: parse since: ", err)
172 w.WriteHeader(http.StatusBadRequest)
173 w.Write([]byte("Could not parse since as date"))
174 return
175 }
176 }
92d1d6ac 177 messages_from_store := make(chan []Message, 1)
fa5e7c1b 178 store.Get <- &StoreRequest{since, messages_from_store}
92d1d6ac 179
9b33d853 180 json_encoded, err := json.Marshal(<-messages_from_store)
92d1d6ac
SW
181 if err != nil {
182 log.Print("json encode: ", err)
183 w.WriteHeader(http.StatusInternalServerError)
184 return
185 }
186 w.Header().Add("Content-Type", "application/json")
79ced6f1 187 w.Header().Add("Access-Control-Allow-Origin", "*")
92d1d6ac
SW
188 w.Write(json_encoded)
189 })
190
191 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
b199796a
SW
192 store.Add <- &Message{
193 time.Now(),
194 r.FormValue("id"),
195 r.FormValue("text")}
92d1d6ac
SW
196 })
197
f0e385c7 198 http.HandleFunc("/frame", func(w http.ResponseWriter, r *http.Request) {
a69e0831 199 frame_count.Add(1)
f0e385c7
SW
200 w.Write([]byte(frame_html));
201 })
202
e3e35bbe
SW
203 http.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
204 w.Write([]byte(robots_txt));
205 })
206
270d2ae5 207 log.Fatal(http.ListenAndServe(*localaddress+":"+strconv.Itoa(*port), nil))
92d1d6ac
SW
208}
209
210func main() {
bc44b6bc 211 flag.Parse()
92d1d6ac
SW
212 store := start_store()
213 start_server(store)
214}