-
Notifications
You must be signed in to change notification settings - Fork 61
/
core.cljc
541 lines (462 loc) · 18.9 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
(ns integrant.core
(:refer-clojure :exclude [ref read-string run!])
(:require #?(:clj [clojure.edn :as edn]
:cljs [clojure.tools.reader.edn :as edn])
[clojure.walk :as walk]
[clojure.set :as set]
[clojure.string :as str]
[weavejester.dependency :as dep]))
(defprotocol RefLike
(ref-key [r] "Return the key of the reference.")
(ref-resolve [r config resolvef] "Return the resolved value."))
(defonce
^{:doc "Return a unique keyword that is derived from an ordered collection of
keywords. The function will return the same keyword for the same collection."
:arglists '([kws])}
composite-keyword
(memoize
(fn [kws]
(let [parts (for [kw kws] (str (namespace kw) "." (name kw)))
prefix (str (str/join "+" parts) "_")
composite (keyword "integrant.composite" (str (gensym prefix)))]
(doseq [kw kws] (derive composite kw))
composite))))
(defn- invalid-ref-exception [ref]
(ex-info (str "Invalid reference: " ref ". Must be a qualified keyword or a "
"vector of qualified keywords.")
{:reason ::invalid-ref, :ref ref}))
(defn- composite-key? [keys]
(and (vector? keys) (every? qualified-keyword? keys)))
(defn valid-config-key?
"Return true if the key is a keyword or valid composite key."
[key]
(or (qualified-keyword? key) (composite-key? key)))
(defn normalize-key
"Given a valid Integrant key, return a keyword that uniquely identifies it."
[key]
{:pre [(valid-config-key? key)]}
(if (composite-key? key) (composite-keyword key) key))
(defn derived-from?
"Return true if a key is derived from candidate keyword or vector of
keywords."
[key candidate]
(let [key (normalize-key key)]
(if (vector? candidate)
(every? #(isa? key %) candidate)
(isa? key candidate))))
(defn find-derived
"Return a seq of all entries in a map, m, where the key is derived from the
a candidate key, k. If there are no matching keys, nil is returned. The
candidate key may be a keyword, or vector of keywords."
[m k]
(seq (filter #(or (= (key %) k) (derived-from? (key %) k)) m)))
(defrecord Ref [key]
RefLike
(ref-key [_] key)
(ref-resolve [_ config resolvef]
(let [[k v] (first (find-derived config key))]
(resolvef k v))))
(defrecord RefSet [key]
RefLike
(ref-key [_] key)
(ref-resolve [_ config resolvef]
(set (for [[k v] (find-derived config key)]
(resolvef k v)))))
(defn ref
"Create a reference to a top-level key in a config map."
[key]
(when-not (valid-config-key? key)
(throw (invalid-ref-exception key)))
(->Ref key))
(defn refset
"Create a set of references to all matching top-level keys in a config map."
[key]
(when-not (valid-config-key? key)
(throw (invalid-ref-exception key)))
(->RefSet key))
(defn ref?
"Return true if its argument is a ref."
[x]
(instance? Ref x))
(defn refset?
"Return true if its argument is a refset."
[x]
(instance? RefSet x))
(defn reflike?
"Return true if its argument is a ref or a refset."
[x]
(satisfies? RefLike x))
(defn- depth-search [pred? coll]
(filter pred? (tree-seq coll? seq coll)))
(defn- ambiguous-key-exception [config key matching-keys]
(ex-info (str "Ambiguous key: " key ". Found multiple candidates: "
(str/join ", " matching-keys))
{:reason ::ambiguous-key
:config config
:key key
:matching-keys matching-keys}))
(defn find-derived-1
"Return the map entry in a map, m, where the key is derived from the keyword,
k. If there are no matching keys, nil is returned. If there is more than one
matching key, an ambiguous key exception is raised."
[m k]
(let [kvs (find-derived m k)]
(when (next kvs)
(throw (ambiguous-key-exception m k (map key kvs))))
(first kvs)))
(defn- find-derived-refs [config v include-refsets?]
(->> (depth-search (if include-refsets? reflike? ref?) v)
(map ref-key)
(mapcat #(map key (find-derived config %)))))
(defn dependency-graph
"Return a dependency graph of all the refs and refsets in a config. Resolves
derived dependencies. Takes the following options:
`:include-refsets?`
: whether to include refsets in the dependency graph (defaults to true)"
([config]
(dependency-graph config {}))
([config {:keys [include-refsets?] :or {include-refsets? true}}]
(letfn [(find-refs [v]
(find-derived-refs config v include-refsets?))]
(reduce-kv (fn [g k v] (reduce #(dep/depend %1 k %2) g (find-refs v)))
(dep/graph)
config))))
(defn key-comparator
"Create a key comparator from the dependency graph of a configuration map.
The comparator is deterministic; it will always result in the same key
order."
[graph]
(dep/topo-comparator #(compare (str %1) (str %2)) graph))
(defn- find-keys [config keys f]
(let [graph (dependency-graph config {:include-refsets? false})
keyset (set (mapcat #(map key (find-derived config %)) keys))]
(->> (f graph keyset)
(set/union keyset)
(sort (key-comparator (dependency-graph config))))))
(defn- dependent-keys [config keys]
(find-keys config keys dep/transitive-dependencies-set))
(defn- reverse-dependent-keys [config keys]
(reverse (find-keys config keys dep/transitive-dependents-set)))
(def ^:private default-readers {'ig/ref ref, 'ig/refset refset})
(defn read-string
"Read a config from a string of edn. Refs may be denotied by tagging keywords
with #ig/ref."
([s]
(read-string {:eof nil} s))
([opts s]
(let [readers (merge default-readers (:readers opts {}))]
(edn/read-string (assoc opts :readers readers) s))))
#?(:clj
(defn- keyword->namespaces [kw]
(when-let [ns (namespace kw)]
[(symbol ns)
(symbol (str ns "." (name kw)))])))
#?(:clj
(defn- key->namespaces [k]
(if (vector? k)
(mapcat keyword->namespaces k)
(keyword->namespaces k))))
#?(:clj
(defn- try-require [sym]
(try (do (require sym) sym)
(catch java.io.FileNotFoundException _))))
#?(:clj
(defn load-namespaces
"Attempt to load the namespaces referenced by the keys in a configuration.
If a key is namespaced, both the namespace and the namespace concatenated
with the name will be tried. For example, if a key is :foo.bar/baz, then the
function will attempt to load the namespaces foo.bar and foo.bar.baz. Upon
completion, a list of all loaded namespaces will be returned."
([config]
(load-namespaces config (keys config)))
([config keys]
(doall (->> (dependent-keys config keys)
(mapcat #(conj (ancestors %) %))
(mapcat key->namespaces)
(distinct)
(keep try-require))))))
(defn- missing-refs-exception [config refs]
(ex-info (str "Missing definitions for refs: " (str/join ", " refs))
{:reason ::missing-refs
:config config
:missing-refs refs}))
(defn- ambiguous-refs [config]
(->> (depth-search ref? config)
(map ref-key)
(filter #(next (find-derived config %)))))
(defn- missing-refs [config]
(->> (depth-search ref? config)
(map ref-key)
(remove #(find-derived config %))))
(defn- invalid-composite-keys [config]
(->> (keys config) (filter vector?) (remove composite-key?)))
(defn- invalid-composite-key-exception [config key]
(ex-info (str "Invalid composite key: " key ". "
"Every keyword must be namespaced.")
{:reason ::invalid-composite-key
:config config
:key key}))
(defn- resolve-refs [config resolvef value]
(walk/postwalk
#(if (reflike? %) (ref-resolve % config resolvef) %)
value))
(defn- run-exception [system completed remaining f k v t]
(ex-info (str "Error on key " k " when running system")
{:reason ::run-threw-exception
:system system
:completed-keys (reverse completed)
:remaining-keys (rest remaining)
:function f
:key k
:value v}
t))
(defn- try-run-action [system completed remaining f k]
(let [v (system k)]
(try (f k v)
(catch #?(:clj Throwable :cljs :default) t
(throw (run-exception system completed remaining f k v t))))))
(defn- run-loop [system keys f]
(loop [completed (), remaining keys]
(when (seq remaining)
(let [k (first remaining)]
(try-run-action system completed remaining f k)
(recur (cons k completed) (rest remaining))))))
(defn- system-origin [system]
(-> system meta ::origin (select-keys (keys system))))
(defn run!
"Apply a side-effectful function f to each key value pair in a system map.
Keys are traversed in dependency order. The function should take two
arguments, a key and value."
[system keys f]
{:pre [(map? system) (some-> system meta ::origin)]}
(run-loop system (dependent-keys (system-origin system) keys) f))
(defn reverse-run!
"Apply a side-effectful function f to each key value pair in a system map.
Keys are traversed in reverse dependency order. The function should take two
arguments, a key and value."
[system keys f]
{:pre [(map? system) (some-> system meta ::origin)]}
(run-loop system (reverse-dependent-keys (system-origin system) keys) f))
(defn fold
"Reduce all the key value pairs in system map in dependency order, starting
from an initial value. The function should take three arguments: the
accumulator, the current key and the current value."
[system f val]
(let [graph (dependency-graph (system-origin system))]
(->> (keys system)
(sort (key-comparator graph))
(reduce #(f %1 %2 (system %2)) val))))
(defn- build-exception [system f k v t]
(ex-info (str "Error on key " k " when building system")
{:reason ::build-threw-exception
:system system
:function f
:key k
:value v}
t))
(defn- try-build-action [system f k v]
(try (f k v)
(catch #?(:clj Throwable :cljs :default) t
(throw (build-exception system f k v t)))))
(defn- build-key [f assertf resolvef system [k v]]
(let [v' (resolve-refs system resolvef v)]
(assertf system k v')
(-> system
(assoc k (try-build-action system f k v'))
(vary-meta assoc-in [::build k] v'))))
(defn build
"Apply a function f to each key value pair in a configuration map. Keys are
traversed in dependency order, and any references in the value expanded. The
function should take two arguments, a key and value, and return a new value.
An optional fourth argument, assertf, may be supplied to provide an assertion
check on the system, key and expanded value."
([config keys f]
(build config keys f (fn [_ _ _])))
([config keys f assertf]
(build config keys f assertf (fn [_ v] v)))
([config keys f assertf resolvef]
{:pre [(map? config)]}
(let [relevant-keys (dependent-keys config keys)
relevant-config (select-keys config relevant-keys)]
(when-let [invalid-key (first (invalid-composite-keys config))]
(throw (invalid-composite-key-exception config invalid-key)))
(when-let [ref (first (ambiguous-refs relevant-config))]
(throw (ambiguous-key-exception config ref
(map key (find-derived config ref)))))
(when-let [refs (seq (missing-refs relevant-config))]
(throw (missing-refs-exception config refs)))
(reduce (partial build-key f assertf resolvef)
(with-meta {} {::origin config})
(map (fn [k] [k (config k)]) relevant-keys)))))
(defmulti resolve-key
"Return a value to substitute for a reference prior to initiation. By default
the value of the key is returned unaltered. This can be used to hide
information that is only necessary to halt or suspend the key."
{:arglists '([key value])}
(fn [key _value] (normalize-key key)))
(defmethod resolve-key :default [_ v] v)
(defmulti prep-key
"Prepare the configuration associated with a key for initiation. This is
generally used to add in default values and references. By default the
method returns the value unaltered."
{:arglists '([key value])}
(fn [key _value] (normalize-key key)))
(defmethod prep-key :default [_ v] v)
(defmulti expand-key
"Expand a config value into a map that is then merged back into the config.
Defaults to returning a map `{key value}`. See: [[expand]]."
{:arglists '([key value])}
(fn [key _value] (normalize-key key)))
(defmethod expand-key :default [k v] {k v})
(defmulti init-key
"Turn a config value associated with a key into a concrete implementation.
For example, a database URL might be turned into a database connection."
{:arglists '([key value])}
(fn [key _value] (normalize-key key)))
(defmulti halt-key!
"Halt a running or suspended implementation associated with a key. This is
often used for stopping processes or cleaning up resources. For example, a
database connection might be closed. This multimethod must be idempotent.
The return value of this multimethod is discarded."
{:arglists '([key value])}
(fn [key _value] (normalize-key key)))
(defmethod halt-key! :default [_ _])
(defmulti resume-key
"Turn a config value associated with a key into a concrete implementation,
but reuse resources (e.g. connections, running threads, etc) from an existing
implementation. By default this multimethod calls init-key and ignores the
additional argument."
{:arglists '([key value old-value old-impl])}
(fn [key _value _old-value _old-impl] (normalize-key key)))
(defmethod resume-key :default [k v _ _]
(init-key k v))
(defmulti suspend-key!
"Suspend a running implementation associated with a key, so that it may be
eventually passed to resume-key. By default this multimethod calls halt-key!,
but it may be customized to do things like keep a server running, but buffer
incoming requests until the server is resumed."
{:arglists '([key value])}
(fn [key _value] (normalize-key key)))
(defmethod suspend-key! :default [k v]
(halt-key! k v))
(defmulti assert-key
"Check that the value of a key is correct immediately before the key is
initiated. If the value is incorrect, an appropriate exception should
be thrown."
{:arglists '([key value])}
(fn [key _value] (normalize-key key)))
(defmethod assert-key :default [_ _])
(defn- wrap-assert-exception [ex system key value]
(ex-info (str "Assertion failed on key " key " when building system")
{:reason ::build-failed-spec
:system system
:key key
:value value}
ex))
(defn- wrapped-assert-key [system key value]
(try (assert-key key value)
(catch #?(:clj Throwable :cljs :default) err
(throw (wrap-assert-exception err system key value)))))
(defn prep
"Prepare a config map for initiation. The prep-key method is applied to each
entry in the map, and the values replaced with the return value. This is used
for adding default values and references to the configuration."
([config]
(prep config (keys config)))
([config keys]
{:pre [(map? config)]}
(let [keyset (set keys)]
(reduce-kv (fn [m k v] (assoc m k (if (keyset k) (prep-key k v) v)))
{} config))))
(defn- expansions [[k v]]
(letfn [(generate-expansions [idx [kn vn]]
(if (map? vn)
(mapcat #(generate-expansions (conj idx kn) %) vn)
(list {:key k, :index (conj idx kn), :value vn})))]
(mapcat #(generate-expansions [] %)
(expand-key k v))))
(defn- override-expansion? [{key :key, [i0] :index}]
(= key i0))
(defn- conflicting-expansions [expansions]
(->> expansions
(group-by :index)
(vals)
(filter #(> (count %) 1))))
(defn- conflicting-expands-exception [config expansions]
(let [index (-> expansions first :index)
keys (map :key expansions)]
(ex-info (str "Conflicting index " index " for expansions: "
(str/join ", " keys))
{:reason ::conflicting-expands
:config config
:conflicting-index index
:expand-keys keys})))
(defn- apply-expansion [config {:keys [index value]}]
(assoc-in config index value))
(defn expand
"Expand modules in the config map prior to initiation. The expand-key method
is applied to each entry in the map, and the results merged together to
produce a new configuration.
When merging, nested maps will also be merged. Conflicts between merged keys
will generate an error, except when the config key matches the expansion key;
in that case, the value will be overwritten instead."
([config]
(expand config (keys config)))
([config keys]
{:pre [(map? config)]}
(let [expansions (mapcat expansions (select-keys config keys))
overrides (filter override-expansion? expansions)
override-idxs (set (map :index overrides))
non-overrides (remove (comp override-idxs :index) expansions)]
(when-let [conflict (first (conflicting-expansions non-overrides))]
(throw (conflicting-expands-exception config conflict)))
(reduce apply-expansion
(apply dissoc config keys)
(concat non-overrides overrides)))))
(defn init
"Turn a config map into an system map. Keys are traversed in dependency
order, initiated via the init-key multimethod, then the refs associated with
the key are resolved."
([config]
(init config (keys config)))
([config keys]
{:pre [(map? config)]}
(build config keys init-key wrapped-assert-key resolve-key)))
(defn halt!
"Halt a system map by applying halt-key! in reverse dependency order."
([system]
(halt! system (keys system)))
([system keys]
{:pre [(map? system) (some-> system meta ::origin)]}
(reverse-run! system keys halt-key!)))
(defn- missing-keys [system ks]
(remove (set ks) (keys system)))
(defn- halt-missing-keys! [config system keys]
(let [graph (-> system meta ::origin dependency-graph)
missing-keys (missing-keys system (dependent-keys config keys))]
(doseq [k (sort (key-comparator graph) missing-keys)]
(halt-key! k (system k)))))
(defn resume
"Turn a config map into a system map, reusing resources from an existing
system when it's possible to do so. Keys are traversed in dependency order,
resumed with the resume-key multimethod, then the refs associated with the
key are resolved."
([config system]
(resume config system (keys config)))
([config system keys]
{:pre [(map? config) (map? system) (some-> system meta ::origin)]}
(halt-missing-keys! config system keys)
(build config keys
(fn [k v]
(if (contains? system k)
(resume-key k v (-> system meta ::build (get k)) (system k))
(init-key k v)))
wrapped-assert-key
resolve-key)))
(defn suspend!
"Suspend a system map by applying suspend-key! in reverse dependency order."
([system]
(suspend! system (keys system)))
([system keys]
{:pre [(map? system) (some-> system meta ::origin)]}
(reverse-run! system keys suspend-key!)))