-
Notifications
You must be signed in to change notification settings - Fork 3
/
handler.go
1374 lines (1182 loc) · 34.9 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
package inngestgo
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"reflect"
"runtime/debug"
"sync"
"time"
"github.com/inngest/inngest/pkg/enums"
"github.com/inngest/inngest/pkg/execution/state"
"github.com/inngest/inngest/pkg/inngest"
"github.com/inngest/inngest/pkg/publicerr"
"github.com/inngest/inngest/pkg/sdk"
sdkerrors "github.com/inngest/inngestgo/errors"
"github.com/inngest/inngestgo/internal/sdkrequest"
"github.com/inngest/inngestgo/internal/types"
"github.com/inngest/inngestgo/step"
)
var (
// DefaultHandler provides a default handler for registering and serving functions
// globally.
//
// It's recommended to call SetOptions() to set configuration before serving
// this in production environments; this is set up for development and will
// attempt to connect to the dev server.
DefaultHandler Handler = NewHandler("Go app", HandlerOpts{})
ErrTypeMismatch = fmt.Errorf("cannot invoke function with mismatched types")
// DefaultMaxBodySize is the default maximum size read within a single incoming
// invoke request (100MB).
DefaultMaxBodySize = 1024 * 1024 * 100
capabilities = sdk.Capabilities{
InBandSync: sdk.InBandSyncV1,
TrustProbe: sdk.TrustProbeV1,
Connect: sdk.ConnectV1,
}
defaultWorkerConcurrency = 1_000
)
// Register adds the given functions to the default handler for serving. You must register all
// functions with a handler prior to serving the handler for them to be enabled.
func Register(funcs ...ServableFunction) {
DefaultHandler.Register(funcs...)
}
// Serve serves all registered functions within the default handler.
func Serve(w http.ResponseWriter, r *http.Request) {
DefaultHandler.ServeHTTP(w, r)
}
func Connect(ctx context.Context) error {
return DefaultHandler.Connect(ctx)
}
type HandlerOpts struct {
// Logger is the structured logger to use from Go's builtin structured
// logging package.
Logger *slog.Logger
// SigningKey is the signing key for your app. If nil, this defaults
// to os.Getenv("INNGEST_SIGNING_KEY").
SigningKey *string
// SigningKeyFallback is the fallback signing key for your app. If nil, this
// defaults to os.Getenv("INNGEST_SIGNING_KEY_FALLBACK").
SigningKeyFallback *string
// APIOrigin is the specified host to be used to make API calls
APIBaseURL *string
// EventAPIOrigin is the specified host to be used to send events to
EventAPIBaseURL *string
// ServeOrigin is the host to used for HTTP base function invoking.
// It's used to specify the host were the functions are hosted on sync.
// e.g. https://example.com
ServeOrigin *string
// ServePath is the path to use for HTTP base function invoking
// It's used to specify the path were the functions are hosted on sync.
// e.g. /api/inngest
ServePath *string
// Env is the branch environment to deploy to. If nil, this uses
// os.Getenv("INNGEST_ENV"). This only deploys to branches if the
// signing key is a branch signing key.
Env *string
// RegisterURL is the URL to use when registering functions. If nil
// this defaults to Inngest's API.
//
// This only needs to be set when self hosting.
RegisterURL *string
// InstanceId represents a stable identifier to be used for identifying connected SDKs.
// This can be a hostname or other identifier that remains stable across restarts.
//
// If nil, this defaults to the current machine's hostname.
InstanceId *string
// BuildId supplies an application version identifier. This should change
// whenever code within one of your Inngest function or any dependency thereof changes.
BuildId *string
// MaxBodySize is the max body size to read for incoming invoke requests
MaxBodySize int
// URL that the function is served at. If not supplied this is taken from
// the incoming request's data.
URL *url.URL
// UseStreaming enables streaming - continued writes to the HTTP writer. This
// differs from true streaming in that we don't support server-sent events.
UseStreaming bool
// AllowInBandSync allows in-band syncs to occur. If nil, in-band syncs are
// disallowed.
AllowInBandSync *bool
// WorkerConcurrency defines the number of goroutines available to handle
// connnect workloads. Defaults to 1000
WorkerConcurrency int
Dev *bool
}
// GetSigningKey returns the signing key defined within HandlerOpts, or the default
// defined within INNGEST_SIGNING_KEY.
//
// This is the private key used to register functions and communicate with the private
// API.
func (h HandlerOpts) GetSigningKey() string {
if h.SigningKey == nil {
return os.Getenv("INNGEST_SIGNING_KEY")
}
return *h.SigningKey
}
// GetSigningKeyFallback returns the signing key fallback defined within
// HandlerOpts, or the default defined within INNGEST_SIGNING_KEY_FALLBACK.
//
// This is the fallback private key used to register functions and communicate
// with the private API. If a request fails auth with the signing key then we'll
// try again with the fallback
func (h HandlerOpts) GetSigningKeyFallback() string {
if h.SigningKeyFallback == nil {
return os.Getenv("INNGEST_SIGNING_KEY_FALLBACK")
}
return *h.SigningKeyFallback
}
// GetAPIOrigin returns the host to use for sending API requests
func (h HandlerOpts) GetAPIBaseURL() string {
if h.isDev() {
return DevServerURL()
}
if h.APIBaseURL == nil {
base := os.Getenv("INNGEST_API_BASE_URL")
if base != "" {
return base
}
return defaultAPIOrigin
}
return *h.APIBaseURL
}
// GetEventAPIOrigin returns the host to use for sending events
func (h HandlerOpts) GetEventAPIBaseURL() string {
if h.isDev() {
return DevServerURL()
}
if h.EventAPIBaseURL == nil {
origin := os.Getenv("INNGEST_EVENT_API_BASE_URL")
if origin != "" {
return origin
}
return defaultEventAPIOrigin
}
return *h.EventAPIBaseURL
}
// GetServeOrigin returns the host used for HTTP based executions
func (h HandlerOpts) GetServeOrigin() string {
if h.ServeOrigin != nil {
return *h.ServeOrigin
}
return ""
}
// GetServePath returns the path used for HTTP based executions
func (h HandlerOpts) GetServePath() string {
if h.ServePath != nil {
return *h.ServePath
}
return ""
}
// GetEnv returns the env defined within HandlerOpts, or the default
// defined within INNGEST_ENV.
//
// This is the environment name used for preview/branch environments within Inngest.
func (h HandlerOpts) GetEnv() string {
if h.Env == nil {
return os.Getenv("INNGEST_ENV")
}
return *h.Env
}
// GetRegisterURL returns the registration URL defined wtihin HandlerOpts,
// defaulting to the production Inngest URL if nil.
func (h HandlerOpts) GetRegisterURL() string {
if h.RegisterURL == nil {
return "https://www.inngest.com/fn/register"
}
return *h.RegisterURL
}
func (h HandlerOpts) IsInBandSyncAllowed() bool {
if h.AllowInBandSync != nil {
return *h.AllowInBandSync
}
// TODO: Default to true once in-band syncing is stable
if isTrue(os.Getenv(envKeyAllowInBandSync)) {
return true
}
return false
}
func (h HandlerOpts) GetWorkerConcurrency() int {
if h.WorkerConcurrency == 0 {
return defaultWorkerConcurrency
}
return h.WorkerConcurrency
}
func (h HandlerOpts) isDev() bool {
if h.Dev != nil {
return *h.Dev
}
return IsDev()
}
// Handler represents a handler which serves the Inngest API via HTTP. This provides
// function registration to Inngest, plus the invocation of registered functions via
// an HTTP POST.
type Handler interface {
http.Handler
// SetAppName updates the handler's app name. This is used to group functions
// and track deploys within the UI.
SetAppName(name string) Handler
// SetOptions sets the handler's options used to register functions.
SetOptions(h HandlerOpts) Handler
// Register registers the given functions with the handler, allowing them to
// be invoked by Inngest.
Register(...ServableFunction)
// Connect establishes an outbound connection to Inngest
Connect(ctx context.Context) error
}
// NewHandler returns a new Handler for serving Inngest functions.
func NewHandler(appName string, opts HandlerOpts) Handler {
if opts.Logger == nil {
opts.Logger = slog.Default()
}
if opts.MaxBodySize == 0 {
opts.MaxBodySize = DefaultMaxBodySize
}
return &handler{
HandlerOpts: opts,
appName: appName,
funcs: []ServableFunction{},
}
}
type handler struct {
HandlerOpts
appName string
funcs []ServableFunction
// lock prevents reading the function maps while serving
l sync.RWMutex
}
func (h *handler) SetOptions(opts HandlerOpts) Handler {
h.HandlerOpts = opts
if opts.MaxBodySize == 0 {
opts.MaxBodySize = DefaultMaxBodySize
}
if opts.Logger == nil {
opts.Logger = slog.Default()
}
return h
}
func (h *handler) SetAppName(name string) Handler {
h.appName = name
return h
}
func (h *handler) Register(funcs ...ServableFunction) {
h.l.Lock()
defer h.l.Unlock()
// Create a map of functions by slug. If we're registering a function
// that already exists, clear it.
slugs := map[string]ServableFunction{}
for _, f := range h.funcs {
slugs[f.Slug()] = f
}
for _, f := range funcs {
slugs[f.Slug()] = f
}
newFuncs := make([]ServableFunction, len(slugs))
i := 0
for _, f := range slugs {
newFuncs[i] = f
i++
}
h.funcs = newFuncs
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.Logger.Debug("received http request", "method", r.Method)
SetBasicResponseHeaders(w)
switch r.Method {
case http.MethodGet:
if err := h.inspect(w, r); err != nil {
_ = publicerr.WriteHTTP(w, err)
}
return
case http.MethodPost:
probe := r.URL.Query().Get("probe")
if probe == "trust" {
err := h.trust(r.Context(), w, r)
if err != nil {
var perr publicerr.Error
if !errors.As(err, &perr) {
perr = publicerr.Error{
Err: err,
Message: err.Error(),
Status: 500,
}
}
if perr.Status == 0 {
perr.Status = http.StatusInternalServerError
}
_ = publicerr.WriteHTTP(w, perr)
}
return
}
if err := h.invoke(w, r); err != nil {
_ = publicerr.WriteHTTP(w, err)
}
return
case http.MethodPut:
if err := h.register(w, r); err != nil {
h.Logger.Error("error registering functions", "error", err.Error())
status := http.StatusInternalServerError
if err, ok := err.(publicerr.Error); ok {
status = err.Status
}
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{
"message": err.Error(),
})
}
return
}
}
// register self-registers the handler's functions with Inngest. This upserts
// all functions and automatically allows all functions to immediately be triggered
// by incoming events or schedules.
func (h *handler) register(w http.ResponseWriter, r *http.Request) error {
var syncKind string
var err error
if r.Header.Get(HeaderKeySyncKind) == SyncKindInBand && h.IsInBandSyncAllowed() {
syncKind = SyncKindInBand
err = h.inBandSync(w, r)
} else {
syncKind = SyncKindOutOfBand
err = h.outOfBandSync(w, r)
}
if err != nil {
h.Logger.Error(
"sync error",
"error", err,
"syncKind", syncKind,
)
}
return err
}
type inBandSynchronizeRequest struct {
URL string `json:"url"`
}
func (i inBandSynchronizeRequest) Validate() error {
if i.URL == "" {
return fmt.Errorf("missing URL")
}
return nil
}
type inBandSynchronizeResponse struct {
AppID string `json:"app_id"`
Env *string `json:"env"`
Framework *string `json:"framework"`
Functions []sdk.SDKFunction `json:"functions"`
Inspection map[string]any `json:"inspection"`
Platform *string `json:"platform"`
SDKAuthor string `json:"sdk_author"`
SDKLanguage string `json:"sdk_language"`
SDKVersion string `json:"sdk_version"`
URL string `json:"url"`
}
func (h *handler) inBandSync(
w http.ResponseWriter,
r *http.Request,
) error {
ctx := r.Context()
defer r.Body.Close()
var sig string
if !h.isDev() {
if sig = r.Header.Get(HeaderKeySignature); sig == "" {
return publicerr.Error{
Err: fmt.Errorf("missing %s header", HeaderKeySignature),
Status: 401,
}
}
}
max := h.HandlerOpts.MaxBodySize
if max == 0 {
max = DefaultMaxBodySize
}
reqByt, err := io.ReadAll(http.MaxBytesReader(w, r.Body, int64(max)))
if err != nil {
return publicerr.Error{
Err: fmt.Errorf("error reading request body"),
Status: 500,
}
}
valid, skey, err := ValidateRequestSignature(
ctx,
sig,
h.GetSigningKey(),
h.GetSigningKeyFallback(),
reqByt,
h.isDev(),
)
if err != nil {
return publicerr.Error{
Err: fmt.Errorf("error validating signature"),
Status: 401,
}
}
if !valid {
return publicerr.Error{
Err: fmt.Errorf("invalid signature"),
Status: 401,
}
}
var reqBody inBandSynchronizeRequest
err = json.Unmarshal(reqByt, &reqBody)
if err != nil {
return publicerr.Error{
Err: fmt.Errorf("malformed input: %w", err),
Status: 400,
}
}
err = reqBody.Validate()
if err != nil {
return publicerr.Error{
Err: fmt.Errorf("malformed input: %w", err),
Status: 400,
}
}
appURL, err := url.Parse(reqBody.URL)
if err != nil {
return publicerr.Error{
Err: fmt.Errorf("malformed input: %w", err),
Status: 400,
}
}
if h.URL != nil {
appURL = h.URL
}
fns, err := createFunctionConfigs(h.appName, h.funcs, *appURL, false)
if err != nil {
return fmt.Errorf("error creating function configs: %w", err)
}
var env *string
if h.GetEnv() != "" {
val := h.GetEnv()
env = &val
}
inspection, err := h.createSecureInspection()
if err != nil {
return fmt.Errorf("error creating inspection: %w", err)
}
inspectionMap, err := types.StructToMap(inspection)
if err != nil {
return fmt.Errorf("error converting inspection to map: %w", err)
}
respBody := inBandSynchronizeResponse{
AppID: h.appName,
Env: env,
Functions: fns,
Inspection: inspectionMap,
SDKAuthor: SDKAuthor,
SDKLanguage: SDKLanguage,
SDKVersion: SDKVersion,
URL: appURL.String(),
}
respByt, err := json.Marshal(respBody)
if err != nil {
return fmt.Errorf("error marshalling response: %w", err)
}
resSig, err := signWithoutJCS(time.Now(), []byte(skey), respByt)
if err != nil {
return fmt.Errorf("error signing response: %w", err)
}
w.Header().Add(HeaderKeySignature, resSig)
w.Header().Add(HeaderKeyContentType, "application/json")
w.Header().Add(HeaderKeySyncKind, SyncKindInBand)
err = json.NewEncoder(w).Encode(respBody)
if err != nil {
return fmt.Errorf("error writing response: %w", err)
}
return nil
}
func (h *handler) outOfBandSync(w http.ResponseWriter, r *http.Request) error {
h.l.Lock()
defer h.l.Unlock()
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
host := r.Host
// Get the sync ID from the URL and then remove it, since we don't want the
// sync ID to show in the function URLs (that would affect the checksum and
// is ugly in the UI)
qp := r.URL.Query()
syncID := qp.Get("deployId")
qp.Del("deployId")
r.URL.RawQuery = qp.Encode()
pathAndParams := r.URL.String()
config := sdk.RegisterRequest{
URL: fmt.Sprintf("%s://%s%s", scheme, host, pathAndParams),
V: "1",
DeployType: sdk.DeployTypePing,
SDK: HeaderValueSDK,
AppName: h.appName,
Headers: sdk.Headers{
Env: h.GetEnv(),
Platform: platform(),
},
Capabilities: capabilities,
}
fns, err := createFunctionConfigs(h.appName, h.funcs, *h.url(r), false)
if err != nil {
return fmt.Errorf("error creating function configs: %w", err)
}
config.Functions = fns
registerURL := fmt.Sprintf("%s/fn/register", defaultAPIOrigin)
if h.isDev() {
// TODO: Check if dev server is up. If not, error. We can't deploy to production.
registerURL = fmt.Sprintf("%s/fn/register", DevServerURL())
}
if h.RegisterURL != nil {
registerURL = *h.RegisterURL
}
createRequest := func() (*http.Request, error) {
byt, err := json.Marshal(config)
if err != nil {
return nil, fmt.Errorf("error marshalling function config: %w", err)
}
req, err := http.NewRequest(http.MethodPost, registerURL, bytes.NewReader(byt))
if err != nil {
return nil, fmt.Errorf("error creating new request: %w", err)
}
if syncID != "" {
qp := req.URL.Query()
qp.Set("deployId", syncID)
req.URL.RawQuery = qp.Encode()
}
// If the request specifies a server kind then include it as an expectation
// in the outgoing request
if r.Header.Get(HeaderKeyServerKind) != "" {
req.Header.Set(
HeaderKeyExpectedServerKind,
r.Header.Get(HeaderKeyServerKind),
)
}
if h.GetEnv() != "" {
req.Header.Add(HeaderKeyEnv, h.GetEnv())
}
SetBasicRequestHeaders(req)
return req, nil
}
resp, err := fetchWithAuthFallback(
createRequest,
h.GetSigningKey(),
h.GetSigningKeyFallback(),
)
if err != nil {
return fmt.Errorf("error performing registration request: %w", err)
}
if resp.StatusCode > 299 {
body := map[string]any{}
byt, _ := io.ReadAll(resp.Body)
if err := json.Unmarshal(byt, &body); err != nil {
return fmt.Errorf("error reading register response: %w\n\n%s", err, byt)
}
return fmt.Errorf("Error registering functions: %s", body["error"])
}
w.Header().Add(HeaderKeySyncKind, SyncKindOutOfBand)
return nil
}
func (h *handler) url(r *http.Request) *url.URL {
if h.URL != nil {
return h.URL
}
// Get the current URL.
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
u, _ := url.Parse(fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI))
return u
}
func createFunctionConfigs(
appName string,
fns []ServableFunction,
appURL url.URL,
isConnect bool,
) ([]sdk.SDKFunction, error) {
if appName == "" {
return nil, fmt.Errorf("missing app name")
}
if !isConnect && appURL == (url.URL{}) {
return nil, fmt.Errorf("missing URL")
}
fnConfigs := make([]sdk.SDKFunction, len(fns))
for i, fn := range fns {
c := fn.Config()
var retries *sdk.StepRetries
if c.Retries != nil {
retries = &sdk.StepRetries{
Attempts: *c.Retries,
}
}
// Modify URL to contain fn ID, step params
values := appURL.Query()
values.Set("fnId", fn.Slug())
values.Set("step", "step")
appURL.RawQuery = values.Encode()
f := sdk.SDKFunction{
Name: fn.Name(),
Slug: appName + "-" + fn.Slug(),
Idempotency: c.Idempotency,
Priority: fn.Config().Priority,
Triggers: inngest.MultipleTriggers{},
RateLimit: fn.Config().GetRateLimit(),
Cancel: fn.Config().Cancel,
Timeouts: fn.Config().GetTimeouts(),
Throttle: (*inngest.Throttle)(fn.Config().Throttle),
Steps: map[string]sdk.SDKStep{
"step": {
ID: "step",
Name: fn.Name(),
Retries: retries,
Runtime: map[string]any{
"url": appURL.String(),
},
},
},
}
if c.Debounce != nil {
f.Debounce = &inngest.Debounce{
Key: &c.Debounce.Key,
Period: c.Debounce.Period.String(),
}
if c.Debounce.Timeout != nil {
str := c.Debounce.Timeout.String()
f.Debounce.Timeout = &str
}
}
if c.BatchEvents != nil {
f.EventBatch = map[string]any{
"maxSize": c.BatchEvents.MaxSize,
"timeout": c.BatchEvents.Timeout,
"key": c.BatchEvents.Key,
}
}
if len(c.Concurrency) > 0 {
// Marshal as an array, as the sdk/handler unmarshals correctly.
f.Concurrency = &inngest.ConcurrencyLimits{Limits: c.Concurrency}
}
triggers := fn.Trigger().Triggers()
for _, trigger := range triggers {
if trigger.EventTrigger != nil {
f.Triggers = append(f.Triggers, inngest.Trigger{
EventTrigger: &inngest.EventTrigger{
Event: trigger.Event,
Expression: trigger.Expression,
},
})
} else {
f.Triggers = append(f.Triggers, inngest.Trigger{
CronTrigger: &inngest.CronTrigger{
Cron: trigger.Cron,
},
})
}
}
fnConfigs[i] = f
}
return fnConfigs, nil
}
// invoke handles incoming POST calls to invoke a function, delegating to invoke() after validating
// the request.
func (h *handler) invoke(w http.ResponseWriter, r *http.Request) error {
var sig string
defer r.Body.Close()
if !h.isDev() {
if sig = r.Header.Get(HeaderKeySignature); sig == "" {
return publicerr.Error{
Message: "unauthorized",
Status: 401,
}
}
}
max := h.HandlerOpts.MaxBodySize
if max == 0 {
max = DefaultMaxBodySize
}
byt, err := io.ReadAll(http.MaxBytesReader(w, r.Body, int64(max)))
if err != nil {
h.Logger.Error("error decoding function request", "error", err)
return publicerr.Error{
Message: "Error reading request",
Status: 500,
}
}
if valid, _, err := ValidateRequestSignature(
r.Context(),
sig,
h.GetSigningKey(),
h.GetSigningKeyFallback(),
byt,
h.isDev(),
); !valid {
h.Logger.Error("unauthorized inngest invoke request", "error", err)
return publicerr.Error{
Message: "unauthorized",
Status: 401,
}
}
fnID := r.URL.Query().Get("fnId")
request := &sdkrequest.Request{}
if err := json.Unmarshal(byt, request); err != nil {
h.Logger.Error("error decoding function request", "error", err)
return publicerr.Error{
Message: "malformed input",
Status: 400,
}
}
if request.UseAPI {
// TODO: implement this
// retrieve data from API
// request.Steps =
// request.Events =
_ = 0 // no-op to avoid linter error
}
h.l.RLock()
var fn ServableFunction
for _, f := range h.funcs {
if f.Slug() == fnID {
fn = f
break
}
}
h.l.RUnlock()
if fn == nil {
// XXX: This is a 500 within the JS SDK. We should probably change
// the JS SDK's status code to 410. 404 indicates that the overall
// API for serving Inngest isn't found.
return publicerr.Error{
Message: fmt.Sprintf("function not found: %s", fnID),
Status: 410,
}
}
l := h.Logger.With("fn", fnID, "call_ctx", request.CallCtx)
l.Debug("calling function")
stream, streamCancel := context.WithCancel(context.Background())
if h.UseStreaming {
w.WriteHeader(201)
go func() {
for {
if stream.Err() != nil {
return
}
_, _ = w.Write([]byte(" "))
<-time.After(5 * time.Second)
}
}()
}
var stepID *string
if rawStepID := r.URL.Query().Get("stepId"); rawStepID != "" && rawStepID != "step" {
stepID = &rawStepID
}
// Invoke the function, then immediately stop the streaming buffer.
resp, ops, err := invoke(r.Context(), fn, request, stepID)
streamCancel()
// NOTE: When triggering step errors, we should have an OpcodeStepError
// within ops alongside an error. We can safely ignore that error, as it's
// only used for checking whether the step used a NoRetryError or RetryAtError
//
// For that reason, we check those values first.
noRetry := sdkerrors.IsNoRetryError(err)
retryAt := sdkerrors.GetRetryAtTime(err)
if len(ops) == 1 && ops[0].Op == enums.OpcodeStepError {
// Now we've handled error types we can ignore step
// errors safely.
err = nil
}
// Now that we've handled the OpcodeStepError, if we *still* ahve
// a StepError kind returned from a function we must have an unhandled
// step error. This is a NonRetryableError, as the most likely code is:
//
// _, err := step.Run(ctx, func() (any, error) { return fmt.Errorf("") })
// if err != nil {
// return err
// }
if sdkerrors.IsStepError(err) {
err = fmt.Errorf("Unhandled step error: %s", err)
noRetry = true
}
if h.UseStreaming {
if err != nil {
// TODO: Add retry-at.
return json.NewEncoder(w).Encode(StreamResponse{
StatusCode: 500,
Body: fmt.Sprintf("error calling function: %s", err.Error()),
NoRetry: noRetry,
RetryAt: retryAt,
})
}
if len(ops) > 0 {
return json.NewEncoder(w).Encode(StreamResponse{
StatusCode: 206,
Body: ops,
})
}
return json.NewEncoder(w).Encode(StreamResponse{
StatusCode: 200,
Body: resp,
})
}
// These may be added even for 2xx codes with step errors.
if noRetry {
w.Header().Add(HeaderKeyNoRetry, "true")
}
if retryAt != nil {
w.Header().Add(HeaderKeyRetryAfter, retryAt.Format(time.RFC3339))
}
if err != nil {
l.Error("error calling function", "error", err)
return publicerr.Error{
Message: fmt.Sprintf("error calling function: %s", err.Error()),
Status: 500,
}
}
if len(ops) > 0 {
// Return the function opcode returned here so that we can re-invoke this
// function and manage state appropriately. Any opcode here takes precedence
// over function return values as the function has not yet finished.
w.WriteHeader(206)
return json.NewEncoder(w).Encode(ops)
}
// Return the function response.
return json.NewEncoder(w).Encode(resp)
}
type insecureInspection struct {
SchemaVersion string `json:"schema_version"`
AuthenticationSucceeded *bool `json:"authentication_succeeded"`
FunctionCount int `json:"function_count"`
HasEventKey bool `json:"has_event_key"`
HasSigningKey bool `json:"has_signing_key"`
HasSigningKeyFallback bool `json:"has_signing_key_fallback"`
Mode string `json:"mode"`
}