-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
204 lines (154 loc) · 4.46 KB
/
main.go
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
26
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"sync"
"github.com/gookit/color"
"github.com/gorilla/mux"
"github.com/imdario/mergo"
)
// ViewDefinition contains the server which can render it.
type ViewDefinition struct {
Server string
}
// ViewJob is request view for hypernova.
type ViewJob struct {
Name string `json:"name"`
Data interface{} `json:"data"`
}
// ViewJobResult is the view result from hypernova.
type ViewJobResult struct {
Name string `json:"name"`
Html string `json:"html"`
Duration float32 `json:"duration"`
Success bool `json:"success"`
Error ViewJobError `json:"error"`
}
// ViewJobError is an error happened during and after a view is requesting.
type ViewJobError struct {
Name string `json:"name"`
Message string `json:"message"`
}
// BatchResponse is an respose which contains several view job results.
type BatchResponse struct {
Results map[string]ViewJobResult `json:"results"`
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Add("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
if r.Method != "OPTIONS" {
next.ServeHTTP(w, r)
}
})
}
func BatchRequest(server string, batch map[string]ViewJob) BatchResponse {
b, encodeErr := json.Marshal(batch)
if encodeErr != nil {
log.Fatal(encodeErr)
}
payload := string(b)
var response BatchResponse
resp, reqErr := http.Post(server, "application/json", strings.NewReader(payload))
if reqErr != nil {
log.Println(reqErr)
response = BatchResponse{
Results: make(map[string]ViewJobResult),
}
for uuid, job := range batch {
response.Results[uuid] = ViewJobResult{
Name: job.Name,
Success: false,
Error: ViewJobError{
Name: "ConnectionRefused",
Message: reqErr.Error(),
},
}
}
return response
}
defer resp.Body.Close()
body, bodyErr := ioutil.ReadAll(resp.Body)
if bodyErr != nil {
log.Fatal(bodyErr)
}
json.Unmarshal(body, &response)
return response
}
func GetViewDefintions() map[string]ViewDefinition {
dat, err := ioutil.ReadFile(os.Getenv("CONFIG_FILE"))
if err != nil {
log.Fatal("Config file not found")
}
var viewDefinitions map[string]ViewDefinition
json.Unmarshal(dat, &viewDefinitions)
return viewDefinitions
}
func BatchHandler(viewDefinitions map[string]ViewDefinition) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
var viewRequests map[string]ViewJob
json.Unmarshal(b, &viewRequests)
aggregatedResponse := BatchResponse{
Results: make(map[string]ViewJobResult),
}
batches := make(map[string]map[string]ViewJob)
for uuid, job := range viewRequests {
server := viewDefinitions[job.Name].Server
if server == "" {
aggregatedResponse.Results[uuid] = ViewJobResult{
Name: job.Name,
Success: false,
Error: ViewJobError{
Name: "ReferenceError",
Message: "Component\"" + job.Name + "\" not registered in cluster",
},
}
continue
}
if batches[server] == nil {
batch := make(map[string]ViewJob)
batches[server] = batch
}
batches[server][uuid] = job
}
var wg sync.WaitGroup
var batchResponsesMap sync.Map
for server, batch := range batches {
wg.Add(1)
go func(server string, batch map[string]ViewJob) {
response := BatchRequest(server, batch)
batchResponsesMap.Store(server, response)
defer wg.Done()
}(server, batch)
}
wg.Wait()
for server := range batches {
response, _ := batchResponsesMap.Load(server)
batchResponse := response.(BatchResponse)
mergo.Merge(&aggregatedResponse.Results, batchResponse.Results)
}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(aggregatedResponse)
}
}
func main() {
router := mux.NewRouter()
router.Use(corsMiddleware)
viewDefinitions := GetViewDefintions()
router.HandleFunc("/batch", BatchHandler(viewDefinitions)).Methods("OPTIONS", "POST")
port := os.Getenv("PORT")
if len(port) == 0 {
port = "8000"
}
color.Info.Printf("Nova cluster running on http://0.0.0.0:%s\n", port)
http.ListenAndServe(":"+port, router)
}