aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/control/concurrency/async.lux
blob: 32f1913b6c8a3452cbcd0dcaa133778954768f20 (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
(.module:
  [library
   [lux (#- and or)
    [abstract
     [functor (#+ Functor)]
     [apply (#+ Apply)]
     ["." monad (#+ Monad do)]]
    [control
     [pipe (#+ case>)]
     ["." function]
     ["." io (#+ IO io)]]
    [data
     ["." product]]
    [type (#+ :sharing)
     abstract]]]
  [//
   ["." thread]
   ["." atom (#+ Atom atom)]])

(abstract: .public (Async a)
  {#.doc "Represents values produced by asynchronous computations (unlike IO, which is synchronous)."}

  (Atom [(Maybe a) (List (-> a (IO Any)))])

  (type: .public (Resolver a)
    {#.doc (example "The function used to give a value to an async."
                    "Will signal 'true' if the async has been resolved for the 1st time, 'false' otherwise.")}
    (-> a (IO Bit)))

  (def: (resolver async)
    {#.doc "Sets an async's value if it has not been done yet."}
    (All [a] (-> (Async a) (Resolver a)))
    (function (resolve value)
      (let [async (:representation async)]
        (do {! io.monad}
          [(^@ old [_value _observers]) (atom.read! async)]
          (case _value
            (#.Some _)
            (in #0)

            #.None
            (do !
              [.let [new [(#.Some value) #.None]]
               succeeded? (atom.compare_and_swap! old new async)]
              (if succeeded?
                (do !
                  [_ (monad.map ! (function (_ f) (f value))
                                _observers)]
                  (in #1))
                (resolve value))))))))

  (def: .public (resolved value)
    {#.doc (example "Produces an async that has already been resolved to the given value.")}
    (All [a] (-> a (Async a)))
    (:abstraction (atom [(#.Some value) (list)])))

  (def: .public (async _)
    {#.doc (example "Creates a fresh async that has not been resolved yet.")}
    (All [a] (-> Any [(Async a) (Resolver a)]))
    (let [async (:abstraction (atom [#.None (list)]))]
      [async (..resolver async)]))

  (def: .public value
    {#.doc "Polls an async for its value."}
    (All [a] (-> (Async a) (IO (Maybe a))))
    (|>> :representation
         atom.read!
         (\ io.functor map product.left)))

  (def: .public (upon! f async)
    {#.doc (example "Executes the given function as soon as the async has been resolved.")}
    (All [a] (-> (-> a (IO Any)) (Async a) (IO Any)))
    (do {! io.monad}
      [.let [async (:representation async)]
       (^@ old [_value _observers]) (atom.read! async)]
      (case _value
        (#.Some value)
        (f value)

        #.None
        (let [new [_value (#.Item f _observers)]]
          (do !
            [swapped? (atom.compare_and_swap! old new async)]
            (if swapped?
              (in [])
              (upon! f (:abstraction async))))))))
  )

(def: .public resolved?
  {#.doc "Checks whether an async's value has already been resolved."}
  (All [a] (-> (Async a) (IO Bit)))
  (|>> ..value
       (\ io.functor map
          (|>> (case> #.None
                      #0

                      (#.Some _)
                      #1)))))

(implementation: .public functor
  (Functor Async)
  
  (def: (map f fa)
    (let [[fb resolve] (..async [])]
      (exec
        (io.run! (..upon! (|>> f resolve) fa))
        fb))))

(implementation: .public apply
  (Apply Async)
  
  (def: &functor ..functor)

  (def: (apply ff fa)
    (let [[fb resolve] (..async [])]
      (exec
        (io.run! (..upon! (function (_ f)
                            (..upon! (|>> f resolve) fa))
                          ff))
        fb))))

(implementation: .public monad
  (Monad Async)
  
  (def: &functor ..functor)

  (def: in ..resolved)

  (def: (join mma)
    (let [[ma resolve] (async [])]
      (exec
        (io.run! (..upon! (..upon! resolve) mma))
        ma))))

(def: .public (and left right)
  {#.doc (example "Combines the results of both asyncs, in-order.")}
  (All [a b] (-> (Async a) (Async b) (Async [a b])))
  (let [[read! write!] (:sharing [a b]
                                 [(Async a) (Async b)]
                                 [left right]

                                 [(Async [a b])
                                  (Resolver [a b])]
                                 (..async []))
        _ (io.run! (..upon! (function (_ left)
                              (..upon! (function (_ right)
                                         (write! [left right]))
                                       right))
                            left))]
    read!))

(def: .public (or left right)
  {#.doc (example "Yields the results of whichever async gets resolved first."
                  "You can tell which one was resolved first through pattern-matching.")}
  (All [a b] (-> (Async a) (Async b) (Async (Or a b))))
  (let [[a|b resolve] (..async [])]
    (with_expansions
      [<sides> (template [<async> <tag>]
                 [(io.run! (upon! (|>> <tag> resolve) <async>))]

                 [left  #.Left]
                 [right #.Right]
                 )]
      (exec
        <sides>
        a|b))))

(def: .public (either left right)
  {#.doc (example "Yields the results of whichever async gets resolved first."
                  "You cannot tell which one was resolved first.")}
  (All [a] (-> (Async a) (Async a) (Async a)))
  (let [[left||right resolve] (..async [])]
    (`` (exec
          (~~ (template [<async>]
                [(io.run! (upon! resolve <async>))]

                [left]
                [right]))
          left||right))))

(def: .public (schedule! milli_seconds computation)
  {#.doc (example "Runs an I/O computation on its own thread (after a specified delay)."
                  "Returns an async that will eventually host its result.")}
  (All [a] (-> Nat (IO a) (Async a)))
  (let [[!out resolve] (..async [])]
    (exec
      (|> (do io.monad
            [value computation]
            (resolve value))
          (thread.schedule! milli_seconds)
          io.run!)
      !out)))

(def: .public future
  {#.doc (example "Runs an I/O computation on its own thread."
                  "Returns an async that will eventually host its result.")}
  (All [a] (-> (IO a) (Async a)))
  (..schedule! 0))

(def: .public (delayed milli_seconds value)
  {#.doc "Delivers a value after a certain period has passed."}
  (All [a] (-> Nat a (Async a)))
  (..schedule! milli_seconds (io value)))

(def: .public (delay milli_seconds)
  {#.doc "An async that will be resolved after the specified amount of milli-seconds."}
  (-> Nat (Async Any))
  (..delayed milli_seconds []))

(def: .public (time_out milli_seconds async)
  {#.doc "Wait for an async to be resolved within the specified amount of milli-seconds."}
  (All [a] (-> Nat (Async a) (Async (Maybe a))))
  (..or (..delay milli_seconds) async))