-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
planner.cljc
1810 lines (1579 loc) · 64.6 KB
/
planner.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.pathom3.connect.planner
(:require
[clojure.set :as set]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[com.fulcrologic.guardrails.core :refer [>def >defn >fdef => | <- ?]]
[com.wsscode.misc.coll :as coll]
[com.wsscode.misc.refs :as refs]
[com.wsscode.pathom3.attribute :as p.attr]
[com.wsscode.pathom3.cache :as p.cache]
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.connect.operation :as pco]
[com.wsscode.pathom3.format.eql :as pf.eql]
[com.wsscode.pathom3.format.shape-descriptor :as pfsd]
[com.wsscode.pathom3.path :as p.path]
[com.wsscode.pathom3.placeholder :as pph]
[edn-query-language.core :as eql])
#?(:cljs
(:require-macros
[com.wsscode.pathom3.connect.planner])))
; region specs
(>def ::node-id
"ID for a execution node in the planner graph."
pos-int?)
(>def ::node-id-set
"A set of node ids."
(s/coll-of ::node-id :kind set?))
(>def ::graph
"The graph container, requires nodes."
(s/keys :req [::nodes]))
(>def ::available-data
"An shape descriptor declaring which data is already available when the planner starts."
(? ::pfsd/shape-descriptor))
(>def ::node-parents
"A set of node-ids containing the direct parents of the current node.
In regular execution nodes, this is the reverse of ::run-next, but in case of
immediate children of branch nodes, this points to the branch node."
::node-id-set)
(>def ::attr-deps-trail
"A set containing attributes already in consideration when computing missing dependencies."
::p.attr/attributes-set)
(>def ::attr-resolvers-trail
"A set containing resolvers already in consideration for the plan, used to track cycles
on nested inputs"
(s/coll-of ::pco/op-name :kind set?))
(>def ::branch-type
"The branch type for a branch node, can be AND or OR"
#{::run-or ::run-and})
(>def ::id-counter
"An atom with a number, used to get the next node-id when creating new nodes."
any?)
(>def ::foreign-ast
"In dynamic resolver nodes, this contains the AST to be sent into the remote"
:edn-query-language.ast/node)
(>def ::node-type
"Type of the nde, can be resolver, AND, OR or unknown."
#{::node-resolver ::node-and ::node-or ::node-unknown})
(>def ::input
"An IO-MAP description of required inputs to run the node."
::pfsd/shape-descriptor)
(>def ::index-attrs
"A index pointing from attribute to the node that provides its value."
(s/map-of ::p.attr/attribute ::node-id-set))
(>def ::index-resolver->nodes
"An index from resolver symbol to a set of execution nodes where its used."
(s/map-of ::pco/op-name ::node-id-set))
(>def ::node-depth
"The node depth on the graph, starts on zero."
nat-int?)
(>def ::node-branch-depth
"How far the branch depth goes from the current node."
nat-int?)
(>def ::node-chain-depth
"The chain depth relative to the current node."
nat-int?)
(defn ignore-nils [m]
(into {} (remove (fn [[_ v]] (nil? v))) m))
(>def ::node
"Node."
(s/and (s/conformer ignore-nils) (s/keys :opt [::node-id ::run-next ::node-parents ::expects ::input])))
(>def ::nodes
"The nodes index."
(s/map-of ::node-id ::node))
(>def ::params
"Params to be used when executing the resolver node"
map?)
(>def ::expects
"An data shape description of what is expected from this execution node to return."
::pfsd/shape-descriptor)
(>def ::root
"A node-id that defines the root in the planner graph."
::node-id)
(>def ::run-and
"Vector containing nodes ids to run in a AND branch."
::node-id-set)
(>def ::run-or
"Vector containing nodes ids to run in a AND branch."
::node-id-set)
(>def ::run-next
"A node-id that points to the next node to run."
::node-id)
(>def ::source-for-attrs
"Set of attributes that are provided by this node."
::p.attr/attributes-set)
(>def ::source-sym
"On dynamic resolvers, this points to the original source resolver in the foreign environment."
::pco/op-name)
(>def ::unreachable-paths
"A shape containing the attributes that can't be reached considering current graph and available data."
::pfsd/shape-descriptor)
(>def ::warn
"Warn message"
string?)
(>def ::warnings
"List of warnings generated during the plan process."
(s/coll-of (s/keys :req [::warn])))
(>def ::conflict-params
"Set of params that were conflicting during merge."
::p.attr/attributes-set)
(>def ::index-ast
"Index to find the AST for a given property."
::pf.eql/prop->ast)
(>def ::mutations
"A vector with the operation name of every mutation that appears in the query."
(s/coll-of ::pco/op-name :kind vector?))
(>def ::nested-process
"Which attributes need further processing due to sub-query requirements."
::p.attr/attributes-set)
(>def ::placeholders
"Placeholder items to nest in."
::p.attr/attributes-set)
(>def ::idents
"Idents collected while scanning query"
(s/coll-of ::eql/ident :kind set?))
(>def ::optimize-graph? boolean?)
(>def ::plan-cache*
"Atom containing the cache atom to support cached planning."
p.cache/cache-store?)
(>def ::snapshots*
"Atom to store each step of the planning process"
refs/atom?)
; endregion
(declare add-snapshot! compute-run-graph compute-run-graph* compute-attribute-graph
optimize-graph optimize-node remove-node-expects-index-attrs find-leaf-node)
; region node helpers
(defn next-node-id
"Return the next node ID in the system, its an incremental number"
[{::keys [id-counter]}]
(swap! id-counter inc))
(defn new-node [env node-data]
(assoc node-data ::node-id (next-node-id env)))
(>defn get-node
([graph node-id]
[(s/keys :req [::nodes]) (? ::node-id)
=> (? ::node)]
(get-in graph [::nodes node-id]))
([graph node-id k]
[(s/keys :req [::nodes]) (? ::node-id) keyword?
=> any?]
(get-in graph [::nodes node-id k])))
(defn node-with-resolver-config
"Get the node plus the resolver config, when the node has an op-name. If node is
not a resolver not it returns nil."
[graph env node-id]
(let [node (get-node graph node-id)
node-name (or (::source-op-name node)
(::pco/op-name node))]
(if-let [config (some->> node-name (pci/resolver-config env))]
(merge node config))))
(defn assoc-node
"Set attribute k about node-id. Only assoc when node exists, otherwise its a noop."
[graph node-id k v]
(if (get-node graph node-id)
(assoc-in graph [::nodes node-id k] v)
graph))
(defn update-node
"Update a given node in a graph, like Clojure native update."
([graph node-id k f]
(if (get-node graph node-id)
(update-in graph (cond-> [::nodes node-id] k (conj k)) f)
graph))
([graph node-id k f v]
(if (get-node graph node-id)
(update-in graph (cond-> [::nodes node-id] k (conj k)) f v)
graph))
([graph node-id k f v v2]
(if (get-node graph node-id)
(update-in graph (cond-> [::nodes node-id] k (conj k)) f v v2)
graph))
([graph node-id k f v v2 v3]
(if (get-node graph node-id)
(update-in graph (cond-> [::nodes node-id] k (conj k)) f v v2 v3)
graph))
([graph node-id k f v v2 v3 & args]
(if (get-node graph node-id)
(apply update-in graph (cond-> [::nodes node-id] k (conj k)) f v v2 v3 args)
graph)))
(defn get-root-node
"Returns the root node of the graph."
[{::keys [root] :as graph}]
(get-node graph root))
(>defn set-root-node
[graph node-id]
[(s/keys :req [::nodes]) (? ::node-id)
=> (s/keys :req [::nodes])]
(if node-id
(assoc graph ::root node-id)
(dissoc graph ::root)))
(>defn node-branches
"Return node branches, which can be the ::run-and or the ::run-or part of the node."
[node]
[(? ::node)
=> (? (s/or :and ::run-and :or ::run-or))]
(or (::run-and node)
(::run-or node)))
(>defn branch-node?
"Returns true when the node is a branch node type."
[node]
[(? ::node) => boolean?]
(boolean (node-branches node)))
(>defn node-kind
"Return a keyword describing the type of the node."
[node]
[(? ::node) => ::node-type]
(cond
(::pco/op-name node)
::node-resolver
(::run-and node)
::node-and
(::run-or node)
::node-or
:else
::node-unknown))
(defn node->label
"Return a string representation for the node, for resolver nodes this is the
symbol, branch nodes get AND / OR respectively."
[node]
(str
(or
(::pco/op-name node)
(if (::run-and node) "AND")
(if (::run-or node) "OR"))))
(defn add-node-parent [graph node-id node-parent-id]
(assert node-parent-id "Tried to add after node with nil value")
(update-node graph node-id ::node-parents coll/sconj node-parent-id))
(defn remove-node-parent [graph node-id node-parent-id]
(let [node (get-node graph node-id)
node-parents' (disj (::node-parents node #{}) node-parent-id)]
(if (seq node-parents')
(assoc-node graph node-id ::node-parents node-parents')
(if node
(update-in graph [::nodes node-id] dissoc ::node-parents)
graph))))
(defn set-node-run-next*
"Update the node-id run-next value, if run-next is nil the attribute
will be removed from the map."
[graph node-id run-next]
(if run-next
(assoc-node graph node-id ::run-next run-next)
(update-in graph [::nodes node-id] dissoc ::run-next)))
(defn set-node-run-next
"Set the node run next value and add the node-parent counter part. Noop if target
and run next are the same node."
([graph run-next] (set-node-run-next graph (::root graph) run-next))
([graph target-node-id run-next]
(let [{target-run-next ::run-next} (get-node graph target-node-id)
graph (if target-run-next
(remove-node-parent graph target-run-next target-node-id)
graph)]
(cond
(not run-next)
(set-node-run-next* graph target-node-id run-next)
(and run-next (not= target-node-id run-next))
(-> graph
(set-node-run-next* target-node-id run-next)
(add-node-parent run-next target-node-id))
:else
graph))))
(defn set-node-expects
"Set node expects, this also removes previous references from index-attrs and add
new ones for the new expects."
[graph node-id expects]
(-> graph
(remove-node-expects-index-attrs node-id)
(assoc-node node-id ::expects expects)
(as-> <>
(reduce
(fn [g attr]
(update-in g [::index-attrs attr] coll/sconj node-id))
<>
(keys expects)))))
(defn set-node-source-for-attrs
([graph env] (set-node-source-for-attrs graph env (::root graph)))
([graph {::p.attr/keys [attribute]} node-id]
(if node-id
(-> graph
(update-in [::index-attrs attribute] coll/sconj node-id))
graph)))
(defn add-branch-to-node
[graph target-node-id branch-type new-branch-node-id]
(-> graph
(add-node-parent new-branch-node-id target-node-id)
(update-node target-node-id branch-type coll/sconj new-branch-node-id)))
(defn add-node-branches [graph target-node-id branch-type node-ids]
(reduce
(fn [g node-id]
(add-branch-to-node g target-node-id branch-type node-id))
graph
node-ids))
(defn remove-branch-node-parents
"When node-id is a branch node, remove all node-parents associated from its children."
[graph node-id]
(let [node (get-node graph node-id)]
(if-let [branches (node-branches node)]
(reduce
(fn [g n-id]
(remove-node-parent g n-id node-id))
graph
branches)
graph)))
(defn remove-from-parent-branches
"Disconnect a branch node from its parents."
[graph {::keys [node-id node-parents]}]
(reduce
(fn [g nid]
(let [n (get-node graph nid)]
(cond
(contains? (::run-and n) node-id)
(-> g
(update-node nid ::run-and disj node-id)
(remove-node-parent node-id nid))
(contains? (::run-or n) node-id)
(-> g
(update-node nid ::run-or disj node-id)
(remove-node-parent node-id nid))
(= (::run-next n) node-id)
(-> g
(set-node-run-next nid nil)
(remove-node-parent node-id nid))
:else
g)))
graph
node-parents))
(defn remove-run-next-edge [graph node-id]
(let [{::keys [run-next]} (get-node graph node-id)]
(if run-next
(-> graph
(remove-node-parent run-next node-id)
(set-node-run-next node-id nil))
graph)))
(defn remove-node-edges
"Remove all node connections. This disconnect the nodes from parents and run-next."
[graph node-id]
(let [node (get-node graph node-id)]
(-> graph
(remove-from-parent-branches node)
(remove-run-next-edge node-id))))
(defn disj-rem [m k item]
(let [new-val (disj (get m k) item)]
(if (seq new-val)
(assoc m k new-val)
(dissoc m k))))
(defn remove-node-expects-index-attrs
"Since the node has attribute indexes associated with it, this removes those links
considering the attributes listed on expects."
[graph node-id]
(let [expects (get-node graph node-id ::expects)]
(reduce
(fn [g attr]
(update g ::index-attrs disj-rem attr node-id))
graph
(keys expects))))
(defn remove-node*
"Remove a node from the graph. Doesn't remove any references, caution!"
[graph node-id]
(let [node (get-node graph node-id)]
(-> graph
(cond->
(::pco/op-name node)
(update-in [::index-resolver->nodes (::pco/op-name node)] disj node-id))
(update ::nodes dissoc node-id))))
(defn remove-node
"Remove a node from the graph. In case of resolver nodes it also removes them
from the ::index-syms, the index-attrs and after node references."
[graph node-id]
(let [{::keys [run-next node-parents] :as node} (get-node graph node-id)]
(assert (if node-parents
(every? #(not= node-id (get-node graph % ::run-next))
node-parents)
true)
(str "Tried to remove node " node-id " that still contains references pointing to it. Move
the run-next references from the pointer nodes before removing it. Also check if
parent is branch and trying to merge."))
(-> graph
(remove-branch-node-parents node-id)
(remove-node-parent run-next node-id)
(remove-from-parent-branches node)
(remove-node-expects-index-attrs node-id)
(remove-node* node-id))))
(defn remove-root-node-cluster
"Remove a complete node cluster, starting from some node root."
[graph node-ids]
(if (seq node-ids)
(let [[node-id & rest] node-ids
{::keys [run-next] :as node} (get-node graph node-id)
branches (or (node-branches node) #{})
next-nodes (cond-> branches run-next (conj run-next))]
(recur (remove-node* graph node-id)
(into rest next-nodes)))
graph))
(defn include-node
"Add new node to the graph, this add the node and the index of in ::index-syms."
[graph {::keys [node-id] ::pco/keys [op-name] :as node}]
(-> graph
(assoc-in [::nodes node-id] node)
(cond->
op-name
(update-in [::index-resolver->nodes op-name] coll/sconj node-id))))
(defn create-and [graph env node-ids]
(if (= 1 (count node-ids))
(get-node graph (first node-ids))
(let [{and-node-id ::node-id
:as and-node} (new-node env {})]
(-> graph
(include-node and-node)
(add-node-branches and-node-id ::run-and node-ids)))))
(defn create-root-and [graph env node-ids]
(if (= 1 (count node-ids))
(set-root-node graph (first node-ids))
(let [{and-node-id ::node-id
:as and-node} (new-node env {})]
(-> graph
(include-node and-node)
(add-node-branches and-node-id ::run-and node-ids)
(set-root-node and-node-id)
(as-> <>
(add-snapshot! <> env
{::snapshot-event ::snapshot-create-and
::snapshot-message "Create root AND"
::highlight-nodes (into #{(::root <>)} node-ids)
::highlight-styles {(::root <>) 1}}))))))
(defn create-root-or
[graph {::p.attr/keys [attribute] :as env} node-ids]
(if (= 1 (count node-ids))
(set-root-node graph (first node-ids))
(let [{or-node-id ::node-id
:as or-node} (new-node env {::expects {attribute {}}})]
(-> graph
(include-node or-node)
(add-node-branches or-node-id ::run-or node-ids)
(set-root-node or-node-id)
(as-> <>
(add-snapshot! <> env
{::snapshot-event ::snapshot-create-or
::snapshot-message "Create root OR"
::highlight-nodes (into #{(::root <>)} node-ids)
::highlight-styles {(::root <>) 1}}))))))
(defn node-attribute-provides
"For a specific attribute, return a vector containing the provides of each node of
that resolver, or the current available data for it."
[graph env attr]
(if-let [available (get-in graph [::available-data attr])]
[available]
(some->>
(get-in graph [::index-attrs attr])
(mapv
#(-> (node-with-resolver-config graph env %)
::pco/provides
(get attr))))))
(defn transfer-node-parent
"Transfer the node parent from source node to target node. This function will also
update the parents references to point to target node."
[graph target-node-id source-node-id node-id]
(-> graph
(remove-node-parent source-node-id node-id)
(add-node-parent target-node-id node-id)
(as-> <>
(cond
(= (get-node graph node-id ::run-next) source-node-id)
(set-node-run-next* <> node-id target-node-id)
(contains? (get-node graph node-id ::run-and) source-node-id)
(-> <>
(add-branch-to-node node-id ::run-and target-node-id)
(update-node node-id ::run-and disj source-node-id))
(contains? (get-node graph node-id ::run-or) source-node-id)
(-> <>
(add-branch-to-node node-id ::run-or target-node-id)
(update-node node-id ::run-or disj source-node-id))
:else
<>))))
(defn transfer-node-parents
"Transfer node parents from source node to target node. In case source node is root,
the root will be transferred to target node."
[graph target-node-id source-node-id]
(let [parents (get-node graph source-node-id ::node-parents)]
(-> graph
; transfer root
(cond->
(= (::root graph) source-node-id)
(set-root-node target-node-id))
(as-> <>
(reduce
(fn [g node-id]
(transfer-node-parent g target-node-id source-node-id node-id))
<>
parents)))))
(defn combine-expects [na nb]
(update na ::expects pfsd/merge-shapes (::expects nb)))
(defn combine-inputs [na nb]
(if (::input nb)
(update na ::input pfsd/merge-shapes (::input nb))
na))
(defn combine-foreign-ast [na nb]
(if (::foreign-ast nb)
(update na ::foreign-ast pf.eql/merge-ast-children (::foreign-ast nb))
na))
(defn transfer-node-indexes [graph target-node-id source-node-id]
(let [attrs (keys (get-node graph source-node-id ::expects))]
(reduce
(fn [graph attr]
(-> graph
(update-in [::index-attrs attr] coll/sconj target-node-id)
(update-in [::index-attrs attr] disj source-node-id)))
graph
attrs)))
(defn combine-run-next
[graph env node-ids pivot]
(let [run-next-nodes (into []
(comp (map #(get-node graph %))
(filter ::run-next))
node-ids)]
(cond
(= 1 (count run-next-nodes))
(let [{::keys [node-id run-next]} (first run-next-nodes)]
(-> graph
(remove-node-parent run-next node-id)
(set-node-run-next pivot run-next)))
(seq run-next-nodes)
(let [and-node (new-node env {::run-and #{}})]
(as-> graph <>
(include-node <> and-node)
(reduce
(fn [g {::keys [node-id run-next]}]
(-> g
(add-branch-to-node (::node-id and-node) ::run-and run-next)
(remove-node-parent run-next node-id)))
<>
run-next-nodes)
(set-node-run-next <> pivot (::node-id and-node))))
:else
graph)))
(defn move-run-next-to-edge
"Find the node at the end of chain from target-node-id and move node-to-move-id
as the next of that"
[graph target-node-id node-to-move-id]
(let [leaf (find-leaf-node graph (get-node graph target-node-id))]
(-> graph
(remove-from-parent-branches (get-node graph node-to-move-id))
(set-node-run-next (::node-id leaf) node-to-move-id))))
(>defn simplify-branch-node
"When a branch node contains a single branch out, remove the AND node and put that
single item in place.
Note in case the branch has a run-next, that run-next gets moved to the end of chain
to retain the same order as it would run with the branch."
[graph env node-id]
[::graph map? ::node-id => ::graph]
(let [node (get-node graph node-id)
target-node-id (or
(and
(= 1 (count (::run-and node)))
(first (::run-and node)))
(and
(= 1 (count (::run-or node)))
(first (::run-or node))))]
(if target-node-id
(-> graph
(add-snapshot! env {::snapshot-message "Simplifying branch with single element"
::highlight-nodes #{node-id target-node-id}
::highlight-styles {node-id 1}})
(cond->
(::run-next node)
(move-run-next-to-edge target-node-id (::run-next node)))
(transfer-node-parents target-node-id node-id)
(remove-node-edges node-id)
(remove-node node-id)
(add-snapshot! env {::snapshot-message "Simplification done"
::highlight-nodes #{target-node-id}})
(optimize-node env target-node-id))
graph)))
(defn merge-sibling-resolver-node
"Merges data from source-node-id into target-node-id, them removes the source node."
[graph target-node-id source-node-id]
(let [source-node (get-node graph source-node-id)]
(-> graph
; merge any extra keys from source node, but without overriding anything
(update-node target-node-id nil coll/merge-defaults source-node)
(update-node target-node-id nil combine-expects source-node)
(update-node target-node-id nil combine-inputs source-node)
(update-node target-node-id nil combine-foreign-ast source-node)
(update-node target-node-id nil dissoc ::source-op-name)
(transfer-node-indexes target-node-id source-node-id)
(remove-node-edges source-node-id)
(remove-node source-node-id))))
(defn merge-sibling-resolver-nodes*
[graph pivot node-ids]
(reduce
(fn [g node-id]
(merge-sibling-resolver-node g pivot node-id))
graph
node-ids))
(defn merge-sibling-resolver-nodes
[graph env parent-node-id node-ids]
(let [[pivot & node-ids'] node-ids
resolver (::pco/op-name (get-node graph pivot))]
(add-snapshot! graph env {::snapshot-message (str "Merging sibling resolver calls to resolver " resolver)
::highlight-nodes (into #{} (conj node-ids parent-node-id))
::highlight-styles {parent-node-id 1}})
(-> graph
(combine-run-next env node-ids pivot)
(merge-sibling-resolver-nodes* pivot node-ids')
(add-snapshot! env {::snapshot-message "Merge complete"
::highlight-nodes #{parent-node-id pivot}
::highlight-styles {parent-node-id 1}}))))
; endregion
; region graph helpers
(defn add-snapshot!
([graph {::keys [snapshots* snapshot-depth]} event-details]
(if snapshots*
(let [pad (str/join (repeat (or snapshot-depth 0) "-"))
pad (if (seq pad) (str pad " ") "")
event-details' (coll/update-if event-details ::snapshot-message #(str pad %))]
(swap! snapshots* conj (-> graph (dissoc ::source-ast ::available-data)
(merge event-details')))))
graph))
(defn base-graph []
{::nodes {}})
(defn base-env []
{::id-counter (atom 0)
::available-data {}})
(defn reset-env
"Restore the original environment sent to run-graph! Use this for nested graphs
that need a clean environment."
[env]
(or (some-> env meta ::original-env
(with-meta (meta env)))
env))
(defn push-path
[env {::p.attr/keys [attribute]
::p.path/keys [path]}]
(cond-> env
attribute
(assoc ::p.path/path (coll/vconj path attribute))))
(defn add-unreachable-path
"Add attribute to unreachable list"
[graph env path]
(-> (update graph ::unreachable-paths pfsd/merge-shapes path)
(add-snapshot! env {::snapshot-event ::snapshot-mark-attr-unreachable
::snapshot-message (str "Mark path " (pr-str path) " as unreachable.")})))
(defn add-warning [graph warn]
(update graph ::warnings coll/vconj warn))
(defn merge-unreachable
"Copy unreachable attributes from discard-graph to target-graph. Using the extra arity
you can also add a new unreachable path in the same call."
([target-graph {::keys [unreachable-paths]}]
(cond-> target-graph
unreachable-paths
(update ::unreachable-paths pfsd/merge-shapes (or unreachable-paths {}))))
([target-graph graph env path]
(-> (merge-unreachable target-graph graph)
(add-unreachable-path env path))))
(>defn graph-provides
"Get a set with all provided attributes from the graph."
[{::keys [index-attrs]}]
[(s/keys :req [::index-attrs])
=> ::p.attr/attributes-set]
(-> index-attrs keys set))
(>defn entry-ast
"Find AST node a given entry from the source AST."
[graph k]
[(s/keys :req [::index-ast]) any?
=> (? :edn-query-language.ast/node)]
(get-in graph [::index-ast k]))
(defn mark-attribute-process-sub-query
"Add information about attribute that is present but requires further processing
due to subquery, this is created so the runner can quickly know which attributes
need to have the subquery processing done."
[graph {:keys [key children query]}]
(if (or children query)
(update graph ::nested-process coll/sconj key)
graph))
(defn add-ident-process [graph {:keys [key]}]
(update graph ::idents coll/sconj key))
(defn add-placeholder-entry [graph attr]
(update graph ::placeholders coll/sconj attr))
(defn inc-snapshot-depth [env]
(update env ::snapshot-depth #(inc (or % 0))))
; endregion
; region node traversal
(>defn find-direct-node-successors
"Direct successors of node, branch nodes and run-next, in case of branch nodes the
branches will always come before the run-next."
[{::keys [run-next] :as node}]
[::node => (s/coll-of ::node-id)]
(let [branches (node-branches node)]
(cond-> []
branches
(into branches)
run-next
(conj run-next))))
(>defn node-ancestors
"Return all node ancestors. The order of the output will go from closest to farthest
nodes, like breathing out of the current node."
[graph node-id]
[::graph ::node-id
=> (s/coll-of ::node-id :kind vector?)]
(loop [node-queue (coll/queue [node-id])
ancestors []]
(if-let [node-id' (peek node-queue)]
(let [{::keys [node-parents]} (get-node graph node-id')]
(recur
(into (pop node-queue) node-parents)
(conj ancestors node-id')))
ancestors)))
(>defn node-successors
"Find successor nodes of node-id, node-id is included in the list. This will add
branch nodes before run-next nodes. Returns a lazy sequence that traverse the graph
as items are requested."
[graph node-id]
[::graph ::node-id => (s/coll-of ::node-id)]
(let [successors (find-direct-node-successors (get-node graph node-id))]
(cond
(seq successors)
(lazy-seq (cons node-id (apply concat (map #(node-successors graph %) successors))))
:else
(lazy-seq [node-id]))))
(>defn find-run-next-descendants
"Return descendants by walking the run-next"
[graph {::keys [node-id]}]
[::graph ::node => (s/coll-of ::node)]
(let [node (get-node graph node-id)]
(loop [descendants [node]
{::keys [run-next]} node]
(if-let [next (get-node graph run-next)]
(recur (conj descendants next) next)
descendants))))
(defn find-leaf-node
"Traverses all run-next still it reaches a leaf."
[graph node]
[::graph ::node => ::node]
(peek (find-run-next-descendants graph node)))
(>defn find-root-resolver-nodes
"Returns the first resolvers to get called in the graph. This will traverse AND and OR
node branches until the first resolvers are found. This function doesn't work the
run-next of nodes."
[{::keys [root] :as graph}]
[::graph => ::node-id-set]
(loop [nodes (transient #{})
queue (coll/queue [root])]
(if-let [node-id (peek queue)]
(let [{::pco/keys [op-name] :as node} (get-node graph node-id)]
(if op-name
(recur (conj! nodes node-id) (pop queue))
(recur nodes (into (pop queue) (node-branches node)))))
(persistent! nodes))))
; endregion
; region sub-query process
(>defn shape-descriptor->ast-children-optional
"Convert pathom output format into shape descriptor format."
[shape]
[::pfsd/shape-descriptor => vector?]
(into []
(map (fn [[k v]]
(if (seq v)
{:type :join
:key k
:dispatch-key k
:children (shape-descriptor->ast-children-optional v)
:params {::pco/optional? true}}
{:type :prop
:key k
:dispatch-key k
:params {::pco/optional? true}})))
shape))
(>defn shape-descriptor->ast-optional
"Convert pathom output format into shape descriptor format."
[shape]
[::pfsd/shape-descriptor => map?]
{:type :root
:children (shape-descriptor->ast-children-optional shape)})
(defn extend-attribute-sub-query
[graph {::keys [optional-process?]} attr shape]
(-> graph
(update-in [::index-ast attr] pf.eql/merge-ast-children
(-> (if optional-process?
(shape-descriptor->ast-optional shape)
(pfsd/shape-descriptor->ast shape))
(assoc :type :prop :key attr :dispatch-key attr)))))
(>defn shape-reachable?
"Given an environment, available data and shape, determines if the whole shape
is reachable (including nested dependencies)."
[{::keys [resolvers attr-resolvers-trail] :as env} available shape]
[map? ::pfsd/shape-descriptor ::pfsd/shape-descriptor => boolean?]
(let [missing (pfsd/missing available shape)]
(if (seq missing)
(let [graph (compute-run-graph
(-> (reset-env env)
(push-path env)
(inc-snapshot-depth)
(assoc
::attr-resolvers-trail (into (or attr-resolvers-trail #{}) resolvers)
::available-data available
:edn-query-language.ast/node (pfsd/shape-descriptor->ast missing))))]
(every?
(fn [[attr sub]]
(if-let [nodes-subs (node-attribute-provides graph env attr)]
(if (seq nodes-subs)
(some #(shape-reachable? env % sub) nodes-subs)
true)))
shape))
true)))
(defn compute-attribute-nested-input-require [graph env attr shape nodes]
(add-snapshot! graph env {::snapshot-message (str "Processing nested requirements " (pr-str {attr shape}))
::highlight-nodes (into #{} (map ::node-id) nodes)})
; TODO this should consider the case that a few of the nodes can provide the
; sub-query, in this case only they should be kept in the graph, and the other
; options must be removed
(let [checked-nodes (into []
(map (fn [node]
(cond-> node
(shape-reachable? (assoc env ::p.attr/attribute attr) (-> node ::pco/provides (get attr)) shape)
(assoc :valid-path? true))))
nodes)]
(if (some :valid-path? checked-nodes)
(-> (reduce
(fn [g {:keys [valid-path?] ::keys [node-id]}]
(if-not valid-path?
(assoc-node g node-id ::invalid-node? true)
g))
graph
checked-nodes)
(extend-attribute-sub-query env attr shape))
(-> graph
(dissoc ::root)
(add-unreachable-path env {attr shape})))))
(defn compute-attribute-dependency-graph
[graph {::keys [recursive-joins] :as env} attr shape]
(add-snapshot! graph env {::snapshot-message (str "Processing dependency " {attr shape})})
(let [graph' (-> graph
(dissoc ::root)
(compute-attribute-graph
(-> env
(dissoc ::p.attr/attribute)
(update ::attr-deps-trail coll/sconj (::p.attr/attribute env))
(assoc
:edn-query-language.ast/node
(first (pfsd/shape-descriptor->ast-children {attr shape}))))))]
(if (::root graph')
(let [nodes
(->> (get-in graph' [::index-attrs attr])
(mapv #(node-with-resolver-config graph' env %)))