aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/control/concurrency/stm.lux
blob: 8b26eb6997792144c3449e6172f1df1567b75218 (plain)
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
(.module:
  [lux #*
   [control
    [functor (#+ Functor)]
    [apply (#+ Apply)]
    ["." monad (#+ do Monad)]]
   ["." io (#+ IO io)]
   [data
    ["." product]
    ["." maybe]
    [collection
     ["." list]]]
   [type
    abstract]]
  [//
   ["." atom (#+ Atom atom)]
   ["." promise (#+ Promise Resolver)]
   ["." frp ("#/." functor)]])

(type: #export (Observer a)
  (-> a (IO Any)))

(abstract: #export (Var a)
  {#.doc "A mutable cell containing a value, and observers that will be alerted of any change to it."}

  (Atom [a (List (Observer a))])

  (def: #export (var value)
    {#.doc "Creates a new STM var, with a default value."}
    (All [a] (-> a (Var a)))
    (:abstraction (atom.atom [value (list)])))

  (def: read!!
    (All [a] (-> (Var a) a))
    (|>> :representation atom.read io.run product.left))

  (def: #export (read! (^:representation var))
    {#.doc "Reads var immediately, without going through a transaction."}
    (All [a] (-> (Var a) (IO a)))
    (|> var
        atom.read
        (:: io.functor map product.left)))

  (def: (write! new-value (^:representation var))
    (All [a] (-> a (Var a) (IO Any)))
    (do io.monad
      [(^@ old [_value _observers]) (atom.read var)
       succeeded? (atom.compare-and-swap old [new-value _observers] var)]
      (if succeeded?
        (do @
          [_ (monad.map @ (function (_ f) (f new-value)) _observers)]
          (wrap []))
        (write! new-value (:abstraction var)))))

  (def: #export (follow target)
    {#.doc "Creates a channel that will receive all changes to the value of the given var."}
    (All [a] (-> (Var a) (IO (frp.Channel a))))
    (do io.monad
      [#let [[channel source] (frp.channel [])
             target (:representation target)]
       _ (atom.update (function (_ [value observers])
                        [value (#.Cons (:: source feed) observers)])
                      target)]
      (wrap channel)))
  )

(type: (Tx-Frame a)
  {#var (Var a)
   #original a
   #current a})

(type: Tx
  (List (Ex [a] (Tx-Frame a))))

(type: #export (STM a)
  {#.doc "A computation which updates a transaction and produces a value."}
  (-> Tx [Tx a]))

(def: (find-var-value var tx)
  (All [a] (-> (Var a) Tx (Maybe a)))
  (|> tx
      (list.find (function (_ [_var _original _current])
                   (is? (:coerce (Var Any) var)
                        (:coerce (Var Any) _var))))
      (:: maybe.monad map (function (_ [_var _original _current])
                            _current))
      (:assume)
      ))

(def: #export (read var)
  (All [a] (-> (Var a) (STM a)))
  (function (_ tx)
    (case (find-var-value var tx)
      (#.Some value)
      [tx value]

      #.None
      (let [value (read!! var)]
        [(#.Cons [var value value] tx)
         value]))))

(def: (update-tx-value var value tx)
  (All [a] (-> (Var a) a Tx Tx))
  (case tx
    #.Nil
    #.Nil
    
    (#.Cons [_var _original _current] tx')
    (if (is? (:coerce (Var Any) var)
             (:coerce (Var Any) _var))
      (#.Cons {#var (:coerce (Var Any) _var)
               #original (:coerce Any _original)
               #current (:coerce Any value)}
              tx')
      (#.Cons {#var _var
               #original _original
               #current _current}
              (update-tx-value var value tx')))
    ))

(def: #export (write value var)
  {#.doc "Writes value to var."}
  (All [a] (-> a (Var a) (STM Any)))
  (function (_ tx)
    (case (find-var-value var tx)
      (#.Some _)
      [(update-tx-value var value tx)
       []]

      #.None
      [(#.Cons [var (read!! var) value] tx)
       []])))

(structure: #export _ (Functor STM)
  (def: (map f fa)
    (function (_ tx)
      (let [[tx' a] (fa tx)]
        [tx' (f a)]))))

(structure: #export apply (Apply STM)
  (def: &functor ..functor)

  (def: (apply ff fa)
    (function (_ tx)
      (let [[tx' f] (ff tx)
            [tx'' a] (fa tx')]
        [tx'' (f a)]))))

(structure: #export monad (Monad STM)
  (def: &functor ..functor)

  (def: (wrap a)
    (function (_ tx) [tx a]))

  (def: (join mma)
    (function (_ tx)
      (let [[tx' ma] (mma tx)]
        (ma tx')))))

(def: #export (update f var)
  {#.doc "Will update a Var's value, and return a tuple with the old and the new values."}
  (All [a] (-> (-> a a) (Var a) (STM [a a])))
  (do ..monad
    [a (read var)
     #let [a' (f a)]
     _ (write a' var)]
    (wrap [a a'])))

(def: (can-commit? tx)
  (-> Tx Bit)
  (list.every? (function (_ [_var _original _current])
                 (is? _original (read!! _var)))
               tx))

(def: (commit-var! [_var _original _current])
  (-> (Ex [a] (Tx-Frame a)) (IO Any))
  (if (is? _original _current)
    (io [])
    (write! _current _var)))

(def: fresh-tx Tx (list))

(type: (Commit a)
  [(STM a)
   (Promise a)
   (Resolver a)])

(def: pending-commits
  (Atom (Rec Commits
          [(Promise [(Ex [a] (Commit a)) Commits])
           (Resolver [(Ex [a] (Commit a)) Commits])]))
  (atom (promise.promise [])))

(def: commit-processor-flag
  (Atom Bit)
  (atom #0))

(def: (issue-commit commit)
  (All [a] (-> (Commit a) (IO Any)))
  (let [entry [commit (promise.promise [])]]
    (do io.monad
      [|commits|&resolve (atom.read pending-commits)]
      (loop [[|commits| resolve] |commits|&resolve]
        (case (promise.poll |commits|)
          #.None
          (do io.monad
            [resolved? (resolve entry)]
            (if resolved?
              (atom.write (product.right entry) pending-commits)
              (recur |commits|&resolve)))
          
          (#.Some [head tail])
          (recur tail))))))

(def: (process-commit commit)
  (All [a] (-> (Commit a) (IO Any)))
  (let [[stm-proc output resolve] commit
        [finished-tx value] (stm-proc fresh-tx)]
    (if (can-commit? finished-tx)
      (do io.monad
        [_ (monad.map @ commit-var! finished-tx)]
        (resolve value))
      (issue-commit commit))))

(def: init-processor!
  (IO Any)
  (do io.monad
    [flag (atom.read commit-processor-flag)]
    (if flag
      (wrap [])
      (do @
        [was-first? (atom.compare-and-swap flag #1 commit-processor-flag)]
        (if was-first?
          (do @
            [[promise resolve] (atom.read pending-commits)]
            (promise.await (function (recur [head [tail _resolve]])
                             (do @
                               [_ (process-commit head)]
                               (promise.await recur tail)))
                           promise))
          (wrap [])))
      )))

(def: #export (commit stm-proc)
  {#.doc (doc "Commits a transaction and returns its result (asynchronously)."
              "Note that a transaction may be re-run an indeterminate number of times if other transactions involving the same variables successfully commit first."
              "For this reason, it's important to note that transactions must be free from side-effects, such as I/O.")}
  (All [a] (-> (STM a) (Promise a)))
  (let [[output resolver] (promise.promise [])]
    (exec (io.run (do io.monad
                    [_ init-processor!]
                    (issue-commit [stm-proc output resolver])))
      output)))