]> git.scottworley.com Git - reliable-chat/blame - server/server.go
Rename "history" to "hist"
[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")
7d92df12 31var max_messages = flag.Int("maxmessages", 1000, "Maximum number of messages to retain")
24a546cf 32
acf0ea5d 33var start_time = expvar.NewInt("start_time")
03513e5c
SW
34var speak_count = expvar.NewInt("speak_count")
35var fetch_count = expvar.NewInt("fetch_count")
36var fetch_wait_count = expvar.NewInt("fetch_wait_count")
37var fetch_wake_count = expvar.NewInt("fetch_wake_count")
549a590f 38var drop_due_to_limit_count = expvar.NewInt("drop_due_to_limit_count")
03513e5c 39
92d1d6ac
SW
40type Message struct {
41 Time time.Time
b199796a 42 ID string
92d1d6ac
SW
43 Text string
44}
45
92d1d6ac
SW
46type StoreRequest struct {
47 StartTime time.Time
48 Messages chan<- []Message
49}
50
51type Store struct {
fa5e7c1b
SW
52 Add chan *Message
53 Get chan *StoreRequest
92d1d6ac
SW
54}
55
2ee4581b
SW
56var monotonic_clock chan chan time.Time
57
58const minimum_clock_increment = time.Millisecond
59
60func start_clock() {
61 internal_monotonic_clock := make(chan chan time.Time, 1)
62 go func() {
63 last_time := time.Now()
64 main:
65 for {
66 select {
67 case request, ok := <-internal_monotonic_clock:
68 if !ok {
69 break main
70 }
71 earliest_acceptable_time := last_time.Add(minimum_clock_increment)
72 current_time := time.Now()
73 if current_time.Before(earliest_acceptable_time) {
74 current_time = earliest_acceptable_time
75 }
76 request <- current_time
77 last_time = current_time
78 }
79 }
80 }()
81 monotonic_clock = internal_monotonic_clock
82}
83
84func now() time.Time {
85 c := make(chan time.Time, 0)
86 monotonic_clock <- c
87 return <-c
88}
92d1d6ac
SW
89
90func manage_store(store Store) {
91 messages := list.New()
92 message_count := 0
92d1d6ac 93 waiting := list.New()
c282d878 94main:
92d1d6ac
SW
95 for {
96 select {
c282d878
SW
97 case new_message, ok := <-store.Add:
98 if !ok {
99 break main
100 }
03513e5c 101 speak_count.Add(1)
92d1d6ac 102 for waiter := waiting.Front(); waiter != nil; waiter = waiter.Next() {
fa5e7c1b
SW
103 waiter.Value.(*StoreRequest).Messages <- []Message{*new_message}
104 close(waiter.Value.(*StoreRequest).Messages)
03513e5c 105 fetch_wake_count.Add(1)
92d1d6ac
SW
106 }
107 waiting.Init()
03513e5c 108 messages.PushBack(new_message)
7d92df12 109 if message_count < *max_messages {
92d1d6ac
SW
110 message_count++
111 } else {
112 messages.Remove(messages.Front())
549a590f 113 drop_due_to_limit_count.Add(1)
92d1d6ac 114 }
c282d878
SW
115 case request, ok := <-store.Get:
116 if !ok {
117 break main
118 }
03513e5c 119 fetch_count.Add(1)
fa5e7c1b 120 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
92d1d6ac 121 waiting.PushBack(request)
03513e5c 122 fetch_wait_count.Add(1)
92d1d6ac
SW
123 } else {
124 start := messages.Back()
125 response_size := 1
fa5e7c1b 126 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
92d1d6ac
SW
127 start = messages.Front()
128 response_size = message_count
129 } else {
fa5e7c1b 130 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
92d1d6ac
SW
131 start = start.Prev()
132 response_size++
133 }
134 }
135 response_messages := make([]Message, 0, response_size)
136 for m := start; m != nil; m = m.Next() {
fa5e7c1b 137 response_messages = append(response_messages, *m.Value.(*Message))
92d1d6ac
SW
138 }
139 request.Messages <- response_messages
140 }
141 }
142 }
143}
144
145func start_store() Store {
fa5e7c1b 146 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
92d1d6ac
SW
147 go manage_store(store)
148 return store
149}
150
e3e35bbe
SW
151const robots_txt = `User-agent: *
152Disallow: /
153`
154
92d1d6ac
SW
155func start_server(store Store) {
156 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
87ac1d98
SW
157 var since time.Time
158 url_since := r.FormValue("since")
159 if url_since != "" {
160 err := json.Unmarshal([]byte(url_since), &since)
161 if err != nil {
162 log.Print("fetch: parse since: ", err)
163 w.WriteHeader(http.StatusBadRequest)
164 w.Write([]byte("Could not parse since as date"))
165 return
166 }
167 }
92d1d6ac 168 messages_from_store := make(chan []Message, 1)
fa5e7c1b 169 store.Get <- &StoreRequest{since, messages_from_store}
92d1d6ac 170
9b33d853 171 json_encoded, err := json.Marshal(<-messages_from_store)
92d1d6ac
SW
172 if err != nil {
173 log.Print("json encode: ", err)
174 w.WriteHeader(http.StatusInternalServerError)
175 return
176 }
177 w.Header().Add("Content-Type", "application/json")
79ced6f1 178 w.Header().Add("Access-Control-Allow-Origin", "*")
92d1d6ac
SW
179 w.Write(json_encoded)
180 })
181
182 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
b199796a 183 store.Add <- &Message{
2ee4581b 184 now(),
b199796a
SW
185 r.FormValue("id"),
186 r.FormValue("text")}
d88cc9a8 187 w.Header().Add("Access-Control-Allow-Origin", "*")
92d1d6ac
SW
188 })
189
e3e35bbe 190 http.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
67dc084d 191 w.Write([]byte(robots_txt))
e3e35bbe
SW
192 })
193
270d2ae5 194 log.Fatal(http.ListenAndServe(*localaddress+":"+strconv.Itoa(*port), nil))
92d1d6ac
SW
195}
196
197func main() {
bc44b6bc 198 flag.Parse()
2ee4581b
SW
199 start_clock()
200 start_time.Set(now().UnixNano())
92d1d6ac
SW
201 store := start_store()
202 start_server(store)
203}