aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/concurrency/promise.lux
blob: b765acc4d30f575ae0a20374c46ec6480f21d91e (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
##  Copyright (c) Eduardo Julian. All rights reserved.
##  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
##  If a copy of the MPL was not distributed with this file,
##  You can obtain one at http://mozilla.org/MPL/2.0/.

(;module:
  lux
  (lux (data (struct [list #* "" Functor<List>])
             number
             text/format
             error)
       (codata [io #- run]
               function)
       (control functor
                applicative
                monad)
       [compiler]
       (macro ["s" syntax #+ syntax: Syntax])
       (concurrency [atom #+ Atom atom])
       host
       ))

(jvm-import java.lang.Runtime
  (#static getRuntime [] Runtime)
  (availableProcessors [] int))

(jvm-import java.lang.Runnable)

(jvm-import java.lang.Thread
  (new [Runnable])
  (start [] void))

(jvm-import java.util.concurrent.Executor
  (execute [Runnable] void))

(jvm-import java.util.concurrent.TimeUnit
  (#enum MILLISECONDS))

(jvm-import (java.util.concurrent.ScheduledFuture a))

(jvm-import java.util.concurrent.ScheduledThreadPoolExecutor
  (new [int])
  (schedule [Runnable long TimeUnit] (ScheduledFuture Object)))

(def: #export concurrency-level
  Nat
  (|> (Runtime.getRuntime [])
      (Runtime.availableProcessors [])
      int-to-nat))

(def: executor
  ScheduledThreadPoolExecutor
  (ScheduledThreadPoolExecutor.new [(nat-to-int concurrency-level)]))

(syntax: (runnable expr)
  (wrap (list (`' (object [java.lang.Runnable]
                    []
                    (java.lang.Runnable (run) void
                                        (exec (~ expr)
                                          [])))))))

(type: (Promise-State a)
  {#value (Maybe a)
   #observers (List (-> a (IO Unit)))})

(type: #export (Promise a)
  {#;doc "Represents values produced by promisehronous computations (unlike IO, which is synchronous)."}
  (Atom (Promise-State a)))

(def: #hidden (promise' ?value)
  (All [a] (-> (Maybe a) (Promise a)))
  (atom {#value ?value
         #observers (list)}))

(syntax: #export (promise {?type (s;opt s;any)})
  {#;doc (doc "Makes an uninitialized Promise (in this example, of Unit)."
              (promise Unit))}
  (case ?type
    (#;Some type)
    (wrap (list (` (: (Promise (~ type))
                      (promise' #;None)))))

    #;None
    (wrap (list (` (promise' #;None))))))

(def: #export (poll promise)
  {#;doc "Checks whether an Promise's value has already been resolved."}
  (All [a] (-> (Promise a) (Maybe a)))
  (|> (atom;get promise)
      io;run
      (get@ #value)))

(def: #export (resolve value promise)
  {#;doc "Sets an Promise's value if it hasn't been done yet."}
  (All [a] (-> a (Promise a) (IO Bool)))
  (do Monad<IO>
    [old (atom;get promise)]
    (case (get@ #value old)
      (#;Some _)
      (wrap false)

      #;None
      (do @
        [#let [new (set@ #value (#;Some value) old)]
         succeeded? (atom;compare-and-swap old new promise)]
        (if succeeded?
          (do @
            [_ (mapM @ (lambda [f] (f value))
                     (get@ #observers old))]
            (wrap true))
          (resolve value promise))))))

(def: (await f promise)
  (All [a] (-> (-> a (IO Unit)) (Promise a) Unit))
  (let [old (io;run (atom;get promise))]
    (case (get@ #value old)
      (#;Some value)
      (io;run (f value))

      #;None
      (let [new (update@ #observers (|>. (#;Cons f)) old)]
        (if (io;run (atom;compare-and-swap old new promise))
          []
          (await f promise))))))

(struct: #export _ (Functor Promise)
  (def: (map f fa)
    (let [fb (promise ($ 1))]
      (exec (await (lambda [a] (do Monad<IO>
                            [_ (resolve (f a) fb)]
                            (wrap [])))
                   fa)
        fb))))

(struct: #export _ (Applicative Promise)
  (def: functor Functor<Promise>)

  (def: (wrap a)
    (atom {#value (#;Some a)
           #observers (list)}))

  (def: (apply ff fa)
    (let [fb (promise ($ 1))]
      (exec (await (lambda [f]
                     (io (await (lambda [a] (do Monad<IO>
                                         [_ (resolve (f a) fb)]
                                         (wrap [])))
                                fa)))
                   ff)
        fb))
    ))

(struct: #export _ (Monad Promise)
  (def: applicative Applicative<Promise>)

  (def: (join mma)
    (let [ma (promise ($ 0))]
      (exec (await (lambda [ma']
                     (io (await (lambda [a']
                                  (do Monad<IO>
                                    [_ (resolve a' ma)]
                                    (wrap [])))
                                ma')))
                   mma)
        ma))))

(def: #export (seq left right)
  {#;doc "Sequencing combinator."}
  (All [a b] (-> (Promise a) (Promise b) (Promise [a b])))
  (do Monad<Promise>
    [a left
     b right]
    (wrap [a b])))

(def: #export (alt left right)
  {#;doc "Heterogeneous alternative combinator."}
  (All [a b] (-> (Promise a) (Promise b) (Promise (| a b))))
  (let [a|b (promise (Either ($ 0) ($ 1)))]
    (let% [<sides> (do-template [<promise> <tag>]
                     [(await (lambda [value]
                               (do Monad<IO>
                                 [_ (resolve (<tag> value) a|b)]
                                 (wrap [])))
                             <promise>)]

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

(def: #export (either left right)
  {#;doc "Homogeneous alternative combinator."}
  (All [a] (-> (Promise a) (Promise a) (Promise a)))
  (let [left||right (promise ($ 0))]
    (let% [<sides> (do-template [<promise>]
                     [(await [(lambda [value]
                                (do Monad<IO>
                                  [_ (resolve value left||right)]
                                  (wrap [])))]
                             <promise>)]

                     [left]
                     [right]
                     )]
      (exec <sides>
        left||right))))

(def: #export (future computation)
  {#;doc "Runs computation on it's own process and returns an Promise that will eventually host it's result."}
  (All [a] (-> (IO a) (Promise a)))
  (let [!out (promise ($ 0))]
    (exec (Thread.start [] (Thread.new [(runnable (io;run (resolve (io;run computation)
                                                                   !out)))]))
      !out)))

(def: #export (wait time)
  (-> Nat (Promise Unit))
  (let [!out (promise Unit)]
    (exec (ScheduledThreadPoolExecutor.schedule [(runnable (io;run (resolve [] !out)))
                                                 (nat-to-int time)
                                                 TimeUnit.MILLISECONDS]
                                                executor)
      !out)))

(def: #export (time-out time promise)
  (All [a] (-> Nat (Promise a) (Promise (Maybe a))))
  (alt (wait time) promise))

(def: #export (delay time value)
  {#;doc "Delivers a value after a certain period has passed."}
  (All [a] (-> Nat a (Promise a)))
  (:: Functor<Promise> map (const value) (wait time)))