1 /* reliable-chat - multipath chat
2 * Copyright (C) 2012 Scott Worley <sworley@chkno.net>
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.
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.
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/>.
20 import "container/list"
21 import "encoding/json"
29 var port = flag.Int("port", 21059, "Port to listen on")
30 var localaddress = flag.String("localaddress", "", "Local address to bind to")
32 var frame_count = expvar.NewInt("frame_count")
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")
44 type StoreRequest struct {
46 Messages chan<- []Message
51 Get chan *StoreRequest
54 // TODO: Monotonic clock
56 func manage_store(store Store) {
57 messages := list.New()
64 case new_message, ok := <-store.Add:
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)
75 messages.PushBack(new_message)
76 if message_count < max_messages {
79 messages.Remove(messages.Front())
81 case request, ok := <-store.Get:
86 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
87 waiting.PushBack(request)
88 fetch_wait_count.Add(1)
90 start := messages.Back()
92 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
93 start = messages.Front()
94 response_size = message_count
96 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
101 response_messages := make([]Message, 0, response_size)
102 for m := start; m != nil; m = m.Next() {
103 response_messages = append(response_messages, *m.Value.(*Message))
105 request.Messages <- response_messages
111 func start_store() Store {
112 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
113 go manage_store(store)
117 const frame_html = `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
118 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
120 <html xmlns="http://www.w3.org/1999/xhtml">
122 <script type="text/javascript"><!--//--><![CDATA[//><!--
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."}]', "*");
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;
133 var r = JSON.parse(rtxt);
135 window.parent.postMessage(rtxt, "*");
137 if (r.length >= 1 && "Time" in r[r.length-1]) {
138 since = r[r.length-1]["Time"];
143 window.setTimeout(go, delay);
148 uri += '?since="' + since + '"';
150 xhr.open("GET", uri);
160 const robots_txt = `User-agent: *
164 func start_server(store Store) {
165 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
167 url_since := r.FormValue("since")
169 err := json.Unmarshal([]byte(url_since), &since)
171 log.Print("fetch: parse since: ", err)
172 w.WriteHeader(http.StatusBadRequest)
173 w.Write([]byte("Could not parse since as date"))
177 messages_from_store := make(chan []Message, 1)
178 store.Get <- &StoreRequest{since, messages_from_store}
180 json_encoded, err := json.Marshal(<-messages_from_store)
182 log.Print("json encode: ", err)
183 w.WriteHeader(http.StatusInternalServerError)
186 w.Header().Add("Content-Type", "application/json")
187 w.Header().Add("Access-Control-Allow-Origin", "*")
188 w.Write(json_encoded)
191 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
192 store.Add <- &Message{
198 http.HandleFunc("/frame", func(w http.ResponseWriter, r *http.Request) {
200 w.Write([]byte(frame_html));
203 http.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
204 w.Write([]byte(robots_txt));
207 log.Fatal(http.ListenAndServe(*localaddress+":"+strconv.Itoa(*port), nil))
212 store := start_store()