aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/control/concurrency/stm.lux
blob: 87dd101c9e8b82f23a35f700dfb67dcfe9400cf9 (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
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
(.using
 [library
  [lux (.except)
   [abstract
    [functor (.only Functor)]
    [apply (.only Apply)]
    ["[0]" monad (.only Monad do)]]
   [control
    ["[0]" io (.only IO io)]
    ["[0]" maybe]
    ["[0]" try]]
   [data
    ["[0]" product]
    [collection
     ["[0]" list]]]
   [macro
    ["^" pattern]]
   [type (.only sharing)
    [primitive (.except)]
    ["[0]" variance (.only Mutable)]]]]
 [//
  ["[0]" atom (.only Atom atom)]
  ["[0]" async (.only Async Resolver)]
  ["[0]" frp (.only Channel Sink)]])

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

(primitive .public (Var'' a)
  (Atom [a (List (Sink a))])

  (type: .public (Var' r w)
    (Var'' (Mutable r w)))
  
  (type: .public (Var a)
    (Var'' (Mutable a a)))

  (def .public (var value)
    (All (_ a) (-> a (Var a)))
    (abstraction (atom.atom [(variance.write value) (list)])))

  (def read!
    (All (_ r w) (-> (Var' r w) r))
    (|>> representation atom.read! io.run! product.left variance.read))

  (def (write! new_value var)
    (All (_ r w) (-> w (Var' r w) (IO Any)))
    (do [! io.monad]
      [.let [var' (representation var)]
       (^.let old [_ observers]) (atom.read! var')
       succeeded? (atom.compare_and_swap! old [(variance.write new_value) observers] var')]
      (if succeeded?
        (do !
          [banned (monad.only ! (function (_ sink)
                                  (do !
                                    [result (at sink feed (variance.write new_value))]
                                    (in (case result
                                          {try.#Success _}
                                          false
                                          
                                          {try.#Failure _}
                                          true))))
                              observers)
           _ (atom.update! (function (_ [value audience])
                             (|> audience
                                 (list.only (function (_ it)
                                              (not (list.any? (same? it) banned))))
                                 [value]))
                           var')]
          (in []))
        (write! new_value var))))

  (def .public (changes target)
    (All (_ a) (-> (Var a) (IO [(Channel a) (Sink a)])))
    (do io.monad
      [.let [[channel sink] (sharing [a]
                              (is (Var a)
                                  target)
                              (is [(Channel a) (Sink a)]
                                  (frp.channel [])))]
       _ (atom.update! (function (_ [value observers])
                         [value {.#Item (implementation
                                         (def close (at sink close))
                                         (def feed (|>> variance.read (at sink feed))))
                                        observers}])
                       (representation target))]
      (in [channel sink])))
  )

(type: (Tx_Frame r w)
  (Record
   [#var (Var' r w)
    #original r
    #current w]))

(type: Tx
  (List (Ex (_ r w) (Tx_Frame r w))))

(type: .public (STM a)
  (-> Tx [Tx a]))

(def (var_value var tx)
  (All (_ r w) (-> (Var' r w) Tx (Maybe r)))
  (|> tx
      (list.example (function (_ [_var _original _current])
                      (same? (as (Var Any) var)
                             (as (Var Any) _var))))
      (at maybe.monad each (function (_ [_var _original _current])
                             _current))
      as_expected))

(def .public (read var)
  (All (_ r w) (-> (Var' r w) (STM r)))
  (function (_ tx)
    (case (var_value var tx)
      {.#Some value}
      [tx value]

      {.#None}
      (let [value (..read! var)]
        [{.#Item [#var var
                  #original value
                  #current (as_expected value)]
                 tx}
         value]))))

(def (with_updated_var var value tx)
  (All (_ r w) (-> (Var' r w) w Tx Tx))
  (case tx
    {.#End}
    {.#End}
    
    {.#Item [_var _original _current] tx'}
    (if (same? (as (Var Any) var)
               (as (Var Any) _var))
      {.#Item [#var _var
               #original _original
               #current (as_expected value)]
              tx'}
      {.#Item [#var _var
               #original _original
               #current _current]
              (with_updated_var var value tx')})))

(def .public (write value var)
  (All (_ r w) (-> w (Var' r w) (STM Any)))
  (function (_ tx)
    (case (var_value var tx)
      {.#Some _}
      [(with_updated_var var value tx)
       []]

      {.#None}
      [{.#Item [#var var
                #original (..read! var)
                #current value]
               tx}
       []])))

(def .public functor
  (Functor STM)
  (implementation
   (def (each f fa)
     (function (_ tx)
       (let [[tx' a] (fa tx)]
         [tx' (f a)])))))

(def .public apply
  (Apply STM)
  (implementation
   (def functor ..functor)

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

(def .public monad
  (Monad STM)
  (implementation
   (def functor ..functor)

   (def (in a)
     (function (_ tx)
       [tx a]))

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

(def .public (update f var)
  (All (_ r w) (-> (-> r w) (Var' r w) (STM [r w])))
  (do ..monad
    [before (..read var)
     .let [after (f before)]
     _ (..write after var)]
    (in [before after])))

(def (can_commit? tx)
  (-> Tx Bit)
  (list.every? (function (_ [_var _original _current])
                 (same? _original (..read! _var)))
               tx))

(def (commit_var! [_var _original _current])
  (-> (Ex (_ r w) (Tx_Frame r w)) (IO Any))
  (if (same? (as Any _original) (as Any _current))
    (io [])
    (..write! _current _var)))

(def fresh_tx Tx (list))

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

(def pending_commits
  (Atom (Rec Commits
          [(Async [(Ex (_ a) (Commit a)) Commits])
           (Resolver [(Ex (_ a) (Commit a)) Commits])]))
  (atom (async.async [])))

(def commit_processor_flag
  (Atom Bit)
  (atom #0))

(def (issue_commit! commit)
  (All (_ a) (-> (Commit a) (IO Any)))
  (let [entry [commit (async.async [])]]
    (do [! io.monad]
      [|commits|&resolve (atom.read! pending_commits)]
      (loop (again [[|commits| resolve] |commits|&resolve])
        (do !
          [|commits| (async.value |commits|)]
          (case |commits|
            {.#None}
            (do io.monad
              [resolved? (resolve entry)]
              (if resolved?
                (atom.write! (product.right entry) pending_commits)
                (again |commits|&resolve)))
            
            {.#Some [head tail]}
            (again 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.each ! ..commit_var! finished_tx)]
        (resolve value))
      (..issue_commit! commit))))

(def start_commit_processor!
  (IO Any)
  (do [! io.monad]
    [flag (atom.read! commit_processor_flag)]
    (if flag
      (in [])
      (do !
        [was_first? (atom.compare_and_swap! flag #1 commit_processor_flag)]
        (if was_first?
          (do !
            [[async resolve] (atom.read! pending_commits)]
            (async.upon! (function (again [head [tail _resolve]])
                           (do !
                             [_ (..process_commit! head)]
                             (async.upon! again tail)))
                         async))
          (in [])))
      )))

(def .public (commit! stm_proc)
  (All (_ a) (-> (STM a) (Async a)))
  (let [[output resolver] (async.async [])]
    (exec
      (io.run! (do io.monad
                 [_ ..start_commit_processor!]
                 (..issue_commit! [stm_proc output resolver])))
      output)))