-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathresolve.go
More file actions
1611 lines (1382 loc) · 50.6 KB
/
Copy pathresolve.go
File metadata and controls
1611 lines (1382 loc) · 50.6 KB
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
//go:generate mockgen -self_package=github.com/wundergraph/graphql-go-tools/v2/pkg/engine/resolve -destination=resolve_mock_test.go -package=resolve . DataSource
package resolve
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"net/http"
"runtime"
"time"
"github.com/buger/jsonparser"
"github.com/pkg/errors"
"go.uber.org/atomic"
"github.com/wundergraph/go-arena"
"github.com/wundergraph/graphql-go-tools/v2/pkg/internal/xcontext"
"github.com/wundergraph/graphql-go-tools/v2/pkg/pool"
)
const (
DefaultHeartbeatInterval = 5 * time.Second
)
// ConnectionIDs is used to create unique connection IDs for each subscription
// Whenever a new connection is created, use this to generate a new ID
// It is public because it can be used in more high level packages to instantiate a new connection
var ConnectionIDs = atomic.NewInt64(0)
type Reporter interface {
// SubscriptionUpdateSent called when a new subscription update is sent
SubscriptionUpdateSent()
// SubscriptionCountInc increased when a new subscription is added to a trigger, this includes inflight subscriptions
SubscriptionCountInc(count int)
// SubscriptionCountDec decreased when a subscription is removed from a trigger e.g. on shutdown
SubscriptionCountDec(count int)
// TriggerCountInc increased when a new trigger is added e.g. when a trigger is started and initialized
TriggerCountInc(count int)
// TriggerCountDec decreased when a trigger is removed e.g. when a trigger is shutdown
TriggerCountDec(count int)
}
type AsyncErrorWriter interface {
WriteError(ctx *Context, err error, res *GraphQLResponse, w io.Writer)
}
// Resolver is a single threaded event loop that processes all events on a single goroutine.
// It is absolutely critical to ensure that all events are processed quickly to prevent blocking
// and that resolver modifications are done on the event loop goroutine. Long-running operations
// should be offloaded to the subscription worker goroutine. If a different goroutine needs to emit
// an event, it should be done through the events channel to avoid race conditions.
type Resolver struct {
ctx context.Context
options ResolverOptions
maxConcurrency chan struct{}
triggers map[uint64]*trigger
events chan subscriptionEvent
triggerUpdateBuf *bytes.Buffer
allowedErrorExtensionFields map[string]struct{}
allowedErrorFields map[string]struct{}
reporter Reporter
asyncErrorWriter AsyncErrorWriter
propagateSubgraphErrors bool
propagateSubgraphStatusCodes bool
// Subscription heartbeat interval
heartbeatInterval time.Duration
// maxSubscriptionFetchTimeout defines the maximum time a subscription fetch can take before it is considered timed out
maxSubscriptionFetchTimeout time.Duration
// resolveArenaPool is the arena pool dedicated for Loader & Resolvable.
// ArenaPool automatically adjusts arena buffer sizes per workload.
// Resolving & response buffering are very different tasks;
// as such, it was best to have two arena pools in terms of memory usage.
// A single pool for both was much less efficient.
resolveArenaPool *arena.Pool
// responseBufferPool is the arena pool dedicated for response buffering before sending to the client
responseBufferPool *arena.Pool
// subgraphRequestSingleFlight is used to de-duplicate subgraph requests
subgraphRequestSingleFlight *SubgraphRequestSingleFlight
// inboundRequestSingleFlight is used to de-duplicate subgraph requests
inboundRequestSingleFlight *InboundRequestSingleFlight
}
func (r *Resolver) SetAsyncErrorWriter(w AsyncErrorWriter) {
r.asyncErrorWriter = w
}
type tools struct {
resolvable *Resolvable
loader *Loader
}
type SubgraphErrorPropagationMode int
const (
// SubgraphErrorPropagationModeWrapped collects all errors and exposes them as a list of errors on the extensions field "errors" of the gateway error.
SubgraphErrorPropagationModeWrapped SubgraphErrorPropagationMode = iota
// SubgraphErrorPropagationModePassThrough propagates all errors as root errors as they are.
SubgraphErrorPropagationModePassThrough
)
type ResolverOptions struct {
// MaxConcurrency limits the number of concurrent tool calls which is used to resolve operations.
// The limit is only applied to getToolsWithLimit() calls. Intentionally, we don't use this limit for
// subscription updates to prevent blocking the subscription during a network collapse because a one-to-one
// relation is not given as in the case of single http request. We already enforce concurrency limits through
// the MaxSubscriptionWorkers option that is a semaphore to limit the number of concurrent subscription updates.
//
// If set to 0, no limit is applied
// It is advised to set this to a reasonable value to prevent excessive memory usage
// Each concurrent resolve operation allocates ~50kb of memory
// In addition, there's a limit of how many concurrent requests can be efficiently resolved
// This depends on the number of CPU cores available, the complexity of the operations, and the origin services
MaxConcurrency int
Debug bool
Reporter Reporter
AsyncErrorWriter AsyncErrorWriter
// PropagateSubgraphErrors adds Subgraph Errors to the response
PropagateSubgraphErrors bool
// PropagateSubgraphStatusCodes adds the status code of the Subgraph to the extensions field of a Subgraph Error
PropagateSubgraphStatusCodes bool
// SubgraphErrorPropagationMode defines how Subgraph Errors are propagated
// SubgraphErrorPropagationModeWrapped wraps Subgraph Errors in a Subgraph Error to prevent leaking internal information
// SubgraphErrorPropagationModePassThrough passes Subgraph Errors through without modification
SubgraphErrorPropagationMode SubgraphErrorPropagationMode
// RewriteSubgraphErrorPaths rewrites the paths of Subgraph Errors to match the path of the field from the perspective of the client
// This means that nested entity requests will have their paths rewritten from e.g. "_entities.foo.bar" to "person.foo.bar" if the root field above is "person"
RewriteSubgraphErrorPaths bool
// OmitSubgraphErrorLocations omits the locations field of Subgraph Errors
OmitSubgraphErrorLocations bool
// OmitSubgraphErrorExtensions omits the extensions field of Subgraph Errors
OmitSubgraphErrorExtensions bool
// AllowAllErrorExtensionFields allows all fields in the extensions field of a root subgraph error
AllowAllErrorExtensionFields bool
// AllowedErrorExtensionFields defines which fields are allowed in the extensions field of a root subgraph error
AllowedErrorExtensionFields []string
// AttachServiceNameToErrorExtensions attaches the service name to the extensions field of a root subgraph error
AttachServiceNameToErrorExtensions bool
// DefaultErrorExtensionCode is the default error code to use for subgraph errors if no code is provided
DefaultErrorExtensionCode string
// MaxRecyclableParserSize limits the size of the Parser that can be recycled back into the Pool.
// If set to 0, no limit is applied
// This helps keep the Heap size more maintainable if you regularly perform large queries.
MaxRecyclableParserSize int
// ResolvableOptions are configuration options for the Resolvable struct
ResolvableOptions ResolvableOptions
// AllowedCustomSubgraphErrorFields defines which fields are allowed in the subgraph error when in passthrough mode
AllowedSubgraphErrorFields []string
// SubscriptionHeartbeatInterval defines the interval in which a heartbeat is sent to all subscriptions (whether or not this does anything is determined by the subscription response writer)
SubscriptionHeartbeatInterval time.Duration
// MaxSubscriptionFetchTimeout defines the maximum time a subscription fetch can take before it is considered timed out
MaxSubscriptionFetchTimeout time.Duration
// ApolloRouterCompatibilitySubrequestHTTPError is a compatibility flag for Apollo Router, it is used to handle HTTP errors in subrequests differently
ApolloRouterCompatibilitySubrequestHTTPError bool
// PropagateFetchReasons enables adding the "fetch_reasons" extension to
// upstream subgraph requests. This extension explains why each field was requested.
// This flag does not expose the data to clients.
PropagateFetchReasons bool
ValidateRequiredExternalFields bool
// SubgraphRequestDeduplicationShardCount defines the number of shards to use for subgraph request deduplication
SubgraphRequestDeduplicationShardCount int
// InboundRequestDeduplicationShardCount defines the number of shards to use for inbound request deduplication
InboundRequestDeduplicationShardCount int
// SetDeduplicationShardCountToGOMAXPROCS sets SubgraphRequestDeduplicationShardCount and InboundRequestDeduplicationShardCount to runtime.GOMAXPROCS(0)
// and will override any values set for those options
// using runtime.GOMAXPROCS(0) allows the deduplication to scale with the CPU resources available to the process
SetDeduplicationShardCountToGOMAXPROCS bool
}
// New returns a new Resolver. ctx.Done() is used to cancel all active subscriptions and streams.
func New(ctx context.Context, options ResolverOptions) *Resolver {
// options.Debug = true
if options.MaxConcurrency <= 0 {
options.MaxConcurrency = 32
}
if options.SubscriptionHeartbeatInterval <= 0 {
options.SubscriptionHeartbeatInterval = DefaultHeartbeatInterval
}
// We transform the allowed fields into a map for faster lookups
allowedExtensionFields := make(map[string]struct{}, len(options.AllowedErrorExtensionFields))
for _, field := range options.AllowedErrorExtensionFields {
allowedExtensionFields[field] = struct{}{}
}
// always allow "message" and "path"
allowedErrorFields := map[string]struct{}{
"message": {},
"path": {},
}
if options.MaxSubscriptionFetchTimeout == 0 {
options.MaxSubscriptionFetchTimeout = 30 * time.Second
}
if !options.OmitSubgraphErrorExtensions {
allowedErrorFields["extensions"] = struct{}{}
}
if !options.OmitSubgraphErrorLocations {
allowedErrorFields[locationsField] = struct{}{}
}
for _, field := range options.AllowedSubgraphErrorFields {
allowedErrorFields[field] = struct{}{}
}
if options.SubgraphRequestDeduplicationShardCount <= 0 {
options.SubgraphRequestDeduplicationShardCount = 8
}
if options.InboundRequestDeduplicationShardCount <= 0 {
options.InboundRequestDeduplicationShardCount = 8
}
if options.SetDeduplicationShardCountToGOMAXPROCS {
/*
runtime.GOMAXPROCS(0) returns the current value without changing it
This is the effective CPU limit for Go scheduling
Since Go 1.20+, this respects:
- cgroup CPU quotas (Docker, Kubernetes)
- cpuset constraints
Setting shard counts to GOMAXPROCS helps allows us to scale deduplication across available CPU resources
*/
n := runtime.GOMAXPROCS(0)
options.SubgraphRequestDeduplicationShardCount = n
options.InboundRequestDeduplicationShardCount = n
}
resolver := &Resolver{
ctx: ctx,
options: options,
propagateSubgraphErrors: options.PropagateSubgraphErrors,
propagateSubgraphStatusCodes: options.PropagateSubgraphStatusCodes,
events: make(chan subscriptionEvent),
triggers: make(map[uint64]*trigger),
reporter: options.Reporter,
asyncErrorWriter: options.AsyncErrorWriter,
triggerUpdateBuf: bytes.NewBuffer(make([]byte, 0, 1024)),
allowedErrorExtensionFields: allowedExtensionFields,
allowedErrorFields: allowedErrorFields,
heartbeatInterval: options.SubscriptionHeartbeatInterval,
maxSubscriptionFetchTimeout: options.MaxSubscriptionFetchTimeout,
resolveArenaPool: arena.NewArenaPool(),
responseBufferPool: arena.NewArenaPool(),
subgraphRequestSingleFlight: NewSingleFlight(options.SubgraphRequestDeduplicationShardCount),
inboundRequestSingleFlight: NewRequestSingleFlight(options.InboundRequestDeduplicationShardCount),
}
resolver.maxConcurrency = make(chan struct{}, options.MaxConcurrency)
for i := 0; i < options.MaxConcurrency; i++ {
resolver.maxConcurrency <- struct{}{}
}
go resolver.processEvents()
return resolver
}
func newTools(options ResolverOptions, allowedExtensionFields map[string]struct{}, allowedErrorFields map[string]struct{}, sf *SubgraphRequestSingleFlight, a arena.Arena) *tools {
return &tools{
resolvable: NewResolvable(a, options.ResolvableOptions),
loader: &Loader{
propagateSubgraphErrors: options.PropagateSubgraphErrors,
propagateSubgraphStatusCodes: options.PropagateSubgraphStatusCodes,
subgraphErrorPropagationMode: options.SubgraphErrorPropagationMode,
rewriteSubgraphErrorPaths: options.RewriteSubgraphErrorPaths,
omitSubgraphErrorLocations: options.OmitSubgraphErrorLocations,
omitSubgraphErrorExtensions: options.OmitSubgraphErrorExtensions,
allowedErrorExtensionFields: allowedExtensionFields,
attachServiceNameToErrorExtension: options.AttachServiceNameToErrorExtensions,
defaultErrorExtensionCode: options.DefaultErrorExtensionCode,
allowedSubgraphErrorFields: allowedErrorFields,
allowAllErrorExtensionFields: options.AllowAllErrorExtensionFields,
apolloRouterCompatibilitySubrequestHTTPError: options.ApolloRouterCompatibilitySubrequestHTTPError,
propagateFetchReasons: options.PropagateFetchReasons,
validateRequiredExternalFields: options.ValidateRequiredExternalFields,
singleFlight: sf,
jsonArena: a,
},
}
}
type GraphQLResolveInfo struct {
// ResolveAcquireWaitTime is the time spent waiting to acquire the resolver semaphore
// the semaphore limits the number of concurrent resolve operations
ResolveAcquireWaitTime time.Duration
// ResolveDeduplicated indicates whether the resolution of the entire operation was deduplicated via single flight
ResolveDeduplicated bool
}
func (r *Resolver) ResolveGraphQLResponse(ctx *Context, response *GraphQLResponse, data []byte, writer io.Writer) (*GraphQLResolveInfo, error) {
resp := &GraphQLResolveInfo{}
start := time.Now()
<-r.maxConcurrency
resp.ResolveAcquireWaitTime = time.Since(start)
defer func() {
r.maxConcurrency <- struct{}{}
}()
t := newTools(r.options, r.allowedErrorExtensionFields, r.allowedErrorFields, r.subgraphRequestSingleFlight, nil)
err := t.resolvable.Init(ctx, data, response.Info.OperationType)
if err != nil {
return nil, err
}
if !ctx.ExecutionOptions.SkipLoader {
err = t.loader.LoadGraphQLResponseData(ctx, response, t.resolvable)
if err != nil {
return nil, err
}
}
err = t.resolvable.Resolve(ctx.ctx, response.Data, response.Fetches, writer)
if err != nil {
return nil, err
}
ctx.ActualListSizes = t.resolvable.actualListSizes
return resp, err
}
func (r *Resolver) ArenaResolveGraphQLResponse(ctx *Context, response *GraphQLResponse, writer io.Writer) (*GraphQLResolveInfo, error) {
resp := &GraphQLResolveInfo{}
inflight, err := r.inboundRequestSingleFlight.GetOrCreate(ctx, response)
if err != nil {
return nil, err
}
if inflight != nil && inflight.Data != nil { // follower
resp.ResolveDeduplicated = true
// Apply the leader's shared state (e.g. response headers) to this follower's context
// before writing the response, so the response writer can propagate headers correctly.
if ctx.SetDeduplicationData != nil && inflight.SharedData != nil {
ctx.SetDeduplicationData(ctx.ctx, inflight.SharedData)
}
_, err = writer.Write(inflight.Data)
return resp, err
}
start := time.Now()
<-r.maxConcurrency
resp.ResolveAcquireWaitTime = time.Since(start)
defer func() {
r.maxConcurrency <- struct{}{}
}()
resolveArena := r.resolveArenaPool.Acquire(ctx.Request.ID)
// we're intentionally not using defer Release to have more control over the timing (see below)
t := newTools(r.options, r.allowedErrorExtensionFields, r.allowedErrorFields, r.subgraphRequestSingleFlight, resolveArena.Arena)
err = t.resolvable.Init(ctx, nil, response.Info.OperationType)
if err != nil {
r.inboundRequestSingleFlight.FinishErr(inflight, err)
r.resolveArenaPool.Release(resolveArena)
return nil, err
}
if !ctx.ExecutionOptions.SkipLoader {
err = t.loader.LoadGraphQLResponseData(ctx, response, t.resolvable)
if err != nil {
r.inboundRequestSingleFlight.FinishErr(inflight, err)
r.resolveArenaPool.Release(resolveArena)
return nil, err
}
}
// only when loading is done, acquire an arena for the response buffer
responseArena := r.responseBufferPool.Acquire(ctx.Request.ID)
buf := arena.NewArenaBuffer(responseArena.Arena)
err = t.resolvable.Resolve(ctx.ctx, response.Data, response.Fetches, buf)
if err != nil {
r.inboundRequestSingleFlight.FinishErr(inflight, err)
r.resolveArenaPool.Release(resolveArena)
r.responseBufferPool.Release(responseArena)
return nil, err
}
ctx.ActualListSizes = t.resolvable.actualListSizes
// first release resolverArena
// all data is resolved and written into the response arena
r.resolveArenaPool.Release(resolveArena)
// next we write back to the client
// this includes flushing and syscalls
// as such, it can take some time
// which is why we split the arenas and released the first one
_, err = writer.Write(buf.Bytes())
// Extract data from the leader's context to share with singleflight followers.
// This runs after the leader has fully resolved and written its response, so all
// subgraph response headers have been accumulated on the leader's context.
// SharedData MUST be set BEFORE FinishOk, which closes the Done channel and
// unblocks followers. Otherwise followers could read SharedData before it is set.
if inflight != nil && ctx.GetDeduplicationData != nil {
inflight.SharedData = ctx.GetDeduplicationData(ctx.ctx)
}
r.inboundRequestSingleFlight.FinishOk(inflight, buf.Bytes())
// all data is written to the client
// we're safe to release our buffer
r.responseBufferPool.Release(responseArena)
return resp, err
}
type trigger struct {
id uint64
cancel context.CancelFunc
subscriptions map[*Context]*sub
// initialized is set to true when the trigger is started and initialized
initialized bool
updater *subscriptionUpdater
}
func (t *trigger) subscriptionIds() map[*Context]SubscriptionIdentifier {
subs := make(map[*Context]SubscriptionIdentifier, len(t.subscriptions))
for ctx, sub := range t.subscriptions {
subs[ctx] = sub.id
}
return subs
}
// workItem is used to encapsulate a function that needs to be
// executed in the worker goroutine. fn will be executed, and if
// final is true the worker will be stopped after fn is executed.
type workItem struct {
fn func()
final bool
}
type sub struct {
resolve *GraphQLSubscription
resolver *Resolver
ctx *Context
writer SubscriptionResponseWriter
id SubscriptionIdentifier
heartbeat bool
completed chan struct{}
// workChan is used to send work to the writer goroutine. All work is processed sequentially.
workChan chan workItem
}
// startWorker runs in its own goroutine to process fetches and write data to the client synchronously
// it also takes care of sending heartbeats to the client but only if the subscription supports it
// TODO implement a goroutine pool that is sharded by the subscription id to avoid creating a new goroutine for each subscription
func (s *sub) startWorker() {
if s.heartbeat {
s.startWorkerWithHeartbeat()
return
}
s.startWorkerWithoutHeartbeat()
}
// startWorkerWithHeartbeat is similar to startWorker but sends heartbeats to the client when enabled.
// It sends a heartbeat to the client every heartbeatInterval. Heartbeats are handled by the SubscriptionResponseWriter interface.
// TODO: Implement a shared timer implementation to avoid creating a new ticker for each subscription.
func (s *sub) startWorkerWithHeartbeat() {
heartbeatTicker := time.NewTicker(s.resolver.heartbeatInterval)
defer heartbeatTicker.Stop()
for {
select {
case <-s.ctx.ctx.Done():
// Complete when the client request context is done for synchronous subscriptions
s.close(SubscriptionCloseKindGoingAway)
return
case <-s.resolver.ctx.Done():
// Abort immediately if the resolver is shutting down
s.close(SubscriptionCloseKindGoingAway)
return
case <-heartbeatTicker.C:
s.resolver.handleHeartbeat(s)
case work := <-s.workChan:
work.fn()
if work.final {
return
}
// Reset the heartbeat ticker after each write to avoid sending unnecessary heartbeats
heartbeatTicker.Reset(s.resolver.heartbeatInterval)
}
}
}
func (s *sub) startWorkerWithoutHeartbeat() {
for {
select {
case <-s.ctx.ctx.Done():
// Complete when the client request context is done for synchronous subscriptions
s.close(SubscriptionCloseKindGoingAway)
return
case <-s.resolver.ctx.Done():
// Abort immediately if the resolver is shutting down
s.close(SubscriptionCloseKindGoingAway)
return
case work := <-s.workChan:
work.fn()
if work.final {
return
}
}
}
}
// Called when subgraph indicates a "complete" subscription
func (s *sub) complete() {
// The channel is used to communicate that the subscription is done
// It is used only in the synchronous subscription case and to avoid sending events
// to a subscription that is already done.
defer close(s.completed)
s.writer.Complete()
}
// Called when subgraph becomes unreachable or closes the connection without a "complete" event
func (s *sub) close(kind SubscriptionCloseKind) {
// The channel is used to communicate that the subscription is done
// It is used only in the synchronous subscription case and to avoid sending events
// to a subscription that is already done.
defer close(s.completed)
s.writer.Close(kind)
}
func (r *Resolver) executeSubscriptionUpdate(resolveCtx *Context, sub *sub, sharedInput []byte) {
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:update:%d\n", sub.id.SubscriptionID)
}
ctx, cancel := context.WithTimeout(resolveCtx.ctx, r.maxSubscriptionFetchTimeout)
defer cancel()
resolveCtx = resolveCtx.WithContext(ctx)
// Copy the input.
input := make([]byte, len(sharedInput))
copy(input, sharedInput)
resolveArena := r.resolveArenaPool.Acquire(resolveCtx.Request.ID)
t := newTools(r.options, r.allowedErrorExtensionFields, r.allowedErrorFields, r.subgraphRequestSingleFlight, resolveArena.Arena)
if err := t.resolvable.InitSubscription(resolveCtx, input, sub.resolve.Trigger.PostProcessing); err != nil {
r.resolveArenaPool.Release(resolveArena)
r.asyncErrorWriter.WriteError(resolveCtx, err, sub.resolve.Response, sub.writer)
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:init:failed:%d\n", sub.id.SubscriptionID)
}
if r.reporter != nil {
r.reporter.SubscriptionUpdateSent()
}
return
}
if err := t.loader.LoadGraphQLResponseData(resolveCtx, sub.resolve.Response, t.resolvable); err != nil {
r.resolveArenaPool.Release(resolveArena)
r.asyncErrorWriter.WriteError(resolveCtx, err, sub.resolve.Response, sub.writer)
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:load:failed:%d\n", sub.id.SubscriptionID)
}
if r.reporter != nil {
r.reporter.SubscriptionUpdateSent()
}
return
}
if err := t.resolvable.Resolve(resolveCtx.ctx, sub.resolve.Response.Data, sub.resolve.Response.Fetches, sub.writer); err != nil {
r.resolveArenaPool.Release(resolveArena)
r.asyncErrorWriter.WriteError(resolveCtx, err, sub.resolve.Response, sub.writer)
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:resolve:failed:%d\n", sub.id.SubscriptionID)
}
if r.reporter != nil {
r.reporter.SubscriptionUpdateSent()
}
return
}
r.resolveArenaPool.Release(resolveArena)
if err := sub.writer.Flush(); err != nil {
// If flush fails (e.g. client disconnected), remove the subscription.
_ = r.AsyncUnsubscribeSubscription(sub.id)
return
}
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:flushed:%d\n", sub.id.SubscriptionID)
}
if r.reporter != nil {
r.reporter.SubscriptionUpdateSent()
}
if t.resolvable.WroteErrorsWithoutData() && r.options.Debug {
fmt.Printf("resolver:trigger:subscription:completing:errors_without_data:%d\n", sub.id.SubscriptionID)
}
}
// processEvents maintains the single threaded event loop that processes all events
func (r *Resolver) processEvents() {
done := r.ctx.Done()
// events channel can't be closed here because producers are
// sending events across multiple goroutines
for {
select {
case <-done:
r.handleShutdown()
return
case event := <-r.events:
r.handleEvent(event)
}
}
}
// handleEvent is a single threaded function that processes events from the events channel
// All events are processed in the order they are received and need to be processed quickly
// to prevent blocking the event loop and any other events from being processed.
// TODO: consider using a worker pool that distributes events from different triggers to different workers
// to avoid blocking the event loop and improve performance.
func (r *Resolver) handleEvent(event subscriptionEvent) {
switch event.kind {
case subscriptionEventKindAddSubscription:
r.handleAddSubscription(event.triggerID, event.addSubscription)
case subscriptionEventKindRemoveSubscription:
r.handleRemoveSubscription(event.id)
case subscriptionEventKindCompleteSubscription:
r.handleCompleteSubscription(event.id)
case subscriptionEventKindRemoveClient:
r.handleRemoveClient(event.id.ConnectionID)
case subscriptionEventKindUpdateSubscription:
r.handleUpdateSubscription(event.triggerID, event.data, event.id, event.subCtx)
case subscriptionEventKindTriggerUpdate:
r.handleTriggerUpdate(event.triggerID, event.data)
case subscriptionEventKindTriggerComplete:
r.handleTriggerComplete(event.triggerID)
case subscriptionEventKindTriggerInitialized:
r.handleTriggerInitialized(event.triggerID)
case subscriptionEventKindTriggerClose:
r.handleTriggerClose(event)
case subscriptionEventKindUnknown:
panic("unknown event")
}
}
// handleHeartbeat sends a heartbeat to the client. It needs to be executed on the same goroutine as the writer.
func (r *Resolver) handleHeartbeat(sub *sub) {
if r.options.Debug {
fmt.Printf("resolver:heartbeat\n")
}
if r.ctx.Err() != nil {
return
}
if sub.ctx.Context().Err() != nil {
return
}
if r.options.Debug {
fmt.Printf("resolver:heartbeat:subscription:%d\n", sub.id.SubscriptionID)
}
if err := sub.writer.Heartbeat(); err != nil {
// If heartbeat fails (e.g. client disconnected), remove the subscription.
_ = r.AsyncUnsubscribeSubscription(sub.id)
return
}
if r.options.Debug {
fmt.Printf("resolver:heartbeat:subscription:done:%d\n", sub.id.SubscriptionID)
}
if r.reporter != nil {
r.reporter.SubscriptionUpdateSent()
}
}
func (r *Resolver) handleTriggerClose(s subscriptionEvent) {
if r.options.Debug {
fmt.Printf("resolver:trigger:shutdown:%d:%d\n", s.triggerID, s.id.SubscriptionID)
}
r.closeTrigger(s.triggerID, s.closeKind)
}
func (r *Resolver) handleTriggerInitialized(triggerID uint64) {
trig, ok := r.triggers[triggerID]
if !ok {
return
}
trig.initialized = true
if r.reporter != nil {
r.reporter.TriggerCountInc(1)
}
}
func (r *Resolver) handleTriggerComplete(triggerID uint64) {
if r.options.Debug {
fmt.Printf("resolver:trigger:complete:%d\n", triggerID)
}
r.completeTrigger(triggerID)
}
type StartupHookContext struct {
Context context.Context
Updater func(data []byte)
}
func (r *Resolver) executeStartupHooks(add *addSubscription, updater *subscriptionUpdater) error {
hook, ok := add.resolve.Trigger.Source.(HookableSubscriptionDataSource)
if ok {
hookCtx := StartupHookContext{
Context: add.ctx.Context(),
Updater: func(data []byte) {
// Writing on the updater channel is safe but has to happen outside of the event loop
// to respect order and not block the event loop
updater.UpdateSubscription(add.ctx, add.id, data)
},
}
err := hook.SubscriptionOnStart(hookCtx, add.input)
if err != nil {
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:startup:failed:%d\n", add.id.SubscriptionID)
}
r.asyncErrorWriter.WriteError(add.ctx, err, add.resolve.Response, add.writer)
_ = r.AsyncUnsubscribeSubscription(add.id)
return err
}
}
return nil
}
func (r *Resolver) handleAddSubscription(triggerID uint64, add *addSubscription) {
var (
err error
)
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:add:%d:%d\n", triggerID, add.id.SubscriptionID)
}
s := &sub{
ctx: add.ctx,
resolve: add.resolve,
writer: add.writer,
id: add.id,
completed: add.completed,
workChan: make(chan workItem, 32),
resolver: r,
}
if add.ctx.ExecutionOptions.SendHeartbeat {
s.heartbeat = true
}
// Start the dedicated worker goroutine where the subscription updates are processed
// and writes are written to the client in a single threaded manner
go s.startWorker()
trig, ok := r.triggers[triggerID]
if ok {
if r.reporter != nil {
r.reporter.SubscriptionCountInc(1)
}
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:added:%d:%d\n", triggerID, add.id.SubscriptionID)
}
// Execute the startup hooks in a separate goroutine to avoid blocking the event loop
s.workChan <- workItem{
fn: func() {
_ = r.executeStartupHooks(add, trig.updater)
// if the startup hooks return an error, we don't have to do anything else
},
final: false,
}
// After the startup hooks are executed, we can add the subscription to the subscriptions registry
// so that it can start receive events
trig.subscriptions[add.ctx] = s
return
}
if r.options.Debug {
fmt.Printf("resolver:create:trigger:%d\n", triggerID)
}
ctx, cancel := context.WithCancel(xcontext.Detach(add.ctx.Context()))
updater := &subscriptionUpdater{
debug: r.options.Debug,
triggerID: triggerID,
ch: r.events,
ctx: ctx,
}
cloneCtx := add.ctx.clone(ctx)
trig = &trigger{
id: triggerID,
subscriptions: make(map[*Context]*sub),
cancel: cancel,
updater: updater,
}
r.triggers[triggerID] = trig
trig.subscriptions[add.ctx] = s
updater.subsFn = trig.subscriptionIds
if r.reporter != nil {
r.reporter.SubscriptionCountInc(1)
}
var asyncDataSource AsyncSubscriptionDataSource
if async, ok := add.resolve.Trigger.Source.(AsyncSubscriptionDataSource); ok {
trig.cancel = func() {
cancel()
async.AsyncStop(triggerID)
}
asyncDataSource = async
}
go func() {
if r.options.Debug {
fmt.Printf("resolver:trigger:start:%d\n", triggerID)
}
// This is blocking so the startup hook can decide if a subscription should be started or not by returning an error
err = r.executeStartupHooks(add, trig.updater)
if err != nil {
return
}
if asyncDataSource != nil {
err = asyncDataSource.AsyncStart(cloneCtx, triggerID, add.headers, add.input, trig.updater)
} else {
err = add.resolve.Trigger.Source.Start(cloneCtx, add.headers, add.input, trig.updater)
}
if err != nil {
if r.options.Debug {
fmt.Printf("resolver:trigger:failed:%d\n", triggerID)
}
r.asyncErrorWriter.WriteError(add.ctx, err, add.resolve.Response, add.writer)
_ = r.emitTriggerClose(triggerID)
return
}
_ = r.emitTriggerInitialized(triggerID)
if r.options.Debug {
fmt.Printf("resolver:trigger:started:%d\n", triggerID)
}
}()
}
func (r *Resolver) emitTriggerClose(triggerID uint64) error {
if r.options.Debug {
fmt.Printf("resolver:trigger:shutdown:%d\n", triggerID)
}
select {
case <-r.ctx.Done():
return r.ctx.Err()
case r.events <- subscriptionEvent{
triggerID: triggerID,
kind: subscriptionEventKindTriggerClose,
closeKind: SubscriptionCloseKindNormal,
}:
}
return nil
}
func (r *Resolver) emitTriggerInitialized(triggerID uint64) error {
if r.options.Debug {
fmt.Printf("resolver:trigger:initialized:%d\n", triggerID)
}
select {
case <-r.ctx.Done():
return r.ctx.Err()
case r.events <- subscriptionEvent{
triggerID: triggerID,
kind: subscriptionEventKindTriggerInitialized,
}:
}
return nil
}
func (r *Resolver) handleCompleteSubscription(id SubscriptionIdentifier) {
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:remove:%d:%d\n", id.ConnectionID, id.SubscriptionID)
}
removed := 0
for u := range r.triggers {
trig := r.triggers[u]
removed += r.completeTriggerSubscriptions(u, func(sID SubscriptionIdentifier) bool {
return sID == id
})
if len(trig.subscriptions) == 0 {
r.completeTrigger(trig.id)
}
}
if r.reporter != nil {
r.reporter.SubscriptionCountDec(removed)
}
}
func (r *Resolver) handleRemoveSubscription(id SubscriptionIdentifier) {
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:remove:%d:%d\n", id.ConnectionID, id.SubscriptionID)
}
removed := 0
for u := range r.triggers {
trig := r.triggers[u]
removed += r.closeTriggerSubscriptions(u, SubscriptionCloseKindNormal, func(sID SubscriptionIdentifier) bool {
return sID == id
})
if len(trig.subscriptions) == 0 {
r.closeTrigger(trig.id, SubscriptionCloseKindNormal)
}
}
if r.reporter != nil {
r.reporter.SubscriptionCountDec(removed)
}
}
func (r *Resolver) handleRemoveClient(id int64) {
if r.options.Debug {
fmt.Printf("resolver:trigger:subscription:remove:client:%d\n", id)
}
removed := 0
for u := range r.triggers {
removed += r.closeTriggerSubscriptions(u, SubscriptionCloseKindNormal, func(sID SubscriptionIdentifier) bool {
return sID.ConnectionID == id
})
if len(r.triggers[u].subscriptions) == 0 {
r.closeTrigger(r.triggers[u].id, SubscriptionCloseKindNormal)
}
}
if r.reporter != nil {
r.reporter.SubscriptionCountDec(removed)
}
}
func (r *Resolver) handleTriggerUpdate(id uint64, data []byte) {
trig, ok := r.triggers[id]
if !ok {
return
}
if r.options.Debug {
fmt.Printf("resolver:trigger:update:%d\n", id)
}
for c, s := range trig.subscriptions {
r.sendUpdateToSubscription(data, c, s)
}
}
func (r *Resolver) handleUpdateSubscription(id uint64, data []byte, subIdentifier SubscriptionIdentifier, subCtx *Context) {
trig, ok := r.triggers[id]
if !ok {
return