3 import "container/list"
12 var port = flag.Int("port", 21059, "Port to listen on")
14 var speak_count = expvar.NewInt("speak_count")
15 var fetch_count = expvar.NewInt("fetch_count")
16 var fetch_wait_count = expvar.NewInt("fetch_wait_count")
17 var fetch_wake_count = expvar.NewInt("fetch_wake_count")
24 type StoreRequest struct {
26 Messages chan<- []Message
31 Get chan *StoreRequest
34 // TODO: Monotonic clock
36 func manage_store(store Store) {
37 messages := list.New()
44 case new_message, ok := <-store.Add:
49 for waiter := waiting.Front(); waiter != nil; waiter = waiter.Next() {
50 waiter.Value.(*StoreRequest).Messages <- []Message{*new_message}
51 close(waiter.Value.(*StoreRequest).Messages)
52 fetch_wake_count.Add(1)
55 messages.PushBack(new_message)
56 if message_count < max_messages {
59 messages.Remove(messages.Front())
61 case request, ok := <-store.Get:
66 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
67 waiting.PushBack(request)
68 fetch_wait_count.Add(1)
70 start := messages.Back()
72 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
73 start = messages.Front()
74 response_size = message_count
76 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
81 response_messages := make([]Message, 0, response_size)
82 for m := start; m != nil; m = m.Next() {
83 response_messages = append(response_messages, *m.Value.(*Message))
85 request.Messages <- response_messages
91 func start_store() Store {
92 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
93 go manage_store(store)
97 func start_server(store Store) {
98 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
100 url_since := r.FormValue("since")
102 err := json.Unmarshal([]byte(url_since), &since)
104 log.Print("fetch: parse since: ", err)
105 w.WriteHeader(http.StatusBadRequest)
106 w.Write([]byte("Could not parse since as date"))
110 messages_from_store := make(chan []Message, 1)
111 store.Get <- &StoreRequest{since, messages_from_store}
113 json_encoded, err := json.Marshal(<-messages_from_store)
115 log.Print("json encode: ", err)
116 w.WriteHeader(http.StatusInternalServerError)
119 w.Header().Add("Content-Type", "application/json")
120 w.Write(json_encoded)
123 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
124 store.Add <- &Message{time.Now(), r.FormValue("text")}
127 log.Fatal(http.ListenAndServe(":" + strconv.Itoa(*port), nil))
131 store := start_store()