-
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy patheffect.ts
More file actions
5600 lines (5172 loc) · 171 KB
/
effect.ts
File metadata and controls
5600 lines (5172 loc) · 171 KB
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as Arr from "../Array.ts"
import type * as Cause from "../Cause.ts"
import type * as Clock from "../Clock.ts"
import type * as Console from "../Console.ts"
import * as Duration from "../Duration.ts"
import type * as Effect from "../Effect.ts"
import * as Equal from "../Equal.ts"
import type * as Exit from "../Exit.ts"
import type * as Fiber from "../Fiber.ts"
import * as Filter from "../Filter.ts"
import { formatJson } from "../Formatter.ts"
import type { LazyArg } from "../Function.ts"
import { constant, constFalse, constTrue, constUndefined, constVoid, dual, identity } from "../Function.ts"
import * as Hash from "../Hash.ts"
import { toJson, toStringUnknown } from "../Inspectable.ts"
import type * as Logger from "../Logger.ts"
import type * as LogLevel from "../LogLevel.ts"
import type * as Metric from "../Metric.ts"
import * as Option from "../Option.ts"
import * as Order from "../Order.ts"
import { pipeArguments } from "../Pipeable.ts"
import type * as Predicate from "../Predicate.ts"
import { hasProperty, isIterable, isString, isTagged } from "../Predicate.ts"
import { currentFiberTypeId, redact } from "../Redactable.ts"
import {
CurrentConcurrency,
CurrentLogAnnotations,
CurrentLogLevel,
CurrentLogSpans,
CurrentStackFrame,
MinimumLogLevel,
type StackFrame,
TracerEnabled,
TracerSpanAnnotations,
TracerSpanLinks,
TracerTimingEnabled
} from "../References.ts"
import * as Result from "../Result.ts"
import * as Scheduler from "../Scheduler.ts"
import type * as Scope from "../Scope.ts"
import * as ServiceMap from "../ServiceMap.ts"
import * as Tracer from "../Tracer.ts"
import type {
Concurrency,
EqualsWith,
ExcludeTag,
ExtractReason,
ExtractTag,
NoInfer,
NotFunction,
ReasonOf,
ReasonTags,
Simplify,
Tags
} from "../Types.ts"
import { internalCall } from "../Utils.ts"
import type { Primitive } from "./core.ts"
import {
args,
causeAnnotate,
causeEmpty,
causeFail,
causeFromFailures,
CauseImpl,
constEmptyAnnotations,
contA,
contAll,
contE,
Die,
evaluate,
exitDie,
exitFail,
exitFailCause,
exitSucceed,
ExitTypeId,
Fail,
FailureBase,
failureIsDie,
failureIsFail,
InterruptorStackTrace,
isCause,
isEffect,
makePrimitive,
makePrimitiveProto,
NoSuchElementError,
StackTraceKey as CauseStackTrace,
TaggedError,
withFiber,
Yield
} from "./core.ts"
import * as doNotation from "./doNotation.ts"
import * as InternalMetric from "./metric.ts"
import { addSpanStackTrace, makeStackCleaner } from "./tracer.ts"
import { version } from "./version.ts"
// ----------------------------------------------------------------------------
// Cause
// ----------------------------------------------------------------------------
/** @internal */
export class Interrupt extends FailureBase<"Interrupt"> implements Cause.Interrupt {
readonly fiberId: number | undefined
constructor(
fiberId: number | undefined,
annotations = constEmptyAnnotations
) {
super("Interrupt", annotations, "Interrupted")
this.fiberId = fiberId
}
override toString() {
return `Interrupt(${this.fiberId})`
}
toJSON(): unknown {
return {
_tag: "Interrupt",
fiberId: this.fiberId
}
}
[Equal.symbol](that: any): boolean {
return (
failureIsInterrupt(that) &&
this.fiberId === that.fiberId &&
this.annotations === that.annotations
)
}
[Hash.symbol](): number {
return Hash.combine(Hash.string(`${this._tag}:${this.fiberId}`))(
Hash.random(this.annotations)
)
}
}
/** @internal */
export const failureInterrupt = (fiberId?: number | undefined): Cause.Interrupt => new Interrupt(fiberId)
/** @internal */
export const causeInterrupt = (
fiberId?: number | undefined
): Cause.Cause<never> => new CauseImpl([new Interrupt(fiberId)])
/** @internal */
export const causeHasFail = <E>(self: Cause.Cause<E>): boolean => self.failures.some(failureIsFail)
/** @internal */
export const causeFilterFail = <E>(self: Cause.Cause<E>): Cause.Fail<E> | Filter.fail<Cause.Cause<never>> => {
const failure = self.failures.find(failureIsFail)
return failure ? failure : Filter.fail(self as Cause.Cause<never>)
}
/** @internal */
export const causeFilterError = <E>(self: Cause.Cause<E>): E | Filter.fail<Cause.Cause<never>> => {
for (let i = 0; i < self.failures.length; i++) {
const failure = self.failures[i]
if (failure._tag === "Fail") {
return failure.error
}
}
return Filter.fail(self as Cause.Cause<never>)
}
/** @internal */
export const causeErrorOption = Filter.toOption(causeFilterError)
/** @internal */
export const causeHasDie = <E>(self: Cause.Cause<E>): boolean => self.failures.some(failureIsDie)
/** @internal */
export const causeFilterDie = <E>(self: Cause.Cause<E>): Cause.Die | Filter.fail<Cause.Cause<E>> => {
const failure = self.failures.find(failureIsDie)
return failure ? failure : Filter.fail(self)
}
/** @internal */
export const causeFilterDefect = <E>(self: Cause.Cause<E>): {} | Filter.fail<Cause.Cause<E>> => {
const failure = self.failures.find(failureIsDie)
return failure ? failure.defect as {} : Filter.fail(self)
}
/** @internal */
export const causeHasInterrupt = <E>(self: Cause.Cause<E>): boolean => self.failures.some(failureIsInterrupt)
/** @internal */
export const causeFilterInterrupt = <E>(self: Cause.Cause<E>): Cause.Interrupt | Filter.fail<Cause.Cause<E>> => {
const failure = self.failures.find(failureIsInterrupt)
return failure ? failure : Filter.fail(self)
}
/** @internal */
export const causeFilterInterruptors = <E>(self: Cause.Cause<E>): Set<number> | Filter.fail<Cause.Cause<E>> => {
let interruptors: Set<number> | undefined
for (let i = 0; i < self.failures.length; i++) {
const f = self.failures[i]
if (f._tag !== "Interrupt") continue
interruptors ??= new Set()
if (f.fiberId !== undefined) {
interruptors.add(f.fiberId)
}
}
return interruptors ? interruptors : Filter.fail(self)
}
/** @internal */
export const causeInterruptors = <E>(self: Cause.Cause<E>): ReadonlySet<number> => {
const result = causeFilterInterruptors(self)
return Filter.isFail(result) ? emptySet : result
}
const emptySet = new Set<number>()
/** @internal */
export const causeIsInterruptedOnly = <E>(self: Cause.Cause<E>): boolean => self.failures.every(failureIsInterrupt)
/** @internal */
export const failureIsInterrupt = <E>(
self: Cause.Failure<E>
): self is Cause.Interrupt => isTagged(self, "Interrupt")
/** @internal */
export const failureAnnotations = <E>(
self: Cause.Failure<E>
): ServiceMap.ServiceMap<never> => ServiceMap.makeUnsafe(self.annotations)
/** @internal */
export const causeAnnotations = <E>(
self: Cause.Cause<E>
): ServiceMap.ServiceMap<never> => {
const map = new Map<string, unknown>()
for (const f of self.failures) {
if (f.annotations.size > 0) {
for (const [key, value] of f.annotations) {
map.set(key, value)
}
}
}
return ServiceMap.makeUnsafe(map)
}
/** @internal */
export const causeMerge: {
<E2>(that: Cause.Cause<E2>): <E>(self: Cause.Cause<E>) => Cause.Cause<E | E2>
<E, E2>(self: Cause.Cause<E>, that: Cause.Cause<E2>): Cause.Cause<E | E2>
} = dual(
2,
<E, E2>(self: Cause.Cause<E>, that: Cause.Cause<E2>): Cause.Cause<E | E2> => {
if (self.failures.length === 0) {
return that as Cause.Cause<E | E2>
} else if (that.failures.length === 0) {
return self as Cause.Cause<E | E2>
}
const newCause = new CauseImpl<E | E2>(
Arr.union(self.failures, that.failures)
)
return Equal.equals(self, newCause) ? self : newCause
}
)
/** @internal */
export const causeMap: {
<E, E2>(f: (error: NoInfer<E>) => E2): (self: Cause.Cause<E>) => Cause.Cause<E2>
<E, E2>(self: Cause.Cause<E>, f: (error: NoInfer<E>) => E2): Cause.Cause<E2>
} = dual(
2,
<E, E2>(self: Cause.Cause<E>, f: (error: NoInfer<E>) => E2): Cause.Cause<E2> => {
let hasFail = false
const failures = self.failures.map((failure) => {
if (failureIsFail(failure)) {
hasFail = true
return new Fail(f(failure.error))
}
return failure
})
return hasFail ? causeFromFailures(failures) : self as any
}
)
/** @internal */
export const causePartition = <E>(
self: Cause.Cause<E>
): {
readonly Fail: ReadonlyArray<Cause.Fail<E>>
readonly Die: ReadonlyArray<Cause.Die>
readonly Interrupt: ReadonlyArray<Cause.Interrupt>
} => {
const obj = {
Fail: [] as Array<Cause.Fail<E>>,
Die: [] as Array<Cause.Die>,
Interrupt: [] as Array<Cause.Interrupt>
}
for (let i = 0; i < self.failures.length; i++) {
obj[self.failures[i]._tag].push(self.failures[i] as any)
}
return obj
}
/** @internal */
export const causeSquash = <E>(self: Cause.Cause<E>): unknown => {
const partitioned = causePartition(self)
if (partitioned.Fail.length > 0) {
return partitioned.Fail[0].error
} else if (partitioned.Die.length > 0) {
return partitioned.Die[0].defect
} else if (partitioned.Interrupt.length > 0) {
return new globalThis.Error("All fibers interrupted without error")
}
return new globalThis.Error("Empty cause")
}
/** @internal */
export const causePrettyErrors = <E>(self: Cause.Cause<E>): Array<Error> => {
const errors: Array<Error> = []
const interrupts: Array<Cause.Interrupt> = []
if (self.failures.length === 0) return errors
const prevStackLimit = Error.stackTraceLimit
Error.stackTraceLimit = 1
for (const failure of self.failures) {
if (failure._tag === "Interrupt") {
interrupts.push(failure)
continue
}
errors.push(
causePrettyError(
failure._tag === "Die" ? failure.defect : failure.error as any,
failure.annotations
)
)
}
if (errors.length === 0) {
const cause = new Error("The fiber was interrupted by:")
cause.name = "InterruptCause"
cause.stack = interruptCauseStack(cause, interrupts)
const error = new globalThis.Error("All fibers interrupted without error", { cause })
error.name = "InterruptError"
error.stack = `${error.name}: ${error.message}`
errors.push(causePrettyError(error, interrupts[0].annotations))
}
Error.stackTraceLimit = prevStackLimit
return errors
}
const causePrettyError = (
original: Record<string, unknown> | Error,
annotations?: ReadonlyMap<string, unknown>
): Error => {
const kind = typeof original
let error: Error
if (original && kind === "object") {
error = new globalThis.Error(causePrettyMessage(original), {
cause: original.cause ? causePrettyError(original.cause as any) : undefined
})
if (typeof original.name === "string") {
error.name = original.name
}
if (typeof original.stack === "string") {
error.stack = cleanErrorStack(original.stack, error, annotations)
} else {
const stack = `${error.name}: ${error.message}`
error.stack = annotations ? addStackAnnotations(stack, annotations) : stack
}
for (const key of Object.keys(original)) {
if (!(key in error)) {
;(error as any)[key] = (original as any)[key]
}
}
} else {
error = new globalThis.Error(
!original ? `Unknown error: ${original}` : kind === "string" ? original as any : formatJson(original)
)
}
return error
}
/** @internal */
export const causePrettyMessage = (u: Record<string, unknown> | Error): string => {
if (typeof u.message === "string") {
return u.message
} else if (
typeof u.toString === "function"
&& u.toString !== Object.prototype.toString
&& u.toString !== Array.prototype.toString
) {
try {
return u.toString()
} catch {
// something's off, rollback to json
}
}
return formatJson(u)
}
const locationRegExp = /\((.*)\)/g
const cleanErrorStack = (
stack: string,
error: Error,
annotations: ReadonlyMap<string, unknown> | undefined
): string => {
const message = `${error.name}: ${error.message}`
const lines = (stack.startsWith(message) ? stack.slice(message.length) : stack).split("\n")
const out: Array<string> = [message]
for (let i = 1; i < lines.length; i++) {
if (/(?:Generator\.next|~effect\/Effect)/.test(lines[i])) {
break
}
out.push(lines[i])
}
return annotations ? addStackAnnotations(out.join("\n"), annotations) : out.join("\n")
}
const addStackAnnotations = (stack: string, annotations: ReadonlyMap<string, unknown>) => {
const frame = annotations?.get(CauseStackTrace.key) as StackFrame | undefined
if (frame) {
stack = `${stack}\n${currentStackTrace(frame)}`
}
return stack
}
const interruptCauseStack = (error: Error, interrupts: Array<Cause.Interrupt>): string => {
const out: Array<string> = [`${error.name}: ${error.message}`]
for (const current of interrupts) {
const fiberId = current.fiberId !== undefined ? `#${current.fiberId}` : "unknown"
const frame = current.annotations.get(InterruptorStackTrace.key) as StackFrame | undefined
out.push(` at fiber (${fiberId})`)
if (frame) out.push(currentStackTrace(frame))
}
return out.join("\n")
}
const currentStackTrace = (frame: StackFrame): string => {
const out: Array<string> = []
let current: StackFrame | undefined = frame
let i = 0
while (current && i < 10) {
const stack = current.stack()
if (stack) {
const locationMatchAll = stack.matchAll(locationRegExp)
let match = false
for (const [, location] of locationMatchAll) {
match = true
out.push(` at ${current.name} (${location})`)
}
if (!match) {
out.push(` at ${current.name} (${stack.replace(/^at /, "")})`)
}
} else {
out.push(` at ${current.name}`)
}
current = current.parent
i++
}
return out.join("\n")
}
/** @internal */
export const causePretty = <E>(cause: Cause.Cause<E>): string =>
causePrettyErrors<E>(cause).map((e) =>
e.cause ? `${e.stack} {\n${renderErrorCause(e.cause as Error, " ")}\n}` : e.stack
).join("\n")
const renderErrorCause = (cause: Error, prefix: string) => {
const lines = cause.stack!.split("\n")
let stack = `${prefix}[cause]: ${lines[0]}`
for (let i = 1, len = lines.length; i < len; i++) {
stack += `\n${prefix}${lines[i]}`
}
if (cause.cause) {
stack += ` {\n${renderErrorCause(cause.cause as Error, `${prefix} `)}\n${prefix}}`
}
return stack
}
// ----------------------------------------------------------------------------
// Fiber
// ----------------------------------------------------------------------------
/** @internal */
export const FiberTypeId = `~effect/Fiber/${version}` as const
const fiberVariance = {
_A: identity,
_E: identity
}
const fiberIdStore = { id: 0 }
/** @internal */
export const getCurrentFiber = (): Fiber.Fiber<any, any> | undefined => (globalThis as any)[currentFiberTypeId]
const keepAlive = (() => {
let count = 0
let running: ReturnType<typeof globalThis.setInterval> | undefined = undefined
return ({
increment() {
count++
running ??= globalThis.setInterval(constVoid, 2_147_483_647)
},
decrement() {
count--
if (count === 0 && running !== undefined) {
globalThis.clearInterval(running)
running = undefined
}
}
})
})()
/** @internal */
export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
constructor(
services: ServiceMap.ServiceMap<never>,
interruptible: boolean = true
) {
this[FiberTypeId] = fiberVariance as any
this.setServices(services)
this.id = ++fiberIdStore.id
this.currentOpCount = 0
this.currentLoopCount = 0
this.interruptible = interruptible
this._stack = []
this._observers = []
this._exit = undefined
this._children = undefined
this._interruptedCause = undefined
this._yielded = undefined
}
readonly [FiberTypeId]: Fiber.Fiber.Variance<A, E>
readonly id: number
interruptible: boolean
currentOpCount: number
currentLoopCount: number
readonly _stack: Array<Primitive>
readonly _observers: Array<(exit: Exit.Exit<A, E>) => void>
_exit: Exit.Exit<A, E> | undefined
_currentExit: Exit.Exit<A, E> | undefined
_children: Set<FiberImpl<any, any>> | undefined
_interruptedCause: Cause.Cause<never> | undefined
_yielded: Exit.Exit<any, any> | (() => void) | undefined
// set in setServices
services!: ServiceMap.ServiceMap<never>
currentScheduler!: Scheduler.Scheduler
currentTracerContext: Tracer.Tracer["context"]
currentSpan: Tracer.AnySpan | undefined
currentStackFrame: StackFrame | undefined
runtimeMetrics: Metric.FiberRuntimeMetricsService | undefined
maxOpsBeforeYield!: number
getRef<X>(ref: ServiceMap.Reference<X>): X {
return ServiceMap.getReferenceUnsafe(this.services, ref)
}
addObserver(cb: (exit: Exit.Exit<A, E>) => void): () => void {
if (this._exit) {
cb(this._exit)
return constVoid
}
this._observers.push(cb)
return () => {
const index = this._observers.indexOf(cb)
if (index >= 0) {
this._observers.splice(index, 1)
}
}
}
interruptUnsafe(fiberId?: number | undefined, annotations?: ServiceMap.ServiceMap<never> | undefined): void {
if (this._exit) {
return
}
let cause = causeInterrupt(fiberId)
if (this.currentStackFrame) {
cause = causeAnnotate(cause, ServiceMap.make(CauseStackTrace, this.currentStackFrame))
}
if (annotations) {
cause = causeAnnotate(cause, annotations)
}
this._interruptedCause = this._interruptedCause
? causeMerge(this._interruptedCause, cause)
: cause
if (this.interruptible) {
this.evaluate(failCause(this._interruptedCause) as any)
}
}
pollUnsafe(): Exit.Exit<A, E> | undefined {
return this._exit
}
evaluate(effect: Primitive): void {
this.runtimeMetrics?.recordFiberStart(this.services)
if (this._exit) {
return
} else if (this._yielded !== undefined) {
const yielded = this._yielded as () => void
this._yielded = undefined
yielded()
}
const exit = this.runLoop(effect)
if (exit === Yield) {
return
}
// the interruptChildren middleware is added in Effect.forkChild, so it can be
// tree-shaken if not used
const interruptChildren = fiberMiddleware.interruptChildren &&
fiberMiddleware.interruptChildren(this)
if (interruptChildren !== undefined) {
return this.evaluate(flatMap(interruptChildren, () => exit) as any)
}
this._exit = exit
this.runtimeMetrics?.recordFiberEnd(this.services, this._exit)
for (let i = 0; i < this._observers.length; i++) {
this._observers[i](exit)
}
this._observers.length = 0
}
runLoop(effect: Primitive): Exit.Exit<A, E> | Yield {
const prevFiber = (globalThis as any)[currentFiberTypeId]
;(globalThis as any)[currentFiberTypeId] = this
let yielding = false
let current: Primitive | Yield = effect
this.currentOpCount = 0
const currentLoop = ++this.currentLoopCount
try {
while (true) {
this.currentOpCount++
if (
!yielding &&
this.currentScheduler.shouldYield(this as any)
) {
yielding = true
const prev = current
current = flatMap(yieldNow, () => prev as any) as any
}
current = this.currentTracerContext
? this.currentTracerContext(() => (current as any)[evaluate](this), this)
: (current as any)[evaluate](this)
if (currentLoop !== this.currentLoopCount) {
// another effect has taken over the loop,
return Yield
} else if (current === Yield) {
const yielded = this._yielded!
if (ExitTypeId in yielded) {
this._yielded = undefined
return yielded
}
return Yield
}
}
} catch (error) {
if (!hasProperty(current, evaluate)) {
return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`)
}
return this.runLoop(exitDie(error) as any)
} finally {
;(globalThis as any)[currentFiberTypeId] = prevFiber
}
}
getCont<S extends contA | contE>(symbol: S):
| (Primitive & Record<S, (value: any, fiber: FiberImpl) => Primitive>)
| undefined
{
while (true) {
const op = this._stack.pop()
if (!op) return undefined
const cont = op[contAll] && op[contAll](this)
if (cont) return { [symbol]: cont } as any
if (op[symbol]) return op as any
}
}
yieldWith(value: Exit.Exit<any, any> | (() => void)): Yield {
this._yielded = value
return Yield
}
children(): Set<Fiber.Fiber<any, any>> {
return (this._children ??= new Set())
}
pipe() {
return pipeArguments(this, arguments)
}
setServices(services: ServiceMap.ServiceMap<never>): void {
this.services = services
this.currentScheduler = this.getRef(Scheduler.Scheduler)
this.currentSpan = services.mapUnsafe.get(Tracer.ParentSpanKey)
this.currentStackFrame = services.mapUnsafe.get(CurrentStackFrame.key)
this.maxOpsBeforeYield = this.getRef(Scheduler.MaxOpsBeforeYield)
this.runtimeMetrics = services.mapUnsafe.get(InternalMetric.FiberRuntimeMetricsKey)
const currentTracer = services.mapUnsafe.get(Tracer.TracerKey)
this.currentTracerContext = currentTracer ? currentTracer["context"] : undefined
}
get currentSpanLocal(): Tracer.Span | undefined {
return this.currentSpan?._tag === "Span" ? this.currentSpan : undefined
}
}
const fiberMiddleware = {
interruptChildren: undefined as
| ((fiber: FiberImpl) => Effect.Effect<void> | undefined)
| undefined
}
const fiberStackAnnotations = (fiber: Fiber.Fiber<any, any>) => {
if (!fiber.currentStackFrame) return undefined
const annotations = new Map<string, unknown>()
annotations.set(CauseStackTrace.key, fiber.currentStackFrame)
return ServiceMap.makeUnsafe(annotations)
}
const fiberInterruptChildren = (fiber: FiberImpl) => {
if (fiber._children === undefined || fiber._children.size === 0) {
return undefined
}
return fiberInterruptAll(fiber._children)
}
/** @internal */
export const fiberAwait = <A, E>(
self: Fiber.Fiber<A, E>
): Effect.Effect<Exit.Exit<A, E>> => {
const impl = self as FiberImpl<A, E>
if (impl._exit) return succeed(impl._exit)
return callback((resume) => {
if (impl._exit) return resume(succeed(impl._exit))
return sync(self.addObserver((exit) => resume(succeed(exit))))
})
}
/** @internal */
export const fiberAwaitAll = <Fiber extends Fiber.Fiber<any, any>>(
self: Iterable<Fiber>
): Effect.Effect<
Array<
Exit.Exit<
Fiber extends Fiber.Fiber<infer _A, infer _E> ? _A : never,
Fiber extends Fiber.Fiber<infer _A, infer _E> ? _E : never
>
>
> =>
callback((resume) => {
const iter = self[Symbol.iterator]() as Iterator<FiberImpl>
const exits: Array<Exit.Exit<any, any>> = []
let cancel: (() => void) | undefined = undefined
function loop() {
let result = iter.next()
while (!result.done) {
if (result.value._exit) {
exits.push(result.value._exit)
result = iter.next()
continue
}
cancel = result.value.addObserver((exit) => {
exits.push(exit)
loop()
})
return
}
resume(succeed(exits))
}
loop()
return sync(() => cancel?.())
})
/** @internal */
export const fiberJoin = <A, E>(self: Fiber.Fiber<A, E>): Effect.Effect<A, E> => {
const impl = self as FiberImpl<A, E>
if (impl._exit) return impl._exit
return callback((resume) => {
if (impl._exit) return resume(impl._exit)
return sync(self.addObserver(resume))
})
}
/** @internal */
export const fiberJoinAll = <A extends Iterable<Fiber.Fiber<any, any>>>(self: A): Effect.Effect<
Arr.ReadonlyArray.With<A, A extends Iterable<Fiber.Fiber<infer _A, infer _E>> ? _A : never>,
A extends Fiber.Fiber<infer _A, infer _E> ? _E : never
> =>
callback((resume) => {
const fibers = Array.from(self)
const out = new Array<any>(fibers.length) as Arr.NonEmptyArray<any>
const cancels = Arr.empty<() => void>()
let done = 0
let failed = false
for (let i = 0; i < fibers.length; i++) {
if (failed) break
cancels.push(fibers[i].addObserver((exit) => {
done++
if (exit._tag === "Failure") {
failed = true
cancels.forEach((cancel) => cancel())
return resume(exit as any)
}
out[i] = exit.value
if (done === fibers.length) {
resume(succeed(out))
}
}))
}
})
/** @internal */
export const fiberInterrupt = <A, E>(
self: Fiber.Fiber<A, E>
): Effect.Effect<void> => withFiber((fiber) => fiberInterruptAs(self, fiber.id))
/** @internal */
export const fiberInterruptAs: {
(fiberId: number): <A, E>(self: Fiber.Fiber<A, E>) => Effect.Effect<void>
<A, E>(self: Fiber.Fiber<A, E>, fiberId: number): Effect.Effect<void>
} = dual(2, <A, E>(self: Fiber.Fiber<A, E>, fiberId: number): Effect.Effect<void> =>
withFiber((parent) => {
self.interruptUnsafe(fiberId, fiberStackAnnotations(parent))
return asVoid(fiberAwait(self))
}))
/** @internal */
export const fiberInterruptAll = <A extends Iterable<Fiber.Fiber<any, any>>>(
fibers: A
): Effect.Effect<void> =>
withFiber((parent) => {
const annotations = fiberStackAnnotations(parent)
for (const fiber of fibers) {
fiber.interruptUnsafe(parent.id, annotations)
}
return asVoid(fiberAwaitAll(fibers))
})
/** @internal */
export const fiberInterruptAllAs: {
(fiberId: number): <A extends Iterable<Fiber.Fiber<any, any>>>(fibers: A) => Effect.Effect<void>
<A extends Iterable<Fiber.Fiber<any, any>>>(fibers: A, fiberId: number): Effect.Effect<void>
} = dual(2, <A extends Iterable<Fiber.Fiber<any, any>>>(
fibers: A,
fiberId: number
): Effect.Effect<void> =>
withFiber((parent) => {
const annotations = fiberStackAnnotations(parent)
for (const fiber of fibers) fiber.interruptUnsafe(fiberId, annotations)
return asVoid(fiberAwaitAll(fibers))
}))
/** @internal */
export const succeed: <A>(value: A) => Effect.Effect<A> = exitSucceed
/** @internal */
export const failCause: <E>(cause: Cause.Cause<E>) => Effect.Effect<never, E> = exitFailCause
/** @internal */
export const fail: <E>(error: E) => Effect.Effect<never, E> = exitFail
/** @internal */
export const sync: <A>(thunk: LazyArg<A>) => Effect.Effect<A> = makePrimitive({
op: "Sync",
[evaluate](fiber): Primitive | Yield {
const value = this[args]()
const cont = fiber.getCont(contA)
return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value))
}
})
/** @internal */
export const suspend: <A, E, R>(
evaluate: LazyArg<Effect.Effect<A, E, R>>
) => Effect.Effect<A, E, R> = makePrimitive({
op: "Suspend",
[evaluate](_fiber) {
return this[args]()
}
})
/** @internal */
export const fromYieldable = <Self extends Effect.Yieldable.Any, A, E, R>(
yieldable: Effect.Yieldable<Self, A, E, R>
): Effect.Effect<A, E, R> => yieldable.asEffect()
/** @internal */
export const fromOption: <A>(option: Option.Option<A>) => Effect.Effect<A, Cause.NoSuchElementError> = fromYieldable
/** @internal */
export const fromResult: <A, E>(result: Result.Result<A, E>) => Effect.Effect<A, E> = fromYieldable
/** @internal */
export const fromNullishOr = <A>(value: A): Effect.Effect<NonNullable<A>, Cause.NoSuchElementError> =>
value == null ? fail(new NoSuchElementError()) : succeed(value)
/** @internal */
export const yieldNowWith: (priority?: number) => Effect.Effect<void> = makePrimitive({
op: "Yield",
[evaluate](fiber) {
let resumed = false
fiber.currentScheduler.scheduleTask(() => {
if (resumed) return
fiber.evaluate(exitVoid as any)
}, this[args] ?? 0)
return fiber.yieldWith(() => {
resumed = true
})
}
})
/** @internal */
export const yieldNow: Effect.Effect<void> = yieldNowWith(0)
/** @internal */
export const succeedSome = <A>(a: A): Effect.Effect<Option.Option<A>> => succeed(Option.some(a))
/** @internal */
export const succeedNone: Effect.Effect<Option.Option<never>> = succeed(
Option.none()
)
/** @internal */
export const failCauseSync = <E>(
evaluate: LazyArg<Cause.Cause<E>>
): Effect.Effect<never, E> => suspend(() => failCause(internalCall(evaluate)))
/** @internal */
export const die = (defect: unknown): Effect.Effect<never> => exitDie(defect)
/** @internal */
export const failSync = <E>(error: LazyArg<E>): Effect.Effect<never, E> => suspend(() => fail(internalCall(error)))
/** @internal */
const void_: Effect.Effect<void> = succeed(void 0)
/** @internal */
export { void_ as void }
/** @internal */
const try_ = <A, E>(options: {
try: LazyArg<A>
catch: (error: unknown) => E
}): Effect.Effect<A, E> =>
suspend(() => {
try {
return succeed(internalCall(options.try))
} catch (err) {
return fail(internalCall(() => options.catch(err)))
}
})
/** @internal */
export { try_ as try }
/** @internal */
export const promise = <A>(
evaluate: (signal: AbortSignal) => PromiseLike<A>
): Effect.Effect<A> =>
callbackOptions<A>(function(resume, signal) {
internalCall(() => evaluate(signal!)).then(
(a) => resume(succeed(a)),
(e) => resume(die(e))
)
}, evaluate.length !== 0)
/** @internal */
export const tryPromise = <A, E = Cause.UnknownError>(
options: {
readonly try: (signal: AbortSignal) => PromiseLike<A>
readonly catch: (error: unknown) => E
} | ((signal: AbortSignal) => PromiseLike<A>)
): Effect.Effect<A, E> => {
const f = typeof options === "function" ? options : options.try
const catcher = typeof options === "function"
? ((cause: unknown) => new UnknownError(cause, "An error occurred in Effect.tryPromise"))
: options.catch
return callbackOptions<A, E>(function(resume, signal) {
try {
internalCall(() => f(signal!)).then(
(a) => resume(succeed(a)),
(e) => resume(fail(internalCall(() => catcher(e)) as E))
)
} catch (err) {
resume(fail(internalCall(() => catcher(err)) as E))
}
}, eval.length !== 0)
}
/** @internal */
export const withFiberId = <A, E, R>(
f: (fiberId: number) => Effect.Effect<A, E, R>
): Effect.Effect<A, E, R> => withFiber((fiber) => f(fiber.id))
/** @internal */
export const fiber = withFiber(succeed)
/** @internal */
export const fiberId = withFiberId(succeed)
const callbackOptions: <A, E = never, R = never>(
register: (
this: Scheduler.Scheduler,
resume: (effect: Effect.Effect<A, E, R>) => void,
signal?: AbortSignal
) => void | Effect.Effect<void, never, R>,
withSignal: boolean
) => Effect.Effect<A, E, R> = makePrimitive({
op: "Async",
single: false,
[evaluate](fiber) {
const register = internalCall(() => this[args][0].bind(fiber.currentScheduler))
let resumed = false
let yielded: boolean | Primitive = false