-
-
Notifications
You must be signed in to change notification settings - Fork 63
/
core.cljc
1030 lines (868 loc) · 33.4 KB
/
core.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.core
(:refer-clojure :exclude [ident?])
#?(:cljs
(:require-macros [com.wsscode.pathom.core]))
(:require
[clojure.spec.alpha :as s]
[clojure.core.async :as async :refer [go <! >!]]
[#?(:clj com.wsscode.common.async-clj
:cljs com.wsscode.common.async-cljs)
:as casync
:refer [go-catch <? let-chan chan? <?maybe <!maybe go-promise]]
[com.wsscode.pathom.parser :as pp]
[com.wsscode.pathom.specs.ast :as spec.ast]
[com.wsscode.pathom.specs.query :as spec.query]
[clojure.set :as set]
[clojure.walk :as walk]
#?(:cljs [goog.object :as gobj])
[com.wsscode.pathom.trace :as pt])
#?(:clj
(:import (clojure.lang IAtom IDeref))))
;; pathom core
(s/def ::env map?)
(s/def ::attribute ::spec.query/property)
(s/def ::reader-map (s/map-of keyword? ::reader))
(s/def ::reader-seq (s/coll-of ::reader :kind vector? :into []))
(s/def ::reader-fn fn?)
(s/def ::optional? boolean?)
(s/def ::reader
(s/or :fn ::reader-fn
:map ::reader-map
:list ::reader-seq))
(s/def ::process-reader
(s/fspec :args (s/cat :reader ::reader)
:ret ::reader))
(s/def ::error
(s/spec any?
:gen #(s/gen #{(ex-info "Generated sample error" {:some "data"})})))
(s/def ::errors (s/map-of vector? any?))
(s/def ::errors* #(instance? IAtom %))
(s/def ::entity any?)
(s/def ::entity-key keyword?)
(s/def ::fail-fast? boolean?)
(s/def ::map-key-transform
(s/fspec :args (s/cat :key any?)
:ret string?))
(s/def ::map-value-transform
(s/fspec :args (s/cat :key any? :value any?)
:ret any?))
(s/def ::placeholder-prefixes set?)
(s/def ::js-key-transform ::map-key-transform)
(s/def ::js-value-transform ::map-value-transform)
(s/def ::parser
(s/fspec :args (s/cat :env map? :tx ::spec.query/query)
:ret map?))
(s/def ::wrap-read
(s/fspec :args (s/cat :reader ::reader-fn)
:ret ::reader-fn))
(s/def ::wrap-parser
(s/fspec :args (s/cat :parser ::parser)
:ret ::parser))
(s/def ::plugin (s/keys :opt [::wrap-read ::wrap-parser]))
#_(s/def ::plugins
(s/with-gen (s/coll-of ::plugin :kind vector?) #(s/gen #{[]})))
(s/def ::parent-join-key (s/or :prop ::spec.query/property
:ident ::spec.query/ident
:call ::spec.query/mutation-key))
(s/def ::parent-query ::spec.query/join-query)
(def break-values #{::reader-error ::not-found})
;; SUPPORT FUNCTIONS
(defn deep-merge [& xs]
"Merges nested maps without overwriting existing keys."
(if (every? #(or (map? %) (nil? %)) xs)
(apply merge-with deep-merge xs)
(last xs)))
(defn query->ast
"Given a query expression convert it into an AST."
[query-expr]
(pp/query->ast query-expr))
(s/fdef query->ast
:args (s/cat :query (s/nilable ::spec.query/query))
:ret ::spec.ast/root)
(defn query->ast1
"Call query->ast and return the first children."
[query-expr]
(-> (query->ast query-expr) :children first))
(s/fdef query->ast1
:args (s/cat :query ::spec.query/query)
:ret ::spec.ast/root)
(defn ast->query [query-ast]
"Given an AST convert it back into a query expression."
(pp/ast->expr query-ast true))
(s/fdef ast->query
:args (s/cat :ast ::spec.ast/node)
:ret ::spec.ast/root)
(defn filter-ast [f ast]
(->> ast
(walk/prewalk
(fn filter-ast-walk [x]
(if (and (map? x)
(contains? x :children))
(update x :children #(filterv f %))
x)))))
(defn update-attribute-param
"Add attribute param, eg:
```
(p/update-attribute-param :keyword assoc :foo \"bar\") => (:keyword {:foo \"bar\"})
(p/update-attribute-param '(:keyword {:param \"prev\"}) assoc :foo \"bar\") => (:keyword {:foo \"bar\" :param \"prev\"})
```
"
[x f & args]
(if (seq? x)
(let [[k p] x]
(list k (apply f p args)))
(list x (apply f {} args))))
(defn optional-attribute [x]
(assert (or (keyword? x) (list x)) "Optional value must be a keyword or a parameterized attribute")
(update-attribute-param x assoc ::optional? true))
; alias for optional-attribute
(def ? optional-attribute)
(defn union-children?
"Given an AST point, check if the children is a union query type."
[ast]
(= :union (some-> ast :children first :type)))
(defn read-from* [{:keys [ast] :as env} reader]
(cond
(map? reader) (let [k (:key ast)]
(if-let [[_ v] (find reader k)]
(read-from* env v)
::continue))
(vector? reader) (let [res (into [] (comp (map #(read-from* env %))
(drop-while #(= % ::continue))
(take 1))
reader)]
(if (seq res)
(first res)
::continue))
(ifn? reader) (reader env)
:else (throw (ex-info "Can't process reader" {:reader reader}))))
(defn read-from
"Runs the read process for the reading, the reader can be a function, a vector or a map:
function: will receive the environment as argument
map: will dispatch from the ast key to a reader on the map value
vector: will try to run each reader in sequence, when a reader returns ::p/continue it will try the next"
[env reader]
(let-chan [res (read-from* env reader)]
(if (= res ::continue) ::not-found res)))
(defn transduce-maps
"Walk the structure and transduce every map with xform."
[xform input]
(walk/prewalk
(fn elide-items-walk [x]
(if (map? x)
(let [old-meta (meta x)]
(with-meta (into {} xform x) old-meta))
x))
input))
(defn transduce-children
"Recursivelly transduce children on the AST, you can use this to apply filter/transformations
on a whole AST. Each iteration of the transducer will get a single AST node to process.
```
(->> [:a {:b [:c :d]} :e]
(p/query->ast)
(p/transduce-children (remove (comp #{:a :c} :key)))
(p/ast->query))
; => [{:b [:d]} :e]
```"
[xform {:keys [children] :as node}]
(cond-> node
(seq children)
(update :children
(fn [children]
(into [] (comp xform (map #(transduce-children xform %))) children)))))
(defn elide-items
"Removes any item on set item-set from the input"
[item-set input]
(let [old-meta (meta input)]
(with-meta
(transduce-maps (remove (fn [[_ v]] (contains? item-set v))) input)
old-meta)))
(defn elide-not-found
"Convert all ::p/not-found values of maps to nil"
[input]
(elide-items #{::not-found} input))
(def focus-subquery pp/focus-subquery)
(defn atom? [x]
#?(:clj (instance? IDeref x)
:cljs (satisfies? IDeref x)))
(defn normalize-atom [x] (if (atom? x) x (atom x)))
(defn raw-entity
[{::keys [entity-key] :as env}]
(get env (or entity-key ::entity)))
(defn maybe-atom [x]
(if (atom? x) (deref x) x))
(defn entity-value-merge
"This is used for merging new parsed attributes from entity, works like regular merge but if the value from the right
direction is not found, then the previous value will be kept."
[x y]
(if (identical? y ::not-found)
x
y))
(defn entity
"Fetch the entity according to the ::entity-key. If the entity is an IAtom, it will be derefed.
If a second argument is sent, calls the parser against current element to guarantee that some fields are loaded. This
is useful when you need to ensure some values are loaded in order to fetch some more complex data. NOTE: When using
this call with an explicit vector of attributes the parser will not be invoked for attributes that already exist in
the current value of the current entity."
([env]
(let [e (raw-entity env)]
(maybe-atom e)))
([{:keys [parser] :as env} attributes]
(let [e (entity env)]
(let-chan [res (parser env (filterv (-> e keys set complement) attributes))]
(merge-with entity-value-merge e res)))))
(s/fdef entity
:args (s/cat :env ::env :attributes (s/? (s/coll-of ::attribute)))
:ret (s/nilable ::entity))
(defn entity-attr
"Helper function to fetch a single attribute from current entity."
([env attr]
(let-chan [e (entity env [attr])]
(get e attr)))
([env attr default]
(let-chan [e (entity env [attr])]
(let [x (get e attr)]
(if (#{nil ::not-found} x)
default
x)))))
(s/fdef entity-attr
:args (s/cat :env ::env :attribute ::attribute :default (s/? any?))
:ret any?)
(defn entity! [{::keys [path] :as env} attributes]
(let-chan [e (entity env attributes)]
(let [missing (set/difference (set attributes)
(set (keys (elide-not-found e))))]
(if (seq missing)
(throw (ex-info (str "Entity attributes " (pr-str missing) " could not be realized")
{::entity e
::path path
::missing-attributes missing})))
e)))
(s/fdef entity!
:args (s/cat :env ::env :attributes (s/? (s/coll-of ::attribute)))
:ret (s/nilable ::entity))
(defn entity-attr!
"Like entity-attr. Raises an exception if the property can't be retrieved."
[env attr]
(let-chan [e (entity! env [attr])]
(get e attr)))
(s/fdef entity-attr!
:args (s/cat :env ::env :attribute ::attribute)
:ret any?)
(defn swap-entity!
"Helper to swap the current entity value."
[env fn & args]
(let [e (raw-entity env)]
(if (atom? e)
(apply swap! e fn args))))
(s/fdef swap-entity!
:args (s/cat :env ::env :fn fn? :args (s/* any?))
:ret any?)
(s/def ::union-path
(s/or :keyword ::spec.query/property
:fn fn?))
(defn update-child
"Given an AST, find the child with a given key and run update against it."
[ast key & args]
(if-let [idx (some->> (:children ast)
(map-indexed vector)
(filter (comp #{key} :key second))
ffirst)]
(apply update-in ast [:children idx] args)
ast))
(defn update-recursive-depth
"Given an AST, find the child with a given key and run update against it."
[ast key & args]
(if-let [idx (some->> (:children ast)
(map-indexed vector)
(filter (comp #(and (= key (:key %))
(pos-int? (:query %))) second))
ffirst)]
(apply update-in ast [:children idx :query] args)
ast))
(defn remove-query-wildcard [query]
(into [] (remove #{'*}) query))
(defn default-union-path [{:keys [query] :as env}]
(let [e (entity env)]
(if-let [path (some->> (keys query)
(filter #(contains? e %))
first)]
path)))
(defn join
"Runs a parser with current sub-query. When run with an `entity` argument, that entity is set as the new environment
value of `::entity`, and the subquery is parsered with that new environment. When run without an `entity` it
parses the current subquery in the context of whatever entity was already in `::entity` of the env."
([entity {::keys [entity-key] :as env}]
(if (atom? entity)
(if (::env @entity)
(join (assoc (get @entity ::env) entity-key entity))
(join (assoc env entity-key entity)))
(if (::env entity)
(join (assoc (get entity ::env) entity-key (atom entity)))
(join (assoc env entity-key (atom entity))))))
([{:keys [parser ast query]
::keys [union-path parent-query processing-sequence placeholder-prefixes]
:as env}]
(let [e (entity env)
placeholder? (contains? (or placeholder-prefixes #{}) (some-> (:dispatch-key ast) namespace))
query (if (union-children? ast)
(let [union-path (or union-path default-union-path)
path (cond
(fn? union-path) (union-path env)
(keyword? union-path) (get (entity! env [union-path]) union-path))]
(or (get query path) ::blank-union))
query)
env' (-> env
(assoc ::parent-query query
::parent-join-key (:key ast))
(cond-> (not placeholder?)
(dissoc ::pp/waiting ::pp/key-watchers)))
env' (if processing-sequence
(if (and (::stop-sequence? (meta processing-sequence))
(not placeholder?))
(dissoc env' ::processing-sequence)
(update env' ::processing-sequence vary-meta assoc ::stop-sequence? true))
env')]
(cond
(= ::blank-union query)
{}
(nil? query) e
(nat-int? query)
(if (zero? query)
nil
(let [parent-query' (-> (query->ast parent-query)
(update-recursive-depth (:key ast) dec)
(ast->query))]
(parser (assoc env' ::parent-query parent-query') (remove-query-wildcard parent-query'))))
(some #{'*} query)
(let-chan [computed-e (parser env' (remove-query-wildcard query))]
(merge (entity env') computed-e))
:else
(parser env' query)))))
(defn join-seq-parallel [env coll]
(if (seq coll)
(go-catch
(let [join-item (fn join-item [env entity]
(join entity env))
env (assoc env ::processing-sequence coll)
[head & tail] coll
first-res (<?maybe (join-item (update env ::path conj 0) head))
from-chan (async/chan 50)
out-chan (async/chan 50)]
(async/onto-chan from-chan (map vector tail (range)))
(async/pipeline-async 10
out-chan
(fn join-seq-pipeline [[ent i] res-ch]
(go
(let [res (<!maybe (join-item (update env ::path conj (inc i)) ent))]
(>! res-ch res)
(async/close! res-ch))))
from-chan)
(<! (async/into [first-res] out-chan))))
[]))
(defn join-seq
"Runs the current subquery against the items of the given collection."
[{::keys [entity-key] ::pp/keys [parallel?] :as env} coll]
(pt/trace env {::pt/event ::join-seq ::seq-count (count coll)})
(if parallel?
(join-seq-parallel env coll)
(letfn [(join-item [ent out]
(join ent (-> env
(assoc ::processing-sequence coll)
(update ::path conj (count out)))))]
(loop [out []
[ent & tail] coll]
(if ent
(let [res (join-item ent out)]
(if (chan? res)
(go-catch
(loop [out [(<? res)]
[ent & tail] tail]
(if ent
(recur
(conj out (<? (join-item ent out)))
tail)
out)))
(recur (conj out res) tail)))
out)))))
(defn ident? [x]
(and (vector? x)
(keyword? (first x))
(= 2 (count x))))
(defn ident-key* [key]
(if (vector? key) (first key)))
(defn ident-key
"The first element of an ident."
[{:keys [ast]}]
(let [key (some-> ast :key)]
(if (vector? key) (first key))))
(defn ident-value* [key]
(if (vector? key) (second key)))
(defn ident-value
"The second element of an ident"
[{:keys [ast]}]
(let [key (some-> ast :key)]
(if (sequential? key) (second key))))
(defn elide-ast-nodes
"Remove items from a query (AST) that have a key listed in the elision-set"
[{:keys [key union-key] :as ast} elision-set]
(let [union-elision? (contains? elision-set union-key)]
(when-not (or union-elision? (contains? elision-set key))
(update ast :children (fn [c] (if c (vec (keep #(elide-ast-nodes % elision-set) c))))))))
(defn normalize-env [{:keys [ast] :as env}]
(cond-> (update env ::path (fnil conj []) (:key ast))
(nil? (::entity-key env)) (assoc ::entity-key ::entity)))
(defn merge-queries* [qa qb]
(reduce (fn [ast {:keys [key type params] :as item-b}]
(if-let [[idx item] (->> ast :children
(keep-indexed #(if (-> %2 :key (= key)) [%1 %2]))
first)]
(cond
(or (= :join (:type item) type)
(= :prop (:type item) type))
(if (= (:params item) params)
(update-in ast [:children idx] merge-queries* item-b)
(reduced nil))
(and (= :prop (:type item))
(= :join type))
(assoc-in ast [:children idx] item-b)
(= :call type)
(reduced nil)
:else ast)
(update ast :children conj item-b)))
qa
(:children qb)))
(defn merge-queries [qa qb]
(some-> (merge-queries* (query->ast qa) (query->ast qb))
(ast->query)))
(defn normalize-query-variables
"Converts ident values and param values to ::p/var."
[query]
(->> (query->ast query)
(transduce-children
(map (fn [x]
(cond-> x
(ident? (:key x))
(assoc :key [(first (:key x)) ::var])
(:params x)
(update :params #(into {} (map (fn [[k _]] [k ::var])) %))))))
(ast->query)))
(defn query-id
"Generates a consistent hash from the query. The query first goes to a process to remove any
variables from idents and params, then we get the Clojure hash of it. You can use this to save
information about a query that can be used to correlate with the query later."
[query]
(hash (normalize-query-variables query)))
;; DISPATCH HELPERS
(defn key-dispatch [{:keys [ast]}]
(:key ast))
(defn entity-dispatch
"Dispatch on the first element (type) of an incoming ident."
[{:keys [ast]}]
(if (vector? (:key ast))
(first (:key ast))))
;; NODE HELPERS
(defn env-placeholder-reader
"Produces a reader that will respond to any keyword whose namespace
is in the set `(::placeholder-prefixes env)`. The join node logical
level stays the same as the parent where the placeholder node is
requested."
[{::keys [placeholder-prefixes] :as env}]
(assert placeholder-prefixes "To use env-placeholder-reader please add ::p/placeholder-prefixes to your environment.")
(if (contains? placeholder-prefixes (namespace (:dispatch-key (:ast env))))
(join env)
::continue))
(defn lift-placeholders
"This will lift the queries from placeholders to the same level of the query, as if there was not placeholders in it."
[{::keys [placeholder-prefixes]} query]
(let [ast (query->ast query)
ast' (walk/postwalk
(fn [x]
(if-let [children (:children x)]
(let [{placeholders true
regular false} (group-by #(and (= :join (:type %))
(contains? placeholder-prefixes
(namespace (:dispatch-key %)))) children)]
(as-> (assoc x :children (or regular [])) <>
(reduce merge-queries* <> placeholders)))
x))
ast)]
(ast->query ast')))
;; BUILT-IN READERS
(defn map-reader
"Map reader will try to find the ast key on the current entity and output it. When the value is a map and a
sub query is present, it will apply the sub query on that value (recursively). When the value is a sequence,
map-reader will do a join on each of the items (and apply sub queries if it's present and values are maps.
Map-reader will defer the read when the key is not present at entity."
[{:keys [ast query] :as env}]
(let [entity (entity env)]
(if-let [[_ v] (find entity (:key ast))]
(if (sequential? v)
(join-seq env v)
(if (and (map? v) query)
(join v env)
v))
::continue)))
(defn map-reader*
"Like map-reader, but it has extra options (read from the environment):
map-key-transform: (fn [key]) will transform the key on the AST before trying to match with entity key
map-value-transform: (fn [key value]) will transform the output value after reading from the entity.
The reason to have a separated reader is so the plain version (map-reader) can be faster by avoiding checking
the presence of transform functions."
[{::keys [map-key-transform map-value-transform]}]
(fn [{:keys [ast query]
::keys [entity-key]
:as env}]
(let [key (cond-> (:key ast) map-key-transform map-key-transform)
entity (entity env)]
(if-let [[_ v] (find entity key)]
(if (sequential? v)
(join-seq env v)
(if (and (map? v) query)
(join (assoc env entity-key v))
(cond->> v
map-value-transform
(map-value-transform (:key ast)))))
::continue))))
#?(:cljs
(defn js-obj-reader
"Like map-reader*, but handles plain Javascript objects instead of Clojure maps."
[{:keys [query ast]
::keys [js-key-transform js-value-transform entity-key]
:as env
:or {js-key-transform name
js-value-transform (fn [_ v] v)}}]
(let [js-key (js-key-transform (:key ast))
entity (entity env)]
(if (gobj/containsKey entity js-key)
(let [v (gobj/get entity js-key)]
(if (js/Array.isArray v)
(join-seq env (array-seq v))
(if (and query (= (type v) js/Object))
(join (assoc env entity-key v))
(js-value-transform (:key ast) v))))
::continue))))
(defn ident-join-reader
"This reader will join on any ident join, the entity for the join will be a map containing the same
key and value expressed on the ident, eg: [{[:id 123] [:id]}], the join entry will be {:id 123}."
[env]
(if-let [key (ident-key env)]
(join {key (ident-value env)} env)
::continue))
;; PLUGINS
; Helpers
(defn post-process-parser-plugin
"Helper to create a plugin to work on the parser output. `f` will run once with the parser final result."
[f]
{::wrap-parser
(fn transform-parser-out-plugin-external [parser]
(fn transform-parser-out-plugin-internal [env tx]
(let-chan [res (parser env tx)]
(f res))))})
; Exception
(defn error-message [err]
#?(:clj (.getMessage err)
:cljs (.-message err)))
(defn error-str [err]
#?(:clj
(let [msg (.getMessage err)
data (ex-data err)]
(cond-> (type err)
msg (str ": " msg)
data (str " - " (pr-str data))))
:cljs
(let [msg (.-message err)
data (ex-data err)]
(cond-> msg
data (str " - " (pr-str data))))))
(defn update-action
"Helper function to update a mutation action."
[m f]
(if (contains? m :action)
(update m :action f)
m))
(defn process-error [{::keys [process-error] :as env} e]
(if process-error (process-error env e)
(error-str e)))
(defn add-error [{::keys [errors* path] :as env} e]
(when errors*
(swap! errors* assoc path (process-error env e)))
::reader-error)
(defn wrap-handle-exception [reader]
(fn wrap-handle-exception-internal
[{::keys [fail-fast?] :as env}]
(if fail-fast?
(reader env)
(try
(let [x (reader env)]
(if (chan? x)
(go
(try
(<? x)
(catch #?(:clj Throwable :cljs :default) e
(add-error env e))))
x))
(catch #?(:clj Throwable :cljs :default) e
(add-error env e))))))
(defn wrap-mutate-handle-exception [mutate]
(fn wrap-mutate-handle-exception-internal
[{::keys [process-error fail-fast?] :as env} k p]
(if fail-fast?
(mutate env k p)
(try
(update-action (mutate env k p)
(fn [action]
(fn []
(try
(let [res (action)]
(if (chan? res)
(go
(try
(<? res)
(catch #?(:clj Throwable :cljs :default) e
(if process-error (process-error env e)
{::reader-error (error-str e)}))))
res))
(catch #?(:clj Throwable :cljs :default) e
(if process-error (process-error env e)
{::reader-error (error-str e)}))))))
(catch #?(:clj Throwable :cljs :default) e
{:action
(fn []
(if process-error (process-error env e)
{::reader-error (error-str e)}))})))))
(defn wrap-parser-exception [parser]
(fn wrap-parser-exception-internal [env tx]
(let [errors (atom {})]
(let-chan [res (parser (assoc env ::errors* errors) tx)]
(cond-> res
(seq @errors) (assoc ::errors @errors))))))
(def error-handler-plugin
{::wrap-read wrap-handle-exception
::wrap-parser wrap-parser-exception
::wrap-mutate wrap-mutate-handle-exception})
(def trace-plugin pt/trace-plugin)
(defn collapse-error-path [m path]
"Reduces the error path to the last available nesting on the map m."
(vec
(loop [path' path]
(if (zero? (count path'))
(take 1 path)
(if (get-in m path')
path'
(recur (butlast path')))))))
(s/fdef collapse-error-path
:args (s/cat :m map? :path vector?)
:ret vector?)
(defn raise-errors [data]
"Extract errors from the data root and inject those in the same level where
the error item is present. For example:
{:query {:item :com.wsscode.pathom/reader-error}
:com.wsscode.pathom.core/errors
{[:query :item] {:error \"some error\"}}}
Is turned into:
{:query {:item :com.wsscode.pathom/reader-error
:com.wsscode.pathom.core/errors {:item {:error \"some error\"}}}
This makes easier to reach for the error when rendering the UI."
(reduce
(fn [m [path err]]
(if (= ::reader-error (get-in m path))
(let [path' (concat (butlast path) [:com.wsscode.pathom.core/errors (last path)])]
(assoc-in m path' err))
m))
(dissoc data :com.wsscode.pathom.core/errors)
(get data :com.wsscode.pathom.core/errors)))
(s/fdef raise-errors
:args (s/cat :data (s/keys :opt [::errors]))
:ret map?)
(defn raise-response
"Mutations running through a parser all come back in a map like this {'my/mutation {:result {...}}}. This function
converts that to {'my/mutation {...}}. Copied from fulcro.server."
[resp]
(walk/prewalk
(fn [x]
(if (map? x)
(reduce (fn [acc [k v]]
(if (and (symbol? k) (not (nil? (:result v))))
(assoc acc k (:result v))
(assoc acc k v)))
{} x)
x))
resp))
(def raise-mutation-result-plugin
{::wrap-parser
(fn raise-mutation-result-wrap-parser [parser]
(fn raise-mutation-result-wrap-internal [env tx]
(raise-response (parser env tx))))})
; Enviroment
(defn env-plugin [extra-env]
{::wrap-parser (fn env-plugin-wrap-parser [parser]
(fn env-plugin-wrap-internal [env tx]
(parser (merge extra-env env) tx)))})
(defn env-wrap-plugin
"This plugin receives a function that will be called to wrap the current
enviroment each time the main parser is called (parser level)."
[extra-env-wrapper]
{::wrap-parser (fn env-wrap-wrap-parser [parser]
(fn env-wrap-wrap-internal [env tx]
(parser (extra-env-wrapper env) tx)))})
; Request cache
(def request-cache-plugin
{::wrap-parser
(fn request-cache-wrap-parser [parser]
(fn request-cache-wrap-internal [env tx]
(parser (assoc env ::request-cache (atom {})) tx)))})
(defn cached* [env key body-fn]
(if-let [cache (get env ::request-cache)]
(if-let [hit (get @cache key)]
(do (pt/trace env {::pt/event ::cache-hit ::cache-key key})
(casync/throw-err hit))
(do
(pt/trace env {::pt/event ::cache-miss ::cache-key key})
(let-chan [hit (try
(body-fn)
(catch #?(:clj Throwable :cljs :default) e
(swap! cache assoc key e)
(throw e)))]
(swap! cache assoc key hit)
hit)))
(body-fn)))
(defmacro cached [env key body]
`(cached* ~env ~key (fn [] ~body)))
(defn cached-async [env key f]
(if-let [cache (get env ::request-cache)]
(do
(swap! cache update key
(fn [x]
(if x
(do
(pt/trace env {::pt/event ::cache-hit ::cache-key key})
x)
(do
(pt/trace env {::pt/event ::cache-miss ::cache-key key})
(go-promise (<!maybe (f)))))))
(get @cache key))
(go-promise (<!maybe (f)))))
(defn cache-hit [{::keys [request-cache] :as env} key value]
(pt/trace env {::pt/event ::cache-miss ::cache-key key})
(swap! request-cache assoc key value)
value)
(defn cache-contains? [{::keys [request-cache]} key]
(contains? @request-cache key))
(defn cache-read [{::keys [request-cache]} key]
(get @request-cache key))
;; PARSER READER
(defn wrap-add-path [reader]
(fn [{:keys [ast] :as env}]
(reader (update env ::path (fnil conj []) (:key ast)))))
(defn group-plugins-by-action [plugins]
(reduce
(fn [g p]
(reduce
(fn [g [k v]]
(update g k (fnil conj []) v))
g
p))
{}
plugins))
(defn wrap-normalize-env
([parser] (wrap-normalize-env parser []))
([parser plugins]
(fn wrap-normalize-env-internal
([env tx] (wrap-normalize-env-internal env tx nil))
([env tx target]
(parser (assoc env ::plugin-actions (group-plugins-by-action plugins)
::plugins plugins
::entity-key ::entity
::parent-query tx
::entity-path-cache (atom {})
:target target)
tx)))))
(defn wrap-reduce-params [reader]
(fn
([env] {:value (reader env)})
([env _ _] {:value (reader env)})))
(defn pathom-read' [{::keys [reader] :as env}]
(read-from env reader))
(defn apply-plugins [v plugins key & params]
(reduce (fn [x plugin]
(let [f (get plugin key)]
(if f (apply f x params) x)))
v plugins))
(defn exec-plugin-actions [env key v & args]
(let [plugins (get-in env [::plugin-actions key] [])
augmented-v (reduce (fn [x f] (f x)) v plugins)]
(apply augmented-v args)))
(defn easy-plugins [{::keys [plugins env]}]
(cond->> plugins
(fn? env)
(into [(env-wrap-plugin env)])
(map? env)
(into [(env-plugin env)])))
(defn settings-mutation [settings]
(or (::mutate settings) (:mutate settings)))
(defn parser [settings]
(let [plugins (easy-plugins settings)
mutate (settings-mutation settings)]
(-> (pp/parser {:read (-> pathom-read'
(apply-plugins plugins ::wrap-read)
wrap-add-path)
:mutate (if mutate (apply-plugins mutate plugins ::wrap-mutate))})
(apply-plugins plugins ::wrap-parser)
(apply-plugins plugins ::wrap-parser2 settings)
(wrap-normalize-env plugins))))
(defn async-parser [settings]
(let [plugins (easy-plugins settings)
mutate (settings-mutation settings)]
(-> (pp/async-parser {:read (-> pathom-read'
(apply-plugins plugins ::wrap-read)
wrap-add-path)
:mutate (if mutate (apply-plugins mutate plugins ::wrap-mutate))})
(apply-plugins plugins ::wrap-parser)
(apply-plugins plugins ::wrap-parser2 settings)
(wrap-normalize-env plugins))))
(defn parallel-parser [settings]
(let [plugins (easy-plugins settings)
mutate (settings-mutation settings)]
(-> (pp/parallel-parser {:read (-> pathom-read'
(apply-plugins plugins ::wrap-read)
wrap-add-path)
:mutate (if mutate (apply-plugins mutate plugins ::wrap-mutate))
:add-error add-error})
(apply-plugins plugins ::wrap-parser)
(apply-plugins plugins ::wrap-parser2 settings)
(wrap-normalize-env plugins))))
;;;; DEPRECATED
;; old names for join and join-seq
(def continue join)
(def continue-seq join-seq)
(defn placeholder-reader
"DEPRECATED: use env-placeholder-reader instead.
Produces a reader that will respond to any keyword with the namespace ns. The join node logical level stays the same
as the parent where the placeholder node is requested."