-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.go
416 lines (387 loc) · 10.4 KB
/
promise.go
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package promise
import (
"fmt"
"reflect"
"sync"
"sync/atomic"
)
// Promise interface that defines
// methods that are similar to those
// of Javascript
type Promise[T any] struct {
// successChannel is were the retun
// of the promise is stored
successChannel chan T
// failureChannel is were the error
// of the primise is stored
failureChannel chan error
// mutex that ensures that the promises
// are executed in order
mutex *sync.Mutex
// promise's wait group
wg *sync.WaitGroup
// boolean's to manage channels
hasThenSubscriber *atomic.Bool
hasCatchSubscriber *atomic.Bool
hasFinallySubscriber *atomic.Bool
hasExecSubscriber *atomic.Bool
thenExecuted *atomic.Bool
catchExecuted *atomic.Bool
awaitSubscriber *atomic.Bool
}
// stores information about any
// object
type meta struct {
objectType reflect.Type
objectValue reflect.Value
}
// newPromise
// Creates a new Promise instance
func newPromise[T any]() *Promise[T] {
return &Promise[T]{
successChannel: make(chan T, 1),
failureChannel: make(chan error, 1),
mutex: &sync.Mutex{},
wg: &sync.WaitGroup{},
hasThenSubscriber: &atomic.Bool{},
hasCatchSubscriber: &atomic.Bool{},
hasFinallySubscriber: &atomic.Bool{},
hasExecSubscriber: &atomic.Bool{},
thenExecuted: &atomic.Bool{},
catchExecuted: &atomic.Bool{},
awaitSubscriber: &atomic.Bool{},
}
}
// fromPromise
// Creates a promise from Promise
func fromPromise[T, S any](promise *Promise[T]) *Promise[S] {
return &Promise[S]{
successChannel: make(chan S, 1),
failureChannel: make(chan error, 1),
mutex: promise.mutex,
wg: promise.wg,
hasThenSubscriber: &atomic.Bool{},
hasCatchSubscriber: &atomic.Bool{},
hasFinallySubscriber: &atomic.Bool{},
hasExecSubscriber: &atomic.Bool{},
thenExecuted: &atomic.Bool{},
catchExecuted: &atomic.Bool{},
awaitSubscriber: &atomic.Bool{},
}
}
// isFunction
// checks whether an obj is a function
func isFunction(obj any) bool {
return reflect.TypeOf(obj).Kind() == reflect.Func
}
// call
// calls any function by reflection
func call(obj any, args ...meta) (any, error) {
vargs := make([]reflect.Value, 0)
for _, arg := range args {
vargs = append(vargs, arg.objectValue)
}
function := reflect.ValueOf(obj)
ret := function.Call(vargs)
if !ret[1].IsNil() {
err := ret[1].Interface().(error)
return ret[0].Interface(), err
}
return ret[0].Interface(), nil
}
// execute
// calls the function that
// creates the promise and
// and runs a function and
// puts the function's return
// in the subsequent promise
func execute[T any](
promise *Promise[T],
f func(any, ...meta) (T, error),
obj any,
args ...meta) {
defer promise.recover()
defer promise.mutex.Unlock()
defer promise.wg.Done()
obj, err := f(obj, args...)
if err == nil {
promise.successChannel <- obj.(T)
promise.failureChannel <- nil
} else {
promise.failureChannel <- err
}
}
// executeObj
// locks the mutex while the promise is
// created from an object
func executeObj[T any](promise *Promise[T], obj T) {
defer promise.mutex.Unlock()
defer promise.wg.Done()
promise.failureChannel <- nil
promise.successChannel <- obj
}
// executeThenCallback
// executes then using two promises
func executeThenCallback[T, S any](
promise1 *Promise[T],
promise2 *Promise[S],
f func(T) (S, error),
) {
defer promise2.recover()
defer promise2.mutex.Unlock()
defer promise2.wg.Done()
defer promise1.thenExecuted.Store(true)
defer promise1.clearChannelsAfterThen()
err := <-promise1.failureChannel
if err == nil {
arg := <-promise1.successChannel
obj, err := f(arg)
promise2.successChannel <- obj
promise2.failureChannel <- err
} else {
promise2.failureChannel <- err
}
}
// executeCatchCallback
// executes catch using two promises
func executeCatchCallback[T, S any](
promise1 *Promise[T],
promise2 *Promise[S],
f func(error) (S, error),
) {
defer promise2.recover()
defer promise2.mutex.Unlock()
defer promise2.wg.Done()
defer promise1.catchExecuted.Store(true)
defer promise1.clearChannelAfterCatch()
err := <-promise1.failureChannel
if err != nil {
obj, err := f(err)
promise2.successChannel <- obj
promise2.failureChannel <- err
} else {
promise2.failureChannel <- nil
}
}
// executeFinally
// executes promise's finally
func executeFinally[T any](
promise *Promise[T],
f func(),
) {
defer promise.mutex.Unlock()
defer promise.wg.Done()
promise.drainChannels()
f()
}
// executeThen
// executes promise then
func executeThen[T any](
promise *Promise[T],
f func(T),
) {
defer promise.recover()
defer promise.mutex.Unlock()
defer promise.wg.Done()
defer promise.thenExecuted.Store(true)
defer promise.clearChannelsAfterThen()
err := <-promise.failureChannel
if err == nil {
obj := <-promise.successChannel
promise.failureChannel <- nil
f(obj)
} else {
promise.failureChannel <- err
}
}
// executeCatch
// executes promise's catch
func executeCatch[T any](
promise *Promise[T],
f func(error),
) {
defer promise.recover()
defer promise.mutex.Unlock()
defer promise.wg.Done()
defer promise.catchExecuted.Store(true)
defer promise.clearChannelAfterCatch()
err := <-promise.failureChannel
if err != nil {
// there can be another then waiting to execute
// putting nil into the failure channel allows
// the following then to work correctly
promise.failureChannel <- nil
f(err)
}
}
// drainChannels
// clears channels
func (promise *Promise[T]) drainChannels() {
if len(promise.failureChannel) == 1 {
err := <-promise.failureChannel
if err != nil {
errMsg := fmt.Sprintf("Promise execution has an unhandled error of %v\nPlease consider using a catch clause to handle errors", err)
panic(errMsg)
}
}
if len(promise.successChannel) == 1 {
<-promise.successChannel
}
}
// funcRunner
// casts call returns to the correct types
func funcRunner[T any](obj any, args ...meta) (T, error) {
obj, err := call(obj, args...)
return obj.(T), err
}
// recover
// recovers if the promise run causes
// a panic
func (promise *Promise[T]) recover() {
if r := recover(); r != nil {
err := fmt.Errorf("Promise entered an unhealth state due to panic:\n %v", r)
if len(promise.failureChannel) == 1 {
<-promise.failureChannel
}
promise.failureChannel <- err
}
}
func Promisify[T any](obj any, args ...any) *Promise[T] {
var promise *Promise[T]
if isFunction(obj) {
argsMeta := make([]meta, 0)
for _, arg := range args {
argsMeta = append(argsMeta, meta{
objectType: reflect.TypeOf(arg),
objectValue: reflect.ValueOf(arg),
})
}
promise = promisifyFunc(funcRunner[T], obj, argsMeta...)
} else {
promise = promisfyObj(obj.(T))
}
return promise
}
func promisfyObj[T any](obj T) *Promise[T] {
promise := newPromise[T]()
promise.wg.Add(1)
promise.mutex.Lock()
go executeObj(promise, obj)
return promise
}
// promisifyFunc
// Executes the function and creates a promise
// from the function's result.
// If the function returns an error, places the err in the failure channel
// If the function returns an object, puts the object in success channel
func promisifyFunc[T any](f func(any, ...meta) (T, error), obj any, args ...meta) *Promise[T] {
promise := newPromise[T]()
promise.wg.Add(1)
promise.mutex.Lock()
go execute(promise, f, obj, args...)
return promise
}
// Then
// runs a function following a promise
// success and creates a new promise from
// promise.
func Then[T, S any](promise *Promise[T], successFunc func(T) (S, error)) *Promise[S] {
promise.hasThenSubscriber.Store(true)
resultPromise := fromPromise[T, S](promise)
promise.mutex.Lock()
resultPromise.wg.Add(1)
go executeThenCallback(promise, resultPromise, successFunc)
return resultPromise
}
// Catch
// runs a function following a promise failure
// and creates a new promise from the failed
// promise.
func Catch[T, S any](promise *Promise[T], catchFunc func(error) (S, error)) *Promise[S] {
promise.hasCatchSubscriber.Store(true)
resultPromise := fromPromise[T, S](promise)
promise.mutex.Lock()
resultPromise.wg.Add(1)
go executeCatchCallback(promise, resultPromise, catchFunc)
return resultPromise
}
// Finally
// runs a function after the promise and subsequent promises
// were executed.
// Ideal for clean up functions
func (promise *Promise[T]) Finally(finallyFunc func()) {
promise.hasFinallySubscriber.Store(true)
promise.mutex.Lock()
promise.wg.Add(1)
go executeFinally(promise, finallyFunc)
}
// Then
// executes a function following a promise sucess
func (promise *Promise[T]) Then(successFunc func(T)) {
promise.hasCatchSubscriber.Store(true)
promise.mutex.Lock()
promise.wg.Add(1)
go executeThen(promise, successFunc)
}
// Catch
// executes a function following a promise failure
func (promise *Promise[T]) Catch(errorFunc func(error)) {
promise.hasCatchSubscriber.Store(true)
promise.mutex.Lock()
promise.wg.Add(1)
go executeCatch(promise, errorFunc)
}
// Exec
// Waits for all of the promises to
// execute without returning the
// value and cleans up the resources
// It's recommended to use it if neither Finally
// nor Await are used
func (promise *Promise[T]) Exec() {
promise.mutex.Lock()
defer promise.mutex.Unlock()
promise.drainChannels()
}
// Await
// Waits for all of the promises to
// execute and returns the computed value
// and the error if there is an error
func (promise *Promise[T]) Await() (T, error) {
promise.awaitSubscriber.Store(true)
promise.wg.Wait()
var obj T
var err error
if len(promise.successChannel) == 1 {
obj = <-promise.successChannel
}
if len(promise.failureChannel) == 1 {
err = <-promise.failureChannel
}
return obj, err
}
func (promise *Promise[T]) clearChannelsAfterThen() {
hasAwait := promise.awaitSubscriber.Load()
hasFinally := promise.hasFinallySubscriber.Load()
hasExec := promise.hasExecSubscriber.Load()
if hasAwait || hasFinally || hasExec {
return
}
hasCatch := promise.hasCatchSubscriber.Load()
catchExecuted := promise.catchExecuted.Load()
if !hasCatch || catchExecuted {
promise.drainChannels()
}
}
func (promise *Promise[T]) clearChannelAfterCatch() {
hasAwait := promise.awaitSubscriber.Load()
hasFinally := promise.hasFinallySubscriber.Load()
hasExec := promise.hasExecSubscriber.Load()
if hasAwait || hasFinally || hasExec {
return
}
hasThen := promise.hasThenSubscriber.Load()
thenExecuted := promise.thenExecuted.Load()
if !hasThen || thenExecuted {
promise.drainChannels()
}
}