/
handler.go
1513 lines (1231 loc) · 42.3 KB
/
handler.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2016 Timo Savola. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"context"
"errors"
"io"
"net"
"net/http"
"sort"
"strconv"
"strings"
server "gate.computer/gate/server/api"
"gate.computer/gate/server/event"
"gate.computer/gate/server/internal/monitor"
"gate.computer/gate/server/web/api"
internalapi "gate.computer/gate/server/web/internal/api"
"gate.computer/gate/server/web/internal/protojson"
"gate.computer/internal/principal"
"github.com/gorilla/websocket"
)
const maxWebsocketRequestSize = 4096
type respondedType struct{}
var responded respondedType
type errorWriter interface {
SetHeader(key, value string)
WriteError(status int, text string)
}
type (
instanceMethod func(ctx context.Context, s server.Server, instance string) error
instanceStatusMethod func(ctx context.Context, s server.Server, instance string) (*server.Status, error)
instanceWaiterMethod func(ctx context.Context, s server.Server, instance string) (server.Instance, error)
)
func deleteInstance(ctx context.Context, s server.Server, instance string) error {
return s.DeleteInstance(ctx, instance)
}
func killInstance(ctx context.Context, s server.Server, instance string) (server.Instance, error) {
return s.KillInstance(ctx, instance)
}
func suspendInstance(ctx context.Context, s server.Server, instance string) (server.Instance, error) {
return s.SuspendInstance(ctx, instance)
}
func waitInstance(ctx context.Context, s server.Server, instance string) (*server.Status, error) {
return s.WaitInstance(ctx, instance)
}
type privateConfig struct {
Config
}
type webserver struct {
privateConfig
identity string // JWT audience.
pathKnownModules string
anyOrigin bool
localAuthorization bool
}
func NewHandler(pattern string, config *Config) http.Handler {
return newHandler(pattern, config, "https", false)
}
// NewHandlerWithUnsecuredLocalAuthorization processes requests with unsigned
// JWT tokens under the local principal's identity. Such tokens can be created
// by anyone without any secret knowledge.
func NewHandlerWithUnsecuredLocalAuthorization(pattern string, config *Config) http.Handler {
for _, origin := range config.Origins {
if strings.Contains(origin, "*") {
panic("origin check disabled for unsecured local handler")
}
}
if config.NonceStorage != nil {
panic("nonce storage not supported for local principal")
}
return newHandler(pattern, config, "http", true)
}
func newHandler(pattern string, config *Config, scheme string, localAuthorization bool) http.Handler {
s := &webserver{
localAuthorization: localAuthorization,
}
if config != nil {
s.Config = *config
}
if s.Authority == "" {
s.Authority = strings.SplitN(pattern, "/", 2)[0]
}
if s.NewRequestID == nil {
s.NewRequestID = defaultNewRequestID
}
if s.Monitor == nil {
s.Monitor = monitor.Default
}
if !s.Configured() {
panic("incomplete webserver configuration")
}
features := s.Server.Features()
configOrigins := s.Origins
s.Origins = nil
for _, origin := range configOrigins {
switch origin = strings.TrimSpace(origin); origin {
case "":
case "*":
s.anyOrigin = true
default:
s.Origins = append(s.Origins, origin)
}
}
p := strings.TrimRight(pattern, "/") // host/path
patternAPI := p + api.Path // host/path/api/
patternModule := p + api.PathModule // host/path/api/module
patternModules := p + api.PathModuleSources // host/path/api/module/
patternKnownModule := p + api.PathModuleSources + api.KnownModuleSource // host/path/api/module/hash
patternKnownModules := p + api.PathKnownModules // host/path/api/module/hash/
patternInstances := p + api.PathInstances // host/path/api/instance/
patternInstance := patternInstances[:len(patternInstances)-1] // host/path/api/instance
p = strings.TrimLeftFunc(p, func(r rune) bool { return r != '/' }) // /path
pathAPI := p + api.Path // /path/api/
pathModule := p + api.PathModule // /path/api/module
pathModules := p + api.PathModuleSources // /path/api/module/
pathKnownModule := p + api.PathModuleSources + api.KnownModuleSource // /path/api/module/hash
s.pathKnownModules = p + api.PathKnownModules // /path/api/module/hash/
pathInstances := p + api.PathInstances // /path/api/instance/
pathInstance := pathInstances[:len(pathInstances)-1] // /path/api/instance
s.identity = scheme + "://" + s.Authority + p + api.Path // https://authority/path/api/
mux := http.NewServeMux()
mux.HandleFunc(patternAPI, newFeatureHandler(s, pathAPI, features))
mux.HandleFunc(patternModule, newRedirectHandler(s, pathModule))
mux.HandleFunc(patternInstance, newRedirectHandler(s, pathInstance))
mux.HandleFunc(patternInstances, newInstanceHandler(s, pathInstances))
mux.HandleFunc(patternKnownModule, newRedirectHandler(s, pathKnownModule))
mux.HandleFunc(patternKnownModules, newKnownModuleHandler(s))
moduleSources := []string{api.KnownModuleSource}
for _, relURI := range features.ModuleSources {
patternSource := patternModule + relURI // host/path/api/module/source
patternSourceDir := patternSource + "/" // host/path/api/module/source/
pathSource := pathModule + relURI // /path/api/module/source
pathSourceDir := pathSource + "/" // /path/api/module/source/
mux.HandleFunc(patternSource, newRedirectHandler(s, pathSource))
mux.HandleFunc(patternSourceDir, newModuleSourceHandler(s, pathModule, pathSourceDir))
moduleSources = append(moduleSources, strings.TrimLeft(relURI, "/"))
}
sort.Strings(moduleSources)
mux.HandleFunc(patternModules, newStaticHandler(s, pathModules, moduleSources))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = server.ContextWithRequest(ctx, s.NewRequestID(r))
ctx = server.ContextWithAddress(ctx, r.RemoteAddr)
r = r.WithContext(ctx)
s.Monitor(&event.Event{
Type: event.TypeIfaceAccess,
Meta: server.ContextMeta(ctx),
}, nil)
defer func() {
if x := recover(); x != nil && x != responded {
panic(x)
}
}()
if !s.anyOrigin {
if origin := r.Header.Get(api.HeaderOrigin); origin != "" {
mustBeAllowedOrigin(w, r, s, origin)
}
}
mux.ServeHTTP(w, r)
})
}
type staticContent struct {
content []byte
contentLength string
}
func prepareStaticContent(data any) staticContent {
content := mustMarshalJSON(data)
return staticContent{
content: content,
contentLength: strconv.Itoa(len(content)),
}
}
// Path handlers. Route methods and set up CORS.
func newRedirectHandler(s *webserver, path string) http.HandlerFunc {
location := path + "/"
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != path {
respondPathNotFound(w, r, s)
return
}
methods := "OPTIONS"
setAccessControl(w, r, s, "GET, HEAD, "+methods)
switch r.Method {
case "GET", "HEAD":
w.Header().Set("Location", location)
w.WriteHeader(http.StatusMovedPermanently)
case "OPTIONS":
setOptions(w, methods)
default:
respondMethodNotAllowed(w, r, s, methods)
}
}
}
func newStaticHandler(s *webserver, path string, data any) http.HandlerFunc {
static := prepareStaticContent(data)
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != path {
respondPathNotFound(w, r, s)
return
}
methods := "OPTIONS"
setAccessControl(w, r, s, "GET, HEAD, "+methods)
switch r.Method {
case "GET", "HEAD":
handleGetStatic(w, r, s, &static)
case "OPTIONS":
setOptions(w, methods)
default:
respondMethodNotAllowed(w, r, s, methods)
}
}
}
func newFeatureHandler(s *webserver, path string, featureAll *server.Features) http.HandlerFunc {
featureScope := &api.Features{
Scope: featureAll.Scope,
}
answers := [3]staticContent{
prepareStaticContent(struct{}{}),
prepareStaticContent(featureScope), // scope
prepareStaticContent(featureScope), // all
}
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != path {
respondPathNotFound(w, r, s)
return
}
methods := "OPTIONS"
setAccessControl(w, r, s, "GET, HEAD, "+methods)
switch r.Method {
case "GET", "HEAD":
handleGetFeatures(w, r, s, &answers)
case "OPTIONS":
setOptions(w, methods)
default:
respondMethodNotAllowed(w, r, s, methods)
}
}
}
func newKnownModuleHandler(s *webserver) http.HandlerFunc {
var (
headersList = join(api.HeaderAuthorization)
headersID = join(api.HeaderAuthorization, api.HeaderContentType)
exposed = join(api.HeaderLocation, api.HeaderInstance, api.HeaderStatus)
)
return func(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) == len(s.pathKnownModules) {
// Module directory listing
methods := "OPTIONS, POST"
setAccessControlAllowHeaders(w, r, s, "GET, HEAD, "+methods, headersList)
switch r.Method {
case "GET", "HEAD":
w.WriteHeader(http.StatusNoContent)
case "OPTIONS":
setOptions(w, methods)
case "POST":
handlePostKnownModules(w, r, s)
default:
respondMethodNotAllowed(w, r, s, methods)
}
} else {
// Module operations
module := r.URL.Path[len(s.pathKnownModules):]
methods := "OPTIONS, POST, PUT"
setAccessControlAllowExposeHeaders(w, r, s, "GET, HEAD, "+methods, headersID, exposed)
switch r.Method {
case "GET", "HEAD":
handleGetKnownModule(w, r, s, module)
case "PUT":
handlePutKnownModule(w, r, s, module)
case "POST":
handlePostKnownModule(w, r, s, module)
case "OPTIONS":
setOptions(w, methods)
default:
respondMethodNotAllowed(w, r, s, methods)
}
}
}
}
func newModuleSourceHandler(s *webserver, sourceURIBase, sourcePath string) http.HandlerFunc {
var (
headers = join(api.HeaderAuthorization)
exposed = join(api.HeaderLocation, api.HeaderInstance, api.HeaderStatus)
)
return func(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) == len(sourcePath) {
// Module directory listing is not supported for sources. The
// directory clearly exists (it has modules in it), but doesn't
// support any methods itself.
methods := "OPTIONS"
setAccessControl(w, r, s, "GET, HEAD, "+methods)
switch r.Method {
case "GET", "HEAD":
w.WriteHeader(http.StatusNoContent)
case "OPTIONS":
setOptions(w, methods)
default:
respondMethodNotAllowed(w, r, s, methods)
}
} else {
// Module operations
module := r.URL.Path[len(sourceURIBase):]
methods := "OPTIONS, POST"
setAccessControlAllowExposeHeaders(w, r, s, "GET, HEAD, "+methods, headers, exposed)
switch r.Method {
case "GET", "HEAD":
handleGetModuleSource(w, r, s, module)
case "POST":
handlePostModuleSource(w, r, s, module)
case "OPTIONS":
setOptions(w, methods)
default:
respondMethodNotAllowed(w, r, s, methods)
}
}
}
}
func newInstanceHandler(s *webserver, instancesPath string) http.HandlerFunc {
var (
headersGet = join(api.HeaderAuthorization)
headersPost = join(api.HeaderAuthorization, api.HeaderContentType)
exposed = join(api.HeaderStatus)
)
return func(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) == len(instancesPath) {
// Instance directory listing
methods := "OPTIONS"
setAccessControlAllowHeaders(w, r, s, "GET, HEAD, "+methods, headersGet)
switch r.Method {
case "GET", "HEAD":
w.WriteHeader(http.StatusNoContent)
case "POST":
handlePostInstances(w, r, s)
case "OPTIONS":
setOptions(w, methods)
default:
respondMethodNotAllowed(w, r, s, methods)
}
} else {
// Instance operations
instance := r.URL.Path[len(instancesPath):]
methods := "OPTIONS, POST"
setAccessControlAllowExposeHeaders(w, r, s, "GET, HEAD, "+methods, headersPost, exposed)
switch r.Method {
case "GET", "HEAD":
handleGetInstance(w, r, s, instance)
case "POST":
handlePostInstance(w, r, s, instance)
case "OPTIONS":
setOptions(w, methods)
default:
respondMethodNotAllowed(w, r, s, methods)
}
}
}
}
// Method handlers. Parse query parameters and check content headers.
func handleGetStatic(w http.ResponseWriter, r *http.Request, s *webserver, static *staticContent) {
mustNotHaveQuery(w, r, s)
mustAcceptJSON(w, r, s)
handleStatic(w, r, s, static)
}
func handleGetFeatures(w http.ResponseWriter, r *http.Request, s *webserver, answers *[3]staticContent) {
query := mustParseOptionalQuery(w, r, s)
features := popOptionalParams(query, api.ParamFeature)
mustNotHaveParams(w, r, s, query)
if len(features) > 0 {
mustAcceptJSON(w, r, s)
}
level := 0
for _, v := range features {
switch v {
case api.FeatureScope:
if level == 0 {
level = 1
}
case api.FeatureAll:
level = len(*answers) - 1
default:
respondUnsupportedFeature(w, r, s)
return
}
}
handleStatic(w, r, s, &(*answers)[level])
}
func handleGetKnownModule(w http.ResponseWriter, r *http.Request, s *webserver, key string) {
query := mustParseOptionalQuery(w, r, s)
pin := popOptionalActionParam(w, r, s, query, api.ActionPin)
var modTags []string
if pin {
modTags = popOptionalParams(query, api.ParamModuleTag)
}
if _, found := query[api.ParamAction]; found {
switch popLastParam(w, r, s, query, api.ParamAction) {
case api.ActionCall:
function := mustPopOptionalLastFunctionParam(w, r, s, query)
instTags := popOptionalParams(query, api.ParamInstanceTag)
invoke := popOptionalLastLogParam(w, r, s, query)
mustNotHaveParams(w, r, s, query)
handleCallWebsocket(w, r, s, pin, "", key, function, modTags, instTags, invoke)
default:
respondUnsupportedAction(w, r, s)
}
} else {
if pin {
respondUnsupportedAction(w, r, s)
} else {
mustNotHaveParams(w, r, s, query)
mustAcceptWebAssembly(w, r, s)
handleModuleDownload(w, r, s, key)
}
}
}
func handlePostKnownModules(w http.ResponseWriter, r *http.Request, s *webserver) {
mustNotHaveQuery(w, r, s)
mustNotHaveContentType(w, r, s)
mustNotHaveContent(w, r, s)
mustAcceptJSON(w, r, s)
handleModuleList(w, r, s)
}
func handlePutKnownModule(w http.ResponseWriter, r *http.Request, s *webserver, key string) {
mustHaveContentType(w, r, s, api.ContentTypeWebAssembly)
mustHaveContentLength(w, r, s)
query := mustParseOptionalQuery(w, r, s)
pin := popOptionalActionParam(w, r, s, query, api.ActionPin)
suspend := popOptionalActionParam(w, r, s, query, api.ActionSuspend)
var modTags []string
if pin {
modTags = popOptionalParams(query, api.ParamModuleTag)
}
if _, found := query[api.ParamAction]; found {
switch popLastParam(w, r, s, query, api.ParamAction) {
case api.ActionCall:
function := mustPopOptionalLastFunctionParam(w, r, s, query)
instTags := popOptionalParams(query, api.ParamInstanceTag)
invoke := popOptionalLastLogParam(w, r, s, query)
mustNotHaveParams(w, r, s, query)
handleCall(w, r, s, server.OpCallUpload, pin, true, "", key, function, modTags, instTags, invoke)
case api.ActionLaunch:
function := mustPopOptionalLastFunctionParam(w, r, s, query)
instance := popOptionalLastParam(w, r, s, query, api.ParamInstance)
instTags := popOptionalParams(query, api.ParamInstanceTag)
invoke := popOptionalLastLogParam(w, r, s, query)
mustNotHaveParams(w, r, s, query)
handleLaunchUpload(w, r, s, pin, key, function, instance, modTags, instTags, suspend, invoke)
default:
respondUnsupportedAction(w, r, s)
}
} else {
if pin {
mustNotHaveParams(w, r, s, query)
handleModuleUpload(w, r, s, key, modTags)
} else {
respondUnsupportedAction(w, r, s)
}
}
}
func handlePostKnownModule(w http.ResponseWriter, r *http.Request, s *webserver, key string) {
query := mustParseQuery(w, r, s)
if len(query[api.ParamAction]) == 0 {
mustNotHaveParams(w, r, s, query)
mustAcceptJSON(w, r, s)
handleKnownModule(w, r, s, key)
return
}
suspend := popOptionalActionParam(w, r, s, query, api.ActionSuspend)
switch popLastParam(w, r, s, query, api.ParamAction) {
case api.ActionCall:
function := mustPopOptionalLastFunctionParam(w, r, s, query)
instTags := popOptionalParams(query, api.ParamInstanceTag)
invoke := popOptionalLastLogParam(w, r, s, query)
mustNotHaveParams(w, r, s, query)
handleCall(w, r, s, server.OpCallExtant, false, false, "", key, function, nil, instTags, invoke)
case api.ActionLaunch:
function := mustPopOptionalLastFunctionParam(w, r, s, query)
instance := popOptionalLastParam(w, r, s, query, api.ParamInstance)
instTags := popOptionalParams(query, api.ParamInstanceTag)
invoke := popOptionalLastLogParam(w, r, s, query)
mustNotHaveParams(w, r, s, query)
mustNotHaveContentType(w, r, s)
mustNotHaveContent(w, r, s)
handleLaunch(w, r, s, server.OpLaunchExtant, false, "", key, function, instance, nil, instTags, suspend, invoke)
case api.ActionPin:
modTags := popOptionalParams(query, api.ParamModuleTag)
mustNotHaveParams(w, r, s, query)
mustNotHaveContentType(w, r, s)
mustNotHaveContent(w, r, s)
handleModulePin(w, r, s, key, modTags)
case api.ActionUnpin:
mustNotHaveParams(w, r, s, query)
mustNotHaveContentType(w, r, s)
mustNotHaveContent(w, r, s)
handleModuleUnpin(w, r, s, key)
default:
respondUnsupportedAction(w, r, s)
}
}
func handleGetModuleSource(w http.ResponseWriter, r *http.Request, s *webserver, source string) {
query := mustParseQuery(w, r, s)
pin := popOptionalActionParam(w, r, s, query, api.ActionPin)
var modTags []string
if pin {
modTags = popOptionalParams(query, api.ParamModuleTag)
}
switch popLastParam(w, r, s, query, api.ParamAction) {
case api.ActionCall:
function := mustPopOptionalLastFunctionParam(w, r, s, query)
instTags := popOptionalParams(query, api.ParamInstanceTag)
invoke := popOptionalLastLogParam(w, r, s, query)
mustNotHaveParams(w, r, s, query)
handleCallWebsocket(w, r, s, pin, source, "", function, modTags, instTags, invoke)
default:
respondUnsupportedAction(w, r, s)
}
}
func handlePostModuleSource(w http.ResponseWriter, r *http.Request, s *webserver, source string) {
query := mustParseQuery(w, r, s)
pin := popOptionalActionParam(w, r, s, query, api.ActionPin)
var modTags []string
if pin {
modTags = popOptionalParams(query, api.ParamModuleTag)
}
if _, found := query[api.ParamAction]; found {
suspend := popOptionalActionParam(w, r, s, query, api.ActionSuspend)
switch popLastParam(w, r, s, query, api.ParamAction) {
case api.ActionCall:
if suspend {
respondUnsupportedAction(w, r, s)
}
function := mustPopOptionalLastFunctionParam(w, r, s, query)
instTags := popOptionalParams(query, api.ParamInstanceTag)
invoke := popOptionalLastLogParam(w, r, s, query)
mustNotHaveParams(w, r, s, query)
handleCall(w, r, s, server.OpCallSource, pin, false, source, "", function, modTags, instTags, invoke)
case api.ActionLaunch:
function := mustPopOptionalLastFunctionParam(w, r, s, query)
instance := popOptionalLastParam(w, r, s, query, api.ParamInstance)
instTags := popOptionalParams(query, api.ParamInstanceTag)
invoke := popOptionalLastLogParam(w, r, s, query)
mustNotHaveParams(w, r, s, query)
mustNotHaveContentType(w, r, s)
mustNotHaveContent(w, r, s)
handleLaunch(w, r, s, server.OpLaunchSource, pin, source, "", function, instance, modTags, instTags, suspend, invoke)
default:
respondUnsupportedAction(w, r, s)
}
} else {
if pin {
mustNotHaveParams(w, r, s, query)
mustNotHaveContentType(w, r, s)
mustNotHaveContent(w, r, s)
handleModuleSource(w, r, s, source, modTags)
} else {
respondUnsupportedAction(w, r, s)
}
}
}
func handleGetInstance(w http.ResponseWriter, r *http.Request, s *webserver, instance string) {
query := mustParseQuery(w, r, s)
switch popLastParam(w, r, s, query, api.ParamAction) {
case api.ActionIO:
mustNotHaveParams(w, r, s, query)
handleInstanceConnectWebsocket(w, r, s, instance)
default:
respondUnsupportedAction(w, r, s)
}
}
func handlePostInstances(w http.ResponseWriter, r *http.Request, s *webserver) {
mustNotHaveQuery(w, r, s)
mustNotHaveContentType(w, r, s)
mustNotHaveContent(w, r, s)
mustAcceptJSON(w, r, s)
handleInstanceList(w, r, s)
}
func handlePostInstance(w http.ResponseWriter, r *http.Request, s *webserver, instance string) {
query := mustParseQuery(w, r, s)
actions := popOptionalParams(query, api.ParamAction)
switch len(actions) {
case 0:
mustNotHaveParams(w, r, s, query)
mustAcceptJSON(w, r, s)
handleInstanceInfo(w, r, s, instance)
return
case 1:
switch actions[0] {
case api.ActionIO:
mustNotHaveParams(w, r, s, query)
handleInstanceConnect(w, r, s, instance)
return
case api.ActionResume:
function := mustPopOptionalLastFunctionParam(w, r, s, query)
invoke := popOptionalLastLogParam(w, r, s, query)
mustNotHaveParams(w, r, s, query)
handleInstanceResume(w, r, s, function, instance, invoke)
return
case api.ActionSnapshot:
modTags := popOptionalParams(query, api.ParamModuleTag)
mustNotHaveParams(w, r, s, query)
handleInstanceSnapshot(w, r, s, instance, modTags)
return
case api.ActionDelete:
mustNotHaveParams(w, r, s, query)
handleInstance(w, r, s, server.OpInstanceDelete, deleteInstance, instance)
return
case api.ActionUpdate:
mustNotHaveParams(w, r, s, query)
handleInstanceUpdate(w, r, s, instance)
return
case api.ActionDebug:
mustNotHaveParams(w, r, s, query)
handleInstanceDebug(w, r, s, instance)
return
}
}
var (
kill bool
suspend bool
wait bool
)
for _, a := range actions {
switch a {
case api.ActionKill:
kill = true
case api.ActionSuspend:
suspend = true
case api.ActionWait:
wait = true
default:
respondUnsupportedAction(w, r, s)
return
}
}
switch {
case kill && !suspend:
mustNotHaveParams(w, r, s, query)
handleInstanceWaiter(w, r, s, server.OpInstanceKill, killInstance, instance, wait)
case suspend && !kill:
mustNotHaveParams(w, r, s, query)
handleInstanceWaiter(w, r, s, server.OpInstanceSuspend, suspendInstance, instance, wait)
case wait && !kill && !suspend:
mustNotHaveParams(w, r, s, query)
handleInstanceStatus(w, r, s, server.OpInstanceWait, waitInstance, instance)
default:
respondUnsupportedAction(w, r, s)
}
}
// Action handlers. Check authorization if needed, and serve the response.
func handleStatic(w http.ResponseWriter, r *http.Request, s *webserver, static *staticContent) {
w.Header().Set("Cache-Control", cacheControlStatic)
w.Header().Set(api.HeaderContentLength, static.contentLength)
w.Header().Set(api.HeaderContentType, contentTypeJSON)
w.WriteHeader(http.StatusOK)
w.Write(static.content)
}
func handleModuleList(w http.ResponseWriter, r *http.Request, s *webserver) {
ctx := server.ContextWithOp(r.Context(), server.OpModuleList)
wr := &requestResponseWriter{w, r}
ctx = mustParseAuthorizationHeader(ctx, wr, s, true)
infos, err := s.Server.Modules(ctx)
if err != nil {
respondServerError(ctx, wr, s, "", "", "", "", err)
return
}
sort.Sort(server.SortableModules(infos))
content := protojson.MustMarshal(infos)
w.Header().Set(api.HeaderContentLength, strconv.Itoa(len(content)))
w.Header().Set(api.HeaderContentType, contentTypeJSON)
w.WriteHeader(http.StatusOK)
w.Write(content)
}
func handleKnownModule(w http.ResponseWriter, r *http.Request, s *webserver, key string) {
ctx := server.ContextWithOp(r.Context(), server.OpModuleInfo)
wr := &requestResponseWriter{w, r}
ctx = mustParseAuthorizationHeader(ctx, wr, s, true)
info, err := s.Server.ModuleInfo(ctx, key)
if err != nil {
respondServerError(ctx, wr, s, "", key, "", "", err)
return
}
content := protojson.MustMarshal(info)
w.Header().Set(api.HeaderContentLength, strconv.Itoa(len(content)))
w.Header().Set(api.HeaderContentType, contentTypeJSON)
w.WriteHeader(http.StatusOK)
w.Write(content)
}
func handleModuleDownload(w http.ResponseWriter, r *http.Request, s *webserver, key string) {
ctx := server.ContextWithOp(r.Context(), server.OpModuleDownload)
wr := &requestResponseWriter{w, r}
ctx = mustParseAuthorizationHeader(ctx, wr, s, true)
content, length, err := s.Server.ModuleContent(ctx, key)
if err != nil {
respondServerError(ctx, wr, s, "", key, "", "", err)
panic(responded)
}
defer content.Close()
w.Header().Set(api.HeaderContentLength, strconv.FormatInt(length, 10))
w.Header().Set(api.HeaderContentType, api.ContentTypeWebAssembly)
w.WriteHeader(http.StatusOK)
if r.Method != "HEAD" {
io.Copy(w, content)
}
}
func handleModuleUpload(w http.ResponseWriter, r *http.Request, s *webserver, key string, modTags []string) {
ctx := server.ContextWithOp(r.Context(), server.OpModuleUpload)
wr := &requestResponseWriter{w, r}
ctx = mustParseAuthorizationHeader(ctx, wr, s, true)
upload := moduleUpload(mustDecodeContent(ctx, wr, s), r.ContentLength, key)
defer upload.Close()
if _, err := s.Server.UploadModule(ctx, upload, modulePin(true, modTags)); err != nil {
respondServerError(ctx, wr, s, "", key, "", "", err)
panic(responded)
}
w.WriteHeader(http.StatusCreated)
}
func handleModuleSource(w http.ResponseWriter, r *http.Request, s *webserver, source string, modTags []string) {
ctx := server.ContextWithOp(r.Context(), server.OpModuleSource)
wr := &requestResponseWriter{w, r}
ctx = mustParseAuthorizationHeader(ctx, wr, s, true)
module, err := s.Server.SourceModule(ctx, source, modulePin(true, modTags))
if err != nil {
respondServerError(ctx, wr, s, source, "", "", "", err)
return
}
w.Header().Set(api.HeaderLocation, s.pathKnownModules+module)
w.WriteHeader(http.StatusCreated)
}
func handleModulePin(w http.ResponseWriter, r *http.Request, s *webserver, key string, modTags []string) {
ctx := server.ContextWithOp(r.Context(), server.OpModulePin)
wr := &requestResponseWriter{w, r}
ctx = mustParseAuthorizationHeader(ctx, wr, s, true)
if err := s.Server.PinModule(ctx, key, modulePin(true, modTags)); err != nil {
respondServerError(ctx, wr, s, "", key, "", "", err)
panic(responded)
}
w.WriteHeader(http.StatusNoContent)
}
func handleModuleUnpin(w http.ResponseWriter, r *http.Request, s *webserver, key string) {
ctx := server.ContextWithOp(r.Context(), server.OpModuleUnpin)
wr := &requestResponseWriter{w, r}
ctx = mustParseAuthorizationHeader(ctx, wr, s, true)
if err := s.Server.UnpinModule(ctx, key); err != nil {
respondServerError(ctx, wr, s, "", key, "", "", err)
panic(responded)
}
w.WriteHeader(http.StatusNoContent)
}
func handleCall(w http.ResponseWriter, r *http.Request, s *webserver, op server.Op, pin, content bool, source, key, function string, modTags, instTags []string, invoke *server.InvokeOptions) {
ctx := server.ContextWithOp(r.Context(), op) // TODO: detail: post
wr := &requestResponseWriter{w, r}
launch := &server.LaunchOptions{
Invoke: invoke,
Function: function,
Transient: true,
Tags: instTags,
}
var (
module string
inst server.Instance
err error
)
switch {
case content:
ctx = mustParseAuthorizationHeader(ctx, wr, s, pin)
upload := moduleUpload(mustDecodeContent(ctx, wr, s), r.ContentLength, key)
defer upload.Close()
module, inst, err = s.Server.UploadModuleInstance(ctx, upload, modulePin(pin, modTags), launch)
if err != nil {
respondServerError(ctx, wr, s, "", key, function, "", err)
return
}
case source == "":
ctx = mustParseAuthorizationHeader(ctx, wr, s, true)
module = key
inst, err = s.Server.NewInstance(ctx, key, launch)
if err != nil {
respondServerError(ctx, wr, s, "", key, function, "", err)
return
}
default:
ctx = mustParseAuthorizationHeader(ctx, wr, s, pin)
module, inst, err = s.Server.SourceModuleInstance(ctx, source, modulePin(pin, modTags), launch)
if err != nil {
// TODO: find out module hash
respondServerError(ctx, wr, s, source, "", function, "", err)
return
}
}
defer inst.Kill(ctx) // TODO: error
trail := acceptsTrailers(r)
if trail {
w.Header().Set("Trailer", api.HeaderStatus)
}
if principal.ContextID(ctx) != nil {
if pin {
w.Header().Set(api.HeaderLocation, s.pathKnownModules+module)
}
w.Header().Set(api.HeaderInstance, inst.ID())
}
if pin {
w.WriteHeader(http.StatusCreated)
} else {
w.WriteHeader(http.StatusOK)
}
inst.Connect(ctx, r.Body, nopCloser{w})
status := inst.Wait(ctx)
if trail {
w.Header().Set(api.HeaderStatus, string(protojson.MustMarshal(status)))
}
}