import * as Chunk from "@effect/data/Chunk" import * as Context from "@effect/data/Context" import * as Duration from "@effect/data/Duration" import * as Either from "@effect/data/Either" import * as Equal from "@effect/data/Equal" import type { LazyArg } from "@effect/data/Function" import { constVoid, dual, pipe } from "@effect/data/Function" import * as Option from "@effect/data/Option" import { pipeArguments } from "@effect/data/Pipeable" import type { Predicate, Refinement } from "@effect/data/Predicate" import type * as Cause from "@effect/io/Cause" import * as Clock from "@effect/io/Clock" import type * as Effect from "@effect/io/Effect" import * as internalCause from "@effect/io/internal/cause" import * as core from "@effect/io/internal/core" import * as effect from "@effect/io/internal/effect" import * as ref from "@effect/io/internal/ref" import * as Random from "@effect/io/Random" import type * as Ref from "@effect/io/Ref" import type * as Schedule from "@effect/io/Schedule" import * as ScheduleDecision from "@effect/io/ScheduleDecision" import * as Interval from "@effect/io/ScheduleInterval" import * as Intervals from "@effect/io/ScheduleIntervals" /** @internal */ const ScheduleSymbolKey = "@effect/io/Schedule" /** @internal */ export const ScheduleTypeId: Schedule.ScheduleTypeId = Symbol.for( ScheduleSymbolKey ) as Schedule.ScheduleTypeId /** @internal */ const ScheduleDriverSymbolKey = "@effect/io/ScheduleDriver" /** @internal */ export const ScheduleDriverTypeId: Schedule.ScheduleDriverTypeId = Symbol.for( ScheduleDriverSymbolKey ) as Schedule.ScheduleDriverTypeId /** @internal */ const scheduleVariance = { _Env: (_: never) => _, _In: (_: unknown) => _, _Out: (_: never) => _ } const scheduleDriverVariance = { _Env: (_: never) => _, _In: (_: unknown) => _, _Out: (_: never) => _ } /** @internal */ class ScheduleImpl implements Schedule.Schedule { [ScheduleTypeId] = scheduleVariance constructor( readonly initial: S, readonly step: ( now: number, input: In, state: S ) => Effect.Effect ) { } pipe() { return pipeArguments(this, arguments) } } /** @internal */ class ScheduleDriverImpl implements Schedule.ScheduleDriver { [ScheduleDriverTypeId] = scheduleDriverVariance constructor( readonly schedule: Schedule.Schedule, readonly ref: Ref.Ref, any]> ) {} state(): Effect.Effect { return core.map(ref.get(this.ref), (tuple) => tuple[1]) } last(): Effect.Effect { return core.flatMap(ref.get(this.ref), ([element, _]) => { switch (element._tag) { case "None": { return core.failSync(() => internalCause.NoSuchElementException()) } case "Some": { return core.succeed(element.value) } } }) } reset(): Effect.Effect { return ref.set(this.ref, [Option.none(), this.schedule.initial]) } next(input: In): Effect.Effect, Out> { return pipe( core.map(ref.get(this.ref), (tuple) => tuple[1]), core.flatMap((state) => pipe( Clock.currentTimeMillis, core.flatMap((now) => pipe( core.suspend(() => this.schedule.step(now, input, state)), core.flatMap(([state, out, decision]) => ScheduleDecision.isDone(decision) ? pipe( ref.set(this.ref, [Option.some(out), state] as const), core.zipRight(core.fail(Option.none())) ) : pipe( ref.set(this.ref, [Option.some(out), state] as const), core.zipRight(effect.sleep(Duration.millis(Intervals.start(decision.intervals) - now))), core.as(out) ) ) ) ) ) ) ) } } /** @internal */ export const makeWithState = ( initial: S, step: ( now: number, input: In, state: S ) => Effect.Effect ): Schedule.Schedule => new ScheduleImpl(initial, step) /** @internal */ export const addDelay = dual< ( f: (out: Out) => Duration.DurationInput ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: Out) => Duration.DurationInput ) => Schedule.Schedule >(2, (self, f) => addDelayEffect(self, (out) => core.sync(() => f(out)))) /** @internal */ export const addDelayEffect = dual< ( f: (out: Out) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: Out) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => modifyDelayEffect(self, (out, duration) => core.map( f(out), (delay) => Duration.sum(duration, Duration.decode(delay)) ))) /** @internal */ export const andThen = dual< ( that: Schedule.Schedule ) => (self: Schedule.Schedule) => Schedule.Schedule< Env | Env1, In & In1, Out | Out2 >, ( self: Schedule.Schedule, that: Schedule.Schedule ) => Schedule.Schedule< Env | Env1, In & In1, Out | Out2 > >(2, (self, that) => map(andThenEither(self, that), Either.merge)) /** @internal */ export const andThenEither = dual< ( that: Schedule.Schedule ) => (self: Schedule.Schedule) => Schedule.Schedule< Env | Env2, In & In2, Either.Either >, ( self: Schedule.Schedule, that: Schedule.Schedule ) => Schedule.Schedule< Env | Env2, In & In2, Either.Either > >(2, ( self: Schedule.Schedule, that: Schedule.Schedule ): Schedule.Schedule< Env | Env2, In & In2, Either.Either > => makeWithState( [self.initial, that.initial, true as boolean] as const, (now, input, state) => state[2] ? core.flatMap(self.step(now, input, state[0]), ([lState, out, decision]) => { if (ScheduleDecision.isDone(decision)) { return core.map(that.step(now, input, state[1]), ([rState, out, decision]) => [ [lState, rState, false as boolean] as const, Either.right(out) as Either.Either, decision as ScheduleDecision.ScheduleDecision ] as const) } return core.succeed( [ [lState, state[1], true as boolean] as const, Either.left(out), decision ] as const ) }) : core.map(that.step(now, input, state[1]), ([rState, out, decision]) => [ [state[0], rState, false as boolean] as const, Either.right(out) as Either.Either, decision ] as const) )) /** @internal */ export const as = dual< (out: Out2) => (self: Schedule.Schedule) => Schedule.Schedule, (self: Schedule.Schedule, out: Out2) => Schedule.Schedule >(2, (self, out) => map(self, () => out)) /** @internal */ export const asUnit = ( self: Schedule.Schedule ): Schedule.Schedule => map(self, constVoid) /** @internal */ export const bothInOut = dual< ( that: Schedule.Schedule ) => (self: Schedule.Schedule) => Schedule.Schedule< Env | Env2, readonly [In, In2], readonly [Out, Out2] >, ( self: Schedule.Schedule, that: Schedule.Schedule ) => Schedule.Schedule< Env | Env2, readonly [In, In2], readonly [Out, Out2] > >(2, (self, that) => makeWithState([self.initial, that.initial] as const, (now, [in1, in2], state) => core.zipWith( self.step(now, in1, state[0]), that.step(now, in2, state[1]), ([lState, out, lDecision], [rState, out2, rDecision]) => { if (ScheduleDecision.isContinue(lDecision) && ScheduleDecision.isContinue(rDecision)) { const interval = pipe(lDecision.intervals, Intervals.union(rDecision.intervals)) return [ [lState, rState] as const, [out, out2] as const, ScheduleDecision.continue(interval) ] as const } return [[lState, rState] as const, [out, out2] as const, ScheduleDecision.done] as const } ))) /** @internal */ export const check = dual< ( test: (input: In, output: Out) => boolean ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, test: (input: In, output: Out) => boolean ) => Schedule.Schedule >(2, (self, test) => checkEffect(self, (input, out) => core.sync(() => test(input, out)))) /** @internal */ export const checkEffect = dual< ( test: (input: In, output: Out) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, test: (input: In, output: Out) => Effect.Effect ) => Schedule.Schedule >(2, (self, test) => makeWithState( self.initial, (now, input, state) => core.flatMap(self.step(now, input, state), ([state, out, decision]) => { if (ScheduleDecision.isDone(decision)) { return core.succeed([state, out, ScheduleDecision.done] as const) } return core.map(test(input, out), (cont) => cont ? [state, out, decision] as const : [state, out, ScheduleDecision.done] as const) }) )) /** @internal */ export const collectAllInputs = (): Schedule.Schedule> => collectAllOutputs(identity()) /** @internal */ export const collectAllOutputs = ( self: Schedule.Schedule ): Schedule.Schedule> => reduce(self, Chunk.empty(), (outs, out) => pipe(outs, Chunk.append(out))) /** @internal */ export const collectUntil = (f: Predicate): Schedule.Schedule> => collectAllOutputs(recurUntil(f)) /** @internal */ export const collectUntilEffect = ( f: (a: A) => Effect.Effect ): Schedule.Schedule> => collectAllOutputs(recurUntilEffect(f)) /** @internal */ export const collectWhile = (f: Predicate): Schedule.Schedule> => collectAllOutputs(recurWhile(f)) /** @internal */ export const collectWhileEffect = ( f: (a: A) => Effect.Effect ): Schedule.Schedule> => collectAllOutputs(recurWhileEffect(f)) /** @internal */ export const compose = dual< ( that: Schedule.Schedule ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, that: Schedule.Schedule ) => Schedule.Schedule >(2, (self, that) => makeWithState( [self.initial, that.initial] as const, (now, input, state) => core.flatMap( self.step(now, input, state[0]), ([lState, out, lDecision]) => core.map(that.step(now, out, state[1]), ([rState, out2, rDecision]) => ScheduleDecision.isDone(lDecision) ? [[lState, rState] as const, out2, ScheduleDecision.done] as const : ScheduleDecision.isDone(rDecision) ? [[lState, rState] as const, out2, ScheduleDecision.done] as const : [ [lState, rState] as const, out2, ScheduleDecision.continue(pipe(lDecision.intervals, Intervals.max(rDecision.intervals))) ] as const) ) )) /** @internal */ export const mapInput = dual< ( f: (in2: In2) => In ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (in2: In2) => In ) => Schedule.Schedule >(2, (self, f) => mapInputEffect(self, (input2) => core.sync(() => f(input2)))) /** @internal */ export const mapInputContext = dual< ( f: (env0: Context.Context) => Context.Context ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (env0: Context.Context) => Context.Context ) => Schedule.Schedule >(2, (self, f) => makeWithState( self.initial, (now, input, state) => core.mapInputContext(self.step(now, input, state), f) )) /** @internal */ export const mapInputEffect = dual< ( f: (in2: In2) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (in2: In2) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => makeWithState(self.initial, (now, input2, state) => core.flatMap( f(input2), (input) => self.step(now, input, state) ))) /** @internal */ export const dayOfMonth = (day: number): Schedule.Schedule => { return makeWithState( [Number.NEGATIVE_INFINITY, 0] as readonly [number, number], (now, _, state) => { if (!Number.isInteger(day) || day < 1 || 31 < day) { return core.dieSync(() => internalCause.IllegalArgumentException( `Invalid argument in: dayOfMonth(${day}). Must be in range 1...31` ) ) } const n = state[1] const initial = n === 0 const day0 = nextDayOfMonth(now, day, initial) const start = beginningOfDay(day0) const end = endOfDay(day0) const interval = Interval.make(start, end) return core.succeed( [ [end, n + 1] as const, n, ScheduleDecision.continueWith(interval) ] as const ) } ) } /** @internal */ export const dayOfWeek = (day: number): Schedule.Schedule => { return makeWithState( [Number.MIN_SAFE_INTEGER, 0] as readonly [number, number], (now, _, state) => { if (!Number.isInteger(day) || day < 1 || 7 < day) { return core.dieSync(() => internalCause.IllegalArgumentException( `Invalid argument in: dayOfWeek(${day}). Must be in range 1 (Monday)...7 (Sunday)` ) ) } const n = state[1] const initial = n === 0 const day0 = nextDay(now, day, initial) const start = beginningOfDay(day0) const end = endOfDay(day0) const interval = Interval.make(start, end) return core.succeed( [ [end, n + 1] as const, n, ScheduleDecision.continueWith(interval) ] as const ) } ) } /** @internal */ export const delayed = dual< ( f: (duration: Duration.Duration) => Duration.DurationInput ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (duration: Duration.Duration) => Duration.DurationInput ) => Schedule.Schedule >(2, (self, f) => delayedEffect(self, (duration) => core.sync(() => f(duration)))) /** @internal */ export const delayedEffect = dual< ( f: (duration: Duration.Duration) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (duration: Duration.Duration) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => modifyDelayEffect(self, (_, delay) => f(delay))) /** @internal */ export const delayedSchedule = ( schedule: Schedule.Schedule ): Schedule.Schedule => addDelay(schedule, (x) => x) /** @internal */ export const delays = ( self: Schedule.Schedule ): Schedule.Schedule => makeWithState(self.initial, (now, input, state) => pipe( self.step(now, input, state), core.flatMap(( [state, _, decision] ): Effect.Effect => { if (ScheduleDecision.isDone(decision)) { return core.succeed([state, Duration.zero, decision] as const) } return core.succeed( [ state, Duration.millis(Intervals.start(decision.intervals) - now), decision ] as const ) }) )) /** @internal */ export const mapBoth = dual< ( options: { readonly onInput: (in2: In2) => In readonly onOutput: (out: Out) => Out2 } ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, options: { readonly onInput: (in2: In2) => In readonly onOutput: (out: Out) => Out2 } ) => Schedule.Schedule >(2, (self, { onInput, onOutput }) => map(mapInput(self, onInput), onOutput)) /** @internal */ export const mapBothEffect = dual< ( options: { readonly onInput: (input: In2) => Effect.Effect readonly onOutput: (out: Out) => Effect.Effect } ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, options: { readonly onInput: (input: In2) => Effect.Effect readonly onOutput: (out: Out) => Effect.Effect } ) => Schedule.Schedule >(2, (self, { onInput, onOutput }) => mapEffect(mapInputEffect(self, onInput), onOutput)) /** @internal */ export const driver = ( self: Schedule.Schedule ): Effect.Effect> => pipe( ref.make, any]>([Option.none(), self.initial]), core.map((ref) => new ScheduleDriverImpl(self, ref)) ) /** @internal */ export const duration = ( durationInput: Duration.DurationInput ): Schedule.Schedule => { const duration = Duration.decode(durationInput) const durationMillis = Duration.toMillis(duration) return makeWithState(true as boolean, (now, _, state) => core.succeed( state ? [ false, duration, ScheduleDecision.continueWith(Interval.after(now + durationMillis)) ] as const : [false, Duration.zero, ScheduleDecision.done] as const )) } /** @internal */ export const either = dual< ( that: Schedule.Schedule ) => (self: Schedule.Schedule) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] >, ( self: Schedule.Schedule, that: Schedule.Schedule ) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] > >(2, (self, that) => union(self, that)) /** @internal */ export const eitherWith = dual< ( that: Schedule.Schedule, f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals ) => (self: Schedule.Schedule) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] >, ( self: Schedule.Schedule, that: Schedule.Schedule, f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals ) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] > >(3, (self, that, f) => unionWith(self, that, f)) /** @internal */ export const ensuring = dual< ( finalizer: Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, finalizer: Effect.Effect ) => Schedule.Schedule >(2, (self, finalizer) => makeWithState( self.initial, (now, input, state) => core.flatMap(self.step(now, input, state), ([state, out, decision]) => ScheduleDecision.isDone(decision) ? core.as(finalizer, [state, out, decision as ScheduleDecision.ScheduleDecision] as const) : core.succeed([state, out, decision] as const)) )) /** @internal */ export const exponential = ( baseInput: Duration.DurationInput, factor = 2.0 ): Schedule.Schedule => { const base = Duration.decode(baseInput) return delayedSchedule(map(forever, (i) => Duration.times(base, Math.pow(factor, i)))) } /** @internal */ export const fibonacci = (oneInput: Duration.DurationInput): Schedule.Schedule => { const one = Duration.decode(oneInput) return delayedSchedule( pipe( unfold( [one, one] as const, ([a, b]) => [b, Duration.sum(a, b)] as const ), map((out) => out[0]) ) ) } /** @internal */ export const fixed = (intervalInput: Duration.DurationInput): Schedule.Schedule => { const interval = Duration.decode(intervalInput) const intervalMillis = Duration.toMillis(interval) return makeWithState( [Option.none(), 0] as readonly [Option.Option, number], (now, _, [option, n]) => core.sync(() => { switch (option._tag) { case "None": { return [ [Option.some([now, now + intervalMillis] as const), n + 1] as const, n, ScheduleDecision.continueWith(Interval.after(now + intervalMillis)) ] as const } case "Some": { const [startMillis, lastRun] = option.value const runningBehind = now > (lastRun + intervalMillis) const boundary = Equal.equals(interval, Duration.zero) ? interval : Duration.millis(intervalMillis - ((now - startMillis) % intervalMillis)) const sleepTime = Equal.equals(boundary, Duration.zero) ? interval : boundary const nextRun = runningBehind ? now : now + Duration.toMillis(sleepTime) return [ [Option.some([startMillis, nextRun] as const), n + 1] as const, n, ScheduleDecision.continueWith(Interval.after(nextRun)) ] as const } } }) ) } /** @internal */ export const fromDelay = (delay: Duration.DurationInput): Schedule.Schedule => duration(delay) /** @internal */ export const fromDelays = ( delay: Duration.DurationInput, ...delays: Array ): Schedule.Schedule => makeWithState( [[delay, ...delays].map((_) => Duration.decode(_)) as Array, true as boolean] as const, (now, _, [durations, cont]) => core.sync(() => { if (cont) { const x = durations[0]! const interval = Interval.after(now + Duration.toMillis(x)) if (durations.length >= 2) { return [ [durations.slice(1), true] as const, x, ScheduleDecision.continueWith(interval) ] as const } const y = durations.slice(1) return [ [[x, ...y] as Array, false] as const, x, ScheduleDecision.continueWith(interval) ] as const } return [[durations, false] as const, Duration.zero, ScheduleDecision.done] as const }) ) /** @internal */ export const fromFunction = (f: (a: A) => B): Schedule.Schedule => map(identity(), f) /** @internal */ export const hourOfDay = (hour: number): Schedule.Schedule => makeWithState( [Number.NEGATIVE_INFINITY, 0] as readonly [number, number], (now, _, state) => { if (!Number.isInteger(hour) || hour < 0 || 23 < hour) { return core.dieSync(() => internalCause.IllegalArgumentException( `Invalid argument in: hourOfDay(${hour}). Must be in range 0...23` ) ) } const n = state[1] const initial = n === 0 const hour0 = nextHour(now, hour, initial) const start = beginningOfHour(hour0) const end = endOfHour(hour0) const interval = Interval.make(start, end) return core.succeed( [ [end, n + 1] as const, n, ScheduleDecision.continueWith(interval) ] as const ) } ) /** @internal */ export const identity = (): Schedule.Schedule => makeWithState(void 0, (now, input, state) => core.succeed( [ state, input, ScheduleDecision.continueWith(Interval.after(now)) ] as const )) /** @internal */ export const intersect = dual< ( that: Schedule.Schedule ) => (self: Schedule.Schedule) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] >, ( self: Schedule.Schedule, that: Schedule.Schedule ) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] > >(2, (self, that) => intersectWith(self, that, Intervals.intersect)) /** @internal */ export const intersectWith = dual< ( that: Schedule.Schedule, f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals ) => (self: Schedule.Schedule) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] >, ( self: Schedule.Schedule, that: Schedule.Schedule, f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals ) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] > >(3, ( self: Schedule.Schedule, that: Schedule.Schedule, f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals ): Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] > => makeWithState([self.initial, that.initial] as const, (now, input: In & In2, state) => pipe( core.zipWith( self.step(now, input, state[0]), that.step(now, input, state[1]), (a, b) => [a, b] as const ), core.flatMap(([ [lState, out, lDecision], [rState, out2, rDecision] ]) => { if (ScheduleDecision.isContinue(lDecision) && ScheduleDecision.isContinue(rDecision)) { return intersectWithLoop( self, that, input, lState, out, lDecision.intervals, rState, out2, rDecision.intervals, f ) } return core.succeed( [ [lState, rState] as const, [out, out2] as const, ScheduleDecision.done ] as const ) }) ))) /** @internal */ const intersectWithLoop = ( self: Schedule.Schedule, that: Schedule.Schedule, input: In & In1, lState: State, out: Out, lInterval: Intervals.Intervals, rState: State1, out2: Out2, rInterval: Intervals.Intervals, f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals ): Effect.Effect< Env | Env1, never, readonly [readonly [State, State1], readonly [Out, Out2], ScheduleDecision.ScheduleDecision] > => { const combined = f(lInterval, rInterval) if (Intervals.isNonEmpty(combined)) { return core.succeed([ [lState, rState], [out, out2], ScheduleDecision.continue(combined) ]) } if (pipe(lInterval, Intervals.lessThan(rInterval))) { return core.flatMap(self.step(Intervals.end(lInterval), input, lState), ([lState, out, decision]) => { if (ScheduleDecision.isDone(decision)) { return core.succeed([ [lState, rState], [out, out2], ScheduleDecision.done ]) } return intersectWithLoop( self, that, input, lState, out, decision.intervals, rState, out2, rInterval, f ) }) } return core.flatMap(that.step(Intervals.end(rInterval), input, rState), ([rState, out2, decision]) => { if (ScheduleDecision.isDone(decision)) { return core.succeed([ [lState, rState], [out, out2], ScheduleDecision.done ]) } return intersectWithLoop( self, that, input, lState, out, lInterval, rState, out2, decision.intervals, f ) }) } /** @internal */ export const jittered = (self: Schedule.Schedule): Schedule.Schedule => jitteredWith(self, { min: 0.8, max: 1.2 }) /** @internal */ export const jitteredWith = dual< (options: { min?: number; max?: number }) => ( self: Schedule.Schedule ) => Schedule.Schedule, ( self: Schedule.Schedule, options: { min?: number; max?: number } ) => Schedule.Schedule >(2, (self, options) => { const { max, min } = Object.assign({ min: 0.8, max: 1.2 }, options) return delayedEffect(self, (duration) => core.map(Random.next, (random) => { const d = Duration.toMillis(duration) const jittered = d * min * (1 - random) + d * max * random return Duration.millis(jittered) })) }) /** @internal */ export const linear = (baseInput: Duration.DurationInput): Schedule.Schedule => { const base = Duration.decode(baseInput) return delayedSchedule(map(forever, (i) => Duration.times(base, i + 1))) } /** @internal */ export const map = dual< ( f: (out: Out) => Out2 ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: Out) => Out2 ) => Schedule.Schedule >(2, (self, f) => mapEffect(self, (out) => core.sync(() => f(out)))) /** @internal */ export const mapEffect = dual< ( f: (out: Out) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: Out) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => makeWithState( self.initial, (now, input, state) => core.flatMap(self.step(now, input, state), ([state, out, decision]) => core.map( f(out), (out2) => [state, out2, decision] as const )) )) /** @internal */ export const minuteOfHour = (minute: number): Schedule.Schedule => makeWithState( [Number.MIN_SAFE_INTEGER, 0] as readonly [number, number], (now, _, state) => { if (!Number.isInteger(minute) || minute < 0 || 59 < minute) { return core.dieSync(() => internalCause.IllegalArgumentException( `Invalid argument in: minuteOfHour(${minute}). Must be in range 0...59` ) ) } const n = state[1] const initial = n === 0 const minute0 = nextMinute(now, minute, initial) const start = beginningOfMinute(minute0) const end = endOfMinute(minute0) const interval = Interval.make(start, end) return core.succeed( [ [end, n + 1], n, ScheduleDecision.continueWith(interval) ] as const ) } ) /** @internal */ export const modifyDelay = dual< ( f: (out: Out, duration: Duration.Duration) => Duration.DurationInput ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: Out, duration: Duration.Duration) => Duration.DurationInput ) => Schedule.Schedule >(2, (self, f) => modifyDelayEffect(self, (out, duration) => core.sync(() => f(out, duration)))) /** @internal */ export const modifyDelayEffect = dual< ( f: (out: Out, duration: Duration.Duration) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: Out, duration: Duration.Duration) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => makeWithState( self.initial, (now, input, state) => core.flatMap(self.step(now, input, state), ([state, out, decision]) => { if (ScheduleDecision.isDone(decision)) { return core.succeed([state, out, decision] as const) } const intervals = decision.intervals const delay = Interval.size(Interval.make(now, Intervals.start(intervals))) return core.map(f(out, delay), (durationInput) => { const duration = Duration.decode(durationInput) const oldStart = Intervals.start(intervals) const newStart = now + Duration.toMillis(duration) const delta = newStart - oldStart const newEnd = Math.min(Math.max(0, Intervals.end(intervals) + delta), Number.MAX_SAFE_INTEGER) const newInterval = Interval.make(newStart, newEnd) return [state, out, ScheduleDecision.continueWith(newInterval)] as const }) }) )) /** @internal */ export const onDecision = dual< ( f: (out: Out, decision: ScheduleDecision.ScheduleDecision) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: Out, decision: ScheduleDecision.ScheduleDecision) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => makeWithState( self.initial, (now, input, state) => core.flatMap( self.step(now, input, state), ([state, out, decision]) => core.as(f(out, decision), [state, out, decision] as const) ) )) /** @internal */ export const passthrough = ( self: Schedule.Schedule ): Schedule.Schedule => makeWithState(self.initial, (now, input, state) => pipe( self.step(now, input, state), core.map(([state, _, decision]) => [state, input, decision] as const) )) /** @internal */ export const provideContext = dual< ( context: Context.Context ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, context: Context.Context ) => Schedule.Schedule >(2, (self, context) => makeWithState(self.initial, (now, input, state) => core.provideContext( self.step(now, input, state), context ))) /** @internal */ export const provideService = dual< >( tag: T, service: Context.Tag.Service ) => ( self: Schedule.Schedule ) => Schedule.Schedule>, In, Out>, >( self: Schedule.Schedule, tag: T, service: Context.Tag.Service ) => Schedule.Schedule>, In, Out> >(3, >( self: Schedule.Schedule, tag: T, service: Context.Tag.Service ): Schedule.Schedule>, In, Out> => makeWithState(self.initial, (now, input, state) => core.contextWithEffect< Exclude>, Exclude>, never, readonly [any, Out, ScheduleDecision.ScheduleDecision] >((env) => core.provideContext( // @ts-expect-error self.step(now, input, state), Context.add(env, tag, service) ) ))) /** @internal */ export const recurUntil = (f: Predicate): Schedule.Schedule => untilInput(identity(), f) /** @internal */ export const recurUntilEffect = ( f: (a: A) => Effect.Effect ): Schedule.Schedule => untilInputEffect(identity(), f) /** @internal */ export const recurUntilOption = (pf: (a: A) => Option.Option): Schedule.Schedule> => untilOutput(map(identity(), pf), Option.isSome) /** @internal */ export const recurUpTo = ( durationInput: Duration.DurationInput ): Schedule.Schedule => { const duration = Duration.decode(durationInput) return whileOutput(elapsed, (elapsed) => Duration.lessThan(elapsed, duration)) } /** @internal */ export const recurWhile = (f: Predicate): Schedule.Schedule => whileInput(identity(), f) /** @internal */ export const recurWhileEffect = ( f: (a: A) => Effect.Effect ): Schedule.Schedule => whileInputEffect(identity(), f) /** @internal */ export const recurs = (n: number): Schedule.Schedule => whileOutput(forever, (out) => out < n) /** @internal */ export const reduce = dual< ( zero: Z, f: (z: Z, out: Out) => Z ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, zero: Z, f: (z: Z, out: Out) => Z ) => Schedule.Schedule >(3, (self, zero, f) => reduceEffect(self, zero, (z, out) => core.sync(() => f(z, out)))) /** @internal */ export const reduceEffect = dual< ( zero: Z, f: (z: Z, out: Out) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, zero: Z, f: (z: Z, out: Out) => Effect.Effect ) => Schedule.Schedule >(3, (self, zero, f) => makeWithState( [self.initial, zero] as const, (now, input, [s, z]) => core.flatMap(self.step(now, input, s), ([s, out, decision]) => ScheduleDecision.isDone(decision) ? core.succeed([[s, z], z, decision as ScheduleDecision.ScheduleDecision] as const) : core.map(f(z, out), (z2) => [[s, z2], z, decision] as const)) )) /** @internal */ export const repeatForever = (self: Schedule.Schedule): Schedule.Schedule => makeWithState(self.initial, (now, input, state) => { const step = ( now: number, input: In, state: any ): Effect.Effect => core.flatMap( self.step(now, input, state), ([state, out, decision]) => ScheduleDecision.isDone(decision) ? step(now, input, self.initial) : core.succeed([state, out, decision]) ) return step(now, input, state) }) /** @internal */ export const repetitions = (self: Schedule.Schedule): Schedule.Schedule => reduce(self, 0, (n, _) => n + 1) /** @internal */ export const resetAfter = dual< ( duration: Duration.DurationInput ) => ( self: Schedule.Schedule ) => Schedule.Schedule, ( self: Schedule.Schedule, duration: Duration.DurationInput ) => Schedule.Schedule >(2, (self, durationInput) => { const duration = Duration.decode(durationInput) return pipe( self, intersect(elapsed), resetWhen(([, time]) => Duration.greaterThanOrEqualTo(time, duration)), map((out) => out[0]) ) }) /** @internal */ export const resetWhen = dual< (f: Predicate) => (self: Schedule.Schedule) => Schedule.Schedule, (self: Schedule.Schedule, f: Predicate) => Schedule.Schedule >(2, (self, f) => makeWithState( self.initial, (now, input, state) => core.flatMap(self.step(now, input, state), ([state, out, decision]) => f(out) ? self.step(now, input, self.initial) : core.succeed([state, out, decision] as const)) )) /** @internal */ export const run = dual< ( now: number, input: Iterable ) => (self: Schedule.Schedule) => Effect.Effect>, ( self: Schedule.Schedule, now: number, input: Iterable ) => Effect.Effect> >(3, (self, now, input) => pipe( runLoop(self, now, Chunk.fromIterable(input), self.initial, Chunk.empty()), core.map((list) => Chunk.reverse(list)) )) /** @internal */ const runLoop = ( self: Schedule.Schedule, now: number, inputs: Chunk.Chunk, state: any, acc: Chunk.Chunk ): Effect.Effect> => { if (!Chunk.isNonEmpty(inputs)) { return core.succeed(acc) } const input = Chunk.headNonEmpty(inputs) const nextInputs = Chunk.tailNonEmpty(inputs) return core.flatMap(self.step(now, input, state), ([state, out, decision]) => { if (ScheduleDecision.isDone(decision)) { return core.sync(() => pipe(acc, Chunk.prepend(out))) } return runLoop( self, Intervals.start(decision.intervals), nextInputs, state, Chunk.prepend(acc, out) ) }) } /** @internal */ export const secondOfMinute = (second: number): Schedule.Schedule => makeWithState( [Number.NEGATIVE_INFINITY, 0] as readonly [number, number], (now, _, state) => { if (!Number.isInteger(second) || second < 0 || 59 < second) { return core.dieSync(() => internalCause.IllegalArgumentException( `Invalid argument in: secondOfMinute(${second}). Must be in range 0...59` ) ) } const n = state[1] const initial = n === 0 const second0 = nextSecond(now, second, initial) const start = beginningOfSecond(second0) const end = endOfSecond(second0) const interval = Interval.make(start, end) return core.succeed( [ [end, n + 1], n, ScheduleDecision.continueWith(interval) ] as const ) } ) /** @internal */ export const spaced = (duration: Duration.DurationInput): Schedule.Schedule => addDelay(forever, () => duration) /** @internal */ export const succeed = (value: A): Schedule.Schedule => map(forever, () => value) /** @internal */ export const sync = (evaluate: LazyArg): Schedule.Schedule => map(forever, evaluate) /** @internal */ export const tapInput = dual< ( f: (input: In2) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (input: In2) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => makeWithState(self.initial, (now, input, state) => core.zipRight( f(input), self.step(now, input, state) ))) /** @internal */ export const tapOutput = dual< ( f: (out: XO) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: XO) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => makeWithState(self.initial, (now, input, state) => core.tap( self.step(now, input, state), ([, out]) => f(out as any) ))) /** @internal */ export const unfold = (initial: A, f: (a: A) => A): Schedule.Schedule => makeWithState(initial, (now, _, state) => core.sync(() => [ f(state), state, ScheduleDecision.continueWith(Interval.after(now)) ] as const )) /** @internal */ export const union = dual< ( that: Schedule.Schedule ) => (self: Schedule.Schedule) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] >, ( self: Schedule.Schedule, that: Schedule.Schedule ) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] > >(2, (self, that) => unionWith(self, that, Intervals.union)) /** @internal */ export const unionWith = dual< ( that: Schedule.Schedule, f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals ) => (self: Schedule.Schedule) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] >, ( self: Schedule.Schedule, that: Schedule.Schedule, f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals ) => Schedule.Schedule< Env | Env2, In & In2, readonly [Out, Out2] > >(3, (self, that, f) => makeWithState([self.initial, that.initial] as const, (now, input, state) => core.zipWith( self.step(now, input, state[0]), that.step(now, input, state[1]), ([lState, l, lDecision], [rState, r, rDecision]) => { if (ScheduleDecision.isDone(lDecision) && ScheduleDecision.isDone(rDecision)) { return [[lState, rState] as const, [l, r] as const, ScheduleDecision.done] as const } if (ScheduleDecision.isDone(lDecision) && ScheduleDecision.isContinue(rDecision)) { return [ [lState, rState] as const, [l, r] as const, ScheduleDecision.continue(rDecision.intervals) ] as const } if (ScheduleDecision.isContinue(lDecision) && ScheduleDecision.isDone(rDecision)) { return [ [lState, rState] as const, [l, r], ScheduleDecision.continue(lDecision.intervals) ] as const } if (ScheduleDecision.isContinue(lDecision) && ScheduleDecision.isContinue(rDecision)) { const combined = f(lDecision.intervals, rDecision.intervals) return [ [lState, rState] as const, [l, r], ScheduleDecision.continue(combined) ] as const } throw new Error( "BUG: Schedule.unionWith - please report an issue at https://github.com/Effect-TS/io/issues" ) } ))) /** @internal */ export const untilInput = dual< (f: Predicate) => (self: Schedule.Schedule) => Schedule.Schedule, (self: Schedule.Schedule, f: Predicate) => Schedule.Schedule >(2, (self, f) => check(self, (input, _) => !f(input))) /** @internal */ export const untilInputEffect = dual< ( f: (input: In) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (input: In) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => checkEffect(self, (input, _) => effect.negate(f(input)))) /** @internal */ export const untilOutput = dual< (f: Predicate) => (self: Schedule.Schedule) => Schedule.Schedule, (self: Schedule.Schedule, f: Predicate) => Schedule.Schedule >(2, (self, f) => check(self, (_, out) => !f(out))) /** @internal */ export const untilOutputEffect = dual< ( f: (out: Out) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: Out) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => checkEffect(self, (_, out) => effect.negate(f(out)))) /** @internal */ export const upTo = dual< (duration: Duration.DurationInput) => ( self: Schedule.Schedule ) => Schedule.Schedule, ( self: Schedule.Schedule, duration: Duration.DurationInput ) => Schedule.Schedule >(2, (self, duration) => zipLeft(self, recurUpTo(duration))) /** @internal */ export const whileInput = dual< (f: Predicate) => (self: Schedule.Schedule) => Schedule.Schedule, (self: Schedule.Schedule, f: Predicate) => Schedule.Schedule >(2, (self, f) => check(self, (input, _) => f(input))) /** @internal */ export const whileInputEffect = dual< ( f: (input: In) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (input: In) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => checkEffect(self, (input, _) => f(input))) /** @internal */ export const whileOutput = dual< (f: Predicate) => (self: Schedule.Schedule) => Schedule.Schedule, (self: Schedule.Schedule, f: Predicate) => Schedule.Schedule >(2, (self, f) => check(self, (_, out) => f(out))) /** @internal */ export const whileOutputEffect = dual< ( f: (out: Out) => Effect.Effect ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, f: (out: Out) => Effect.Effect ) => Schedule.Schedule >(2, (self, f) => checkEffect(self, (_, out) => f(out))) /** @internal */ export const windowed = (intervalInput: Duration.DurationInput): Schedule.Schedule => { const interval = Duration.decode(intervalInput) const millis = Duration.toMillis(interval) return makeWithState( [Option.none(), 0] as readonly [Option.Option, number], (now, _, [option, n]) => { switch (option._tag) { case "None": { return core.succeed( [ [Option.some(now), n + 1], n, ScheduleDecision.continueWith(Interval.after(now + millis)) ] as const ) } case "Some": { return core.succeed( [ [Option.some(option.value), n + 1], n, ScheduleDecision.continueWith( Interval.after(now + (millis - ((now - option.value) % millis))) ) ] as const ) } } } ) } /** @internal */ export const zipLeft = dual< ( that: Schedule.Schedule ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, that: Schedule.Schedule ) => Schedule.Schedule >(2, (self, that) => map(intersect(self, that), (out) => out[0])) /** @internal */ export const zipRight = dual< ( that: Schedule.Schedule ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, that: Schedule.Schedule ) => Schedule.Schedule >(2, (self, that) => map(intersect(self, that), (out) => out[1])) /** @internal */ export const zipWith = dual< ( that: Schedule.Schedule, f: (out: Out, out2: Out2) => Out3 ) => (self: Schedule.Schedule) => Schedule.Schedule, ( self: Schedule.Schedule, that: Schedule.Schedule, f: (out: Out, out2: Out2) => Out3 ) => Schedule.Schedule >(3, (self, that, f) => map(intersect(self, that), ([out, out2]) => f(out, out2))) // ----------------------------------------------------------------------------- // Seconds // ----------------------------------------------------------------------------- /** @internal */ export const beginningOfSecond = (now: number): number => { const date = new Date(now) return new Date( date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), 0 ).getTime() } /** @internal */ export const endOfSecond = (now: number): number => { const date = new Date(beginningOfSecond(now)) return date.setSeconds(date.getSeconds() + 1) } /** @internal */ export const nextSecond = (now: number, second: number, initial: boolean): number => { const date = new Date(now) if (date.getSeconds() === second && initial) { return now } if (date.getSeconds() < second) { return date.setSeconds(second) } // Set seconds to the provided value and add one minute const newDate = new Date(date.setSeconds(second)) return newDate.setTime(newDate.getTime() + 1000 * 60) } // ----------------------------------------------------------------------------- // Minutes // ----------------------------------------------------------------------------- /** @internal */ export const beginningOfMinute = (now: number): number => { const date = new Date(now) return new Date( date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), 0, 0 ).getTime() } /** @internal */ export const endOfMinute = (now: number): number => { const date = new Date(beginningOfMinute(now)) return date.setMinutes(date.getMinutes() + 1) } /** @internal */ export const nextMinute = (now: number, minute: number, initial: boolean): number => { const date = new Date(now) if (date.getMinutes() === minute && initial) { return now } if (date.getMinutes() < minute) { return date.setMinutes(minute) } // Set minutes to the provided value and add one hour const newDate = new Date(date.setMinutes(minute)) return newDate.setTime(newDate.getTime() + 1000 * 60 * 60) } // ----------------------------------------------------------------------------- // Hours // ----------------------------------------------------------------------------- /** @internal */ export const beginningOfHour = (now: number): number => { const date = new Date(now) return new Date( date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), 0, 0, 0 ).getTime() } /** @internal */ export const endOfHour = (now: number): number => { const date = new Date(beginningOfHour(now)) return date.setHours(date.getHours() + 1) } /** @internal */ export const nextHour = (now: number, hour: number, initial: boolean): number => { const date = new Date(now) if (date.getHours() === hour && initial) { return now } if (date.getHours() < hour) { return date.setHours(hour) } // Set hours to the provided value and add one day const newDate = new Date(date.setHours(hour)) return newDate.setTime(newDate.getTime() + 1000 * 60 * 60 * 24) } // ----------------------------------------------------------------------------- // Days // ----------------------------------------------------------------------------- /** @internal */ export const beginningOfDay = (now: number): number => { const date = new Date(now) return new Date( date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0 ).getTime() } /** @internal */ export const endOfDay = (now: number): number => { const date = new Date(beginningOfDay(now)) return date.setDate(date.getDate() + 1) } /** @internal */ export const nextDay = (now: number, dayOfWeek: number, initial: boolean): number => { const date = new Date(now) if (date.getDay() === dayOfWeek && initial) { return now } const nextDayOfWeek = (7 + dayOfWeek - date.getDay()) % 7 return date.setDate(date.getDate() + (nextDayOfWeek === 0 ? 7 : nextDayOfWeek)) } /** @internal */ export const nextDayOfMonth = (now: number, day: number, initial: boolean): number => { const date = new Date(now) if (date.getDate() === day && initial) { return now } if (date.getDate() < day) { return date.setDate(day) } return findNextMonth(now, day, 1) } /** @internal */ export const findNextMonth = (now: number, day: number, months: number): number => { const d = new Date(now) const tmp1 = new Date(d.setDate(day)) const tmp2 = new Date(tmp1.setMonth(tmp1.getMonth() + months)) if (tmp2.getDate() === day) { const d2 = new Date(now) const tmp3 = new Date(d2.setDate(day)) return tmp3.setMonth(tmp3.getMonth() + months) } return findNextMonth(now, day, months + 1) } // circular with Effect /** @internal */ export const repeat_Effect = dual< ( schedule: Schedule.Schedule ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, schedule: Schedule.Schedule ) => Effect.Effect >(2, (self, schedule) => repeatOrElse_Effect(self, schedule, (e, _) => core.fail(e))) /** @internal */ export const repeatOrElse_Effect = dual< ( schedule: Schedule.Schedule, orElse: (error: E, option: Option.Option) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, schedule: Schedule.Schedule, orElse: (error: E, option: Option.Option) => Effect.Effect ) => Effect.Effect >(3, (self, schedule, orElse) => core.flatMap(driver(schedule), (driver) => core.matchEffect(self, { onFailure: (error) => orElse(error, Option.none()), onSuccess: (value) => repeatOrElseEffectLoop(self, driver, orElse, value) }))) /** @internal */ const repeatOrElseEffectLoop = ( self: Effect.Effect, driver: Schedule.ScheduleDriver, orElse: (error: E, option: Option.Option) => Effect.Effect, value: A ): Effect.Effect => { return core.matchEffect(driver.next(value), { onFailure: () => core.orDie(driver.last()), onSuccess: (b) => core.matchEffect(self, { onFailure: (error) => orElse(error, Option.some(b)), onSuccess: (value) => repeatOrElseEffectLoop(self, driver, orElse, value) }) }) } /** @internal */ export const repeatUntil_Effect = dual< { (f: Refinement): (self: Effect.Effect) => Effect.Effect (f: Predicate): (self: Effect.Effect) => Effect.Effect }, { (self: Effect.Effect, f: Predicate): Effect.Effect (self: Effect.Effect, f: Predicate): Effect.Effect } >( 2, (self: Effect.Effect, f: Predicate) => repeatUntilEffect_Effect(self, (a) => core.sync(() => f(a))) ) /** @internal */ export const repeatUntilEffect_Effect: { ( f: (a: A) => Effect.Effect ): (self: Effect.Effect) => Effect.Effect ( self: Effect.Effect, f: (a: A) => Effect.Effect ): Effect.Effect } = dual< ( f: (a: A) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (a: A) => Effect.Effect ) => Effect.Effect >(2, (self, f) => core.flatMap(self, (a) => core.flatMap(f(a), (result) => result ? core.succeed(a) : core.flatMap( core.yieldNow(), () => repeatUntilEffect_Effect(self, f) )))) /** @internal */ export const repeatWhile_Effect = dual< (f: Predicate) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, f: Predicate) => Effect.Effect >(2, (self, f) => repeatWhileEffect_Effect(self, (a) => core.sync(() => f(a)))) /** @internal */ export const repeatWhileEffect_Effect = dual< ( f: (a: A) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (a: A) => Effect.Effect ) => Effect.Effect >(2, (self, f) => repeatUntilEffect_Effect(self, (a) => effect.negate(f(a)))) /** @internal */ export const retry_Effect = dual< ( policy: Schedule.Schedule ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, policy: Schedule.Schedule ) => Effect.Effect >(2, (self, policy) => retryOrElse_Effect(self, policy, (e, _) => core.fail(e))) /** @internal */ export const retryN_Effect = dual< (n: number) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, n: number) => Effect.Effect >(2, (self, n) => retryN_EffectLoop(self, n)) /** @internal */ const retryN_EffectLoop = ( self: Effect.Effect, n: number ): Effect.Effect => { return core.catchAll(self, (e) => n < 0 ? core.fail(e) : core.flatMap(core.yieldNow(), () => retryN_EffectLoop(self, n - 1))) } /** @internal */ export const retryOrElse_Effect = dual< ( policy: Schedule.Schedule, orElse: (e: E, out: A1) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, policy: Schedule.Schedule, orElse: (e: E, out: A1) => Effect.Effect ) => Effect.Effect >(3, (self, policy, orElse) => core.flatMap( driver(policy), (driver) => retryOrElse_EffectLoop(self, driver, orElse) )) /** @internal */ const retryOrElse_EffectLoop = ( self: Effect.Effect, driver: Schedule.ScheduleDriver, orElse: (e: E, out: A1) => Effect.Effect ): Effect.Effect => { return core.catchAll( self, (e) => core.matchEffect(driver.next(e), { onFailure: () => pipe( driver.last(), core.orDie, core.flatMap((out) => orElse(e, out)) ), onSuccess: () => retryOrElse_EffectLoop(self, driver, orElse) }) ) } /** @internal */ export const retryUntil_Effect = dual< { (f: Refinement): (self: Effect.Effect) => Effect.Effect (f: Predicate): (self: Effect.Effect) => Effect.Effect }, { (self: Effect.Effect, f: Refinement): Effect.Effect (self: Effect.Effect, f: Predicate): Effect.Effect } >(2, (self: Effect.Effect, f: Predicate) => retryUntilEffect_Effect( self, (e) => core.sync(() => f(e)) )) /** @internal */ export const retryUntilEffect_Effect: { ( f: (e: E) => Effect.Effect ): (self: Effect.Effect) => Effect.Effect ( self: Effect.Effect, f: (e: E) => Effect.Effect ): Effect.Effect } = dual< ( f: (e: E) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (e: E) => Effect.Effect ) => Effect.Effect >(2, (self, f) => core.catchAll(self, (e) => core.flatMap(f(e), (b) => b ? core.fail(e) : core.flatMap( core.yieldNow(), () => retryUntilEffect_Effect(self, f) )))) /** @internal */ export const retryWhile_Effect = dual< (f: Predicate) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, f: Predicate) => Effect.Effect >(2, (self, f) => retryWhileEffect_Effect(self, (e) => core.sync(() => f(e)))) /** @internal */ export const retryWhileEffect_Effect = dual< ( f: (e: E) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, f: (e: E) => Effect.Effect ) => Effect.Effect >(2, (self, f) => retryUntilEffect_Effect(self, (e) => effect.negate(f(e)))) /** @internal */ export const schedule_Effect = dual< ( schedule: Schedule.Schedule ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, schedule: Schedule.Schedule ) => Effect.Effect >(2, ( self: Effect.Effect, schedule: Schedule.Schedule ) => scheduleFrom_Effect(self, void 0, schedule)) /** @internal */ export const scheduleFrom_Effect = dual< ( initial: In, schedule: Schedule.Schedule ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, initial: In, schedule: Schedule.Schedule ) => Effect.Effect >(3, (self, initial, schedule) => core.flatMap( driver(schedule), (driver) => scheduleFrom_EffectLoop(self, initial, driver) )) /** @internal */ const scheduleFrom_EffectLoop = ( self: Effect.Effect, initial: In, driver: Schedule.ScheduleDriver ): Effect.Effect => core.matchEffect(driver.next(initial), { onFailure: () => core.orDie(driver.last()), onSuccess: () => core.flatMap(self, (a) => scheduleFrom_EffectLoop(self, a, driver)) }) /** @internal */ export const count: Schedule.Schedule = unfold(0, (n) => n + 1) /** @internal */ export const elapsed: Schedule.Schedule = makeWithState( Option.none() as Option.Option, (now, _, state) => { switch (state._tag) { case "None": { return core.succeed( [ Option.some(now), Duration.zero, ScheduleDecision.continueWith(Interval.after(now)) ] as const ) } case "Some": { return core.succeed( [ Option.some(state.value), Duration.millis(now - state.value), ScheduleDecision.continueWith(Interval.after(now)) ] as const ) } } } ) /** @internal */ export const forever: Schedule.Schedule = unfold(0, (n) => n + 1) /** @internal */ export const once: Schedule.Schedule = asUnit(recurs(1)) /** @internal */ export const stop: Schedule.Schedule = asUnit(recurs(0))