-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
tx_processing.cljc
650 lines (609 loc) · 31.9 KB
/
tx_processing.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
(ns com.fulcrologic.fulcro.algorithms.tx-processing
"The transaction processing in Fulcro is pluggable. This namespace is the
implementation for the default transaction processing ."
(:require
[clojure.set :as set]
[clojure.spec.alpha :as s]
[com.fulcrologic.fulcro.algorithms.lookup :as ah]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
[com.fulcrologic.fulcro.algorithms.do-not-use :as futil]
[com.fulcrologic.fulcro.algorithms.scheduling :as sched :refer [schedule!]]
[com.fulcrologic.fulcro.mutations :as m]
[com.fulcrologic.fulcro.specs]
[com.fulcrologic.fulcro.inspect.inspect-client :as inspect :refer [ido ilet]]
com.fulcrologic.fulcro.specs
[ghostwheel.core :refer [>defn => |]]
[edn-query-language.core :as eql]
[taoensso.encore :as enc]
[taoensso.timbre :as log]))
(declare schedule-activation! process-queue! remove-send!)
(>defn app->remotes
"Returns the remotes map from an app"
[app]
[:com.fulcrologic.fulcro.application/app => :com.fulcrologic.fulcro.application/remotes]
(-> app :com.fulcrologic.fulcro.application/runtime-atom deref :com.fulcrologic.fulcro.application/remotes))
(>defn app->remote-names
"Returns a set of the names of the remotes from an app"
[app]
[:com.fulcrologic.fulcro.application/app => :com.fulcrologic.fulcro.application/remote-names]
(-> app :com.fulcrologic.fulcro.application/runtime-atom deref :com.fulcrologic.fulcro.application/remotes keys set))
(>defn extract-parallel
"Splits the given send queue into two send queues:
[parallel-items sequential-items]."
[sends]
[(s/coll-of ::send-node :kind vector?) => (s/cat :p ::send-queue :rest ::send-queue)]
(let [parallel? (fn [{:keys [::options]}]
(boolean (or (:parallel? options) (::parallel? options))))
{parallel true
sequential false} (group-by parallel? sends)]
[(vec parallel) (vec sequential)]))
(>defn every-ast?
"Check if the given `test` predicate is true for an AST node or for all the immediate children of an AST tree."
[ast-node-or-tree test]
[::ast fn? => boolean?]
(if (= :root (:type ast-node-or-tree))
(every? test (:children ast-node-or-tree))
(test ast-node-or-tree)))
(>defn mutation-ast?
"Returns true if the given AST node or tree represents a mutation or sequence of mutations."
[ast-node-or-tree]
[::ast => boolean?]
(every-ast? ast-node-or-tree #(= :call (:type %))))
(>defn query-ast?
"Returns true if the given AST node or tree represents a mutation or sequence of mutations."
[ast-node-or-tree]
[::ast => boolean?]
(every-ast? ast-node-or-tree #(not= :call (:type %))))
(>defn sort-queue-writes-before-reads
"Sort function on a send queue. Leaves any active nodes in front, and sorts the remainder of the queue so that writes
appear before reads, without changing the relative order in blocks of reads/writes."
[send-queue]
[::send-queue => ::send-queue]
(let [[active-queue send-queue] (split-with ::active? send-queue)
id-sequence (mapv (fn [n] (-> n first ::id)) (partition-by ::id send-queue))
clusters (group-by ::id (vec send-queue))
{:keys [reads writes]} (reduce
(fn [result id]
(let [[{:keys [::ast] :as n} & _ :as cluster] (get clusters id)]
(cond
(nil? ast) result
(query-ast? ast) (update result :reads into cluster)
(mutation-ast? ast) (update result :writes into cluster)
:else result)))
{:reads [] :writes []}
id-sequence)
send-queue (into [] (concat active-queue writes reads))]
send-queue))
(>defn top-keys
[{:keys [type key children] :as ast}]
[::ast => (s/coll-of :edn-query-language.ast/key)]
(if (= :root type)
(into #{} (map :key) children)
#{key}))
(>defn combine-sends
"Takes a send queue and returns a map containing a new combined send node that can act as a single network request,
along with the updated send queue."
[app remote-name send-queue]
[:com.fulcrologic.fulcro.application/app :com.fulcrologic.fulcro.application/remote-name ::send-queue => (s/keys :opt [::send-node] :req [::send-queue])]
(let [[active-nodes send-queue] (split-with ::active? send-queue)
send-queue (sort-queue-writes-before-reads (vec send-queue))
id-to-send (-> send-queue first ::id)
options (-> send-queue first ::options)
[to-send to-defer] (split-with #(= id-to-send (::id %)) send-queue)
tx (reduce
(fn [acc {:keys [::ast]}]
(let [tx (if (= :root (:type ast))
(eql/ast->query ast)
[(eql/ast->query ast)])]
(into acc tx)))
[]
to-send)
ast (eql/query->ast tx)
combined-node-id (tempid/uuid)
combined-node-idx 0
combined-node {::id combined-node-id
::idx combined-node-idx
::ast ast
::options options
::update-handler (fn [{:keys [body] :as combined-result}]
(doseq [{::keys [update-handler]} to-send]
(when update-handler
(update-handler combined-result))))
::result-handler (fn [{:keys [body] :as combined-result}]
(doseq [{::keys [ast result-handler]} to-send]
(let [new-body (select-keys body (top-keys ast))
result (assoc combined-result :body new-body)]
(inspect/ilet [{:keys [status-code body]} result]
(if (= 200 status-code)
(inspect/send-finished! app remote-name combined-node-id body)
(inspect/send-failed! app remote-name (str status-code))))
(result-handler result)))
(remove-send! app remote-name combined-node-id combined-node-idx))
::active? true}]
(if (seq to-send)
{::send-node combined-node
::send-queue (into [] (concat active-nodes [combined-node] to-defer))}
{::send-queue send-queue})))
(>defn net-send!
"Process the send against the user-defined remote. Catches exceptions and calls error handler with status code 500
if the remote itself throws exceptions."
[app send-node remote-name]
[:com.fulcrologic.fulcro.application/app ::send-node :com.fulcrologic.fulcro.application/remote-name => any?]
(enc/if-let [remote (get (app->remotes app) remote-name)
transmit! (get remote :transmit!)
query-transform (ah/app-algorithm app :global-eql-transform)
send-node (if query-transform
(update send-node ::ast query-transform)
send-node)]
(try
(inspect/ilet [tx (eql/ast->query (::ast send-node))]
(inspect/send-started! app remote-name (::id send-node) tx))
(transmit! remote send-node)
(catch #?(:cljs :default :clj Exception) e
(log/error e "Send threw an exception!")
(try
(inspect/ido
(inspect/send-failed! app (::id send-node) "Transmit Exception"))
((::result-handler send-node) {:status-code 500
:client-exception e})
(catch #?(:cljs :default :clj Exception) e
(log/fatal e "Error handler failed to handle exception!")))))
(do
(log/error "Transmit was not defined on remote" remote-name)
((::result-handler send-node) {:status-code 500
:message "Transmit missing on remote."}))))
(>defn process-send-queues!
"Process the send queues against the remotes. Updates the send queues on the app and returns the updated send queues."
[{:com.fulcrologic.fulcro.application/keys [runtime-atom] :as app}]
[:com.fulcrologic.fulcro.application/app => ::send-queues]
(let [send-queues (-> runtime-atom deref ::send-queues)
remote-names (app->remote-names app)
new-send-queues (reduce
(fn [new-send-queues remote]
(let [send-queue (get send-queues remote [])
[p serial] (extract-parallel send-queue)
front (first serial)]
;; parallel items are removed from the queues, since they don't block anything
(doseq [item p]
(net-send! app item remote))
;; sequential items are kept in queue to prevent out-of-order operation
(if (::active? front)
(assoc new-send-queues remote serial)
(let [{::keys [send-queue send-node]} (combine-sends app remote serial)]
(when send-node
(net-send! app send-node remote))
(assoc new-send-queues remote send-queue)))))
{}
remote-names)]
(swap! runtime-atom assoc ::send-queues new-send-queues)
new-send-queues))
(>defn tx-node
([tx]
[::tx => ::tx-node]
(tx-node tx {}))
([tx options]
[::tx ::options => ::tx-node]
(let [ast (eql/query->ast tx)
ast-nodes (:children ast)
elements (into []
(comp
(filter (fn txfilt* [n] (= :call (:type n))))
(map-indexed
(fn ->txnode* [idx ast-node]
{::idx idx
::original-ast-node ast-node
::started? #{}
::complete? #{}
::results {}
::dispatch {}})))
ast-nodes)]
{::id (tempid/uuid)
::created (futil/now)
::options options
::tx tx
::elements elements})))
(>defn build-env
([app {::keys [options] :as tx-node} addl]
[:com.fulcrologic.fulcro.application/app ::tx-node map? => map?]
(let [{:keys [ref component]} options]
(cond-> (merge addl {:state (-> app :com.fulcrologic.fulcro.application/state-atom)
:app app})
options (assoc ::options options)
ref (assoc :ref ref)
component (assoc :component component))))
([app {:keys [::options] :as tx-node}]
[:com.fulcrologic.fulcro.application/app ::tx-node => map?]
(build-env app tx-node {})))
(>defn dispatch-elements
"Run through the elements on the given tx-node and do the side-effect-free dispatch. This generates the dispatch map
of things to do on that node."
[tx-node env dispatch-fn]
[::tx-node map? any? => ::tx-node]
(let [do-dispatch (fn run* [env]
(try
(dispatch-fn env)
(catch #?(:clj Exception :cljs :default) e
(log/error e "Dispatch of mutation failed with an exception. No dispatch generated.")
{})))
dispatch (fn dispatch* [{:keys [::original-ast-node] :as ele}]
(let [{:keys [type]} original-ast-node
env (assoc env :ast original-ast-node)]
(cond-> ele
(= :call type) (assoc ::dispatch (do-dispatch env)))))
dispatch-all (fn [eles] (mapv dispatch eles))]
(update tx-node ::elements dispatch-all)))
(>defn activate-submissions!
"Activate all of the transactions that have been submitted since the last activation. After the items are activated
a single processing step will run for the active queue."
[{:keys [:com.fulcrologic.fulcro.application/runtime-atom] :as app}]
[:com.fulcrologic.fulcro.application/app => any?]
(let [dispatched-nodes (mapv #(dispatch-elements % (build-env app %) m/mutate) (::submission-queue @runtime-atom))]
(swap! runtime-atom (fn [a]
(-> a
(update ::active-queue #(reduce conj % dispatched-nodes))
(assoc ::submission-queue []))))
(process-queue! app)))
(>defn schedule-activation!
"Schedule activation of submitted transactions. The default implementation copies all submitted transactions onto
the active queue and immediately does an active queue processing step. If `tm` is not supplied (in ms) it defaults to 10ms."
([app tm]
[:com.fulcrologic.fulcro.application/app int? => any?]
(schedule! app ::activation-scheduled? activate-submissions! tm))
([app]
[:com.fulcrologic.fulcro.application/app => any?]
(schedule-activation! app 10)))
(>defn schedule-queue-processing!
"Schedule a processing of the active queue, which will advance the active transactions by a step.
If `tm` is not supplied (in ms) it defaults to 10ms."
([app tm]
[:com.fulcrologic.fulcro.application/app int? => any?]
(schedule! app ::queue-processing-scheduled? process-queue! tm))
([app]
[:com.fulcrologic.fulcro.application/app => any?]
(schedule-queue-processing! app 10)))
(>defn schedule-sends!
"Schedule actual network activity. If `tm` is not supplied (in ms) it defaults to 0ms."
([app tm]
[:com.fulcrologic.fulcro.application/app int? => any?]
(schedule! app ::sends-scheduled? process-send-queues! tm))
([app]
[:com.fulcrologic.fulcro.application/app => any?]
(schedule-sends! app 0)))
(>defn advance-actions!
"Runs any incomplete and non-blocked optimistic operations on a node."
[app {::keys [id elements] :as node}]
[:com.fulcrologic.fulcro.application/app ::tx-node => ::tx-node]
(let [remotes (app->remote-names app)
reduction (reduce
(fn [{:keys [done? new-elements] :as acc} element]
(if done?
(update acc :new-elements conj element)
(let [{::keys [complete? dispatch original-ast-node idx]} element
{:keys [action]} dispatch
remote-set (set/intersection remotes (set (keys dispatch)))
exec? (and action (not (or done? (complete? :action))))
fully-complete? (and (or exec? (complete? :action)) (empty? (set/difference remote-set complete?)))
state-before (-> app :com.fulcrologic.fulcro.application/state-atom deref)
updated-element (if exec? (-> element
(assoc ::state-before-action state-before)
(update ::complete? conj :action)) element)
done? (not fully-complete?)
new-acc {:done? done?
:new-elements (conj new-elements updated-element)}
env (build-env app node {:ast original-ast-node})]
(when exec?
(try
(when action
(action env))
(catch #?(:cljs :default :clj Exception) e
(log/error e "Failure dispatching optimistic action for AST node" element "of transaction node" node)))
(ilet [tx (eql/ast->query original-ast-node)]
(inspect/optimistic-action-finished! app env {:tx-id (str id "-" idx)
:state-before state-before
:tx tx})))
new-acc)))
{:done? false :new-elements []}
elements)
new-elements (:new-elements reduction)]
(assoc node ::elements new-elements)))
(>defn run-actions!
[app {::keys [id elements] :as node}]
[:com.fulcrologic.fulcro.application/app ::tx-node => ::tx-node]
(let [new-elements (reduce
(fn [new-elements element]
(let [{::keys [idx complete? dispatch original-ast-node]} element
{:keys [action]} dispatch
exec? (and action (not (complete? :action)))
state-before (-> app :com.fulcrologic.fulcro.application/state-atom deref)
updated-node (if exec? (-> element
(assoc ::state-before-action state-before)
(update ::complete? conj :action)) element)
new-acc (conj new-elements updated-node)
env (build-env app node {:ast original-ast-node})]
(when exec?
(try
(action env)
(catch #?(:cljs :default :clj Exception) e
(log/error e "Failure dispatching optimistic action for AST node" element "of transaction node" node)))
(ilet [tx (eql/ast->query original-ast-node)]
(inspect/optimistic-action-finished! app env {:tx-id (str id "-" idx)
:state-before state-before
:tx tx})))
new-acc))
[]
elements)]
(assoc node ::elements new-elements)))
(>defn fully-complete?
[app {:keys [::elements] :as tx-node}]
[:com.fulcrologic.fulcro.application/app ::tx-node => boolean?]
(let [element-complete? (fn [{:keys [::dispatch ::complete?]}]
(let [remotes (app->remote-names app)
active-keys (set/union #{:action} remotes)
desired-set (set/intersection active-keys (set (keys dispatch)))]
(empty? (set/difference desired-set complete?))))]
(every? element-complete? elements)))
(>defn remove-send!
"Removes the send node (if present) from the send queue on the given remote."
[{:com.fulcrologic.fulcro.application/keys [runtime-atom] :as app} remote txn-id ele-idx]
[:com.fulcrologic.fulcro.application/app :com.fulcrologic.fulcro.application/remote-name ::id ::idx => any?]
(let [{:keys [::send-queues]} @runtime-atom
queue (get send-queues remote)
queue (filterv (fn [{:keys [::id ::idx]}]
(not (and (= txn-id id) (= ele-idx idx)))) queue)]
(swap! runtime-atom assoc-in [::send-queues remote] queue)))
(>defn record-result!
"Record a network result on the given txn/element.
If result-key is given it is used, otherwise defaults to ::results. Also removes the network send from the send
queue so that remaining items can proceed, and schedules send processing."
([{:com.fulcrologic.fulcro.application/keys [runtime-atom] :as app} txn-id ele-idx remote result result-key]
[:com.fulcrologic.fulcro.application/app ::id int? keyword? any? keyword? => any?]
(let [active-queue (::active-queue @runtime-atom)
txn-idx (reduce
(fn [idx {:keys [::id]}]
(if (= id txn-id)
(reduced idx)
(inc idx)))
0
active-queue)
not-found? (or (>= txn-idx (count active-queue)) (not= txn-id (::id (get active-queue txn-idx))))]
(if not-found?
(log/error "Network result for" remote "does not have a valid node on the active queue!")
(swap! runtime-atom assoc-in [::active-queue txn-idx ::elements ele-idx result-key remote] result))))
([app txn-id ele-idx remote result]
[:com.fulcrologic.fulcro.application/app ::id int? keyword? any? => any?]
(record-result! app txn-id ele-idx remote result ::results)))
(>defn add-send!
"Generate a new send node and add it to the appropriate send queue. Returns the new send node."
[{:com.fulcrologic.fulcro.application/keys [runtime-atom] :as app} {::keys [id options] :as tx-node} ele-idx remote]
[:com.fulcrologic.fulcro.application/app ::tx-node ::idx :com.fulcrologic.fulcro.application/remote-name
=> (s/nilable ::send-node)]
(let [handler (fn result-handler* [result]
(record-result! app id ele-idx remote result)
(remove-send! app remote id ele-idx)
(schedule-sends! app 1)
(schedule-queue-processing! app 0))
update-handler (fn progress-handler* [result]
(record-result! app id ele-idx remote result ::progress)
(schedule-queue-processing! app 0))
{:keys [::dispatch ::original-ast-node ::state-before-action]} (get-in tx-node [::elements ele-idx])
env (build-env app tx-node {:ast original-ast-node
:state-before-action state-before-action})
remote-fn (get dispatch remote)
remote-desire (when remote-fn (remote-fn env))
ast (cond
(or (false? remote-desire) (nil? remote-desire)) nil
(true? remote-desire) original-ast-node
(and (map? remote-desire) (contains? remote-desire :ast)) (:ast remote-desire)
(and (map? remote-desire) (contains? remote-desire :type)) remote-desire
:else (do
(log/error "Remote dispatch for" remote "returned an invalid value." remote-desire)
remote-desire))
send-node {::id id
::idx ele-idx
::ast ast
::options options
::active? false
::result-handler handler
::update-handler update-handler}]
(if ast
(do
(swap! runtime-atom update-in [::send-queues remote] (fnil conj []) send-node)
send-node)
(do
(handler {:status-code 500 :body "The remote AST was empty!"})
nil))))
(>defn queue-element-sends!
"Queue all (unqueued) remote actions for the given element. Returns the (possibly updated) node."
[app tx-node {:keys [::idx ::dispatch ::started?]}]
[:com.fulcrologic.fulcro.application/app ::tx-node ::tx-element => ::tx-node]
(let [remotes (set/intersection (set (keys dispatch)) (app->remote-names app))
to-dispatch (set/difference remotes started?)]
(reduce
(fn [node remote]
(if (contains? (get-in node [::elements idx ::started?] #{}) remote)
node
(do
(add-send! app node idx remote)
(update-in node [::elements idx ::started?] conj remote))))
tx-node
to-dispatch)))
(>defn idle-node?
"Returns true if the given node has no active network operations."
[{:keys [::elements] :as tx-node}]
[::tx-node => boolean?]
(every?
(fn idle?* [{:keys [::started? ::complete?]}]
(let [in-progress (set/difference started? complete?)]
(empty? in-progress)))
elements))
(>defn element-with-work
"Returns a txnode element iff it has remaining (remote) work that has not been queued. Returns nil if there
is no such element.
remote-names is the set of legal remote names."
[remote-names {:keys [::dispatch ::started?] :as element}]
[:com.fulcrologic.fulcro.application/remote-names ::tx-element => (s/nilable ::tx-element)]
(let [todo (set/intersection remote-names (set (keys dispatch)))
remaining (set/difference todo started?)]
(when (seq remaining)
element)))
(>defn queue-next-send!
"Assumes tx-node is to be processed pessimistically. Queues the next send if the node is currently idle
on the network and there are any sends left to do. Adds to the send queue, and returns the updated
tx-node."
[app {:keys [::elements] :as tx-node}]
[:com.fulcrologic.fulcro.application/app ::tx-node => ::tx-node]
(if (idle-node? tx-node)
(let [remotes (app->remote-names app)
with-work (partial element-with-work remotes)
element (some with-work elements)]
(if element
(queue-element-sends! app tx-node element)
tx-node))
tx-node))
(>defn queue-sends!
"Finds any item(s) on the given node that are ready to be placed on the network queues and adds them. Non-optimistic
multi-element nodes will only queue one remote operation at a time."
[app {:keys [::options ::elements] :as tx-node}]
[:com.fulcrologic.fulcro.application/app ::tx-node => ::tx-node]
(let [optimistic? (boolean (:optimistic? options))]
(schedule-sends! app 0)
(if optimistic?
(reduce
(fn [node element]
(queue-element-sends! app node element))
tx-node
elements)
(queue-next-send! app tx-node))))
(>defn dispatch-result!
"Figure out the dispatch routine to trigger for the given network result. If it exists, send the result
to it.
Returns the tx-element with the remote marked complete."
[app tx-node {:keys [::results ::dispatch ::original-ast-node] :as tx-element} remote]
[:com.fulcrologic.fulcro.application/app ::tx-node ::tx-element keyword? => ::tx-element]
(schedule-queue-processing! app 0)
(let [result (get results remote)
handler (get dispatch :result-action)]
(when handler
(let [env (build-env app tx-node {:dispatch dispatch :result result})]
(try
(handler env)
(catch #?(:cljs :default :clj Exception) e
(log/error e "The result-action mutation handler for mutation" (:dispatch-key original-ast-node) "threw an exception."))))))
(update tx-element ::complete? conj remote))
(>defn distribute-element-results!
"Distribute results and mark the remotes for those elements as complete."
[app tx-node {:keys [::results ::complete?] :as tx-element}]
[:com.fulcrologic.fulcro.application/app ::tx-node ::tx-element => ::tx-element]
(reduce
(fn [new-element remote]
(if (complete? remote)
new-element
(dispatch-result! app tx-node new-element remote)))
tx-element
(keys results)))
(>defn distribute-results!
"Walk all elements of the tx-node and call result dispatch handlers for any results that have
not been distributed."
[app {:keys [::elements] :as tx-node}]
[:com.fulcrologic.fulcro.application/app ::tx-node => ::tx-node]
(assoc tx-node
::elements (mapv
(fn [element] (distribute-element-results! app tx-node element))
elements)))
(>defn update-progress!
"Report all progress items to any registered progress dispatch and clear them from the tx-node.
Returns the updated tx-node."
[app {:keys [::elements] :as tx-node}]
[:com.fulcrologic.fulcro.application/app ::tx-node => ::tx-node]
(let [get-env (fn get-env* [remote progress] (build-env app tx-node {:remote remote :progress progress}))]
(reduce
(fn [node {:keys [::idx ::progress ::dispatch] :as element}]
(doseq [[remote value] progress]
(let [env (get-env remote value)
action (get dispatch :progress-action)]
(when action
(try
(action env)
(catch #?(:cljs :default :clj Exception) e
(log/error e "Progress action threw an exception for txn element" element))))))
(update-in node [::elements idx] dissoc ::progress))
tx-node
elements)))
(>defn process-tx-node!
[app {:keys [::options] :as tx-node}]
[:com.fulcrologic.fulcro.application/app ::tx-node => (s/nilable ::tx-node)]
(let [optimistic? (boolean (:optimistic? options))]
(if (fully-complete? app tx-node)
nil
(-> tx-node
(cond->>
optimistic? (run-actions! app)
(not optimistic?) (advance-actions! app))
(->>
(queue-sends! app)
(update-progress! app)
(distribute-results! app))))))
(>defn requested-refreshes [app queue]
[:com.fulcrologic.fulcro.application/app (s/coll-of ::tx-node) => set?]
"Returns a set of refreshes that have been requested by active mutations in the queue"
(reduce
(fn [outer-acc tx-node]
(let [env (build-env app tx-node)]
(reduce
(fn [acc element]
(let [{::keys [dispatch]} element
refresh (:refresh dispatch)]
(if refresh
(into acc (set (refresh env)))
acc)))
outer-acc
(::elements tx-node))))
#{}
queue))
(>defn remotes-active-on-node
"Given a tx node and the set of legal remotes: returns a set of remotes that are active on that node."
[{::keys [elements] :as tx-node} remotes]
[::tx-node :com.fulcrologic.fulcro.application/remote-names
=> :com.fulcrologic.fulcro.application/remote-names]
(let [active-on-element (fn [{::keys [dispatch complete?]}]
(let [remotes (set remotes)]
(-> remotes
(set/intersection (set (keys dispatch)))
(set/difference complete?))))]
(reduce
(fn [acc ele]
(set/union acc (active-on-element ele)))
#{}
elements)))
(>defn active-remotes
"Calculate which remotes still have network activity to do on the given active queue."
[queue remotes]
[::active-queue :com.fulcrologic.fulcro.application/remote-names
=> :com.fulcrologic.fulcro.application/active-remotes]
(reduce
(fn [ra n]
(set/union ra (remotes-active-on-node n remotes)))
#{}
queue))
(>defn process-queue!
"Run through the active queue and do a processing step."
[{:com.fulcrologic.fulcro.application/keys [state-atom runtime-atom] :as app}]
[:com.fulcrologic.fulcro.application/app => any?]
(let [new-queue (reduce
(fn *pstep [new-queue n]
(if-let [new-node (process-tx-node! app n)]
(conj new-queue new-node)
new-queue))
[]
(::active-queue @runtime-atom))
accumulate (fn [r items] (into (set r) items))
remotes (app->remote-names app)
schedule-render! (ah/app-algorithm app :schedule-render!)
explicit-refresh (requested-refreshes app new-queue)
remotes-active? (active-remotes new-queue remotes)]
(swap! state-atom assoc :com.fulcrologic.fulcro.application/active-remotes remotes-active?)
(swap! runtime-atom assoc ::active-queue new-queue)
(when (seq explicit-refresh)
(swap! runtime-atom update :com.fulcrologic.fulcro.application/to-refresh accumulate explicit-refresh))
(schedule-render! app)
nil))