aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/control/concurrency/async.lux
blob: dc95a97e15fdc985fa715789712d48b59354d378 (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
(.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: #export (Async a)
  (Atom [(Maybe a) (List (-> a (IO Any)))])

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

  (type: #export (Resolver a)
    {#.doc (doc "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: #export (resolved value)
    {#.doc (doc "Produces an async that has already been resolved to the given value.")}
    (All [a] (-> a (Async a)))
    (:abstraction (atom [(#.Some value) (list)])))

  (def: #export (async _)
    {#.doc (doc "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: #export poll
    {#.doc "Polls an async for its value."}
    (All [a] (-> (Async a) (IO (Maybe a))))
    (|>> :representation
         atom.read
         (\ io.functor map product.left)))

  (def: #export (await f async)
    {#.doc (doc "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 [])
              (await f (:abstraction async))))))))
  )

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

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

(implementation: #export functor
  (Functor Async)
  
  (def: (map f fa)
    (let [[fb resolve] (..async [])]
      (exec (io.run (..await (|>> f resolve) fa))
        fb))))

(implementation: #export apply
  (Apply Async)
  
  (def: &functor ..functor)

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

(implementation: #export monad
  (Monad Async)
  
  (def: &functor ..functor)

  (def: in ..resolved)

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

(def: #export (and left right)
  {#.doc (doc "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 (..await (function (_ left)
                             (..await (function (_ right)
                                        (write! [left right]))
                                      right))
                           left))]
    read!))

(def: #export (or left right)
  {#.doc (doc "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 (await (|>> <tag> resolve) <async>))]

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

(def: #export (either left right)
  {#.doc (doc "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 (await resolve <async>))]

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

(def: #export (schedule millis_delay computation)
  {#.doc (doc "Runs an I/O computation on its own thread (after a specified delay)."
              "Returns a aromise 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 millis_delay)
              io.run)
      !out)))

(def: #export future
  {#.doc (doc "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: #export (delay time_millis value)
  {#.doc "Delivers a value after a certain period has passed."}
  (All [a] (-> Nat a (Async a)))
  (..schedule time_millis (io value)))

(def: #export (wait time_millis)
  {#.doc "Returns an async that will be resolved after the specified amount of milliseconds."}
  (-> Nat (Async Any))
  (..delay time_millis []))

(def: #export (time_out time_millis async)
  {#.doc "Wait for an async to be resolved within the specified amount of milliseconds."}
  (All [a] (-> Nat (Async a) (Async (Maybe a))))
  (..or (wait time_millis) async))