]> git.scottworley.com Git - reliable-chat/blob - server/server.go
Make message limit flag-controlled
[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
38 type Message struct {
39 Time time.Time
40 ID string
41 Text string
42 }
43
44 type StoreRequest struct {
45 StartTime time.Time
46 Messages chan<- []Message
47 }
48
49 type Store struct {
50 Add chan *Message
51 Get chan *StoreRequest
52 }
53
54 // TODO: Monotonic clock
55
56 func manage_store(store Store) {
57 messages := list.New()
58 message_count := 0
59 waiting := list.New()
60 main:
61 for {
62 select {
63 case new_message, ok := <-store.Add:
64 if !ok {
65 break main
66 }
67 speak_count.Add(1)
68 for waiter := waiting.Front(); waiter != nil; waiter = waiter.Next() {
69 waiter.Value.(*StoreRequest).Messages <- []Message{*new_message}
70 close(waiter.Value.(*StoreRequest).Messages)
71 fetch_wake_count.Add(1)
72 }
73 waiting.Init()
74 messages.PushBack(new_message)
75 if message_count < *max_messages {
76 message_count++
77 } else {
78 messages.Remove(messages.Front())
79 }
80 case request, ok := <-store.Get:
81 if !ok {
82 break main
83 }
84 fetch_count.Add(1)
85 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
86 waiting.PushBack(request)
87 fetch_wait_count.Add(1)
88 } else {
89 start := messages.Back()
90 response_size := 1
91 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
92 start = messages.Front()
93 response_size = message_count
94 } else {
95 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
96 start = start.Prev()
97 response_size++
98 }
99 }
100 response_messages := make([]Message, 0, response_size)
101 for m := start; m != nil; m = m.Next() {
102 response_messages = append(response_messages, *m.Value.(*Message))
103 }
104 request.Messages <- response_messages
105 }
106 }
107 }
108 }
109
110 func start_store() Store {
111 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
112 go manage_store(store)
113 return store
114 }
115
116 const robots_txt = `User-agent: *
117 Disallow: /
118 `
119
120 func start_server(store Store) {
121 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
122 var since time.Time
123 url_since := r.FormValue("since")
124 if url_since != "" {
125 err := json.Unmarshal([]byte(url_since), &since)
126 if err != nil {
127 log.Print("fetch: parse since: ", err)
128 w.WriteHeader(http.StatusBadRequest)
129 w.Write([]byte("Could not parse since as date"))
130 return
131 }
132 }
133 messages_from_store := make(chan []Message, 1)
134 store.Get <- &StoreRequest{since, messages_from_store}
135
136 json_encoded, err := json.Marshal(<-messages_from_store)
137 if err != nil {
138 log.Print("json encode: ", err)
139 w.WriteHeader(http.StatusInternalServerError)
140 return
141 }
142 w.Header().Add("Content-Type", "application/json")
143 w.Header().Add("Access-Control-Allow-Origin", "*")
144 w.Write(json_encoded)
145 })
146
147 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
148 store.Add <- &Message{
149 time.Now(),
150 r.FormValue("id"),
151 r.FormValue("text")}
152 })
153
154 http.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
155 w.Write([]byte(robots_txt));
156 })
157
158 log.Fatal(http.ListenAndServe(*localaddress+":"+strconv.Itoa(*port), nil))
159 }
160
161 func main() {
162 flag.Parse()
163 store := start_store()
164 start_server(store)
165 }