Open History to see the last commit
1/**
2 * One-time coordination cells for Effect programs. A `Deferred<A, E>` starts
3 * empty, can be completed exactly once with a success, failure, defect, or
4 * interruption, and lets any number of fibers wait for that result. Awaiting a
5 * `Deferred` suspends the fiber instead of blocking an operating-system thread,
6 * and every waiter observes the same completion.
7 *
8 * @since 2.0.0
9 */
10import type * as Cause from "./Cause.ts"
11import type { Effect } from "./Effect.ts"
12import type * as Exit from "./Exit.ts"
13import { dual, identity, type LazyArg } from "./Function.ts"
14import * as core from "./internal/core.ts"
15import * as internalEffect from "./internal/effect.ts"
16import * as Option from "./Option.ts"
17import type { Pipeable } from "./Pipeable.ts"
18import { pipeArguments } from "./Pipeable.ts"
19import { hasProperty } from "./Predicate.ts"
20import type * as Types from "./Types.ts"
21
22const TypeId = "~effect/Deferred"
23
24/**
25 * A `Deferred` represents an asynchronous variable that can be set exactly
26 * once, with the ability for an arbitrary number of fibers to suspend (by
27 * calling `Deferred.await`) and automatically resume when the variable is set.
28 *
29 * **When to use**
30 *
31 * Use to coordinate multiple fibers around a value or failure that will be
32 * supplied exactly once.
33 *
34 * **Example** (Creating a Deferred for inter-fiber communication)
35 *
36 * ```ts
37 * import { Deferred, Effect, Fiber } from "effect"
38 *
39 * // Create and use a Deferred for inter-fiber communication
40 * const program = Effect.gen(function*() {
41 * // Create a Deferred that will hold a string value
42 * const deferred: Deferred.Deferred<string> = yield* Deferred.make<string>()
43 *
44 * // Fork a fiber that will set the deferred value
45 * const producer = yield* Effect.forkChild(
46 * Effect.gen(function*() {
47 * yield* Effect.sleep("100 millis")
48 * yield* Deferred.succeed(deferred, "Hello, World!")
49 * })
50 * )
51 *
52 * // Fork a fiber that will await the deferred value
53 * const consumer = yield* Effect.forkChild(
54 * Effect.gen(function*() {
55 * const value = yield* Deferred.await(deferred)
56 * console.log("Received:", value)
57 * return value
58 * })
59 * )
60 *
61 * // Wait for both fibers to complete
62 * yield* Fiber.join(producer)
63 * const result = yield* Fiber.join(consumer)
64 * return result
65 * })
66 * ```
67 *
68 * @category models
69 * @since 2.0.0
70 */
71export interface Deferred<in out A, in out E = never> extends Deferred.Variance<A, E>, Pipeable {
72 effect?: Effect<A, E>
73 resumes?: Array<(effect: Effect<A, E>) => void> | undefined
74}
75
76/**
77 * Checks whether a value is a `Deferred`.
78 *
79 * **When to use**
80 *
81 * Use to validate unknown values at runtime boundaries before treating them as
82 * `Deferred` values.
83 *
84 * @category guards
85 * @since 4.0.0
86 */
87export const isDeferred = <A, E>(u: unknown): u is Deferred<A, E> => hasProperty(u, TypeId)
88
89/**
90 * Companion namespace containing type-level metadata for `Deferred`.
91 *
92 * **When to use**
93 *
94 * Use to reference type-level metadata associated with `Deferred`.
95 *
96 * @since 2.0.0
97 */
98export declare namespace Deferred {
99 /**
100 * Type-level variance marker for the value and error channels of `Deferred`.
101 *
102 * **When to use**
103 *
104 * Use to carry the value and error type parameters for `Deferred` in Effect's
105 * type machinery.
106 *
107 * **Details**
108 *
109 * This interface is part of the public type structure and is not intended to
110 * be constructed directly.
111 *
112 * @category models
113 * @since 2.0.0
114 */
115 export interface Variance<in out A, in out E> {
116 readonly [TypeId]: {
117 readonly _A: Types.Invariant<A>
118 readonly _E: Types.Invariant<E>
119 }
120 }
121}
122
123const DeferredProto = {
124 [TypeId]: {
125 _A: identity,
126 _E: identity
127 },
128 pipe() {
129 return pipeArguments(this, arguments)
130 }
131}
132
133/**
134 * Creates an empty `Deferred` synchronously outside the `Effect` runtime.
135 *
136 * **When to use**
137 *
138 * Use to allocate a `Deferred` synchronously when direct allocation outside
139 * `Effect` is required.
140 *
141 * **Example** (Creating a Deferred unsafely)
142 *
143 * ```ts
144 * import { Deferred } from "effect"
145 *
146 * const deferred = Deferred.makeUnsafe<number>()
147 * console.log(deferred)
148 * ```
149 *
150 * @category unsafe
151 * @since 4.0.0
152 */
153export const makeUnsafe = <A, E = never>(): Deferred<A, E> => {
154 const self = Object.create(DeferredProto)
155 self.resumes = undefined
156 self.effect = undefined
157 return self
158}
159
160/**
161 * Creates a new `Deferred`.
162 *
163 * **When to use**
164 *
165 * Use to allocate an empty `Deferred` inside an `Effect` workflow.
166 *
167 * **Example** (Creating a Deferred)
168 *
169 * ```ts
170 * import { Deferred, Effect } from "effect"
171 *
172 * const program = Effect.gen(function*() {
173 * const deferred = yield* Deferred.make<number>()
174 * yield* Deferred.succeed(deferred, 42)
175 * const value = yield* Deferred.await(deferred)
176 * console.log(value) // 42
177 * })
178 * ```
179 *
180 * @category constructors
181 * @since 2.0.0
182 */
183export const make = <A, E = never>(): Effect<Deferred<A, E>> => internalEffect.sync(() => makeUnsafe())
184
185const _await = <A, E>(self: Deferred<A, E>): Effect<A, E> =>
186 internalEffect.callback<A, E>((resume) => {
187 if (self.effect) return resume(self.effect)
188 self.resumes ??= []
189 self.resumes.push(resume)
190 return internalEffect.sync(() => {
191 const index = self.resumes!.indexOf(resume)
192 self.resumes!.splice(index, 1)
193 })
194 })
195
196export {
197 /**
198 * Retrieves the value of the `Deferred`, suspending the fiber running the
199 * workflow until the result is available.
200 *
201 * **When to use**
202 *
203 * Use to wait for a `Deferred` to be completed and resume with its success,
204 * failure, defect, or interruption.
205 *
206 * **Details**
207 *
208 * Awaiters observe the completion effect stored in the `Deferred`.
209 *
210 * **Example** (Awaiting a Deferred value)
211 *
212 * ```ts
213 * import { Deferred, Effect } from "effect"
214 *
215 * const program = Effect.gen(function*() {
216 * const deferred = yield* Deferred.make<number>()
217 * yield* Deferred.succeed(deferred, 42)
218 *
219 * const value = yield* Deferred.await(deferred)
220 * console.log(value) // 42
221 * })
222 * ```
223 *
224 * @see {@link complete} for completing from an effect and memoizing its result
225 * @see {@link completeWith} for completing with an effect directly
226 *
227 * @category getters
228 * @since 2.0.0
229 */
230 _await as await
231}
232
233/**
234 * Runs the supplied `Effect` and attempts to complete the `Deferred` with its
235 * memoized result.
236 *
237 * **When to use**
238 *
239 * Use when completing a `Deferred` should run an effect once and share its
240 * result with all awaiters.
241 *
242 * **Details**
243 *
244 * The returned effect succeeds with `true` when this call completed the
245 * `Deferred`, or `false` if it was already completed.
246 *
247 * **Example** (Completing a Deferred from an effect)
248 *
249 * ```ts
250 * import { Deferred, Effect } from "effect"
251 *
252 * const program = Effect.gen(function*() {
253 * const deferred = yield* Deferred.make<number>()
254 * const completed = yield* Deferred.complete(deferred, Effect.succeed(42))
255 * console.log(completed) // true
256 *
257 * const value = yield* Deferred.await(deferred)
258 * console.log(value) // 42
259 * })
260 * ```
261 *
262 * @see {@link completeWith} for storing an effect directly without memoizing its result
263 *
264 * @category completion
265 * @since 2.0.0
266 */
267export const complete: {
268 <A, E, R>(effect: Effect<A, E, R>): (self: Deferred<A, E>) => Effect<boolean, never, R>
269 <A, E, R>(self: Deferred<A, E>, effect: Effect<A, E, R>): Effect<boolean, never, R>
270} = dual(
271 2,
272 <A, E, R>(self: Deferred<A, E>, effect: Effect<A, E, R>): Effect<boolean, never, R> =>
273 internalEffect.suspend(() => self.effect ? internalEffect.succeed(false) : into(effect, self))
274)
275
276/**
277 * Attempts to complete the `Deferred` with the specified effect directly.
278 *
279 * **When to use**
280 *
281 * Use to store an already environment-free effect as the completion without
282 * running it during completion.
283 *
284 * **Details**
285 *
286 * The returned effect succeeds with `true` when this call completed the
287 * `Deferred`, or `false` if it was already completed.
288 *
289 * **Gotchas**
290 *
291 * The supplied effect is not memoized by `completeWith`; each awaiter may run
292 * the stored effect independently.
293 *
294 * **Example** (Completing a Deferred with an effect)
295 *
296 * ```ts
297 * import { Deferred, Effect } from "effect"
298 *
299 * const program = Effect.gen(function*() {
300 * const deferred = yield* Deferred.make<number>()
301 * const completed = yield* Deferred.completeWith(deferred, Effect.succeed(42))
302 * console.log(completed) // true
303 *
304 * const value = yield* Deferred.await(deferred)
305 * console.log(value) // 42
306 * })
307 * ```
308 *
309 * @see {@link complete} for running an effect once and sharing its result
310 * @see {@link done} for completing from an already computed `Exit`
311 *
312 * @category completion
313 * @since 2.0.0
314 */
315export const completeWith: {
316 <A, E>(effect: Effect<A, E>): (self: Deferred<A, E>) => Effect<boolean>
317 <A, E>(self: Deferred<A, E>, effect: Effect<A, E>): Effect<boolean>
318} = dual(
319 2,
320 <A, E>(self: Deferred<A, E>, effect: Effect<A, E>): Effect<boolean> =>
321 internalEffect.sync(() => doneUnsafe(self, effect))
322)
323
324/**
325 * Completes the `Deferred` with the specified `Exit` value, which will be
326 * propagated to all fibers waiting on the value of the `Deferred`.
327 *
328 * **When to use**
329 *
330 * Use to complete a `Deferred` from an already computed `Exit`.
331 *
332 * **Details**
333 *
334 * The returned effect succeeds with `true` when this call completed the
335 * `Deferred`, or `false` if it was already completed.
336 *
337 * **Example** (Completing a Deferred with an Exit)
338 *
339 * ```ts
340 * import { Deferred, Effect, Exit } from "effect"
341 *
342 * const program = Effect.gen(function*() {
343 * const deferred = yield* Deferred.make<number>()
344 * yield* Deferred.done(deferred, Exit.succeed(42))
345 *
346 * const value = yield* Deferred.await(deferred)
347 * console.log(value) // 42
348 * })
349 * ```
350 *
351 * @see {@link complete} for completing from an effect and memoizing its result
352 * @see {@link completeWith} for storing an effect directly
353 * @see {@link succeed} for completing with a success value
354 * @see {@link failCause} for completing with a failure cause
355 *
356 * @category completion
357 * @since 2.0.0
358 */
359export const done: {
360 <A, E>(exit: Exit.Exit<A, E>): (self: Deferred<A, E>) => Effect<boolean>
361 <A, E>(self: Deferred<A, E>, exit: Exit.Exit<A, E>): Effect<boolean>
362} = completeWith as any
363
364/**
365 * Attempts to complete the `Deferred` with the specified error.
366 *
367 * **When to use**
368 *
369 * Use to complete a `Deferred` with a typed failure value.
370 *
371 * **Details**
372 *
373 * Fibers waiting on the `Deferred` fail with that error only if this call
374 * completes it. The returned effect succeeds with `true` when this call
375 * completed the `Deferred`, or `false` if it was already completed.
376 *
377 * **Example** (Failing a Deferred with an error)
378 *
379 * ```ts
380 * import { Deferred, Effect } from "effect"
381 *
382 * const program = Effect.gen(function*() {
383 * const deferred = yield* Deferred.make<number, string>()
384 * const success = yield* Deferred.fail(deferred, "Operation failed")
385 * console.log(success) // true
386 * })
387 * ```
388 *
389 * @category completion
390 * @since 2.0.0
391 */
392export const fail: {
393 <E>(error: E): <A>(self: Deferred<A, E>) => Effect<boolean>
394 <A, E>(self: Deferred<A, E>, error: E): Effect<boolean>
395} = dual(2, <A, E>(self: Deferred<A, E>, error: E): Effect<boolean> => done(self, core.exitFail(error)))
396
397/**
398 * Computes an error when the returned effect is run, then attempts to complete
399 * the `Deferred` with that error.
400 *
401 * **When to use**
402 *
403 * Use to lazily compute a typed failure value when the `Deferred` completion
404 * effect runs.
405 *
406 * **Details**
407 *
408 * Fibers waiting on the `Deferred` fail with the computed error only if this
409 * call completes it. The returned effect succeeds with `true` when this call
410 * completed the `Deferred`, or `false` if it was already completed.
411 *
412 * **Example** (Failing a Deferred with a lazy error)
413 *
414 * ```ts
415 * import { Deferred, Effect } from "effect"
416 *
417 * const program = Effect.gen(function*() {
418 * const deferred = yield* Deferred.make<number, string>()
419 * const success = yield* Deferred.failSync(deferred, () => "Lazy error")
420 * console.log(success) // true
421 * })
422 * ```
423 *
424 * @category completion
425 * @since 2.0.0
426 */
427export const failSync: {
428 <E>(evaluate: LazyArg<E>): <A>(self: Deferred<A, E>) => Effect<boolean>
429 <A, E>(self: Deferred<A, E>, evaluate: LazyArg<E>): Effect<boolean>
430} = dual(
431 2,
432 <A, E>(self: Deferred<A, E>, evaluate: LazyArg<E>): Effect<boolean> =>
433 internalEffect.suspend(() => fail(self, evaluate()))
434)
435
436/**
437 * Attempts to complete the `Deferred` with the specified `Cause`.
438 *
439 * **When to use**
440 *
441 * Use to complete a `Deferred` with a full failure cause.
442 *
443 * **Details**
444 *
445 * Fibers waiting on the `Deferred` observe that cause only if this call
446 * completes it. The returned effect succeeds with `true` when this call
447 * completed the `Deferred`, or `false` if it was already completed.
448 *
449 * **Example** (Failing a Deferred with a Cause)
450 *
451 * ```ts
452 * import { Cause, Deferred, Effect } from "effect"
453 *
454 * const program = Effect.gen(function*() {
455 * const deferred = yield* Deferred.make<number, string>()
456 * const success = yield* Deferred.failCause(
457 * deferred,
458 * Cause.fail("Operation failed")
459 * )
460 * console.log(success) // true
461 * })
462 * ```
463 *
464 * @category completion
465 * @since 2.0.0
466 */
467export const failCause: {
468 <E>(cause: Cause.Cause<E>): <A>(self: Deferred<A, E>) => Effect<boolean>
469 <A, E>(self: Deferred<A, E>, cause: Cause.Cause<E>): Effect<boolean>
470} = dual(
471 2,
472 <A, E>(self: Deferred<A, E>, cause: Cause.Cause<E>): Effect<boolean> => done(self, core.exitFailCause(cause))
473)
474
475/**
476 * Computes a `Cause` when the returned effect is run, then attempts to
477 * complete the `Deferred` with that cause.
478 *
479 * **When to use**
480 *
481 * Use to lazily compute a full failure cause when the `Deferred` completion
482 * effect runs.
483 *
484 * **Details**
485 *
486 * Fibers waiting on the `Deferred` observe the computed cause only if this
487 * call completes it. The returned effect succeeds with `true` when this call
488 * completed the `Deferred`, or `false` if it was already completed.
489 *
490 * **Example** (Failing a Deferred with a lazy Cause)
491 *
492 * ```ts
493 * import { Cause, Deferred, Effect } from "effect"
494 *
495 * const program = Effect.gen(function*() {
496 * const deferred = yield* Deferred.make<number, string>()
497 * const success = yield* Deferred.failCauseSync(
498 * deferred,
499 * () => Cause.fail("Lazy error")
500 * )
501 * console.log(success) // true
502 * })
503 * ```
504 *
505 * @category completion
506 * @since 2.0.0
507 */
508export const failCauseSync: {
509 <E>(evaluate: LazyArg<Cause.Cause<E>>): <A>(self: Deferred<A, E>) => Effect<boolean>
510 <A, E>(self: Deferred<A, E>, evaluate: LazyArg<Cause.Cause<E>>): Effect<boolean>
511} = dual(
512 2,
513 <A, E>(self: Deferred<A, E>, evaluate: LazyArg<Cause.Cause<E>>): Effect<boolean> =>
514 internalEffect.suspend(() => failCause(self, evaluate()))
515)
516
517/**
518 * Attempts to complete the `Deferred` with a defect.
519 *
520 * **When to use**
521 *
522 * Use to complete a `Deferred` with an unexpected defect.
523 *
524 * **Details**
525 *
526 * Fibers waiting on the `Deferred` die with that defect only if this call
527 * completes it. The returned effect succeeds with `true` when this call
528 * completed the `Deferred`, or `false` if it was already completed.
529 *
530 * **Example** (Killing a Deferred with a defect)
531 *
532 * ```ts
533 * import { Deferred, Effect } from "effect"
534 *
535 * const program = Effect.gen(function*() {
536 * const deferred = yield* Deferred.make<number>()
537 * const success = yield* Deferred.die(
538 * deferred,
539 * new Error("Something went wrong")
540 * )
541 * console.log(success) // true
542 * })
543 * ```
544 *
545 * @category completion
546 * @since 2.0.0
547 */
548export const die: {
549 (defect: unknown): <A, E>(self: Deferred<A, E>) => Effect<boolean>
550 <A, E>(self: Deferred<A, E>, defect: unknown): Effect<boolean>
551} = dual(2, <A, E>(self: Deferred<A, E>, defect: unknown): Effect<boolean> => done(self, core.exitDie(defect)))
552
553/**
554 * Computes a defect when the returned effect is run, then attempts to complete
555 * the `Deferred` with that defect.
556 *
557 * **When to use**
558 *
559 * Use to lazily compute an unexpected defect when the completion effect runs.
560 *
561 * **Details**
562 *
563 * Fibers waiting on the `Deferred` die with the computed defect only if this
564 * call completes it. The returned effect succeeds with `true` when this call
565 * completed the `Deferred`, or `false` if it was already completed.
566 *
567 * **Example** (Killing a Deferred with a lazy defect)
568 *
569 * ```ts
570 * import { Deferred, Effect } from "effect"
571 *
572 * const program = Effect.gen(function*() {
573 * const deferred = yield* Deferred.make<number>()
574 * const success = yield* Deferred.dieSync(
575 * deferred,
576 * () => new Error("Lazy error")
577 * )
578 * console.log(success) // true
579 * })
580 * ```
581 *
582 * @category completion
583 * @since 2.0.0
584 */
585export const dieSync: {
586 (evaluate: LazyArg<unknown>): <A, E>(self: Deferred<A, E>) => Effect<boolean>
587 <A, E>(self: Deferred<A, E>, evaluate: LazyArg<unknown>): Effect<boolean>
588} = dual(
589 2,
590 <A, E>(self: Deferred<A, E>, evaluate: LazyArg<unknown>): Effect<boolean> =>
591 internalEffect.suspend(() => die(self, evaluate()))
592)
593
594/**
595 * Attempts to complete the `Deferred` with interruption by the current fiber.
596 *
597 * **When to use**
598 *
599 * Use to complete a `Deferred` as interrupted by the current fiber.
600 *
601 * **Details**
602 *
603 * Fibers waiting on the `Deferred` are interrupted with the current fiber id
604 * only if this call completes it. The returned effect succeeds with `true`
605 * when this call completed the `Deferred`, or `false` if it was already
606 * completed.
607 *
608 * **Example** (Interrupting a Deferred)
609 *
610 * ```ts
611 * import { Deferred, Effect } from "effect"
612 *
613 * const program = Effect.gen(function*() {
614 * const deferred = yield* Deferred.make<number>()
615 * const success = yield* Deferred.interrupt(deferred)
616 * console.log(success) // true
617 * })
618 * ```
619 *
620 * @category completion
621 * @since 2.0.0
622 */
623export const interrupt = <A, E>(self: Deferred<A, E>): Effect<boolean> =>
624 core.withFiber((fiber) => interruptWith(self, fiber.id))
625
626/**
627 * Attempts to complete the `Deferred` with interruption by the specified
628 * `FiberId`.
629 *
630 * **When to use**
631 *
632 * Use to complete a `Deferred` as interrupted by a specific fiber id.
633 *
634 * **Details**
635 *
636 * Fibers waiting on the `Deferred` are interrupted with that fiber id only if
637 * this call completes it. The returned effect succeeds with `true` when this
638 * call completed the `Deferred`, or `false` if it was already completed.
639 *
640 * **Example** (Interrupting a Deferred with a fiber id)
641 *
642 * ```ts
643 * import { Deferred, Effect } from "effect"
644 *
645 * const program = Effect.gen(function*() {
646 * const deferred = yield* Deferred.make<number>()
647 * const success = yield* Deferred.interruptWith(deferred, 42)
648 * console.log(success) // true
649 * })
650 * ```
651 *
652 * @category completion
653 * @since 2.0.0
654 */
655export const interruptWith: {
656 (fiberId: number): <A, E>(self: Deferred<A, E>) => Effect<boolean>
657 <A, E>(self: Deferred<A, E>, fiberId: number): Effect<boolean>
658} = dual(
659 2,
660 <A, E>(self: Deferred<A, E>, fiberId: number): Effect<boolean> =>
661 failCause(self, internalEffect.causeInterrupt(fiberId))
662)
663
664/**
665 * Returns `true` if this `Deferred` has already been completed with a value or
666 * an error, `false` otherwise.
667 *
668 * **When to use**
669 *
670 * Use to check completion status inside an `Effect` workflow.
671 *
672 * **Example** (Checking Deferred completion)
673 *
674 * ```ts
675 * import { Deferred, Effect } from "effect"
676 *
677 * const program = Effect.gen(function*() {
678 * const deferred = yield* Deferred.make<number>()
679 * const beforeCompletion = yield* Deferred.isDone(deferred)
680 * console.log(beforeCompletion) // false
681 *
682 * yield* Deferred.succeed(deferred, 42)
683 * const afterCompletion = yield* Deferred.isDone(deferred)
684 * console.log(afterCompletion) // true
685 * })
686 * ```
687 *
688 * @category getters
689 * @since 2.0.0
690 */
691export const isDone = <A, E>(self: Deferred<A, E>): Effect<boolean> => internalEffect.sync(() => isDoneUnsafe(self))
692
693/**
694 * Returns whether this `Deferred` has already been completed synchronously.
695 *
696 * **When to use**
697 *
698 * Use to check `Deferred` completion synchronously in code that cannot return
699 * an `Effect`, such as low-level integration code.
700 *
701 * @see {@link isDone} for checking completion inside `Effect`
702 * @see {@link poll} for reading the completed effect when available
703 *
704 * @category getters
705 * @since 4.0.0
706 */
707export const isDoneUnsafe = <A, E>(self: Deferred<A, E>): boolean => self.effect !== undefined
708
709/**
710 * Returns the current completion effect as an `Option`. This returns
711 * `Option.some(effect)` when the `Deferred` is completed, `Option.none()`
712 * otherwise.
713 *
714 * **When to use**
715 *
716 * Use to inspect whether a `Deferred` is already completed and retrieve its
717 * stored completion effect when available.
718 *
719 * **Example** (Polling Deferred completion)
720 *
721 * ```ts
722 * import { Deferred, Effect } from "effect"
723 *
724 * const program = Effect.gen(function*() {
725 * const deferred = yield* Deferred.make<number>()
726 * const beforeCompletion = yield* Deferred.poll(deferred)
727 * console.log(beforeCompletion._tag === "None") // true
728 *
729 * yield* Deferred.succeed(deferred, 42)
730 * const afterCompletion = yield* Deferred.poll(deferred)
731 * console.log(afterCompletion._tag === "Some") // true
732 * })
733 * ```
734 *
735 * @category getters
736 * @since 2.0.0
737 */
738export function poll<A, E>(self: Deferred<A, E>): Effect<Option.Option<Effect<A, E>>> {
739 return internalEffect.sync(() => Option.fromUndefinedOr(self.effect))
740}
741
742/**
743 * Attempts to complete the `Deferred` with the specified value.
744 *
745 * **When to use**
746 *
747 * Use to complete a `Deferred` with a successful value.
748 *
749 * **Details**
750 *
751 * Fibers waiting on the `Deferred` receive the value only if this call
752 * completes it. The returned effect succeeds with `true` when this call
753 * completed the `Deferred`, or `false` if it was already completed.
754 *
755 * **Example** (Completing a Deferred with a value)
756 *
757 * ```ts
758 * import { Deferred, Effect } from "effect"
759 *
760 * const program = Effect.gen(function*() {
761 * const deferred = yield* Deferred.make<number>()
762 * yield* Deferred.succeed(deferred, 42)
763 *
764 * const value = yield* Deferred.await(deferred)
765 * console.log(value) // 42
766 * })
767 * ```
768 *
769 * @category completion
770 * @since 2.0.0
771 */
772export const succeed: {
773 <A>(value: A): <E>(self: Deferred<A, E>) => Effect<boolean>
774 <A, E>(self: Deferred<A, E>, value: A): Effect<boolean>
775} = dual(2, <A, E>(self: Deferred<A, E>, value: A): Effect<boolean> => done(self, core.exitSucceed(value)))
776
777/**
778 * Computes a value when the returned effect is run, then attempts to complete
779 * the `Deferred` with that value.
780 *
781 * **When to use**
782 *
783 * Use to lazily compute a successful value when the `Deferred` completion
784 * effect runs.
785 *
786 * **Details**
787 *
788 * Fibers waiting on the `Deferred` receive the computed value only if this call
789 * completes it. The returned effect succeeds with `true` when this call
790 * completed the `Deferred`, or `false` if it was already completed.
791 *
792 * **Example** (Completing a Deferred with a lazy value)
793 *
794 * ```ts
795 * import { Deferred, Effect } from "effect"
796 *
797 * const program = Effect.gen(function*() {
798 * const deferred = yield* Deferred.make<number>()
799 * yield* Deferred.sync(deferred, () => 42)
800 *
801 * const value = yield* Deferred.await(deferred)
802 * console.log(value) // 42
803 * })
804 * ```
805 *
806 * @category completion
807 * @since 2.0.0
808 */
809export const sync: {
810 <A>(evaluate: LazyArg<A>): <E>(self: Deferred<A, E>) => Effect<boolean>
811 <A, E>(self: Deferred<A, E>, evaluate: LazyArg<A>): Effect<boolean>
812} = dual(
813 2,
814 <A, E>(self: Deferred<A, E>, evaluate: LazyArg<A>): Effect<boolean> =>
815 internalEffect.suspend(() => succeed(self, evaluate()))
816)
817
818/**
819 * Attempts to complete the `Deferred` synchronously with the specified
820 * completion effect.
821 *
822 * **When to use**
823 *
824 * Use to complete a `Deferred` synchronously in low-level code that already has
825 * the completion effect.
826 *
827 * **Details**
828 *
829 * This mutates the `Deferred` directly and should be reserved for low-level
830 * code; prefer the effectful completion APIs when possible. Returns `true` if
831 * this call completed the `Deferred`, or `false` if it was already completed.
832 *
833 * **Example** (Completing a Deferred unsafely)
834 *
835 * ```ts
836 * import { Deferred, Effect } from "effect"
837 *
838 * const deferred = Deferred.makeUnsafe<number>()
839 * const success = Deferred.doneUnsafe(deferred, Effect.succeed(42))
840 * console.log(success) // true
841 * ```
842 *
843 * @category unsafe
844 * @since 4.0.0
845 */
846export const doneUnsafe = <A, E>(self: Deferred<A, E>, effect: Effect<A, E>): boolean => {
847 if (self.effect) return false
848 self.effect = effect
849 if (self.resumes) {
850 for (let i = 0; i < self.resumes.length; i++) {
851 self.resumes[i](effect)
852 }
853 self.resumes = undefined
854 }
855 return true
856}
857
858/**
859 * Runs an `Effect` and attempts to complete a `Deferred` with the effect's
860 * result.
861 *
862 * **When to use**
863 *
864 * Use to pipe an effect result into a `Deferred` while preserving success,
865 * failure, defects, and interruption.
866 *
867 * **Details**
868 *
869 * If the effect succeeds, fails, dies, or is interrupted, that result is used
870 * as the attempted completion. The returned effect cannot fail; it succeeds
871 * with `true` if it completed the `Deferred`, or `false` if the `Deferred` was
872 * already completed.
873 *
874 * **Example** (Completing a Deferred from an effect result)
875 *
876 * ```ts
877 * import { Deferred, Effect } from "effect"
878 *
879 * // Define an effect that succeeds
880 * const successEffect = Effect.succeed(42)
881 *
882 * const program = Effect.gen(function*() {
883 * // Create a deferred
884 * const deferred = yield* Deferred.make<number, string>()
885 *
886 * // Complete the deferred using the successEffect
887 * const isCompleted = yield* Deferred.into(successEffect, deferred)
888 *
889 * // Access the value of the deferred
890 * const value = yield* Deferred.await(deferred)
891 * console.log(value)
892 *
893 * return isCompleted
894 * })
895 *
896 * Effect.runPromise(program).then(console.log)
897 * // Output:
898 * // 42
899 * // true
900 * ```
901 *
902 * @category Synchronization Utilities
903 * @since 4.0.0
904 */
905export const into: {
906 <A, E>(deferred: Deferred<A, E>): <R>(self: Effect<A, E, R>) => Effect<boolean, never, R>
907 <A, E, R>(self: Effect<A, E, R>, deferred: Deferred<A, E>): Effect<boolean, never, R>
908} = dual(
909 2,
910 <A, E, R>(self: Effect<A, E, R>, deferred: Deferred<A, E>): Effect<boolean, never, R> =>
911 internalEffect.uninterruptibleMask((restore) =>
912 internalEffect.flatMap(
913 internalEffect.exit(restore(self)),
914 (exit) => done(deferred, exit)
915 )
916 )
917)