]> git.scottworley.com Git - reliable-chat/blame - server/server.go
Switch to using defer to clean up after tests
[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
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")
549a590f 37var drop_due_to_limit_count = expvar.NewInt("drop_due_to_limit_count")
03513e5c 38
92d1d6ac
SW
39type Message struct {
40 Time time.Time
b199796a 41 ID string
92d1d6ac
SW
42 Text string
43}
44
92d1d6ac
SW
45type StoreRequest struct {
46 StartTime time.Time
47 Messages chan<- []Message
48}
49
50type Store struct {
fa5e7c1b
SW
51 Add chan *Message
52 Get chan *StoreRequest
92d1d6ac
SW
53}
54
55// TODO: Monotonic clock
56
57func manage_store(store Store) {
58 messages := list.New()
59 message_count := 0
92d1d6ac 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)
7d92df12 76 if message_count < *max_messages {
92d1d6ac
SW
77 message_count++
78 } else {
79 messages.Remove(messages.Front())
549a590f 80 drop_due_to_limit_count.Add(1)
92d1d6ac 81 }
c282d878
SW
82 case request, ok := <-store.Get:
83 if !ok {
84 break main
85 }
03513e5c 86 fetch_count.Add(1)
fa5e7c1b 87 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
92d1d6ac 88 waiting.PushBack(request)
03513e5c 89 fetch_wait_count.Add(1)
92d1d6ac
SW
90 } else {
91 start := messages.Back()
92 response_size := 1
fa5e7c1b 93 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
92d1d6ac
SW
94 start = messages.Front()
95 response_size = message_count
96 } else {
fa5e7c1b 97 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
92d1d6ac
SW
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() {
fa5e7c1b 104 response_messages = append(response_messages, *m.Value.(*Message))
92d1d6ac
SW
105 }
106 request.Messages <- response_messages
107 }
108 }
109 }
110}
111
112func start_store() Store {
fa5e7c1b 113 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
92d1d6ac
SW
114 go manage_store(store)
115 return store
116}
117
e3e35bbe
SW
118const robots_txt = `User-agent: *
119Disallow: /
120`
121
92d1d6ac
SW
122func start_server(store Store) {
123 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
87ac1d98
SW
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 }
92d1d6ac 135 messages_from_store := make(chan []Message, 1)
fa5e7c1b 136 store.Get <- &StoreRequest{since, messages_from_store}
92d1d6ac 137
9b33d853 138 json_encoded, err := json.Marshal(<-messages_from_store)
92d1d6ac
SW
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")
79ced6f1 145 w.Header().Add("Access-Control-Allow-Origin", "*")
92d1d6ac
SW
146 w.Write(json_encoded)
147 })
148
149 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
b199796a
SW
150 store.Add <- &Message{
151 time.Now(),
152 r.FormValue("id"),
153 r.FormValue("text")}
92d1d6ac
SW
154 })
155
e3e35bbe 156 http.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
67dc084d 157 w.Write([]byte(robots_txt))
e3e35bbe
SW
158 })
159
270d2ae5 160 log.Fatal(http.ListenAndServe(*localaddress+":"+strconv.Itoa(*port), nil))
92d1d6ac
SW
161}
162
163func main() {
bc44b6bc 164 flag.Parse()
92d1d6ac
SW
165 store := start_store()
166 start_server(store)
167}