-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathloader.go
More file actions
2336 lines (2116 loc) · 76.1 KB
/
loader.go
File metadata and controls
2336 lines (2116 loc) · 76.1 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
package resolve
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/http/httptrace"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/buger/jsonparser"
"github.com/cespare/xxhash/v2"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"golang.org/x/sync/errgroup"
"github.com/wundergraph/astjson"
"github.com/wundergraph/go-arena"
"github.com/wundergraph/graphql-go-tools/v2/pkg/ast"
"github.com/wundergraph/graphql-go-tools/v2/pkg/engine/datasource/httpclient"
"github.com/wundergraph/graphql-go-tools/v2/pkg/errorcodes"
"github.com/wundergraph/graphql-go-tools/v2/pkg/internal/unsafebytes"
)
const (
IntrospectionSchemaTypeDataSourceID = "introspection__schema&__type"
IntrospectionTypeFieldsDataSourceID = "introspection__type__fields"
IntrospectionTypeEnumValuesDataSourceID = "introspection__type__enumValues"
)
type LoaderHooks interface {
// OnLoad is called before a fetch is executed.
// The returned context is passed to OnFinished after the fetch completes.
// OnLoad is not called when the fetch is skipped (e.g. null parent data, auth rejection).
OnLoad(ctx context.Context, ds DataSourceInfo) context.Context
// OnFinished is called after a fetch has been executed and the response has been processed and merged.
// It is only called when OnLoad was called, i.e. when the fetch was not skipped.
OnFinished(ctx context.Context, ds DataSourceInfo, info *ResponseInfo)
}
type DataSourceInfo struct {
ID string
Name string
}
type ResponseInfo struct {
StatusCode int
Err error
// Request is the original request that was sent to the subgraph. This should only be used for reading purposes,
// in order to ensure there aren't memory conflicts, and the body will be nil, as it was read already.
Request *http.Request
// ResponseHeaders contains a clone of the headers of the response from the subgraph.
ResponseHeaders http.Header
// This should be private as we do not want user's to access the raw responseBody directly
responseBody []byte
}
func (r *ResponseInfo) GetResponseBody() string {
return string(r.responseBody)
}
func newResponseInfo(res *result, subgraphErrors map[string]error) *ResponseInfo {
responseInfo := &ResponseInfo{
StatusCode: res.statusCode,
Err: subgraphErrors[res.ds.Name],
responseBody: res.out,
}
if res.httpResponseContext != nil {
// We're using the response.Request here, because the body will be nil (since the response was read) and won't
// cause a memory leak.
if res.httpResponseContext.Response != nil {
if res.httpResponseContext.Response.Request != nil {
responseInfo.Request = res.httpResponseContext.Response.Request
}
if res.httpResponseContext.Response.Header != nil {
responseInfo.ResponseHeaders = res.httpResponseContext.Response.Header.Clone()
}
}
if responseInfo.Request == nil {
// In cases where the request errors, the response will be nil, and so we need to get the original request
responseInfo.Request = res.httpResponseContext.Request
}
}
return responseInfo
}
type result struct {
postProcessing PostProcessingConfiguration
// batchStats represents per-unique-batch-item merge targets.
// Outer slice index corresponds to the unique representation index in the request batch,
// and the inner slice contains all target values that should be merged with the response at that index.
//
// Example:
// For 4 original items that deduplicate to 2 unique representations, we might have:
// [
//
// [item0, item2], // merge response[0] into item0 and item2
// [item1, item3], // merge response[1] into item1 and item3
//
// ]
batchStats [][]*astjson.Value
fetchSkipped bool
nestedMergeItems []*result
statusCode int
err error
ds DataSourceInfo
authorizationRejected bool
authorizationRejectedReasons []string
rateLimitRejected bool
rateLimitRejectedReason string
// loaderHookContext is set by OnLoad during fetch execution.
// It is nil when the fetch was skipped (e.g. null parent data, auth rejection),
// in which case OnFinished must not be called.
loaderHookContext context.Context
httpResponseContext *httpclient.ResponseContext
// out is the subgraph response body
out []byte
singleFlightStats *singleFlightStats
tools *batchEntityTools
fetchInfo *FetchInfo // Stored for updateL2Cache debug context enrichment
cache LoaderCache
cacheMustBeUpdated bool
l1CacheKeys []*CacheKey // L1 cache keys (no prefix, used for merging)
l2CacheKeys []*CacheKey // L2 cache keys (with subgraph header prefix)
cacheSkipFetch bool
cacheConfig FetchCacheConfiguration
providesData *Object // ProvidesData for alias normalization in L2 cache storage
// Partial cache loading fields
partialCacheEnabled bool // Whether partial loading is enabled for this fetch
cachedItemIndices []int // Indices of items fully served from cache
fetchItemIndices []int // Indices of items that need to be fetched
// l2AnalyticsEvents accumulates L2 cache key events per-result for goroutine safety.
// Merged into the collector on the main thread after goroutines complete.
l2AnalyticsEvents []CacheKeyEvent
// l2EntitySources accumulates entity source records in goroutines, merged on main thread.
l2EntitySources []entitySourceRecord
// l2FetchTimings accumulates fetch timing events in goroutines, merged on main thread.
l2FetchTimings []FetchTimingEvent
// l2ErrorEvents accumulates error events in goroutines, merged on main thread.
l2ErrorEvents []SubgraphErrorEvent
// analyticsEntityType caches the entity type name for analytics recording.
// Set during prepareCacheKeys, used by L2 write recording.
analyticsEntityType string
// shadowCachedValues stores cached L2 values when shadow mode is active.
// After fresh data arrives, these are compared to detect staleness.
// Key is the index into l1CacheKeys (entity fetches) or l2CacheKeys (root fetches).
shadowCachedValues map[int]shadowCacheEntry
}
// shadowCacheEntry holds a cached value saved during shadow mode L2 lookup.
type shadowCacheEntry struct {
cachedValue *astjson.Value // saved from L2 cache hit
cacheKey string // for correlation
remainingTTL time.Duration // remaining TTL from L2 CacheEntry (0 = unknown)
}
func (r *result) init(postProcessing PostProcessingConfiguration, info *FetchInfo) {
r.postProcessing = postProcessing
if info != nil {
r.ds = DataSourceInfo{
ID: info.DataSourceID,
Name: info.DataSourceName,
}
r.fetchInfo = info
}
}
func (l *Loader) createOrInitResult(res *result, postProcessing PostProcessingConfiguration, info *FetchInfo) *result {
if res == nil {
res = &result{}
}
res.postProcessing = postProcessing
if info != nil {
res.ds = DataSourceInfo{
ID: info.DataSourceID,
Name: info.DataSourceName,
}
res.fetchInfo = info
}
return res
}
func IsIntrospectionDataSource(dataSourceID string) bool {
return dataSourceID == IntrospectionSchemaTypeDataSourceID || dataSourceID == IntrospectionTypeFieldsDataSourceID || dataSourceID == IntrospectionTypeEnumValuesDataSourceID
}
type Loader struct {
resolvable *Resolvable
ctx *Context
info *GraphQLResponseInfo
caches map[string]LoaderCache
propagateSubgraphErrors bool
propagateSubgraphStatusCodes bool
subgraphErrorPropagationMode SubgraphErrorPropagationMode
rewriteSubgraphErrorPaths bool
omitSubgraphErrorLocations bool
omitSubgraphErrorExtensions bool
attachServiceNameToErrorExtension bool
allowAllErrorExtensionFields bool
allowedErrorExtensionFields map[string]struct{}
defaultErrorExtensionCode string
allowedSubgraphErrorFields map[string]struct{}
apolloRouterCompatibilitySubrequestHTTPError bool
propagateFetchReasons bool
validateRequiredExternalFields bool
taintedObjs taintedObjects
// jsonArena is the arena for JSON allocation, supplied by the Resolver.
// Not thread safe — only use from the main goroutine.
// Don't Reset or Release; the Resolver handles this.
//
// IMPORTANT: All astjson *Value nodes returned by ParseWithArena,
// ParseBytesWithArena, StringValue, etc. live on this arena.
// Never store heap-allocated *Value into an arena-owned container —
// the GC cannot trace pointers inside arena (noscan) memory, so
// a heap *Value could be collected while still referenced.
jsonArena arena.Arena
// singleFlight is the SubgraphRequestSingleFlight object shared across all client requests.
// It's thread safe and can be used to de-duplicate subgraph requests.
singleFlight *SubgraphRequestSingleFlight
// l1Cache is the per-request entity cache (L1).
// Key: cache key string (WITHOUT subgraph header prefix)
// Value: *astjson.Value pointer to entity in jsonArena
// Thread-safe via sync.Map for parallel fetch support.
// Only used for entity fetches, NOT root fetches (root fields have no prior entity data).
l1Cache sync.Map
}
func (l *Loader) Free() {
l.info = nil
l.ctx = nil
l.resolvable = nil
l.taintedObjs = nil
}
func (l *Loader) LoadGraphQLResponseData(ctx *Context, response *GraphQLResponse, resolvable *Resolvable) (err error) {
l.resolvable = resolvable
l.ctx = ctx
l.info = response.Info
l.taintedObjs = make(taintedObjects)
ctx.initCacheAnalytics()
return l.resolveFetchNode(response.Fetches)
}
func (l *Loader) resolveFetchNode(node *FetchTreeNode) error {
if node == nil {
return nil
}
switch node.Kind {
case FetchTreeNodeKindSingle:
return l.resolveSingle(node.Item)
case FetchTreeNodeKindSequence:
return l.resolveSerial(node.ChildNodes)
case FetchTreeNodeKindParallel:
return l.resolveParallel(node.ChildNodes)
default:
return nil
}
}
func (l *Loader) resolveParallel(nodes []*FetchTreeNode) error {
if len(nodes) == 0 {
return nil
}
results := make([]*result, len(nodes))
defer func() {
for i := range results {
// no-op if tools == nil
batchEntityToolPool.Put(results[i].tools)
}
}()
itemsItems := make([][]*astjson.Value, len(nodes))
// Phase 1: Prepare cache keys + L1 check on MAIN thread for ALL nodes
// L1 stats use non-atomic operations, so they MUST be on the main thread
for i := range nodes {
results[i] = &result{}
itemsItems[i] = l.selectItemsForPath(nodes[i].Item.FetchPath)
f := nodes[i].Item.Fetch
info := getFetchInfo(f)
cfg := getFetchCaching(f)
// Set partial loading flag BEFORE cache lookup so tracking arrays are populated
// Shadow mode forces partial loading off - all items always fetched
if cfg.ShadowMode {
results[i].partialCacheEnabled = false
} else {
results[i].partialCacheEnabled = cfg.EnablePartialCacheLoad
}
// Prepare cache keys for L1 and L2
isEntityFetch, err := l.prepareCacheKeys(info, cfg, itemsItems[i], results[i])
if err != nil {
return errors.WithStack(err)
}
// L1 Check (main thread only - not thread-safe)
// UseL1Cache flag is set by postprocessor to optimize L1 usage
if isEntityFetch && l.ctx.ExecutionOptions.Caching.EnableL1Cache && cfg.UseL1Cache && len(results[i].l1CacheKeys) > 0 {
allComplete := l.tryL1CacheLoad(info, results[i].l1CacheKeys, results[i])
if allComplete {
// All entities found in L1 - mark to skip goroutine
results[i].cacheSkipFetch = true
} else if results[i].partialCacheEnabled && len(results[i].cachedItemIndices) > 0 {
// Partial hit with partial loading enabled - keep FromCache values
// Continue to L2/fetch for remaining items
} else {
// All-or-nothing mode OR no hits - clear FromCache for L2 to try
for _, ck := range results[i].l1CacheKeys {
ck.FromCache = nil
}
results[i].cachedItemIndices = nil
results[i].fetchItemIndices = nil
}
}
}
// Phase 2: Parallel L2 + fetch for nodes that didn't fully hit L1
// L2 stats use atomic operations - thread-safe
g, ctx := errgroup.WithContext(l.ctx.ctx)
for i := range nodes {
f := nodes[i].Item.Fetch
item := nodes[i].Item
items := itemsItems[i]
res := results[i]
// Skip goroutine if L1 was a complete hit
if res.cacheSkipFetch {
continue
}
g.Go(func() error {
return l.loadFetchL2Only(ctx, f, item, items, res)
})
}
err := g.Wait()
if err != nil {
return errors.WithStack(err)
}
// Phase 3: Merge L2 analytics events and entity sources from goroutines (main thread)
if l.ctx.cacheAnalyticsEnabled() {
for i := range results {
if len(results[i].l2AnalyticsEvents) > 0 {
l.ctx.cacheAnalytics.MergeL2Events(results[i].l2AnalyticsEvents)
}
if len(results[i].l2EntitySources) > 0 {
l.ctx.cacheAnalytics.MergeEntitySources(results[i].l2EntitySources)
}
if len(results[i].l2FetchTimings) > 0 {
l.ctx.cacheAnalytics.MergeL2FetchTimings(results[i].l2FetchTimings)
}
if len(results[i].l2ErrorEvents) > 0 {
l.ctx.cacheAnalytics.MergeL2Errors(results[i].l2ErrorEvents)
}
}
}
// Phase 4: Merge results (main thread)
for i := range results {
if results[i].nestedMergeItems != nil {
for j := range results[i].nestedMergeItems {
err = l.mergeResult(nodes[i].Item, results[i].nestedMergeItems[j], itemsItems[i][j:j+1])
l.callOnFinished(results[i].nestedMergeItems[j])
if err != nil {
return errors.WithStack(err)
}
}
} else {
err = l.mergeResult(nodes[i].Item, results[i], itemsItems[i])
l.callOnFinished(results[i])
if err != nil {
return errors.WithStack(err)
}
}
}
return nil
}
func (l *Loader) resolveSerial(nodes []*FetchTreeNode) error {
for i := range nodes {
err := l.resolveFetchNode(nodes[i])
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
func (l *Loader) resolveSingle(item *FetchItem) error {
if item == nil {
return nil
}
items := l.selectItemsForPath(item.FetchPath)
switch f := item.Fetch.(type) {
case *SingleFetch:
res := l.createOrInitResult(nil, f.PostProcessing, f.Info)
skip, err := l.tryCacheLoad(l.ctx.ctx, f.Info, f.Caching, items, res)
if err != nil {
return errors.WithStack(err)
}
if !skip {
err = l.loadSingleFetch(l.ctx.ctx, f, item, items, res)
if err != nil {
return err
}
}
err = l.mergeResult(item, res, items)
l.callOnFinished(res)
return err
case *BatchEntityFetch:
res := l.createOrInitResult(nil, f.PostProcessing, f.Info)
defer batchEntityToolPool.Put(res.tools)
skip, err := l.tryCacheLoad(l.ctx.ctx, f.Info, f.Caching, items, res)
if err != nil {
return errors.WithStack(err)
}
if !skip {
err = l.loadBatchEntityFetch(l.ctx.ctx, item, f, items, res)
if err != nil {
return errors.WithStack(err)
}
}
err = l.mergeResult(item, res, items)
l.callOnFinished(res)
return err
case *EntityFetch:
res := l.createOrInitResult(nil, f.PostProcessing, f.Info)
skip, err := l.tryCacheLoad(l.ctx.ctx, f.Info, f.Caching, items, res)
if err != nil {
return errors.WithStack(err)
}
if !skip {
err = l.loadEntityFetch(l.ctx.ctx, item, f, items, res)
if err != nil {
return errors.WithStack(err)
}
}
err = l.mergeResult(item, res, items)
l.callOnFinished(res)
return err
default:
return nil
}
}
func (l *Loader) callOnFinished(res *result) {
if l.ctx.LoaderHooks != nil && res.loaderHookContext != nil {
l.ctx.LoaderHooks.OnFinished(res.loaderHookContext, res.ds, newResponseInfo(res, l.ctx.subgraphErrors))
}
}
func (l *Loader) selectItemsForPath(path []FetchItemPathElement) []*astjson.Value {
// Use arena allocation for the initial items slice
items := arena.AllocateSlice[*astjson.Value](l.jsonArena, 1, 1)
items[0] = l.resolvable.data
if len(path) == 0 {
return l.taintedObjs.filterOutTainted(items)
}
for i := range path {
if len(items) == 0 {
break
}
items = selectItems(l.jsonArena, items, path[i])
}
return l.taintedObjs.filterOutTainted(items)
}
func isItemAllowedByTypename(obj *astjson.Value, typeNames []string) bool {
if len(typeNames) == 0 {
return true
}
if obj == nil || obj.Type() != astjson.TypeObject {
return true
}
__typeName := obj.GetStringBytes("__typename")
if __typeName == nil {
return true
}
__typeNameStr := string(__typeName)
return slices.Contains(typeNames, __typeNameStr)
}
func selectItems(a arena.Arena, items []*astjson.Value, element FetchItemPathElement) []*astjson.Value {
if len(items) == 0 {
return nil
}
if len(element.Path) == 0 {
return items
}
if len(items) == 1 {
if !isItemAllowedByTypename(items[0], element.TypeNames) {
return nil
}
field := items[0].Get(element.Path...)
if field == nil {
return nil
}
if field.Type() == astjson.TypeArray {
return field.GetArray()
}
return []*astjson.Value{field}
}
selected := arena.AllocateSlice[*astjson.Value](a, 0, len(items))
for _, item := range items {
if !isItemAllowedByTypename(item, element.TypeNames) {
continue
}
field := item.Get(element.Path...)
if field == nil {
continue
}
if field.Type() == astjson.TypeArray {
selected = arena.SliceAppend(a, selected, field.GetArray()...)
continue
}
selected = arena.SliceAppend(a, selected, field)
}
return selected
}
func (l *Loader) itemsData(items []*astjson.Value) *astjson.Value {
if len(items) == 0 {
return astjson.NullValue
}
if len(items) == 1 {
return items[0]
}
// previously, we used: l.resolvable.astjsonArena.NewArray()
// however, itemsData can be called concurrently, so this might result in a race
arr := astjson.MustParseBytes([]byte(`[]`))
for i, item := range items {
arr.SetArrayItem(nil, i, item)
}
return arr
}
// loadFetchL2Only loads data assuming L1 cache has already been checked on main thread.
// Used by resolveParallel to avoid L1 access from goroutines (L1 stats are not thread-safe).
// If res.cacheSkipFetch is true, returns immediately (L1 hit).
// Otherwise checks L2 cache (thread-safe) and performs actual fetch if needed.
func (l *Loader) loadFetchL2Only(ctx context.Context, fetch Fetch, fetchItem *FetchItem, items []*astjson.Value, res *result) error {
// If L1 was a complete hit, skip everything
if res.cacheSkipFetch {
return nil
}
info := getFetchInfo(fetch)
// Check L2 cache (thread-safe - uses atomic stats)
if l.ctx.ExecutionOptions.Caching.EnableL2Cache && len(res.l2CacheKeys) > 0 {
skip, err := l.tryL2CacheLoad(ctx, info, res)
if err != nil {
return errors.WithStack(err)
}
if skip {
return nil
}
}
// Perform actual fetch
switch f := fetch.(type) {
case *SingleFetch:
res = l.createOrInitResult(res, f.PostProcessing, f.Info)
return l.loadSingleFetch(ctx, f, fetchItem, items, res)
case *EntityFetch:
res = l.createOrInitResult(res, f.PostProcessing, f.Info)
return l.loadEntityFetch(ctx, fetchItem, f, items, res)
case *BatchEntityFetch:
res = l.createOrInitResult(res, f.PostProcessing, f.Info)
return l.loadBatchEntityFetch(ctx, fetchItem, f, items, res)
}
return nil
}
func (l *Loader) loadFetch(ctx context.Context, fetch Fetch, fetchItem *FetchItem, items []*astjson.Value, res *result) error {
switch f := fetch.(type) {
case *SingleFetch:
return l.loadSingleFetch(ctx, f, fetchItem, items, res)
case *EntityFetch:
return l.loadEntityFetch(ctx, fetchItem, f, items, res)
case *BatchEntityFetch:
return l.loadBatchEntityFetch(ctx, fetchItem, f, items, res)
}
return nil
}
type ErrMergeResult struct {
Subgraph string
Reason error
Path string
}
func (e ErrMergeResult) Error() string {
if errors.Is(e.Reason, astjson.ErrMergeDifferingArrayLengths) {
if e.Path == "" {
return fmt.Sprintf("unable to merge results from subgraph %s: differing array lengths", e.Subgraph)
}
return fmt.Sprintf("unable to merge results from subgraph '%s' at path '%s': differing array lengths", e.Subgraph, e.Path)
}
if errors.Is(e.Reason, astjson.ErrMergeDifferentTypes) {
if e.Path == "" {
return fmt.Sprintf("unable to merge results from subgraph %s: differing types", e.Subgraph)
}
return fmt.Sprintf("unable to merge results from subgraph '%s' at path '%s': differing types", e.Subgraph, e.Path)
}
return fmt.Sprintf("unable to merge results from subgraph %s", e.Subgraph)
}
func (l *Loader) mergeResult(fetchItem *FetchItem, res *result, items []*astjson.Value) error {
if res.err != nil {
return l.renderErrorsFailedToFetch(fetchItem, res, failedToFetchNoReason)
}
if rejected, err := l.evaluateRejected(fetchItem, res, items); err != nil || rejected {
return err
}
if res.cacheSkipFetch {
// Merge cached data into items
for _, key := range res.l1CacheKeys {
// Merge cached data into item
_, _, err := astjson.MergeValues(l.jsonArena, key.Item, key.FromCache)
if err != nil {
return l.renderErrorsFailedToFetch(fetchItem, res, "invalid cache item")
}
}
return nil
}
// Handle partial cache loading: merge cached items first
if res.partialCacheEnabled && len(res.cachedItemIndices) > 0 {
for _, idx := range res.cachedItemIndices {
if idx < len(res.l1CacheKeys) && res.l1CacheKeys[idx] != nil && res.l1CacheKeys[idx].FromCache != nil {
_, _, err := astjson.MergeValues(l.jsonArena, res.l1CacheKeys[idx].Item, res.l1CacheKeys[idx].FromCache)
if err != nil {
return l.renderErrorsFailedToFetch(fetchItem, res, "invalid cache item")
}
}
}
}
if res.fetchSkipped {
return nil
}
if len(res.out) == 0 {
return l.renderErrorsFailedToFetch(fetchItem, res, emptyGraphQLResponse)
}
// astjson.ParseBytesWithArena copies bytes onto the arena internally,
// tying the byte lifecycle to the arena and preventing GC-related segfaults.
response, err := astjson.ParseBytesWithArena(l.jsonArena, res.out)
if err != nil {
// Fall back to status code if parsing fails and non-2XX
if (res.statusCode > 0 && res.statusCode < 200) || res.statusCode >= 300 {
return l.renderErrorsStatusFallback(fetchItem, res, res.statusCode)
}
return l.renderErrorsFailedToFetch(fetchItem, res, invalidGraphQLResponse)
}
var responseData *astjson.Value
if res.postProcessing.SelectResponseDataPath != nil {
responseData = response.Get(res.postProcessing.SelectResponseDataPath...)
} else {
responseData = response
}
hasErrors := false
var taintedIndices []int
// Check if the subgraph response has errors.
if res.postProcessing.SelectResponseErrorsPath != nil {
responseErrors := response.Get(res.postProcessing.SelectResponseErrorsPath...)
if astjson.ValueIsNonNull(responseErrors) {
hasErrors = len(responseErrors.GetArray()) > 0
// If the response has the "errors" key, and its value is empty,
// we don't consider it as an error. Note: it is not compliant with graphql spec.
if hasErrors {
if l.validateRequiredExternalFields && res.postProcessing.SelectResponseDataPath != nil {
taintedIndices = getTaintedIndices(fetchItem.Fetch, responseData, responseErrors)
}
if len(taintedIndices) > 0 {
// Override errors with generic error about missing deps.
err = l.renderErrorsFailedDeps(fetchItem, res)
if err != nil {
return errors.WithStack(err)
}
}
// Look for errors in the response and merge them into the "errors" array.
err = l.mergeErrors(res, fetchItem, responseErrors)
if err != nil {
return errors.WithStack(err)
}
}
}
}
// Check if data needs processing.
if res.postProcessing.SelectResponseDataPath != nil && astjson.ValueIsNull(responseData) {
// When:
// - No errors or data are present
// - Status code is not within the 2XX range
// We can fall back to a status code based error
if !hasErrors && ((res.statusCode > 0 && res.statusCode < 200) || res.statusCode >= 300) {
return l.renderErrorsStatusFallback(fetchItem, res, res.statusCode)
}
// If we didn't get any data nor errors, we return an error because the response is invalid
// Returning an error here also avoids the need to walk over it later.
if !hasErrors && !l.resolvable.options.ApolloCompatibilitySuppressFetchErrors {
return l.renderErrorsFailedToFetch(fetchItem, res, invalidGraphQLResponseShape)
}
// we have no data but only errors
// skip value completion
if hasErrors && l.resolvable.options.ApolloCompatibilityValueCompletionInExtensions {
l.resolvable.skipValueCompletion = true
}
// no data
return nil
}
if len(items) == 0 {
// If the data is set, it must be an object according to GraphQL over HTTP spec
if responseData.Type() != astjson.TypeObject {
return l.renderErrorsFailedToFetch(fetchItem, res, invalidGraphQLResponseShape)
}
l.resolvable.data = responseData
// Only populate caches on success (no errors)
if !hasErrors {
l.populateCachesAfterFetch(fetchItem, res, items, responseData)
}
return nil
}
if len(items) == 1 && res.batchStats == nil {
items[0], _, err = astjson.MergeValuesWithPath(l.jsonArena, items[0], responseData, res.postProcessing.MergePath...)
if err != nil {
return errors.WithStack(ErrMergeResult{
Subgraph: res.ds.Name,
Reason: err,
Path: fetchItem.ResponsePath,
})
}
if slices.Contains(taintedIndices, 0) {
l.taintedObjs.add(items[0])
}
// Update cache key items to point to merged data for L1 and L2 caches
if len(res.l1CacheKeys) > 0 && res.l1CacheKeys[0] != nil {
res.l1CacheKeys[0].Item = items[0]
}
if len(res.l2CacheKeys) > 0 && res.l2CacheKeys[0] != nil {
res.l2CacheKeys[0].Item = items[0]
}
// Only populate caches on success (no errors)
if !hasErrors {
defer func() {
l.populateCachesAfterFetch(fetchItem, res, items, responseData)
}()
}
return nil
}
batch := responseData.GetArray()
if batch == nil {
return l.renderErrorsFailedToFetch(fetchItem, res, invalidGraphQLResponseShape)
}
if res.batchStats != nil {
if len(res.batchStats) != len(batch) {
return l.renderErrorsFailedToFetch(fetchItem, res, fmt.Sprintf(invalidBatchItemCount, len(res.batchStats), len(batch)))
}
// Build a mapping from original item pointers to merged pointers
// This is needed because MergeValuesWithPath may return new objects
originalToMerged := make(map[*astjson.Value]*astjson.Value)
for batchIndex, targets := range res.batchStats {
src := batch[batchIndex]
for targetIdx, target := range targets {
mergedTarget, _, mErr := astjson.MergeValuesWithPath(l.jsonArena, target, src, res.postProcessing.MergePath...)
if mErr != nil {
return errors.WithStack(ErrMergeResult{
Subgraph: res.ds.Name,
Reason: mErr,
Path: fetchItem.ResponsePath,
})
}
// Track the original to merged mapping
originalToMerged[target] = mergedTarget
// Update the target in batchStats with the merged result
res.batchStats[batchIndex][targetIdx] = mergedTarget
if slices.Contains(taintedIndices, batchIndex) {
l.taintedObjs.add(mergedTarget)
}
}
}
// Update cache key items to point to merged data for L1 and L2 caches
for _, ck := range res.l1CacheKeys {
if ck != nil && ck.Item != nil {
if merged, ok := originalToMerged[ck.Item]; ok {
ck.Item = merged
}
}
}
for _, ck := range res.l2CacheKeys {
if ck != nil && ck.Item != nil {
if merged, ok := originalToMerged[ck.Item]; ok {
ck.Item = merged
}
}
}
// Only populate caches on success (no errors)
if !hasErrors {
l.populateCachesAfterFetch(fetchItem, res, items, responseData)
}
return nil
}
if batchCount, itemCount := len(batch), len(items); batchCount != itemCount {
return l.renderErrorsFailedToFetch(fetchItem, res, fmt.Sprintf(invalidBatchItemCount, itemCount, batchCount))
}
for i := range items {
items[i], _, err = astjson.MergeValuesWithPath(l.jsonArena, items[i], batch[i], res.postProcessing.MergePath...)
if err != nil {
return errors.WithStack(ErrMergeResult{
Subgraph: res.ds.Name,
Reason: err,
Path: fetchItem.ResponsePath,
})
}
if slices.Contains(taintedIndices, i) {
l.taintedObjs.add(items[i])
}
// Update cache key items to point to merged data for L1 and L2 caches
if i < len(res.l1CacheKeys) && res.l1CacheKeys[i] != nil {
res.l1CacheKeys[i].Item = items[i]
}
if i < len(res.l2CacheKeys) && res.l2CacheKeys[i] != nil {
res.l2CacheKeys[i].Item = items[i]
}
}
// Only populate caches on success (no errors)
if !hasErrors {
l.populateCachesAfterFetch(fetchItem, res, items, responseData)
}
return nil
}
// populateCachesAfterFetch runs shadow comparison, mutation impact detection,
// and L1/L2 cache population. Called after a successful (error-free) fetch merge.
func (l *Loader) populateCachesAfterFetch(fetchItem *FetchItem, res *result, items []*astjson.Value, responseData *astjson.Value) {
l.compareShadowValues(res, getFetchInfo(fetchItem.Fetch))
l.detectMutationEntityImpact(res, getFetchInfo(fetchItem.Fetch), responseData)
l.populateL1Cache(fetchItem, res, items)
l.updateL2Cache(res)
}
func (l *Loader) evaluateRejected(fetchItem *FetchItem, res *result, items []*astjson.Value) (bool, error) {
if res.authorizationRejected {
err := l.renderAuthorizationRejectedErrors(fetchItem, res)
if err != nil {
return false, err
}
l.setSkipErrors(res, items)
return true, nil
}
if res.rateLimitRejected {
err := l.renderRateLimitRejectedErrors(fetchItem, res)
if err != nil {
return false, err
}
l.setSkipErrors(res, items)
return true, nil
}
return false, nil
}
func (l *Loader) setSkipErrors(res *result, items []*astjson.Value) {
trueValue := astjson.TrueValue(l.jsonArena)
skipErrorsPath := make([]string, len(res.postProcessing.MergePath)+1)
copy(skipErrorsPath, res.postProcessing.MergePath)
skipErrorsPath[len(skipErrorsPath)-1] = "__skipErrors"
for _, item := range items {
astjson.SetValue(l.jsonArena, item, trueValue, skipErrorsPath...)
}
}
var (
errorsInvalidInputHeader = []byte(`{"errors":[{"message":"Failed to render Fetch Input","path":[`)
errorsInvalidInputFooter = []byte(`]}]}`)
)
func (l *Loader) renderErrorsInvalidInput(fetchItem *FetchItem) []byte {
out := bytes.NewBuffer(nil)
elements := fetchItem.ResponsePathElements
if len(elements) > 0 && elements[len(elements)-1] == "@" {
elements = elements[:len(elements)-1]
}
if len(elements) > 0 {
elements = elements[1:]
}
_, _ = out.Write(errorsInvalidInputHeader)
for i := range elements {
if i != 0 {
_, _ = out.Write(comma)
}
_, _ = out.Write(quote)
_, _ = out.WriteString(elements[i])
_, _ = out.Write(quote)
}
_, _ = out.Write(errorsInvalidInputFooter)
return out.Bytes()
}
func (l *Loader) appendSubgraphError(res *result, fetchItem *FetchItem, value *astjson.Value, values []*astjson.Value) error {
// print them into the buffer to be able to parse them
errorsJSON := value.MarshalTo(nil)
graphqlErrors := make([]GraphQLError, 0, len(values))
err := json.Unmarshal(errorsJSON, &graphqlErrors)
if err != nil {
return errors.WithStack(err)
}
subgraphError := NewSubgraphError(res.ds, fetchItem.ResponsePath, failedToFetchNoReason, res.statusCode)
for _, gqlError := range graphqlErrors {
gErr := gqlError
subgraphError.AppendDownstreamError(&gErr)
}
l.ctx.appendSubgraphErrors(res.ds, res.err, subgraphError)
return nil
}
func (l *Loader) mergeErrors(res *result, fetchItem *FetchItem, value *astjson.Value) error {
values := value.GetArray()
// Record subgraph error analytics before processing modifies the values
if l.ctx.cacheAnalyticsEnabled() && len(values) > 0 {
l.recordSubgraphErrorAnalytics(res, values)
}
l.optionallyOmitErrorLocations(values)
if l.rewriteSubgraphErrorPaths {
rewriteErrorPaths(l.jsonArena, fetchItem, values)
}
l.optionallyEnsureExtensionErrorCode(values)
if !l.allowAllErrorExtensionFields {
l.optionallyAllowCustomExtensionProperties(values)
}
if l.subgraphErrorPropagationMode == SubgraphErrorPropagationModePassThrough {
// Attach datasource information to all errors when we don't wrap them
l.optionallyAttachServiceNameToErrorExtension(values, res.ds.Name)
l.setSubgraphStatusCode(values, res.statusCode)
// Allow to delete extensions entirely
l.optionallyOmitErrorExtensions(values)
l.optionallyOmitErrorFields(values)
// If enabled, add the extra http status error for Apollo Router compat
if err := l.addApolloRouterCompatibilityError(res); err != nil {
return err