aboutsummaryrefslogtreecommitdiff
path: root/src/core/clojure/src/mediator.clj
blob: 75d81faba636c9f1030a30b4335085d7b2f478c9 (plain) (blame)
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
(ns mediator
  (:require [clojure.spec.alpha :as s]
            [clojure.test :as t]
            [clojure.spec.gen.alpha :as gen]
            [clojure.spec.test.alpha :as stest]
            [clojure.tools.cli :as cli]
            [clojure.edn :as edn]
            [clojure.string :as str]
            [clojure.set :as set]
            [clojure.pprint :as pprint]))

(comment
  (require '[puget.printer])

  (defn tap
    [sexp]
    (puget.printer/cprint sexp)
    sexp)

  (def db
    (edn/read-string (slurp "test/fixtures/minimalistic-timelines.edn"))))

(defn
  ^{:test
    #(assert (= :v
                (third [:e :a :v :t :o])))}
  third
  "Same as functions first and second, useful for
   fetching the positional Value (as in EAVT) datoms."
  [coll]
  (nth coll 2))

(s/check-asserts true)

(s/def :db/ident
  (s/and keyword? namespace))

(s/def :db/value-type
  #{:db.type/keyword :db.type/symbol
    :db.type/string  :db.type/boolean
    :db.type/long    :db.type/bigint
    :db.type/float   :db.type/double
    :db.type/bigdec  :db.type/ref
    :db.type/instant :db.type/uuid
    :db.type/uri     :db.type/bytes})

(s/def :db/cardinality
  #{:db.cardinality/one :db.cardinality/many})

(s/def :db/doc string?)
(s/def :db/unique #{:db.unique/value :db.unique/identity})
(s/def :db/index boolean?)
(s/def :db/fulltext boolean?)
(s/def :db/is-component boolean?)

(s/def ::schema
  (s/keys :req #{:db/ident
                 :db/value-type
                 :db/cardinality}
          :opt #{:db/doc
                 :db/unique
                 :db/index
                 :db/fulltext
                 :db/is-component}))

(defn predicate-fn
  [class]
  #(= (type %) class))

(s/fdef predicate-fn
  :args (s/cat :class #(= (type %) java.lang.Class))
  :ret boolean?)

(s/def :db.type/keyword keyword?)
(s/def :db.type/symbol symbol?)
(s/def :db.type/string string?)
(s/def :db.type/boolean boolean?)
(s/def :db.type/long (predicate-fn java.lang.Long))
(s/def :db.type/bigint (predicate-fn java.math.BigInteger))
(s/def :db.type/float (predicate-fn java.lang.Float))
(s/def :db.type/double (predicate-fn java.lang.Double))
(s/def :db.type/bigdec (predicate-fn java.math.BigDecimal))
(s/def :db.type/ref (s/or :uuid uuid?
                          :symbol symbol?))
(s/def :db.type/instant (predicate-fn java.time.Instant))
(s/def :db.type/uuid uuid?)
(s/def :db.type/uri (predicate-fn java.net.URI))
(s/def :db.type/bytes bytes?)
(s/def :db/parent :db.type/ref)
(s/def :db/timeline :db.type/ref)

(def built-in-cardinality
  #:db{:value-type  :db.cardinality/one
       :ident       :db.cardinality/one
       :cardinality :db.cardinality/one

       :timeline :db.cardinality/one
       :parent   :db.cardinality/many})

(def built-in-value-type
  #:db{:value-type  :db.type/keyword
       :ident       :db.type/keyword
       :cardinality :db.type/keyword

       :timeline :db.type/ref
       :parent   :db.type/ref})

(defn expand-entity-to-datoms
  [{:db/keys [id] :as entity} e tx]
  (map (fn [[a v]]
         [(or id e) a v tx true])
       entity))

(defn expand-transaction-data
  [current-tx parent-tx timeline-id ids->entities]
  (let [entities-datoms (reduce (fn [acc [eid entity]]
                                  (conj acc
                                        (expand-entity-to-datoms entity eid current-tx)))
                                []
                                ids->entities)]
    (into #{}
          (concat
           (apply concat entities-datoms)
           [[current-tx :db/parent parent-tx current-tx true]
            [current-tx :db/timeline timeline-id current-tx true]]))))

