-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextens.go
672 lines (569 loc) · 18.6 KB
/
extens.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
// Copyright 2023 Ahmad Sameh(asmsh)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package promise
import (
"log"
"os"
"github.com/asmsh/uniquerand"
)
type logger struct {
enabled bool
l *log.Logger
}
func (l logger) Println(v ...any) {
if !l.enabled {
return
}
l.l.Println(v...)
}
var logr = logger{
//enabled: true,
l: func() *log.Logger {
return log.New(os.Stderr, "", log.Lmicroseconds)
}(),
}
// Select returns a Promise value that resolves to the first Promise that's
// resolved from the Promise values passed.
// It doesn't wait for all passed Promise values to resolve.
// The resulting IdxRes value holds the Result value of the resolved Promise.
// The original order of the IdxRes's Promise can be retrieved from its Idx field.
func Select[T any](p ...*Promise[T]) *Promise[IdxRes[T]] {
return selectCall[T](p...)
}
func selectCall[T any](p ...*Promise[T]) *Promise[IdxRes[T]] {
if len(p) == 0 {
return Wrap[IdxRes[T]](nil)
}
nextProm := newPromInter[IdxRes[T]](nil)
go selectHandler(nextProm, p)
return nextProm
}
func selectHandler[T any](
newProm *Promise[IdxRes[T]],
ps []*Promise[T],
) {
// resChan is populated lazily, only if it's needed.
var resChan chan IdxRes[T]
// res represent the resolve result.
res := IdxRes[T]{}
// loopCnt records how many iterations happened in the loop below
var loopCnt int
// randIdx responsible for returning a random, unique, index in the provided
// list of promises.
var randIdx uniquerand.Int
randIdx.Reset(len(ps))
loop:
for idx, ok := randIdx.Get(); ok; idx, ok = randIdx.Get() {
currProm := ps[idx]
loopCnt++
logr.Println("idx", idx, "loopCnt", loopCnt, "of length", len(ps))
// Select with non-blocking or with blocking, based on whether we might be
// interested to check other promises for potential immediate resolution.
// Only do that if we haven't already looped over the list before, otherwise
// we might end up in an (almost) infinite loop.
// Non-blocking gives us the benefit of catching other possibly resolved
// promises, without being stuck(blocked) on the first one we encounter.
blocking := loopCnt > len(ps)
if !blocking {
logr.Println("non-blocking block")
select {
case <-currProm.syncCtx.Done():
logr.Println("non-blocking block syncChan case")
// the promise is resolved...
// create a result value based on the current promise.
res = IdxRes[T]{
Idx: idx,
Result: getFinalRes(currProm.res),
}
logr.Println(
"non-blocking block syncChan case with res.state",
res.State(),
)
default:
logr.Println("non-blocking block default case")
// This would happen when the promise is not resolved yet, and there's
// another extension call that owns the extQueue value.
// Re-put the index in the randIdx source, to re-visit this case later.
randIdx.Put(idx)
}
} else {
logr.Println("blocking block")
extsChan := currProm.extsChan()
select {
case <-currProm.syncCtx.Done():
logr.Println("blocking block syncChan case")
res = IdxRes[T]{
Idx: idx,
Result: getFinalRes(currProm.res),
}
logr.Println(
"blocking block syncChan case with res.state",
res.State(),
)
case extQ := <-extsChan:
logr.Println("blocking block extQ case")
// make sure to check the state again and get the sync result,
// in case the promise is resolved...
if extQ.initState != unknown {
logr.Println("blocking block extQ case sync res")
res = IdxRes[T]{
Idx: idx,
Result: getFinalRes(currProm.res),
}
logr.Println(
"blocking block extQ case with sync res.state",
res.State(),
)
} else {
// the promise is not resolved yet...
// create the res chan if it's not already created.
if resChan == nil {
logr.Println("blocking block extQ case new chan")
resChan = make(chan IdxRes[T])
}
logr.Println(
"blocking block extQ case prev queue valid",
extQ.valid,
"len",
len(extQ.extra),
)
// update the queue with this extension call.
addExtCallToQ(&extQ, resChan, newProm.syncCtx.Done(), idx)
logr.Println(
"blocking block extQ case new queue valid",
extQ.valid,
"len",
len(extQ.extra),
)
}
// send the updated queue back for either another extension call,
// or to be included in the currProm's resolving logic.
extsChan <- extQ
}
}
// if the promise was resolved synchronously, break and use its result.
if res.Result != nil {
break loop
}
}
// because this is a Select extension call, only one result is expected
if res.Result == nil {
logr.Println("blocking on resChan receive")
res = <-resChan
}
// resolve the next promise, based on the final Result got
switch res.State() {
case Panicked:
logr.Println("idx", res.Idx, "Panicked")
newProm.resolveToPanickedRes(panickedResultSingleIdxRes[T]{res})
case Rejected:
logr.Println("idx", res.Idx, "Rejected")
newProm.resolveToRejectedRes(rejectedResultSingleIdxRes[T]{res})
case Fulfilled:
logr.Println("idx", res.Idx, "Fulfilled")
newProm.resolveToFulfilledRes(fulfilledResultSingleIdxRes[T]{res})
}
}
// All returns a Promise value that resolves to Fulfilled if all Promise values
// passed resolved to Fulfilled.
// It resolves to Panicked if at least one resolved to Panicked.
// It resolves to Rejected if at least one resolved to Rejected and none resolves
// to Panicked.
//
// It doesn't wait for all passed Promise values to resolve, unless the resolved
// one(s) is Panicked.
//
// The resulting IdxRes slice holds the Result values of the Promise values passed
// up to when the returned Promise was resolved.
// The original order of any IdxRes's Promise can be retrieved from its Idx field.
func All[T any](p ...*Promise[T]) *Promise[[]IdxRes[T]] {
return allCall(false, p)
}
// AllWait returns a Promise value that resolves to Fulfilled if all Promise values
// passed resolved to Fulfilled.
// It resolves to Panicked if at least one resolved to Panicked.
// It resolves to Rejected if at least one resolved to Rejected and none resolves
// to Panicked.
//
// It waits for all passed Promise values to resolve.
//
// The resulting IdxRes slice holds the Result values of all Promise values passed.
// The original order of any IdxRes's Promise can be retrieved from its Idx field.
func AllWait[T any](p ...*Promise[T]) *Promise[[]IdxRes[T]] {
return allCall(true, p)
}
func allCall[T any](waitAll bool, ps []*Promise[T]) *Promise[[]IdxRes[T]] {
if len(ps) == 0 {
return Wrap[[]IdxRes[T]](nil)
}
nextProm := newPromInter[[]IdxRes[T]](nil)
go joinHandler(nextProm, ps, waitAll, true, false)
return nextProm
}
// Any returns a Promise value that resolves to Fulfilled if at least one of
// the Promise values passed resolves to Fulfilled and none resolves to Panicked.
// It resolves to Panicked if at least one resolved to Panicked.
// It resolves to Rejected if all resolves to Rejected.
//
// It doesn't wait for all passed Promise values to resolve, unless the resolved
// one(s) is Panicked.
//
// The resulting IdxRes slice holds the Result values of the Promise values passed
// up to when the returned Promise was resolved.
// The original order of any IdxRes's Promise can be retrieved from its Idx field.
func Any[T any](p ...*Promise[T]) *Promise[[]IdxRes[T]] {
return anyCall(false, p)
}
// AnyWait returns a Promise value that resolves to Fulfilled if at least one of
// the Promise values passed resolves to Fulfilled and none resolves to Panicked.
// It resolves to Panicked if at least one resolved to Panicked.
// It resolves to Rejected if all resolves to Rejected.
//
// It waits for all passed Promise values to resolve.
//
// The resulting IdxRes slice holds the Result values of all Promise values passed.
// The original order of any IdxRes's Promise can be retrieved from its Idx field.
func AnyWait[T any](p ...*Promise[T]) *Promise[[]IdxRes[T]] {
return anyCall(true, p)
}
func anyCall[T any](waitAll bool, ps []*Promise[T]) *Promise[[]IdxRes[T]] {
if len(ps) == 0 {
return Wrap[[]IdxRes[T]](nil)
}
nextProm := newPromInter[[]IdxRes[T]](nil)
go joinHandler(nextProm, ps, waitAll, false, true)
return nextProm
}
// Join returns a Promise value that resolves to Fulfilled after all Promise
// values passed resolves.
//
// It waits for all passed Promise values to resolve.
//
// The resulting IdxRes slice holds the Result values of all Promise values passed.
// The original order of any IdxRes's Promise can be retrieved from its Idx field.
func Join[T any](p ...*Promise[T]) *Promise[[]IdxRes[T]] {
return joinCall(p)
}
func joinCall[T any](ps []*Promise[T]) *Promise[[]IdxRes[T]] {
if len(ps) == 0 {
return Wrap[[]IdxRes[T]](nil)
}
nextProm := newPromInter[[]IdxRes[T]](nil)
go joinHandler(nextProm, ps, true, false, false)
return nextProm
}
func joinHandler[T any](
newProm *Promise[[]IdxRes[T]],
ps []*Promise[T],
waitAll bool,
allSuccess bool,
anySuccess bool,
) {
// resChan is populated lazily, only if it's needed.
var resChan chan IdxRes[T]
// resArr and resState, collectively, represent the resolve result.
resArr := make([]IdxRes[T], 0, len(ps))
resState := unknown
// loopCnt records how many iterations happened in the loop below
var loopCnt int
// randIdx responsible for returning a random, unique, index in the provided
// list of promises.
var randIdx uniquerand.Int
randIdx.Reset(len(ps))
logr.Println(
"join with: waitAll",
waitAll,
"allSuccess",
allSuccess,
"anySuccess",
anySuccess,
"resState",
resState,
)
// try to find a suitable resolved promise, based on the provided flags,
// or arrange for a notification once a promise is resolved.
loop:
for idx, ok := randIdx.Get(); ok; idx, ok = randIdx.Get() {
currProm := ps[idx]
loopCnt++
logr.Println("loop with: idx", idx, "loopCnt", loopCnt, "of length", len(ps))
// Select with non-blocking or with blocking, based on whether we might be
// interested to check other promises for potential immediate resolution.
// Only do that if we haven't already looped over the list before, otherwise
// we might end up in an (almost) infinite loop.
// Non-blocking gives us the benefit of catching other possibly resolved
// promises, without being stuck(blocked) on the first one we encounter.
blocking := loopCnt > len(ps)
var res IdxRes[T]
if !blocking {
logr.Println("non-blocking block")
select {
case <-currProm.syncCtx.Done():
logr.Println("non-blocking block syncChan case")
// the promise is resolved...
// create a result value based on the current promise.
res = IdxRes[T]{
Idx: idx,
Result: getFinalRes(currProm.res),
}
logr.Println(
"non-blocking block syncChan case with res.state",
res.State(),
"resState",
resState,
)
default:
logr.Println("non-blocking block default case")
// this would happen when the promise is not resolved yet, and there's
// another extension call that owns the extQueue value.
// re-put the index in the randIdx source, to re-visit this case later.
randIdx.Put(idx)
}
} else {
logr.Println("blocking block")
extsChan := currProm.extsChan()
select {
case <-currProm.syncCtx.Done():
logr.Println("blocking block syncChan case")
res = IdxRes[T]{
Idx: idx,
Result: getFinalRes(currProm.res),
}
logr.Println(
"blocking block syncChan case with res.state",
res.State(),
"resState",
resState,
)
case extQ := <-extsChan:
logr.Println("blocking block extQ case")
// make sure to check the state again and get the sync result,
// in case the promise is resolved...
if extQ.initState != unknown {
logr.Println("blocking block extQ case sync res")
res = IdxRes[T]{
Idx: idx,
Result: getFinalRes(currProm.res),
}
logr.Println(
"blocking block extQ case with sync res.state",
res.State(),
"resState",
resState,
)
} else {
// the promise is not resolved yet...
// create the res chan if it's not already created.
if resChan == nil {
logr.Println("blocking block extQ case new chan")
resChan = make(chan IdxRes[T])
}
logr.Println(
"blocking block extQ case prev queue valid",
extQ.valid,
"len",
len(extQ.extra),
)
// update the queue with this extension call.
addExtCallToQ(&extQ, resChan, newProm.syncCtx.Done(), idx)
logr.Println(
"blocking block extQ case new queue valid",
extQ.valid,
"len",
len(extQ.extra),
)
}
// send the updated queue back for either another extension call,
// or to be included in the currProm's resolving logic.
extsChan <- extQ
}
}
// if the promise was resolved synchronously, update the result fields.
if res.Result != nil {
// add it to the result array.
resArr = append(resArr, res)
// get the final promise's state, based on the previous resState and
// the recent resolved promise's state, using the selected mode rules.
if allSuccess {
newResState := getAllResState(res.State(), resState)
logr.Println(
"block syncChan allSuccess res.state",
res.State(),
"prevResState",
resState,
"newResState",
newResState,
)
resState = newResState
// stop, if we found the target break state based on the current flags.
// note: for the allSuccess case, we can only continue if the waitAll
// flag is not set, or the recent resolved promise got resolved to
// anything but Rejected.
// note: by default, we won't break on Panicked states, as it will be
// used only to alter the final state.
if !waitAll && res.State() == Rejected {
logr.Println("block syncChan allSuccess break")
break loop
}
}
if anySuccess {
newResState := getAnyResState(res.State(), resState)
logr.Println(
"block syncChan anySuccess res.state",
res.State(),
"prevResState",
resState,
"newResState",
newResState,
)
resState = newResState
if !waitAll && res.State() == Fulfilled {
logr.Println("block syncChan anySuccess break")
break loop
}
}
}
}
// no resolved promises, or the resolved promise(s) didn't meet the requirements
// set by the provided flags.
if waitAll || resState == unknown ||
(allSuccess && resState == Fulfilled) ||
(anySuccess && resState != Fulfilled) {
// the waitAll flag is set, no promise got resolved by the wait logic above,
// or the resolved promise(s) didn't meet the requirements set by the flags...
// get the number of pending promises against the initially provided list.
pending := len(ps) - len(resArr)
logr.Println("pending promises", pending, "resState", resState)
// if there are no pending promises and no result state computed, then it
// must be a Join call, which means the result state expected is Fulfilled.
if pending == 0 && resState == unknown {
resState = Fulfilled
}
// otherwise, wait until a matching result is received.
if pending != 0 {
logr.Println("waiting for pending promises", pending)
for i := 0; i < pending; i++ {
res := <-resChan
resArr = append(resArr, res)
logr.Println(
"waiting block with res.state",
res.State(),
"resState",
resState,
)
// get the final promise's state, based on the previous resState and
// the recent resolved promise's state, using the selected mode rules.
if allSuccess {
newResState := getAllResState(res.State(), resState)
logr.Println(
"waiting block allSuccess res.state",
res.State(),
"prevResState",
resState,
"newResState",
newResState,
)
resState = newResState
// stop, if we found the target break state based on the current flags.
// note: for the allSuccess case, we can only continue if the waitAll
// flag is not set, or the recent resolved promise got resolved to
// anything but Rejected.
// note: by default, we won't break on Panicked states, as it will be
// used only to alter the final state.
if !waitAll && res.State() == Rejected {
logr.Println("waiting block allSuccess break")
break
}
}
if anySuccess {
newResState := getAnyResState(res.State(), resState)
logr.Println(
"waiting block anySuccess res.state",
res.State(),
"prevResState",
resState,
"newResState",
newResState,
)
resState = newResState
if !waitAll && res.State() == Fulfilled {
logr.Println("waiting block anySuccess break")
break
}
}
if !allSuccess && !anySuccess {
resState = Fulfilled
}
}
}
}
logr.Println("resolving to", resState)
// resolve the next promise as expected, based on the final resState.
switch resState {
case Panicked:
newProm.resolveToPanickedRes(panickedResultMultiIdxRes[T]{resArr})
case Rejected:
newProm.resolveToRejectedRes(rejectedResultMultiIdxRes[T]{resArr})
case Fulfilled:
newProm.resolveToFulfilledRes(fulfilledResultMultiIdxRes[T]{resArr})
}
}
func addExtCallToQ[T any](
q *extQueue[T],
resChan chan IdxRes[T],
syncChan <-chan struct{},
idx int,
) {
call := extCall[T]{
resChan: resChan,
syncChan: syncChan,
idx: idx,
}
if !q.valid {
q.valid = true
q.call = call
} else {
q.extra = append(q.extra, call)
}
}
// getAllResState returns the resolve state of the promise returned by All.
// Panicked has the highest priority.
// Rejected has the highest priority between Fulfilled and Rejected.
func getAllResState(newState, prevState State) State {
switch {
case newState == Panicked || prevState == Panicked:
return Panicked
case newState == Rejected:
return Rejected
case prevState == unknown:
return newState
default:
return prevState
}
}
// getAnyResState returns the resolve state of the promise returned by Any.
// Panicked has the highest priority.
// Fulfilled has the highest priority between Fulfilled and Rejected.
func getAnyResState(newState, prevState State) State {
switch {
case newState == Panicked || prevState == Panicked:
return Panicked
case newState == Fulfilled:
return Fulfilled
case prevState == unknown:
return newState
default:
return prevState
}
}