This repository has been archived by the owner on Mar 7, 2024. It is now read-only.
forked from cloudflare/cloudflare-go
-
Notifications
You must be signed in to change notification settings - Fork 8
/
workers.go
1110 lines (983 loc) · 35.8 KB
/
workers.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
package cloudflare
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
"strings"
"time"
)
// WorkerRequestParams provides parameters for worker requests for both enterprise and standard requests.
type WorkerRequestParams struct {
ZoneID string
ScriptName string
NamespaceName string
}
// WorkerScriptParams provides a worker script and the associated bindings.
type WorkerScriptParams struct {
Script string
// Module changes the Content-Type header to specify the script is an
// ES Module syntax script.
Module bool
// Bindings should be a map where the keys are the binding name, and the
// values are the binding content
Bindings map[string]WorkerBinding
// Compatibility options
CompatibilityFlags []string
CompatibilityDate string
Logpush *bool
}
// WorkerRoute is used to map traffic matching a URL pattern to a workers
//
// API reference: https://api.cloudflare.com/#worker-routes-properties
type WorkerRoute struct {
ID string `json:"id,omitempty"`
Pattern string `json:"pattern"`
Enabled bool `json:"enabled"` // this is deprecated: https://api.cloudflare.com/#worker-filters-deprecated--properties
Script string `json:"script,omitempty"`
}
// WorkerRoutesResponse embeds Response struct and slice of WorkerRoutes.
type WorkerRoutesResponse struct {
Response
Routes []WorkerRoute `json:"result"`
}
// WorkerRouteResponse embeds Response struct and a single WorkerRoute.
type WorkerRouteResponse struct {
Response
WorkerRoute `json:"result"`
}
// WorkerScript Cloudflare Worker struct with metadata.
type WorkerScript struct {
WorkerMetaData
Script string `json:"script"`
UsageModel string `json:"usage_model,omitempty"`
}
// WorkerMetaData contains worker script information such as size, creation & modification dates.
type WorkerMetaData struct {
ID string `json:"id,omitempty"`
ETAG string `json:"etag,omitempty"`
ETAGBypass string `json:"etag_bypass,omitempty"`
Size int `json:"size,omitempty"`
CreatedOn time.Time `json:"created_on,omitempty"`
ModifiedOn time.Time `json:"modified_on,omitempty"`
CompatibiltyFlags []string `json:"compatibility_flags,omitempty"`
CompatibiltyDate string `json:"compatibility_date,omitempty"`
}
// WorkerListResponse wrapper struct for API response to worker script list API call.
type WorkerListResponse struct {
Response
WorkerList []WorkerMetaData `json:"result"`
}
// WorkerScriptResponse wrapper struct for API response to worker script calls.
type WorkerScriptResponse struct {
Response
Module bool
WorkerScript `json:"result"`
}
// WorkerBindingType represents a particular type of binding.
type WorkerBindingType string
func (b WorkerBindingType) String() string {
return string(b)
}
const (
// WorkerDurableObjectBindingType is the type for Durable Object bindings.
WorkerDurableObjectBindingType WorkerBindingType = "durable_object_namespace"
// WorkerInheritBindingType is the type for inherited bindings.
WorkerInheritBindingType WorkerBindingType = "inherit"
// WorkerKvNamespaceBindingType is the type for KV Namespace bindings.
WorkerKvNamespaceBindingType WorkerBindingType = "kv_namespace"
// WorkerWebAssemblyBindingType is the type for Web Assembly module bindings.
WorkerWebAssemblyBindingType WorkerBindingType = "wasm_module"
// WorkerSecretTextBindingType is the type for secret text bindings.
WorkerSecretTextBindingType WorkerBindingType = "secret_text"
// WorkerPlainTextBindingType is the type for plain text bindings.
WorkerPlainTextBindingType WorkerBindingType = "plain_text"
// WorkerServiceBindingType is the type for service bindings.
WorkerServiceBindingType WorkerBindingType = "service"
// WorkerR2BucketBindingType is the type for R2 bucket bindings.
WorkerR2BucketBindingType WorkerBindingType = "r2_bucket"
// WorkerAnalyticsEngineBindingType is the type for Analytics Engine dataset bindings.
WorkerAnalyticsEngineBindingType WorkerBindingType = "analytics_engine"
// WorkerDynamicDispatchBindingType is the type for dynamic dispatch bindings.
WorkerDynamicDispatchBindingType WorkerBindingType = "dynamic_dispatch"
)
// WorkerBindingListItem a struct representing an individual binding in a list of bindings.
type WorkerBindingListItem struct {
Name string `json:"name"`
Binding WorkerBinding
}
// WorkerBindingListResponse wrapper struct for API response to worker binding list API call.
type WorkerBindingListResponse struct {
Response
BindingList []WorkerBindingListItem
}
// Workers supports multiple types of bindings, e.g. KV namespaces or WebAssembly modules, and each type
// of binding will be represented differently in the upload request body. At a high-level, every binding
// will specify metadata, which is a JSON object with the properties "name" and "type". Some types of bindings
// will also have additional metadata properties. For example, KV bindings also specify the KV namespace.
// In addition to the metadata, some binding types may need to include additional data as part of the
// multipart form. For example, WebAssembly bindings will include the contents of the WebAssembly module.
// WorkerBinding is the generic interface implemented by all of
// the various binding types.
type WorkerBinding interface {
Type() WorkerBindingType
// serialize is responsible for returning the binding metadata as well as an optionally
// returning a function that can modify the multipart form body. For example, this is used
// by WebAssembly bindings to add a new part containing the WebAssembly module contents.
serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error)
}
// workerBindingMeta is the metadata portion of the binding.
type workerBindingMeta = map[string]interface{}
// workerBindingBodyWriter allows for a binding to add additional parts to the multipart body.
type workerBindingBodyWriter func(*multipart.Writer) error
// WorkerInheritBinding will just persist whatever binding content was previously uploaded.
type WorkerInheritBinding struct {
// Optional parameter that allows for renaming a binding without changing
// its contents. If `OldName` is empty, the binding name will not be changed.
OldName string
}
type WorkerTraceDetails struct {
Service string `json:"service"`
Environment string `json:"environment"`
}
type WorkerTraceMetaData struct {
TAG string `json:"tag,omitempty"`
CreatedOn time.Time `json:"created_on,omitempty"`
UpdatedOn time.Time `json:"updated_on,omitempty"`
Producer WorkerTraceDetails `json:"producer"`
Consumer WorkerTraceDetails `json:"consumer"`
}
type WorkerTraceListResponse struct {
Response
WorkerTraceList []WorkerTraceMetaData `json:"result"`
}
type WorkerTraceResponse struct {
Response
WorkerTrace WorkerTraceMetaData `json:"result"`
}
type WorkerTraceParams struct {
Producer WorkerTraceDetails `json:"producer"`
Consumer WorkerTraceDetails `json:"consumer"`
}
// Type returns the type of the binding.
func (b WorkerInheritBinding) Type() WorkerBindingType {
return WorkerInheritBindingType
}
func (b WorkerInheritBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
meta := workerBindingMeta{
"name": bindingName,
"type": b.Type(),
}
if b.OldName != "" {
meta["old_name"] = b.OldName
}
return meta, nil, nil
}
// WorkerKvNamespaceBinding is a binding to a Workers KV Namespace
//
// https://developers.cloudflare.com/workers/archive/api/resource-bindings/kv-namespaces/
type WorkerKvNamespaceBinding struct {
NamespaceID string
}
// Type returns the type of the binding.
func (b WorkerKvNamespaceBinding) Type() WorkerBindingType {
return WorkerKvNamespaceBindingType
}
func (b WorkerKvNamespaceBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
if b.NamespaceID == "" {
return nil, nil, fmt.Errorf(`NamespaceID for binding "%s" cannot be empty`, bindingName)
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"namespace_id": b.NamespaceID,
}, nil, nil
}
// WorkerDurableObjectBinding is a binding to a Workers Durable Object
//
// https://api.cloudflare.com/#durable-objects-namespace-properties
type WorkerDurableObjectBinding struct {
ClassName string
ScriptName string
}
// Type returns the type of the binding.
func (b WorkerDurableObjectBinding) Type() WorkerBindingType {
return WorkerDurableObjectBindingType
}
func (b WorkerDurableObjectBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
if b.ClassName == "" {
return nil, nil, fmt.Errorf(`ClassName for binding "%s" cannot be empty`, bindingName)
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"class_name": b.ClassName,
"script_name": b.ScriptName,
}, nil, nil
}
// WorkerWebAssemblyBinding is a binding to a WebAssembly module
//
// https://developers.cloudflare.com/workers/archive/api/resource-bindings/webassembly-modules/
type WorkerWebAssemblyBinding struct {
Module io.Reader
}
// Type returns the type of the binding.
func (b WorkerWebAssemblyBinding) Type() WorkerBindingType {
return WorkerWebAssemblyBindingType
}
func (b WorkerWebAssemblyBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
partName := getRandomPartName()
bodyWriter := func(mpw *multipart.Writer) error {
var hdr = textproto.MIMEHeader{}
hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"`, partName))
hdr.Set("content-type", "application/wasm")
pw, err := mpw.CreatePart(hdr)
if err != nil {
return err
}
_, err = io.Copy(pw, b.Module)
return err
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"part": partName,
}, bodyWriter, nil
}
// WorkerPlainTextBinding is a binding to plain text
//
// https://developers.cloudflare.com/workers/tooling/api/scripts/#add-a-plain-text-binding
type WorkerPlainTextBinding struct {
Text string
}
// Type returns the type of the binding.
func (b WorkerPlainTextBinding) Type() WorkerBindingType {
return WorkerPlainTextBindingType
}
func (b WorkerPlainTextBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
if b.Text == "" {
return nil, nil, fmt.Errorf(`Text for binding "%s" cannot be empty`, bindingName)
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"text": b.Text,
}, nil, nil
}
// WorkerSecretTextBinding is a binding to secret text
//
// https://developers.cloudflare.com/workers/tooling/api/scripts/#add-a-secret-text-binding
type WorkerSecretTextBinding struct {
Text string
}
// Type returns the type of the binding.
func (b WorkerSecretTextBinding) Type() WorkerBindingType {
return WorkerSecretTextBindingType
}
func (b WorkerSecretTextBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
if b.Text == "" {
return nil, nil, fmt.Errorf(`Text for binding "%s" cannot be empty`, bindingName)
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"text": b.Text,
}, nil, nil
}
type WorkerServiceBinding struct {
Service string
Environment *string
}
func (b WorkerServiceBinding) Type() WorkerBindingType {
return WorkerServiceBindingType
}
func (b WorkerServiceBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
if b.Service == "" {
return nil, nil, fmt.Errorf(`Service for binding "%s" cannot be empty`, bindingName)
}
meta := workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"service": b.Service,
}
if b.Environment != nil {
meta["environment"] = *b.Environment
}
return meta, nil, nil
}
// WorkerR2BucketBinding is a binding to an R2 bucket.
type WorkerR2BucketBinding struct {
BucketName string
}
// Type returns the type of the binding.
func (b WorkerR2BucketBinding) Type() WorkerBindingType {
return WorkerR2BucketBindingType
}
func (b WorkerR2BucketBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
if b.BucketName == "" {
return nil, nil, fmt.Errorf(`BucketName for binding "%s" cannot be empty`, bindingName)
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"bucket_name": b.BucketName,
}, nil, nil
}
// WorkerAnalyticsEngineBinding is a binding to an Analytics Engine dataset.
type WorkerAnalyticsEngineBinding struct {
Dataset string
}
// Type returns the type of the binding.
func (b WorkerAnalyticsEngineBinding) Type() WorkerBindingType {
return WorkerAnalyticsEngineBindingType
}
func (b WorkerAnalyticsEngineBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
if b.Dataset == "" {
return nil, nil, fmt.Errorf(`Dataset for binding "%s" cannot be empty`, bindingName)
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"dataset": b.Dataset,
}, nil, nil
}
// WorkerDynamicDispatchBinding is a binding to a dispatcher than can dispatch another Worker
//
// https://developers.cloudflare.com/workers/tooling/api/scripts/#add-a-plain-text-binding
type WorkerDynamicDispatchBinding struct{}
// Type returns the type of the binding.
func (b WorkerDynamicDispatchBinding) Type() WorkerBindingType {
return WorkerDynamicDispatchBindingType
}
func (b WorkerDynamicDispatchBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
if bindingName == "" {
return nil, nil, fmt.Errorf(`Name for Dynamic Dispatch binding "%s" cannot be empty`, bindingName)
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
}, nil, nil
}
// Each binding that adds a part to the multipart form body will need
// a unique part name so we just generate a random 128bit hex string.
func getRandomPartName() string {
randBytes := make([]byte, 16)
rand.Read(randBytes) //nolint:errcheck
return hex.EncodeToString(randBytes)
}
// DeleteWorker deletes worker for a zone.
//
// API reference: https://api.cloudflare.com/#worker-script-delete-worker
func (api *API) DeleteWorker(ctx context.Context, requestParams *WorkerRequestParams) (WorkerScriptResponse, error) {
// if ScriptName is provided we will treat as org request
if requestParams.ScriptName != "" {
return api.deleteWorkerWithName(ctx, requestParams.ScriptName)
}
uri := fmt.Sprintf("/zones/%s/workers/script", requestParams.ZoneID)
res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)
var r WorkerScriptResponse
if err != nil {
return r, err
}
err = json.Unmarshal(res, &r)
if err != nil {
return r, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return r, nil
}
// DeleteWorkerWithName deletes worker for a zone.
// Sccount must be specified as api option https://godoc.org/github.com/cloudflare/cloudflare-go#UsingAccount
//
// API reference: https://developers.cloudflare.com/workers/tooling/api/scripts/
func (api *API) deleteWorkerWithName(ctx context.Context, scriptName string) (WorkerScriptResponse, error) {
if api.AccountID == "" {
return WorkerScriptResponse{}, errors.New("account ID required")
}
uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s", api.AccountID, scriptName)
res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)
var r WorkerScriptResponse
if err != nil {
return r, err
}
err = json.Unmarshal(res, &r)
if err != nil {
return r, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return r, nil
}
// DownloadWorker fetch raw script content for your worker returns []byte containing worker code js
//
// API reference: https://api.cloudflare.com/#worker-script-download-worker
func (api *API) DownloadWorker(ctx context.Context, requestParams *WorkerRequestParams) (WorkerScriptResponse, error) {
if requestParams.ScriptName != "" {
return api.downloadWorkerWithName(ctx, requestParams.ScriptName)
}
uri := fmt.Sprintf("/zones/%s/workers/script", requestParams.ZoneID)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
var r WorkerScriptResponse
if err != nil {
return r, err
}
r.Script = string(res)
r.Module = false
r.Success = true
return r, nil
}
// DownloadWorkerWithName fetch raw script content for your worker returns string containing worker code js
//
// API reference: https://developers.cloudflare.com/workers/tooling/api/scripts/
func (api *API) downloadWorkerWithName(ctx context.Context, scriptName string) (WorkerScriptResponse, error) {
if api.AccountID == "" {
return WorkerScriptResponse{}, errors.New("account ID required")
}
uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s", api.AccountID, scriptName)
res, err := api.makeRequestContextWithHeadersComplete(ctx, http.MethodGet, uri, nil, nil)
var r WorkerScriptResponse
if err != nil {
return r, err
}
// Check if the response type is multipart, in which case this was a module worker
mediaType, mediaParams, _ := mime.ParseMediaType(res.Headers.Get("content-type"))
if strings.HasPrefix(mediaType, "multipart/") {
bytesReader := bytes.NewReader(res.Body)
mimeReader := multipart.NewReader(bytesReader, mediaParams["boundary"])
mimePart, err := mimeReader.NextPart()
if err != nil {
return r, fmt.Errorf("could not get multipart response body: %w", err)
}
mimePartBody, err := io.ReadAll(mimePart)
if err != nil {
return r, fmt.Errorf("could not read multipart response body: %w", err)
}
r.Script = string(mimePartBody)
r.Module = true
} else {
r.Script = string(res.Body)
r.Module = false
}
r.Success = true
return r, nil
}
// ListWorkerBindings returns all the bindings for a particular worker.
func (api *API) ListWorkerBindings(ctx context.Context, requestParams *WorkerRequestParams) (WorkerBindingListResponse, error) {
if requestParams.ScriptName == "" {
return WorkerBindingListResponse{}, errors.New("ScriptName is required")
}
if api.AccountID == "" {
return WorkerBindingListResponse{}, errors.New("account ID required")
}
uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/bindings", api.AccountID, requestParams.ScriptName)
var jsonRes struct {
Response
Bindings []workerBindingMeta `json:"result"`
}
var r WorkerBindingListResponse
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return r, err
}
err = json.Unmarshal(res, &jsonRes)
if err != nil {
return r, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
r = WorkerBindingListResponse{
Response: jsonRes.Response,
BindingList: make([]WorkerBindingListItem, 0, len(jsonRes.Bindings)),
}
for _, jsonBinding := range jsonRes.Bindings {
name, ok := jsonBinding["name"].(string)
if !ok {
return r, fmt.Errorf("Binding missing name %v", jsonBinding)
}
bType, ok := jsonBinding["type"].(string)
if !ok {
return r, fmt.Errorf("Binding missing type %v", jsonBinding)
}
bindingListItem := WorkerBindingListItem{
Name: name,
}
switch WorkerBindingType(bType) {
case WorkerDurableObjectBindingType:
class_name := jsonBinding["class_name"].(string)
script_name := jsonBinding["script_name"].(string)
bindingListItem.Binding = WorkerDurableObjectBinding{
ClassName: class_name,
ScriptName: script_name,
}
case WorkerKvNamespaceBindingType:
namespaceID := jsonBinding["namespace_id"].(string)
bindingListItem.Binding = WorkerKvNamespaceBinding{
NamespaceID: namespaceID,
}
case WorkerWebAssemblyBindingType:
bindingListItem.Binding = WorkerWebAssemblyBinding{
Module: &bindingContentReader{
ctx: ctx,
api: api,
requestParams: requestParams,
bindingName: name,
},
}
case WorkerPlainTextBindingType:
text := jsonBinding["text"].(string)
bindingListItem.Binding = WorkerPlainTextBinding{
Text: text,
}
case WorkerServiceBindingType:
service := jsonBinding["service"].(string)
environment := jsonBinding["environment"].(string)
bindingListItem.Binding = WorkerServiceBinding{
Service: service,
Environment: &environment,
}
case WorkerSecretTextBindingType:
bindingListItem.Binding = WorkerSecretTextBinding{}
case WorkerR2BucketBindingType:
bucketName := jsonBinding["bucket_name"].(string)
bindingListItem.Binding = WorkerR2BucketBinding{
BucketName: bucketName,
}
case WorkerAnalyticsEngineBindingType:
dataset := jsonBinding["dataset"].(string)
bindingListItem.Binding = WorkerAnalyticsEngineBinding{
Dataset: dataset,
}
case WorkerDynamicDispatchBindingType:
bindingListItem.Binding = WorkerDynamicDispatchBinding{}
default:
bindingListItem.Binding = WorkerInheritBinding{}
}
r.BindingList = append(r.BindingList, bindingListItem)
}
return r, nil
}
// bindingContentReader is an io.Reader that will lazily load the
// raw bytes for a binding from the API when the Read() method
// is first called. This is only useful for binding types
// that store raw bytes, like WebAssembly modules.
type bindingContentReader struct {
api *API
requestParams *WorkerRequestParams
ctx context.Context
bindingName string
content []byte
position int
}
func (b *bindingContentReader) Read(p []byte) (n int, err error) {
// Lazily load the content when Read() is first called
if b.content == nil {
uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/bindings/%s/content", b.api.AccountID, b.requestParams.ScriptName, b.bindingName)
res, err := b.api.makeRequestContext(b.ctx, http.MethodGet, uri, nil)
if err != nil {
return 0, err
}
b.content = res
}
if b.position >= len(b.content) {
return 0, io.EOF
}
bytesRemaining := len(b.content) - b.position
bytesToProcess := 0
if len(p) < bytesRemaining {
bytesToProcess = len(p)
} else {
bytesToProcess = bytesRemaining
}
for i := 0; i < bytesToProcess; i++ {
p[i] = b.content[b.position]
b.position = b.position + 1
}
return bytesToProcess, nil
}
// ListWorkerScripts returns list of worker scripts for given account.
//
// API reference: https://developers.cloudflare.com/workers/tooling/api/scripts/
func (api *API) ListWorkerScripts(ctx context.Context) (WorkerListResponse, error) {
if api.AccountID == "" {
return WorkerListResponse{}, errors.New("account ID required")
}
uri := fmt.Sprintf("/accounts/%s/workers/scripts", api.AccountID)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return WorkerListResponse{}, err
}
var r WorkerListResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerListResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return r, nil
}
// UploadWorker push raw script content for your worker.
//
// API reference: https://api.cloudflare.com/#worker-script-upload-worker
func (api *API) UploadWorker(ctx context.Context, requestParams *WorkerRequestParams, params *WorkerScriptParams) (WorkerScriptResponse, error) {
if params.Module || params.Logpush != nil {
return api.UploadWorkerWithBindings(ctx, requestParams, params)
}
contentType := "application/javascript"
if requestParams.ScriptName != "" {
return api.uploadWorkerWithName(ctx, requestParams.ScriptName, contentType, []byte(params.Script))
}
return api.uploadWorkerForZone(ctx, requestParams.ZoneID, contentType, []byte(params.Script))
}
// UploadWorkerWithBindings push raw script content and bindings for your worker
//
// API reference: https://api.cloudflare.com/#worker-script-upload-worker
func (api *API) UploadWorkerWithBindings(ctx context.Context, requestParams *WorkerRequestParams, data *WorkerScriptParams) (WorkerScriptResponse, error) {
contentType, body, err := formatMultipartBody(data)
if err != nil {
return WorkerScriptResponse{}, err
}
if requestParams.NamespaceName != "" && requestParams.ScriptName != "" {
return api.uploadWorkerWithNamespace(ctx, requestParams.NamespaceName, requestParams.ScriptName, contentType, body)
}
if requestParams.ScriptName != "" {
return api.uploadWorkerWithName(ctx, requestParams.ScriptName, contentType, body)
}
return api.uploadWorkerForZone(ctx, requestParams.ZoneID, contentType, body)
}
func (api *API) uploadWorkerForZone(ctx context.Context, zoneID, contentType string, body []byte) (WorkerScriptResponse, error) {
uri := fmt.Sprintf("/zones/%s/workers/script", zoneID)
headers := make(http.Header)
headers.Set("Content-Type", contentType)
res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPut, uri, body, headers)
var r WorkerScriptResponse
if err != nil {
return r, err
}
err = json.Unmarshal(res, &r)
if err != nil {
return r, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return r, nil
}
func (api *API) uploadWorkerWithName(ctx context.Context, scriptName, contentType string, body []byte) (WorkerScriptResponse, error) {
if api.AccountID == "" {
return WorkerScriptResponse{}, errors.New("account ID required")
}
uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s", api.AccountID, scriptName)
headers := make(http.Header)
headers.Set("Content-Type", contentType)
res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPut, uri, body, headers)
var r WorkerScriptResponse
if err != nil {
return r, err
}
err = json.Unmarshal(res, &r)
if err != nil {
return r, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return r, nil
}
func (api *API) uploadWorkerWithNamespace(ctx context.Context, namespaceName, scriptName, contentType string, body []byte) (WorkerScriptResponse, error) {
if api.AccountID == "" {
return WorkerScriptResponse{}, errors.New("account ID required")
}
uri := fmt.Sprintf("/accounts/%s/workers/dispatch/namespaces/%s/scripts/%s", api.AccountID, namespaceName, scriptName)
headers := make(http.Header)
headers.Set("Content-Type", contentType)
res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPut, uri, body, headers)
var r WorkerScriptResponse
if err != nil {
return r, err
}
err = json.Unmarshal(res, &r)
if err != nil {
return r, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return r, nil
}
// Returns content-type, body, error.
func formatMultipartBody(params *WorkerScriptParams) (string, []byte, error) {
var buf = &bytes.Buffer{}
var mpw = multipart.NewWriter(buf)
defer mpw.Close()
// Write metadata part
var scriptPartName string
meta := struct {
BodyPart string `json:"body_part,omitempty"`
MainModule string `json:"main_module,omitempty"`
Bindings []workerBindingMeta `json:"bindings"`
CompatibilityFlags []string `json:"compatibility_flags"`
CompatibilityDate string `json:"compatibility_date"`
Logpush *bool `json:"logpush,omitempty"`
}{
Bindings: make([]workerBindingMeta, 0, len(params.Bindings)),
CompatibilityFlags: params.CompatibilityFlags,
CompatibilityDate: params.CompatibilityDate,
Logpush: params.Logpush,
}
if params.Module {
scriptPartName = "worker.mjs"
meta.MainModule = scriptPartName
} else {
scriptPartName = "script"
meta.BodyPart = scriptPartName
}
bodyWriters := make([]workerBindingBodyWriter, 0, len(params.Bindings))
for name, b := range params.Bindings {
bindingMeta, bodyWriter, err := b.serialize(name)
if err != nil {
return "", nil, err
}
meta.Bindings = append(meta.Bindings, bindingMeta)
bodyWriters = append(bodyWriters, bodyWriter)
}
var hdr = textproto.MIMEHeader{}
hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"`, "metadata"))
hdr.Set("content-type", "application/json")
pw, err := mpw.CreatePart(hdr)
if err != nil {
return "", nil, err
}
metaJSON, err := json.Marshal(meta)
if err != nil {
return "", nil, err
}
_, err = pw.Write(metaJSON)
if err != nil {
return "", nil, err
}
// Write script part
hdr = textproto.MIMEHeader{}
contentType := "application/javascript"
if params.Module {
contentType = "application/javascript+module"
hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"; filename="%[1]s"`, scriptPartName))
} else {
hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"`, scriptPartName))
}
hdr.Set("content-type", contentType)
pw, err = mpw.CreatePart(hdr)
if err != nil {
return "", nil, err
}
_, err = pw.Write([]byte(params.Script))
if err != nil {
return "", nil, err
}
// Write other bindings with parts
for _, w := range bodyWriters {
if w != nil {
err = w(mpw)
if err != nil {
return "", nil, err
}
}
}
mpw.Close()
return mpw.FormDataContentType(), buf.Bytes(), nil
}
// CreateWorkerRoute creates worker route for a zone
//
// API reference: https://api.cloudflare.com/#worker-filters-create-filter, https://api.cloudflare.com/#worker-routes-create-route
func (api *API) CreateWorkerRoute(ctx context.Context, zoneID string, route WorkerRoute) (WorkerRouteResponse, error) {
pathComponent, err := getRouteEndpoint(route)
if err != nil {
return WorkerRouteResponse{}, err
}
uri := fmt.Sprintf("/zones/%s/workers/%s", zoneID, pathComponent)
res, err := api.makeRequestContext(ctx, http.MethodPost, uri, route)
if err != nil {
return WorkerRouteResponse{}, err
}
var r WorkerRouteResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerRouteResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return r, nil
}
// DeleteWorkerRoute deletes worker route for a zone
//
// API reference: https://api.cloudflare.com/#worker-routes-delete-route
func (api *API) DeleteWorkerRoute(ctx context.Context, zoneID string, routeID string) (WorkerRouteResponse, error) {
uri := fmt.Sprintf("/zones/%s/workers/routes/%s", zoneID, routeID)
res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)
if err != nil {
return WorkerRouteResponse{}, err
}
var r WorkerRouteResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerRouteResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return r, nil
}
// ListWorkerRoutes returns list of worker routes
//
// API reference: https://api.cloudflare.com/#worker-filters-list-filters, https://api.cloudflare.com/#worker-routes-list-routes
func (api *API) ListWorkerRoutes(ctx context.Context, zoneID string) (WorkerRoutesResponse, error) {
pathComponent := "filters"
// Unfortunately we don't have a good signal of whether the user is wanting
// to use the deprecated filters endpoint (https://api.cloudflare.com/#worker-filters-list-filters)
// or the multi-script routes endpoint (https://api.cloudflare.com/#worker-script-list-workers)
//
// The filters endpoint does not support API tokens, so if an API token is specified we need to use
// the routes endpoint. Otherwise, since the multi-script API endpoints that operate on a script
// require an AccountID, we assume that anyone specifying an AccountID is using the routes endpoint.
// This is likely too presumptuous. In the next major version, we should just remove the deprecated
// filter endpoints entirely to avoid this ambiguity.
if api.AccountID != "" || api.APIToken != "" {
pathComponent = "routes"
}
uri := fmt.Sprintf("/zones/%s/workers/%s", zoneID, pathComponent)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return WorkerRoutesResponse{}, err
}
var r WorkerRoutesResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerRoutesResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
for i := range r.Routes {
route := &r.Routes[i]
// The Enabled flag will not be set in the multi-script API response
// so we manually set it to true if the script name is not empty
// in case any multi-script customers rely on the Enabled field
if route.Script != "" {
route.Enabled = true
}
}
return r, nil
}
// GetWorkerRoute returns a worker route.
//
// API reference: https://api.cloudflare.com/#worker-routes-get-route
func (api *API) GetWorkerRoute(ctx context.Context, zoneID string, routeID string) (WorkerRouteResponse, error) {
uri := fmt.Sprintf("/zones/%s/workers/routes/%s", zoneID, routeID)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return WorkerRouteResponse{}, err
}
var r WorkerRouteResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerRouteResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return r, nil
}
// UpdateWorkerRoute updates worker route for a zone.
//
// API reference: https://api.cloudflare.com/#worker-filters-update-filter, https://api.cloudflare.com/#worker-routes-update-route
func (api *API) UpdateWorkerRoute(ctx context.Context, zoneID string, routeID string, route WorkerRoute) (WorkerRouteResponse, error) {
pathComponent, err := getRouteEndpoint(route)
if err != nil {
return WorkerRouteResponse{}, err
}
uri := fmt.Sprintf("/zones/%s/workers/%s/%s", zoneID, pathComponent, routeID)
res, err := api.makeRequestContext(ctx, http.MethodPut, uri, route)
if err != nil {
return WorkerRouteResponse{}, err
}
var r WorkerRouteResponse
err = json.Unmarshal(res, &r)