broker.go 3.79 KB
Newer Older
Bengfort's avatar
Bengfort committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
	"sync"
	"time"
)

type RequestMsg struct {
	id   int
	Data []byte
}

type ResponseMsg struct {
	success bool
	Data    []byte
}

var mux = &sync.RWMutex{}
var verbose = false
Bengfort's avatar
Bengfort committed
26
var secret = ""
Bengfort's avatar
Bengfort committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
var connected = false
var lastId = 1
var jobs = make(map[int](chan ResponseMsg))
var sse = make(chan RequestMsg)

func releaseConnection() {
	connected = false
}

func createJob() (int, chan ResponseMsg) {
	mux.Lock()
	defer mux.Unlock()

	lastId += 1
	ch := make(chan ResponseMsg)
	jobs[lastId] = ch
	return lastId, ch
}

func deleteJob(id int) {
	mux.Lock()
	delete(jobs, id)
	mux.Unlock()
}

func schedulerPost(w http.ResponseWriter, r *http.Request) {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Println("error reading request body:", err)
		http.Error(w, "", http.StatusInternalServerError)
		return
	}

	id, ch := createJob()
	defer deleteJob(id)

	sse <- RequestMsg{id, body}

	ctx := r.Context()
	timeout := time.NewTimer(10 * time.Second)

	select {
	case <-ctx.Done():
		return
	case <-timeout.C:
		http.Error(w, "", http.StatusGatewayTimeout)
	case msg := <-ch:
		if !msg.success {
			http.Error(w, "", http.StatusInternalServerError)
		}
		w.Write(msg.Data)
	}
}

func parseUrl(r *http.Request) (int, bool, bool) {
	query := r.URL.Query()

	ids, ok := query["id"]
	if !ok {
		return 0, false, false
	}

	if len(ids) != 1 {
		return 0, false, false
	}

	id, err := strconv.Atoi(ids[0])
	if err != nil {
		return 0, false, false
	}

	_, success := query["success"]

	return id, success, true
}

func castellumPost(w http.ResponseWriter, r *http.Request) {
	id, success, ok := parseUrl(r)
	if !ok {
		http.Error(w, "", http.StatusNotFound)
		return
	}

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Println("error reading request body:", err)
		http.Error(w, "", http.StatusInternalServerError)
		return
	}

	mux.RLock()
	ch, ok := jobs[id]
	mux.RUnlock()

	if !ok {
		http.Error(w, "", http.StatusNotFound)
		return
	}

	ch <- ResponseMsg{success, body}
}

func castellumGet(w http.ResponseWriter, r *http.Request) {
	if connected {
		http.Error(w, "", http.StatusInternalServerError)
		return
	} else {
		connected = true
		defer releaseConnection()
	}

	ctx := r.Context()

	ticker := time.NewTicker(15 * time.Second)
	defer ticker.Stop()

	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("X-Accel-Buffering", "no")
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, ": ping\n\n")
	flusher.Flush()

	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			fmt.Fprintf(w, ": ping\n\n")
			flusher.Flush()
		case msg := <-sse:
			fmt.Fprintf(w, "id: %d\ndata: %s\n\n", msg.id, msg.Data)
			flusher.Flush()
		}
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	if verbose {
		log.Println(r.Method, r.URL)
	}

Bengfort's avatar
Bengfort committed
174
175
176
	if secret != "" && r.Header.Get("Authorization") != fmt.Sprintf("token %s", secret) {
		http.Error(w, "", http.StatusForbidden)
	} else if r.URL.Path == "/castellum/" {
Bengfort's avatar
Bengfort committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
		if r.Method == http.MethodGet {
			castellumGet(w, r)
		} else if r.Method == http.MethodPost {
			castellumPost(w, r)
		} else {
			http.Error(w, "", http.StatusMethodNotAllowed)
		}
	} else if r.URL.Path == "/scheduler/" {
		if r.Method == http.MethodPost {
			schedulerPost(w, r)
		} else {
			http.Error(w, "", http.StatusMethodNotAllowed)
		}
	} else {
			http.Error(w, "", http.StatusNotFound)
	}
}

func main() {
	addr := "localhost:8001"
197
198
199
200

	port, ok := os.LookupEnv("BROKER_PORT")
	if ok {
		addr = fmt.Sprintf("localhost:%s", port)
Bengfort's avatar
Bengfort committed
201
202
	}

203
	_, verbose = os.LookupEnv("BROKER_VERBOSE")
Bengfort's avatar
Bengfort committed
204
	secret = os.Getenv("BROKER_SECRET")
205

Bengfort's avatar
Bengfort committed
206
207
208
209
210
	http.HandleFunc("/", handler)

	log.Printf("Serving on http://%s", addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}