(do
(defn add-tx->timeline-id
  [{:keys [datoms] :as index}]
  (->> datoms
       (filter #(= (% 1) :db/timeline))
       (map (juxt first third))
       (into {})
       (assoc-in index [:idxs :tx->timeline-id])))

(defn add-timeline-id->txs
  [index]
  (->> (get-in index [:idxs :tx->timeline-id])
       (reduce (fn [acc [tx timeline-id]]
                 (update acc timeline-id (fnil conj #{}) tx))
               {})
       (assoc-in index [:idxs :timeline-id->txs])))

(defn add-tx->parent-txs
  [{:keys [datoms] :as index}]
  (->> datoms
       (filter #(= (% 1) :db/parent))
       (map (juxt first third))
       (group-by first)
       (map (fn [[tx parent-pairs]]
              [tx (set (map second parent-pairs))]))
       (into {})
       (assoc-in index [:idxs :tx->parent-txs])))

(defn add-tx->children-tx-by-timeline
  [index]
  (->> (get-in index [:idxs :tx->parent-txs])
       (reduce (fn [acc [child parents]]
                 (let [timeline-id (get-in index [:idxs :tx->timeline-id child])]
                   (reduce (fn [child-acc parent]
                             (assoc-in acc [parent timeline-id] child))
                           {}
                           parents)))
               {})
       (assoc-in index [:idxs :tx->children-tx-by-timeline])))

(defn add-tx->datoms
  [{:keys [datoms] :as index}]
  (->> datoms
       (reduce (fn [acc [_e _a _v t _o :as datom]]
                 (update acc t (fnil conj #{}) datom))
               {})
       (assoc-in index [:idxs :tx->datoms])))

(defn add-timeline-ids
  [index]
  (assoc index
    :timeline-ids (set (vals (get-in index [:idxs :tx->timeline-id])))))

(defn parent-tx-for-timeline-id
  [index tx timeline-id]
  (let [parents (get-in index [:idxs :tx->parent-txs tx])]
    (first
     (filter #(= timeline-id
                 (get-in index [:idxs :tx->timeline-id %]))
             parents))))

(defn root-tx-for-timeline-id
  ([index timeline-id]
   (let [some-tx (-> index :idxs :timeline-id->txs timeline-id first)]
     (root-tx-for-timeline-id index some-tx timeline-id)))
  ([index tx timeline-id]
   (if-let [parent-tx (parent-tx-for-timeline-id index tx timeline-id)]
     (root-tx-for-timeline-id index parent-tx timeline-id)
     tx)))

(defn child-tx-for-timeline-id
  [index tx timeline-id]
  (get-in index [:idxs :tx->children-tx-by-timeline tx timeline-id]))

(defn leaf-tx-for-timeline-id
  ([index timeline-id]
   (let [some-tx (-> index :idxs :timeline-id->txs timeline-id first)]
     (leaf-tx-for-timeline-id index some-tx timeline-id)))
  ([index tx timeline-id]
   (if-let [child-tx (child-tx-for-timeline-id index tx timeline-id)]
     (leaf-tx-for-timeline-id index child-tx timeline-id)
     tx)))

(defn add-timeline-id->edge-txs
  [{:keys [timeline-ids] :as index}]
  (->> timeline-ids
       (reduce (fn [acc timeline-id]
                 (assoc acc
                   timeline-id
                   {:root (root-tx-for-timeline-id index timeline-id)
                    :leaf (leaf-tx-for-timeline-id index timeline-id)}))
               {})
       (assoc-in index [:idxs :timeline-id->edge-txs])))

(defn add-root-txs
  [index]
  (let [txs-index (get-in index [:idxs :tx->parent-txs])]
    (assoc index
      :root-txs
      (set/difference (reduce set/union (vals txs-index))
                      (set (keys txs-index))))))

(defn add-root-timeline-ids
  [index]
  (assoc index
    :root-timeline-ids (into #{}
                             (map #(get-in index [:idxs :tx->timeline-id %])
                                  (get-in index [:root-txs])))))

(defn add-timeline-id->source-tx
  [{:keys [timeline-ids root-timeline-ids] :as index}]
  (->> timeline-ids
       (reduce
        (fn [acc timeline-id]
          (if (root-timeline-ids timeline-id)
            acc
            (let [tx     (get-in index [:idxs :timeline-id->edge-txs timeline-id :root])
                  source (-> index :idxs :tx->parent-txs tx first)]
              (assoc acc
                timeline-id source))))
        {})
       (assoc-in index [:idxs :timeline-id->source-tx])))

(defn add-attr->x-fn
  [attribute-name built-in-attr-map index-entry-name]
  (fn [{:keys [datoms] :as index}]
    (->> datoms
         (filter #(= (% 1) attribute-name))
         (map (juxt first third))
         (map (fn [[entity-id cardinality]]
                (let [[_e _a v _t _o] (first
                                       (filter #(and (= (% 0) entity-id)
                                                     (= (% 1) :db/ident))
                                               datoms))]
                  [v cardinality])))
         (into {})
         (merge built-in-attr-map)
         (assoc-in index [:schemas index-entry-name]))))

(def add-attr->cardinality
  (add-attr->x-fn :db/cardinality built-in-cardinality :attr->cardinality))
(def add-attr->value-type
  (add-attr->x-fn :db/value-type built-in-value-type :attr->value-type))

(defn bundle-datoms-into-entities
  [datoms entities attribute->cardinality]
  (reduce (fn [acc [e a v _t o]]
            (case (attribute->cardinality a)
              :db.cardinality/one
              (if o
                (assoc-in acc [e a] v)
                (update acc e dissoc a))

              :db.cardinality/many
              (if o
                (update-in acc [e a] (fnil conj #{}) v)
                ;; assumption: no retractions before assertions
                (update-in acc [e a] disj v))))
          entities
          datoms))

(defn eavt-for-tx
  [index tx]
  (let [parent-eavts (->> (get-in index [:idxs :tx->parent-txs tx])
                          (map (juxt identity (partial eavt-for-tx index)))
                          (into {}))]
    (bundle-datoms-into-entities (get-in index [:idxs :tx->datoms tx])
                                 ;; assumption: a single tx never has conflicts
                                 ;; (apply merge-with merge parent-eavts)
                                 {}
                                 (get-in index [:schemas :attribute->cardinality]))))

(defn add-eavt-as-of-tx
  [index]
  (let [noteworthy-txs (->> index
                            :idxs
                            :timeline-id->edge-txs
                            vals
                            (map :leaf))]
    (->> noteworthy-txs
         (reduce (fn [acc tx]
                   (assoc acc
                     tx (eavt-for-tx index tx)))
                 {})
         (assoc-in index [:idxs :eavt-as-of-tx]))))

(defn index-database
  [database]
  (-> {:datoms database}
      add-tx->timeline-id
      add-timeline-id->txs
      add-tx->parent-txs
      add-tx->children-tx-by-timeline
      add-tx->datoms
      add-timeline-ids
      add-timeline-id->edge-txs
      add-root-txs
      add-root-timeline-ids
      add-timeline-id->source-tx
      add-attr->cardinality
      add-attr->value-type
      #_
      add-eavt-as-of-tx))

#_
(index-database db))

(defn enforce-schema
  ([database]
   (enforce-schema database (index-database database)))
  ([database {{:keys [attr->value-type]} :schemas :as index}]
   (doseq [[_e a v _t _o] database]
     (let [attribute-type (attr->value-type a)]
       (when-not attribute-type
         (throw (ex-info "Unknown attribute"
                         {:attribute a})))
       (when-not (s/valid? (s/spec attribute-type) v)
         (throw (ex-info "Attribute with invalid schema"
                         {:attribute a
                          :value     v})))))
   database))

(defn grow-database
  [database new-tx timeline-id ids->entities]
  (let [index   (index-database database)
        leaf-tx (leaf-tx-for-timeline-id index timeline-id)]
    (enforce-schema
     (set/union (enforce-schema database index)
                (expand-transaction-data new-tx
                                         leaf-tx
                                         timeline-id
                                         ids->entities)))))

(defn transact!
  [database timeline-id data]
  (grow-database database
                 (java.util.UUID/randomUUID)
                 timeline-id
                 (into {}
                       (map (fn [{:db/keys [id] :as e}]
                              [(or id (java.util.UUID/randomUUID)) e])
                            data))))

(defn query
  [])

(defn run-shell
  [edn-filename action]
  (let [database             (edn/read-string (slurp edn-filename))
        [command & args] (str/split action #"\s")
        args-str (str/join " " args)]
    (case command
      ".tx" (let [new-db (apply transact!
                                database
                                (with-in-str args-str
                                  [(edn/read *in*)
                                   (edn/read *in*)]))]
              (binding [pprint/*print-right-margin* 180]
                (pprint/pprint new-db)))
      ".query" (query))))

(defn -main [& args]
  (let [{:keys [arguments]} (cli/parse-opts args [])
        [subcommand & sub-arguments] arguments]
    (case subcommand
      "shell" (apply run-shell sub-arguments))))