/
connect.cljc
2142 lines (1865 loc) · 87.3 KB
/
connect.cljc
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
(ns com.wsscode.pathom.connect
(:require
[clojure.core.async :as async :refer [<! >! go]]
[clojure.set :as set]
[clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as gen]
[com.fulcrologic.guardrails.core :refer [>def >defn >fdef => | <- ?]]
[#?(:clj com.wsscode.async.async-clj
:cljs com.wsscode.async.async-cljs)
:as p.async
:refer [let-chan let-chan* go-promise go-catch <? <?maybe <!maybe]]
[com.wsscode.common.combinatorics :as combo]
[com.wsscode.pathom.connect.indexes :as pci]
[com.wsscode.pathom.connect.planner :as pcp]
[com.wsscode.pathom.core :as p]
[com.wsscode.pathom.misc :as p.misc]
[com.wsscode.pathom.parser :as pp]
[com.wsscode.pathom.trace :as pt]
[edn-query-language.core :as eql])
#?(:cljs
[:require-macros com.wsscode.pathom.connect]))
(declare reader3-run-node data->shape)
(defn atom-with [spec]
(s/with-gen p/atom? #(gen/fmap atom (s/gen spec))))
(>def ::sym-set (s/coll-of ::sym :kind set?))
(>def ::batch? boolean?)
(>def ::alias? boolean?)
(>def ::resolve fn?)
(>def ::mutate fn?)
(>def ::resolver (s/keys :opt [::sym ::input ::output ::params ::resolve]))
(>def ::mutation (s/keys :opt [::sym ::input ::output ::params ::mutate]))
(>def ::idents ::attributes-set)
(>def ::input ::attributes-set)
(>def ::out-attribute (s/or :plain ::attribute :composed (s/map-of ::attribute ::output)))
(>def ::output (s/or :attribute-list (s/coll-of ::out-attribute :kind vector? :min-count 1)
:union (s/map-of ::attribute ::output)))
(>def ::params ::output)
(>def ::resolver-data (s/keys :req [::sym] :opt [::input ::output ::cache?]))
(>def ::resolver-weights (atom-with (s/map-of ::sym number?)))
(>def ::index-resolvers (s/map-of ::sym ::resolver-data))
(>def ::mutation-data (s/keys :req [::sym] :opt [::params ::output]))
(>def ::mutations (s/map-of ::sym ::resolver-data))
(>def ::index-io (s/map-of ::attributes-set ::io-map))
(>def ::attribute-paths (s/map-of ::attributes-set (s/coll-of ::sym :kind set?)))
(>def ::index-oir (s/map-of ::attribute ::attribute-paths))
(>def ::indexes (s/keys :opt [::index-resolvers ::index-io ::index-oir ::idents ::index-mutations]))
(>def ::dependency-track (s/coll-of (s/tuple ::sym-set ::attributes-set) :kind set?))
(>def ::resolver-dispatch ifn?)
(>def ::mutate-dispatch ifn?)
(>def ::mutation-join-globals (s/coll-of ::attribute))
(>def ::attr-input-in ::sym-set)
(>def ::attr-output-in ::sym-set)
(>def ::attr-reach-via-simple-key ::input)
(>def ::attr-reach-via-deep-key (s/cat :input ::input :path (s/+ ::attribute)))
(>def ::attr-reach-via-key (s/or :simple ::attr-reach-via-simple-key
:deep ::attr-reach-via-deep-key))
(>def ::attr-reach-via (s/map-of ::attr-reach-via-key ::sym-set))
(>def ::attr-provides-key (s/or :simple ::attribute
:deep (s/coll-of ::attribute :min-count 2 :kind vector?)))
(>def ::attr-provides (s/map-of ::attr-provides-key ::sym-set))
(>def ::attr-combinations (s/coll-of ::attributes-set :kind set?))
(>def ::attribute-info
(s/keys :opt [::attr-input-in
::attr-combinations
::attr-reach-via
::attr-output-in]))
(>def ::attribute-id
(s/or :simple ::attribute
:global #{#{}}
:multi ::attributes-set))
(>def ::index-attributes
(s/map-of ::attribute-id ::attribute-info))
(>def ::index-mutations
(s/map-of ::sym ::mutation-data))
(>def ::map-resolver
(s/merge ::resolver-data (s/keys :req [::output ::resolve])))
(>def ::map-mutation
(s/merge ::mutation-data (s/keys :req [::mutate])))
(>def ::map-operation
(s/or :resolver ::map-resolver :mutation ::map-mutation))
(>def ::register
(s/or :operation ::map-operation
:operations (s/coll-of ::register)))
(>def ::path-coordinate (s/tuple ::attribute ::sym))
(>def ::plan-path (s/coll-of ::path-coordinate))
(>def ::plan (s/or :flat-plan (s/coll-of ::plan-path)
:graph-plan ::pcp/graph))
(>def ::sort-plan (s/fspec :args (s/cat :env ::p/env :plan ::plan-path)))
(>def ::transform fn?)
(>def ::reader3-computed-plans
"A set containing the paths where reader3 was already processed, this allows recursive
calls to the same path (for other readers processing) while avoiding re-doing plan work."
(s/coll-of ::p/path :kind set?))
(def resolver-data pci/resolver-data)
(defn mutation-data
"Get mutation map information in env from the resolver sym."
[env-or-indexes sym]
(let [idx (cond-> env-or-indexes
(contains? env-or-indexes ::indexes)
::indexes)]
(get-in idx [::index-mutations sym])))
(defn- flat-query [query]
(if (map? query)
(apply concat (map flat-query (vals query)))
(->> query p/query->ast :children (mapv :key))))
(def merge-io-attrs pci/merge-io-attrs)
(def normalize-io pci/normalize-io)
(def merge-io pci/merge-io)
(def merge-oir pci/merge-oir)
(defn merge-grow [a b]
(cond
(and (set? a) (set? b))
(set/union a b)
(and (map? a) (map? b))
(merge-with merge-grow a b)
(nil? b) a
:else
b))
(defmulti index-merger
"This is an extensible gateway so you can define different strategies for merging different
kinds of indexes."
(fn [k _ _] k))
(defmethod index-merger ::index-io [_ ia ib]
(merge-io ia ib))
(defmethod index-merger ::index-oir [_ ia ib]
(merge-oir ia ib))
(defmethod index-merger ::index-attributes [_ a b]
(merge-grow a b))
(defmethod index-merger :default [_ a b]
(merge-grow a b))
(defn merge-indexes [ia ib]
(reduce-kv
(fn [idx k v]
(if (contains? idx k)
(update idx k #(index-merger k % v))
(assoc idx k v)))
ia ib))
(defn output-provides* [{:keys [key children]}]
(let [children (if (some-> children first :type (= :union))
(mapcat :children (-> children first :children))
children)]
(cond-> [key]
(seq children)
(into (mapcat (comp
(fn [x]
(mapv #(vec (flatten (vector key %))) x))
#(output-provides* %))) children))))
(defn output-provides [query]
(if (map? query)
(into [] (mapcat output-provides) (vals query))
(into [] (mapcat output-provides*) (:children (eql/query->ast query)))))
(defn normalized-children [{:keys [children]}]
(if (some-> children first :type (= :union))
(mapcat :children (-> children first :children))
children))
(defn index-attributes [{::keys [sym input output]}]
(let [provides (remove #(contains? input %) (output-provides output))
sym-group #{sym}
attr-provides (zipmap provides (repeat sym-group))
input-count (count input)]
(as-> {} <>
; inputs
(reduce
(fn [idx in-attr]
(update idx in-attr merge
{::attribute-id in-attr
::attr-provides attr-provides
::attr-input-in sym-group}))
<>
(case input-count
0 [#{}]
1 input
[input]))
; combinations
(if (> input-count 1)
(reduce
(fn [idx in-attr]
(update idx in-attr merge
{::attribute-id in-attr
::attr-combinations #{input}
::attr-input-in sym-group}))
<>
input)
<>)
; provides
(reduce
(fn [idx out-attr]
(if (vector? out-attr)
(update idx (peek out-attr) (partial merge-with merge-grow)
{::attribute-id (peek out-attr)
::attr-reach-via {(into [input] (pop out-attr)) sym-group}
::attr-output-in sym-group})
(update idx out-attr (partial merge-with merge-grow)
{::attribute-id out-attr
::attr-reach-via {input sym-group}
::attr-output-in sym-group})))
<>
provides)
; leaf / branches
(reduce
(fn [idx {:keys [key children]}]
(cond-> idx
key
(update key (partial merge-with merge-grow)
{(if children ::attr-branch-in ::attr-leaf-in) sym-group})))
<>
(if (map? output)
(mapcat #(tree-seq :children normalized-children (eql/query->ast %)) (vals output))
(tree-seq :children :children (eql/query->ast output)))))))
(defn add
"Low level function to add resolvers to the index. This function adds the resolver
configuration to the index set, adds the resolver to the ::pc/index-resolvers, add
the output to input index in the ::pc/index-oir and the reverse index for auto-complete
to the index ::pc/index-io.
This is a low level function, for adding to your index prefer using `pc/register`."
([indexes sym] (add indexes sym {}))
([indexes sym sym-data]
(let [provides (normalize-io (get sym-data ::output []))
{::keys [input output] :as sym-data} (merge {::sym sym
::input #{}
::provides provides}
sym-data)
input' (if (and (= 1 (count input))
(contains? (get-in indexes [::index-io #{}]) (first input)))
#{}
input)]
(merge-indexes indexes
(cond-> {::index-resolvers {sym sym-data}
::index-attributes (index-attributes sym-data)
::index-io {input' provides}
::index-oir (reduce (fn [indexes out-attr]
(cond-> indexes
(not= #{out-attr} input)
(update-in [out-attr input] p.misc/sconj sym)))
{}
(flat-query output))}
(= 1 (count input'))
(assoc ::idents #{(first input')}))))))
(defn add-mutation
[indexes sym {::keys [params output] :as data}]
(merge-indexes indexes
{::index-mutations {sym (assoc data ::sym sym)}
::index-attributes (as-> {} <>
(reduce
(fn [idx attribute]
(update idx attribute (partial merge-with merge-grow)
{::attribute-id attribute
::attr-mutation-param-in #{sym}}))
<>
(some-> params eql/query->ast p/ast-properties))
(reduce
(fn [idx attribute]
(update idx attribute (partial merge-with merge-grow)
{::attribute-id attribute
::attr-mutation-output-in #{sym}}))
<>
(some-> output eql/query->ast p/ast-properties)))}))
(defn register
"Updates the index by registering the given resolver or mutation (lets call it item),
an item can be:
1. a resolver map
2. a mutation map
3. a sequence with items
The sequence version can have nested sequences, they will be recursively add.
Examples of possible usages:
(-> {} ; blank index
(pc/register one-resolver) ; single resolver
(pc/register one-mutation) ; single mutation
(pc/register [one-resolver one-mutation]) ; sequence of resolvers/mutations
(pc/register [[resolver1 resolver2] [resolver3 mutation]]) ; nested sequences
(pc/register [[resolver1 resolver2] resolver-out [resolver3 mutation]]) ; all mixed
)
"
[indexes item-or-items]
(if (sequential? item-or-items)
(reduce
register
indexes
item-or-items)
(cond
(::resolve item-or-items)
(add indexes (::sym item-or-items) item-or-items)
(::mutate item-or-items)
(add-mutation indexes (::sym item-or-items) item-or-items))))
(defn sort-resolvers [{::p/keys [request-cache]} resolvers e]
(->> resolvers
(sort-by (fn [s]
(if request-cache
(if (contains? @request-cache [s e])
0
1)
1)))))
(defn pick-resolver
"DEPRECATED"
[{::keys [indexes dependency-track]
:as env}]
(let [k (-> env :ast :key)
e (p/entity env)]
(if-let [attr-resolvers (get-in indexes [::index-oir k])]
(let [r (->> attr-resolvers
(map (fn [[attrs sym]]
(let [missing (set/difference attrs (set (keys e)))]
{:sym sym
:attrs attrs
:missing missing})))
(sort-by (comp count :missing)))]
(loop [[{:keys [sym attrs]} & t :as xs] r]
(if xs
(if-not (contains? dependency-track [sym attrs])
(let [e (try
(->> (p/entity (-> env
(assoc ::p/fail-fast? true)
(update ::dependency-track (fnil conj #{}) [sym attrs])) attrs)
(p/elide-items p/break-values))
(catch #?(:clj Throwable :cljs :default) _ {}))
missing (set/difference (set attrs) (set (keys e)))]
(if (seq missing)
(recur t)
(let [e (select-keys e attrs)]
{:e e
:s (first (sort-resolvers env sym e))}))))))))))
(defn async-pick-resolver
"DEPRECATED"
[{::keys [indexes dependency-track] :as env}]
(go-catch
(let [k (-> env :ast :key)
e (p/entity env)]
(if-let [attr-resolvers (get-in indexes [::index-oir k])]
(let [r (->> attr-resolvers
(map (fn [[attrs sym]]
(let [missing (set/difference attrs (set (keys e)))]
{:sym sym
:attrs attrs
:missing missing})))
(sort-by (comp count :missing)))]
(loop [[{:keys [sym attrs]} & t :as xs] r]
(if xs
(if-not (contains? dependency-track [sym attrs])
(let [e (try
(->> (p/entity (-> env
(assoc ::p/fail-fast? true)
(update ::dependency-track (fnil conj #{}) [sym attrs])) attrs)
<?
(p/elide-items p/break-values))
(catch #?(:clj Throwable :cljs :default) _ {}))
missing (set/difference (set attrs) (set (keys e)))]
(if (seq missing)
(recur t)
{:e (select-keys e attrs)
:s (first (sort-resolvers env sym e))}))))))))))
(defn default-resolver-dispatch [_env _entity]
#?(:clj
(let [{{::keys [sym] :as resolver} ::resolver-data :as env} _env]
(if-let [f (resolve sym)]
(f env _entity)
(throw (ex-info "Can't resolve symbol" {:resolver resolver}))))
:cljs
(throw (ex-info "Default resolver-dispatch is not supported on CLJS, please implement ::p.connect/resolver-dispatch in your parser environment." {}))))
(defn resolver-dispatch
"Helper method that extract resolver symbol from env. It's recommended to use as a dispatch method for creating
multi-methods for resolver dispatch."
([env] (get-in env [::resolver-data ::sym]))
([env _]
(get-in env [::resolver-data ::sym])))
(defn resolver-dispatch-embedded
"This dispatch method will fire the resolver by looking at the ::pc/resolve
key in the resolver map details."
[{{::keys [resolve sym]} ::resolver-data :as env} entity]
(assert resolve (str "Can't find resolve fn for " sym))
(resolve env entity))
#?(:clj
(defn create-thread-pool
"Returns a channel that will enqueue and execute messages using a thread pool.
The returned channel here can be used as the ::pc/pool-chan argument to be used
for executing resolvers (and avoid blocking the limited go block threads).
You must provide the channel ch that will be used to listen for commands.
You may provide a thread-count, if you do a fixed size thread will be created
and shared across all calls to the parser. In case you don't provide the
thread-count the threads will be managed by core.async built-in thread pool
for threads (not the same as the go block threads).
"
([ch]
(async/go
(loop []
(when-let [{:keys [f out]} (async/<! ch)]
(async/thread
(try
(if-let [x (com.wsscode.async.async-clj/<!!maybe (f))]
(async/put! out x)
(async/close! out))
(catch Throwable e (async/put! out e))))
(recur))))
ch)
([thread-count ch]
(doseq [_ (range thread-count)]
(async/thread
(loop []
(when-let [{:keys [f out]} (async/<!! ch)]
(try
(if-let [x (com.wsscode.async.async-clj/<!!maybe (f))]
(async/put! out x)
(async/close! out))
(catch Throwable e (async/put! out e)))
(recur)))))
ch)))
(defn step-weight [value new-value]
(* (+ (or value 0) new-value) 0.5))
(defn update-resolver-weight [{::keys [resolver-weights]} resolver & args]
(if resolver-weights
(apply swap! resolver-weights update resolver args)))
(defn call-resolver*
[{::keys [resolver-dispatch resolver-weights]
:or {resolver-dispatch default-resolver-dispatch}
:as env}
entity]
(let [resolver-sym (-> env ::resolver-data ::sym)
tid (pt/trace-enter env {::pt/event ::call-resolver
::pt/label (str resolver-sym)
:key (-> env :ast :key)
::sym resolver-sym
::input-data entity})
start (pt/now)]
(let-chan* [x (try
(p/exec-plugin-actions env ::wrap-resolve resolver-dispatch env entity)
(catch #?(:clj Throwable :cljs :default) e e))]
(if resolver-weights
(swap! resolver-weights update resolver-sym step-weight (- (pt/now) start)))
(pt/trace-leave env tid (cond-> {::pt/event ::call-resolver}
(p.async/error? x) (assoc ::p/error (p/process-error env x))))
(p.async/throw-err x))))
(defn call-resolver [{::keys [pool-chan]
:as env}
entity]
(if (seq (filter #(contains? p/break-values (second %)) entity))
(throw (ex-info "Insufficient resolver input" {:entity entity}))
(if pool-chan
(let [out (async/promise-chan)]
(go
(let [tid (pt/trace-enter env {::pt/event ::schedule-resolver
::pt/label (-> env ::resolver-data ::sym str)
:key (-> env :ast :key)
::sym (-> env ::resolver-data ::sym)
::input-data entity})]
(>! pool-chan {:out out
:f #(do
(pt/trace-leave env tid {::pt/event ::schedule-resolver})
(try
(call-resolver* env entity)
(catch #?(:clj Throwable :cljs :default) e e)))})))
out)
(call-resolver* env entity))))
(defn- entity-select-keys [env entity input]
(let [entity (p/maybe-atom entity)]
(let-chan [e (if (set/subset? input entity)
entity
(p/entity (-> env
(assoc ::p/entity (atom entity))
(dissoc ::pp/waiting ::pp/key-watchers)) (vec input)))]
(select-keys e input))))
(defn all-values-valid? [m input]
(and (every? (fn [[_ v]] (not (p/break-values v))) m)
(every? m input)))
(defn- cache-batch [env resolver-sym linked-results]
(let [params (p/params env)]
(doseq [[input value] linked-results]
(p/cached env [resolver-sym input params] value))))
;; resolve plan
(defn output->provides [output]
(let [ast (p/query->ast output)]
(into #{} (map :key) (:children ast))))
(defn compute-paths* [index-oir keys bad-keys attr pending]
(if (contains? index-oir attr)
(reduce-kv
(fn [paths input resolvers]
(if (or (some bad-keys input)
(contains? input attr)
(and (seq input) (every? pending input)))
paths
(let [new-paths (into #{} (map #(vector [attr %])) resolvers)
missing (set/difference input keys pending)]
(if (seq missing)
(let [missing-paths
(->> missing
(into #{}
(map #(compute-paths*
index-oir
keys
bad-keys
%
(conj pending %))))
(apply combo/cartesian-product)
(mapv #(reduce (fn [acc x] (into acc x)) (first %) (next %))))]
(if (seq missing-paths)
(into paths (->> (combo/cartesian-product new-paths missing-paths)
(mapv #(reduce (fn [acc x] (into acc x)) (first %) (next %)))))
paths))
(into paths new-paths)))))
#{}
(get index-oir attr))
#{}))
(defn compute-paths
"This function will return a set of possible paths given a set of available keys to reach some attribute. You also
send a set of bad keys, bad keys mean information you cannot use (maybe they already got an error, or you known will
not be available)."
[index-oir keys bad-keys attr]
(into #{}
(map (comp #(p.misc/distinct-by second %)
#(p.misc/distinct-by first %)
rseq))
(compute-paths* index-oir keys bad-keys attr #{attr})))
(defn split-good-bad-keys [entity]
(let [{bad-keys true
good-keys false} (group-by #(contains? p/break-values (second %)) entity)
good-keys (into #{} (map first) good-keys)
bad-keys (into #{} (map first) bad-keys)]
[good-keys bad-keys]))
(defn path-cost [{::keys [resolver-weights]
::p/keys [request-cache]
:as env} path]
(let [weights (or (some-> resolver-weights deref) {})]
(transduce (map (fn [sym]
(let [e (select-keys (p/entity env) (-> (resolver-data env sym)
::input))]
(if (and request-cache (contains? @request-cache [sym e]))
1
(get weights sym 1))))) + (distinct path))))
(defn default-sort-plan [env plan]
(sort-by #(path-cost env (map second %)) plan))
(defn resolve-plan [{::keys [indexes sort-plan] :as env}]
(let [key (-> env :ast :key)
sort-plan (or sort-plan default-sort-plan)
[good-keys bad-keys] (split-good-bad-keys (p/entity env))]
(->> (compute-paths (::index-oir indexes) good-keys bad-keys key)
(sort-plan env))))
(defn resolver->output [env resolver-sym]
(let [{::keys [output compute-output]} (get-in env [::indexes ::index-resolvers resolver-sym])]
(cond
compute-output (compute-output env)
output output
:else (throw (ex-info "No output available" {::sym resolver-sym})))))
(defn plan->provides [env plan]
(into #{} (mapcat #(output->provides (resolver->output env (second %)))) plan))
(defn plan->resolvers [plan]
(->> plan
(flatten)
(into #{} (filter symbol?))))
(defn decrease-path-costs [{::keys [resolver-weights resolver-weight-decrease-amount]
:or {resolver-weight-decrease-amount 1}} plan]
(if resolver-weights
(swap! resolver-weights
#(reduce
(fn [rw rsym]
(assoc rw rsym (max 1 (- (get rw rsym 0) resolver-weight-decrease-amount))))
%
(plan->resolvers plan)))))
(defn reader-compute-plan [env failed-resolvers]
(let [plan-trace-id (pt/trace-enter env {::pt/event ::compute-plan})
plan (->> (resolve-plan env)
(remove #(some failed-resolvers (map second %))))]
(if (seq plan)
(let [plan' (first plan)
out (plan->provides env plan')]
(pt/trace-leave env plan-trace-id {::pt/event ::compute-plan ::plan plan ::pp/provides out})
(decrease-path-costs env plan)
[plan' out])
(do
(pt/trace-leave env plan-trace-id {::pt/event ::compute-plan})
nil))))
(defn project-query-attributes
"Returns a set containing all attributes that are expected to participate in path
resolution given a query. This function is intended to help dynamic
resolvers that need to know which attributes are required before doing a call to the
information source. For example, we never want to issue more than one GraphQL query
to the same server at the same query level, but if we just look at the parent query
is not enough; that's because some of the attributes might require other attributes
to be fetched, this function will scan the attributes and figure everything that is
required so you can issue a single request.
Please note the attribute calculation might depend on the data currently available
in the `::p/entity`, if you are calculating attributes for a different context
you might want to replace some of the entity data.
This function is intended to be called during resolver code."
[env query]
(let [children (->> query (p/lift-placeholders env) p/query->ast :children)]
(->> (reduce
(fn [{:keys [provided] :as acc} {:keys [key]}]
(if (contains? provided key)
(update acc :items conj key)
(if-let [plan (first (resolve-plan (assoc-in env [:ast :key] key)))]
(-> acc
(update :items into (or (some->> plan first second (resolver-data env) ::input)))
(update :items into (map first) plan)
(update :provided into (plan->provides env plan)))
(update acc :items conj key))))
{:items #{}
:provided #{}}
children)
:items)))
(defn project-parent-query-attributes
"Project query attributes for the parent query. See"
[{::p/keys [parent-query] :as env}]
(project-query-attributes env parent-query))
;; readers
(defn reader
"DEPRECATED: use reader2 instead
Connect reader, this reader will lookup the given key in the index
to process it, in case the resolver input can't be satisfied it will
do a recursive lookup trying to find the next input.
I recommend you switch to reader2, which instead plans ahead of time
the full path it will need to cover to go from the current data to
the requested attribute."
[{::keys [indexes] :as env
::p/keys [processing-sequence]}]
(let [k (-> env :ast :key)
p (p/params env)]
(if (get-in indexes [::index-oir k])
(if-let [{:keys [e s]} (pick-resolver env)]
(let [{::keys [cache? batch? input] :or {cache? true} :as resolver}
(resolver-data env s)
env (assoc env ::resolver-data resolver)
response (if cache?
(p.async/throw-err
(p/cached env [s e p]
(if (and batch? processing-sequence)
(let [items (->> processing-sequence
(mapv #(entity-select-keys env % input))
(filterv #(all-values-valid? % input))
(distinct))
batch-result (call-resolver env items)
linked-results (zipmap items batch-result)]
(cache-batch env s linked-results)
(get linked-results e))
(call-resolver env e))))
(call-resolver env e))
env' (get response ::env env)
response (dissoc response ::env)]
(if-not (or (nil? response) (map? response))
(throw (ex-info "Response from resolver must be a map." {:sym s :response response})))
(p/swap-entity! env' #(merge response %))
(let [x (get response k)]
(cond
(sequential? x)
(->> (mapv atom x) (p/join-seq env'))
(nil? x)
(if (contains? response k)
nil
::p/continue)
:else
(p/join (atom x) env'))))
::p/continue)
::p/continue)))
(defn serial-resolver-call-batch
[{::p/keys [processing-sequence]
{::keys [sym input]} ::resolver-data
:as env}
e]
(let [trace-data {:key key
::sym sym
::input-data e}]
(pt/tracing env (assoc trace-data ::pt/event ::call-resolver-batch)
(let [_ (pt/trace env (assoc trace-data ::pt/event ::call-resolver-with-cache))
items (->> processing-sequence
(mapv #(entity-select-keys env % input))
(filterv #(all-values-valid? % input))
(distinct))
_ (pt/trace env {::pt/event ::batch-items-ready
::items items})
batch-result (call-resolver env items)
_ (pt/trace env {::pt/event ::batch-result-ready
::items-count (count batch-result)})
linked-results (zipmap items batch-result)]
(cache-batch env sym linked-results)
(get linked-results e)))))
(defn serial-cache-resolver-call
[{::p/keys [processing-sequence]
{::keys [sym batch?]} ::resolver-data
:as env}
e]
(let [p (p/params env)]
(p/cached env [sym e p]
(if (and batch? processing-sequence)
(serial-resolver-call-batch env e)
(call-resolver env e)))))
(defn reader2
"Recommended reader to use with Pathom serial parser.
This reader uses the connect index to compute a EQL property requirement.
The process goes as:
- find possible paths to realize the attribute, given the current available data, generating a plan
- executes the plan
- in case a resolver fails (due to exception, or missing required data) the reader will
try to backtrack and execute another path (if there is one available).
This only handles sync process, if you return a core.async channel, the channel itself
will be the response. If you need to handle async use `async-reader2`."
[{::keys [indexes max-resolver-weight]
::p/keys [processing-sequence]
:or {max-resolver-weight 3600000}
:as env}]
(if-let [[plan out] (reader-compute-plan env #{})]
(let [key (-> env :ast :key)]
(loop [[step & tail] plan
failed-resolvers {}
out-left out]
(if step
(let [[key' resolver-sym] step
{::keys [cache? batch? input] :or {cache? true} :as resolver}
(get-in indexes [::index-resolvers resolver-sym])
output (resolver->output env resolver-sym)
env (assoc env ::resolver-data resolver)
entity (p/entity env)
e (select-keys entity input)
p (p/params env)
trace-data {:key key
::sym resolver-sym
::input-data e}
response (cond
(contains? entity key')
(select-keys entity [key])
cache?
(p.async/throw-err
(p/cached env [resolver-sym e p]
(if (and batch? processing-sequence)
(pt/tracing env (assoc trace-data ::pt/event ::call-resolver-batch)
(let [_ (pt/trace env (assoc trace-data ::pt/event ::call-resolver-with-cache))
items (->> processing-sequence
(mapv #(entity-select-keys env % input))
(filterv #(all-values-valid? % input))
(distinct))
_ (pt/trace env {::pt/event ::batch-items-ready
::items items})
batch-result (call-resolver env items)
_ (pt/trace env {::pt/event ::batch-result-ready
::items-count (count batch-result)})
linked-results (zipmap items batch-result)]
(cache-batch env resolver-sym linked-results)
(get linked-results e)))
(call-resolver env e))))
:else
(call-resolver env e))
response (or response {})
replan (fn [error]
(let [failed-resolvers (assoc failed-resolvers resolver-sym error)]
(update-resolver-weight env resolver-sym #(min (* (or % 1) 2) max-resolver-weight))
(if-let [[plan out'] (reader-compute-plan env failed-resolvers)]
[plan failed-resolvers out'])))]
(cond
(map? response)
(let [env' (get response ::env env)
response (dissoc response ::env)]
(p/swap-entity! env' #(merge response %))
(if (and (contains? response key')
(not (p/break-values (get response key'))))
(let [out-provides (output->provides output)]
(pt/trace env' {::pt/event ::merge-resolver-response
:key key
::sym resolver-sym})
(if (seq tail)
(recur tail failed-resolvers (set/difference out-left out-provides))
(p/map-reader env')))
(if-let [[plan failed-resolvers out'] (replan (ex-info "Insufficient resolver output" {::pp/response-value response :key key'}))]
(recur plan failed-resolvers out')
(do
(if (and (seq tail)
(p/break-values (get response key')))
(throw (ex-info "Insufficient resolver output" {::pp/response-value response :key key'})))
(p/map-reader env')))))
:else
(if-let [[plan failed-resolvers out'] (replan (ex-info "Invalid resolve response" {::pp/response-value response}))]
(recur plan failed-resolvers out')
(do
(pt/trace env {::pt/event ::invalid-resolve-response
:key key
::sym resolver-sym
::pp/response-value response})
(throw (ex-info "Invalid resolve response" {::pp/response-value response})))))))))
::p/continue))
(defn- map-async-serial [f s]
(go-catch
(loop [out []
rest s]
(if-let [item (first rest)]
(recur
(conj out (<?maybe (f item)))
(next rest))
out))))
(defn async-reader
"DEPRECATED: use async-reader2
Like reader, but supports async values on resolver return."
[{::keys [indexes] :as env
::p/keys [processing-sequence]}]
(let [k (-> env :ast :key)
p (p/params env)]
(if (get-in indexes [::index-oir k])
(go-catch
(if-let [{:keys [e s]} (<? (async-pick-resolver env))]
(let [{::keys [cache? batch? input] :or {cache? true} :as resolver}
(resolver-data env s)
env (assoc env ::resolver-data resolver)
response (if cache?
(<?maybe
(p/cached-async env [s e p]
(fn []
(go-catch
(if (and batch? processing-sequence)
(let [items (->> (<? (map-async-serial #(entity-select-keys env % input) processing-sequence))
(filterv #(all-values-valid? % input)))
batch-result (<?maybe (call-resolver env items))
linked-results (zipmap items batch-result)]
(cache-batch env s linked-results)
(get linked-results e))
(<?maybe (call-resolver env e)))))))
(<?maybe (call-resolver env e)))
env' (get response ::env env)
response (dissoc response ::env)]
(if-not (or (nil? response) (map? response))
(throw (ex-info "Response from reader must be a map." {:sym s :response response})))
(p/swap-entity! env' #(merge response %))
(let [x (get response k)]
(cond
(sequential? x)
(->> (mapv atom x) (p/join-seq env') <?maybe)
(nil? x)
(if (contains? response k)
x
::p/continue)
:else
(-> (p/join (atom x) env') <?maybe))))
::p/continue))
::p/continue)))
(defn- async-read-call-batch
[{::p/keys [processing-sequence]
{::keys [sym]} ::resolver-data
:as env}
e trace-data input]
(go-promise
(pt/tracing env (assoc trace-data ::pt/event ::call-resolver-batch)
(let [_ (pt/trace env (assoc trace-data ::pt/event ::call-resolver-with-cache))
items (->> processing-sequence
(map-async-serial #(entity-select-keys env % input)) <?
(filterv #(all-values-valid? % input))
(distinct))
_ (pt/trace env {::pt/event ::batch-items-ready
::items items})
batch-result (<?maybe (call-resolver env items))
_ (pt/trace env {::pt/event ::batch-result-ready
::items-count (count batch-result)})
linked-results (zipmap items batch-result)]
(cache-batch env sym linked-results)
(get linked-results e)))))
(defn- async-read-cache-read
[{::p/keys [processing-sequence]
{::keys [sym batch?]} ::resolver-data
:as env}
e trace-data input]
(let [params (p/params env)]
(p/cached-async env [sym e params]
(fn []
(go-promise
(or
(if (and batch? processing-sequence)
(<?maybe (async-read-call-batch env e trace-data input))
(<?maybe (call-resolver env e)))
{}))))))
(defn async-reader2
"Works in the same way `reader2`, but supports async values (core.async channels)
on resolver return."
[{::keys [indexes max-resolver-weight]
:or {max-resolver-weight 3600000}
:as env}]
(if-let [[plan out] (reader-compute-plan env #{})]
(go-catch
(let [key (-> env :ast :key)]