1010 * @since 4.0.0
1111 */
1212import type { NonEmptyReadonlyArray } from "../Array.ts"
13- import * as Cause from "../Cause.ts"
13+ import type * as Cause from "../Cause.ts"
14+ import * as Clock from "../Clock.ts"
1415import * as Context from "../Context.ts"
1516import * as Effect from "../Effect.ts"
16- import * as Effectable from "../Effectable .ts"
17+ import * as Exit from "../Exit .ts"
1718import { dual } from "../Function.ts"
19+ import * as Hash from "../Hash.ts"
20+ import { findRecoverableError } from "../internal/effect.ts"
21+ import { Random } from "../internal/random.ts"
22+ import { buildFromOptions } from "../internal/schedule.ts"
23+ import * as Pull from "../Pull.ts"
24+ import type * as RandomService from "../Random.ts"
25+ import * as Result from "../Result.ts"
1826import * as Schedule from "../Schedule.ts"
1927import * as Schema from "../Schema.ts"
2028import type { Scope } from "../Scope.ts"
2129import type * as Types from "../Types.ts"
30+ import * as DurableClock from "./DurableClock.ts"
2231import * as DurableDeferred from "./DurableDeferred.ts"
32+ import * as internal from "./internal/activity.ts"
2333import { makeHashDigest } from "./internal/crypto.ts"
2434import { RetryingExecution } from "./internal/retry.ts"
25- import * as Workflow from "./Workflow.ts"
2635import type { WorkflowEngine , WorkflowInstance } from "./WorkflowEngine.ts"
2736
28- const TypeId = "~effect/workflow/Activity"
37+ const TypeId = internal . TypeId
2938
3039/**
3140 * Durable workflow activity that behaves as an `Effect` and records its name,
@@ -133,7 +142,7 @@ export interface AnyWithProps {
133142 * @category constructors
134143 * @since 4.0.0
135144 */
136- export const make = <
145+ export const make : <
137146 R ,
138147 Success extends Schema . Constraint = Schema . Void ,
139148 Error extends Schema . Constraint = Schema . Never
@@ -144,89 +153,34 @@ export const make = <
144153 readonly execute : Effect . Effect < Success [ "Type" ] , Error [ "Type" ] , R >
145154 readonly interruptRetryPolicy ?: Schedule . Schedule < any , Cause . Cause < unknown > > | undefined
146155 readonly annotations ?: Context . Context < never > | undefined
147- } ) : Activity < Success , Error , Exclude < R , WorkflowInstance | WorkflowEngine | Scope > > => {
148- const successSchema = options . success ?? ( Schema . Void as any as Success )
149- const errorSchema = options . error ?? ( Schema . Never as any as Error )
150- const successSchemaJson = Schema . toCodecJson ( successSchema )
151- const errorSchemaJson = Schema . toCodecJson ( errorSchema )
152- // oxlint-disable-next-line prefer-const
153- let execute ! : Effect . Effect < Success [ "Type" ] , Error [ "Type" ] , any >
154- const executeWithoutInterrupt = retryOnInterrupt (
155- options . name ,
156- options . interruptRetryPolicy
157- ) ( options . execute )
158- const self : Activity < Success , Error , Exclude < R , WorkflowInstance | WorkflowEngine > > = {
159- ...Effectable . Prototype < Activity < Success , Error , R > > ( {
160- label : "Activity" ,
161- evaluate ( _ ) {
162- return execute
163- }
164- } ) ,
165- [ TypeId ] : TypeId ,
166- name : options . name ,
167- successSchema,
168- errorSchema,
169- exitSchema : Schema . Exit ( successSchemaJson , errorSchemaJson , Schema . Defect ( ) ) ,
170- exitSchemaPartial : Schema . Exit ( successSchemaJson , errorSchemaJson , Schema . Unknown ) ,
171- annotations : options . annotations ?? Context . empty ( ) ,
172- annotate ( tag : Context . Key < any , any > , value : any ) {
173- return make ( {
174- ...options ,
175- annotations : Context . add ( self . annotations , tag , value )
176- } )
177- } ,
178- annotateMerge ( context : Context . Context < any > ) {
179- return make ( {
180- ...options ,
181- annotations : Context . merge ( self . annotations , context )
182- } )
183- } ,
184- execute : executeWithoutInterrupt ,
185- executeEncoded : Effect . matchEffect ( executeWithoutInterrupt , {
186- onFailure : ( error ) => Effect . flatMap ( Effect . orDie ( Schema . encodeEffect ( errorSchemaJson ) ( error ) ) , Effect . fail ) ,
187- onSuccess : ( value ) => Effect . orDie ( Schema . encodeEffect ( successSchemaJson ) ( value ) )
188- } )
189- } as any
190- execute = makeExecute ( self )
191- return self
192- }
193-
194- const interruptRetryPolicy = Schedule . min ( [
195- Schedule . exponential ( 400 , 1.5 ) ,
196- Schedule . spaced ( "10 seconds" )
197- ] ) . pipe (
198- Schedule . setInputType < Cause . Cause < unknown > > ( ) ,
199- Schedule . while ( ( meta ) => meta . attempt <= 10 && Cause . hasInterrupts ( meta . input ) )
200- )
201-
202- const retryOnInterrupt = (
203- name : string ,
204- policy : Schedule . Schedule < any , Cause . Cause < unknown > > = interruptRetryPolicy
205- ) =>
206- < A , E , R > ( effect : Effect . Effect < A , E , R > ) : Effect . Effect < A , E , R | WorkflowInstance > =>
207- Effect . flatMap ( InstanceTag , ( instance ) =>
208- effect . pipe (
209- Effect . sandbox ,
210- // A suspension interrupts the activity body on purpose and must surface
211- // as a suspended result instead of being retried.
212- Effect . retry ( { schedule : policy , while : ( ) => ! instance . suspended } ) ,
213- Effect . catch ( ( cause ) =>
214- Cause . hasInterrupts ( cause ) && ! instance . suspended
215- ? Effect . die ( `Activity "${ name } " interrupted and retry attempts exhausted` )
216- : Effect . failCause ( cause )
217- )
218- ) )
156+ } ) => Activity < Success , Error , Exclude < R , WorkflowInstance | WorkflowEngine | Scope > > = internal . make
219157
220158/**
221- * Retries an effect with `Effect.retry` while updating `CurrentAttempt` for
222- * each attempt.
159+ * Retries an effect while updating `CurrentAttempt` for each attempt.
223160 *
224161 * **Details**
225162 *
163+ * Without `schedule`, retries run immediately through `Effect.retry`.
164+ *
165+ * With `schedule`, delays use `DurableClock.sleep`, so long waits suspend the
166+ * workflow. `name` must identify the retry uniquely within the workflow and
167+ * defaults to a bare activity's name. Wrapped or plain effects must supply it.
168+ * Replay steps the schedule with recorded attempt times and seeded randomness.
169+ *
226170 * Under `Workflow.SuspendOnFailure`, failed attempts reach the retry policy
227171 * instead of suspending immediately. If the policy is exhausted and the error
228172 * escapes, the workflow suspends and `resume` replays the stored failures.
229173 *
174+ * **Gotchas**
175+ *
176+ * - Effects in a schedule (including `while`, `until`, `modifyDelay` and taps)
177+ * rerun on replay. Keep them deterministic; read time from schedule metadata,
178+ * not `Clock`.
179+ * - Replay skips random draws inside memoized activities, shifting later draws
180+ * in the same schedule step.
181+ * - Changing a running workflow's policy can stop replay early or repeat
182+ * completed waits.
183+ *
230184 * @stability unstable
231185 * @category error handling
232186 * @since 4.0.0
@@ -235,22 +189,115 @@ export const retry: {
235189 < E , O extends Types . NoExcessProperties < Omit < Effect . Retry . Options < E > , "schedule" > , O > > (
236190 options : O
237191 ) : < A , R > ( self : Effect . Effect < A , E , R > ) => Effect . Retry . Return < R , E , A , O >
192+ <
193+ E ,
194+ O extends Types . NoExcessProperties <
195+ Effect . Retry . Options < E > & {
196+ readonly schedule : Schedule . Schedule < any , E , any , any >
197+ readonly name ?: string | undefined
198+ } ,
199+ O
200+ >
201+ > (
202+ options : O
203+ ) : < A , R > (
204+ self : Effect . Effect < A , E , R > & ( O extends { readonly name : string } ? unknown : Any )
205+ ) => Effect . Retry . Return < R | WorkflowEngine | WorkflowInstance , E , A , O >
238206 < A , E , R , O extends Types . NoExcessProperties < Omit < Effect . Retry . Options < E > , "schedule" > , O > > (
239207 self : Effect . Effect < A , E , R > ,
240208 options : O
241209 ) : Effect . Retry . Return < R , E , A , O >
210+ <
211+ A ,
212+ E ,
213+ R ,
214+ O extends Types . NoExcessProperties <
215+ Effect . Retry . Options < E > & {
216+ readonly schedule : Schedule . Schedule < any , E , any , any >
217+ readonly name ?: string | undefined
218+ } ,
219+ O
220+ >
221+ > (
222+ self : Effect . Effect < A , E , R > & ( O extends { readonly name : string } ? unknown : Any ) ,
223+ options : O
224+ ) : Effect . Retry . Return < R | WorkflowEngine | WorkflowInstance , E , A , O >
242225} = dual (
243226 2 ,
244- ( effect : Effect . Effect < any , any , any > , options : { } ) =>
245- Effect . contextWith ( ( context : Context . Context < never > ) => {
246- let attempt = 1
247- return Effect . suspend ( ( ) => Effect . provideService ( effect , CurrentAttempt , attempt ++ ) ) . pipe (
248- Effect . provideService ( RetryingExecution , Context . getOrUndefined ( context , InstanceTag ) ?. executionId ) ,
249- Effect . retry ( options )
250- )
251- } )
227+ ( effect : Effect . Effect < any , any , any > , options : Effect . Retry . Options < any > & { readonly name ?: string | undefined } ) =>
228+ options . schedule ?
229+ retryDurable ( effect , options , options . name ?? ( effect as any as Any ) . name ) :
230+ Effect . contextWith ( ( context : Context . Context < never > ) => {
231+ let attempt = 1
232+ return Effect . suspend ( ( ) => Effect . provideService ( effect , CurrentAttempt , attempt ++ ) ) . pipe (
233+ Effect . provideService ( RetryingExecution , Context . getOrUndefined ( context , internal . InstanceTag ) ?. executionId ) ,
234+ Effect . retry ( options )
235+ )
236+ } )
252237)
253238
239+ const retryDurable = Effect . fnUntraced ( function * (
240+ effect : Effect . Effect < any , any , any > ,
241+ options : Effect . Retry . Options < any > ,
242+ name : string
243+ ) {
244+ const instance = yield * internal . InstanceTag
245+ // Separate seeds prevent skipped draws on replay from shifting later steps.
246+ const step = yield * Effect . provideService (
247+ Schedule . toStep ( buildFromOptions ( options ) ) ,
248+ Random ,
249+ seededRandom ( `${ instance . executionId } /Activity.retry/${ name } ` )
250+ )
251+ let meta = Schedule . CurrentMetadata . defaultValue ( )
252+ for ( let attempt = 1 ; ; attempt ++ ) {
253+ const exit = yield * effect . pipe (
254+ Effect . provideService ( CurrentAttempt , attempt ) ,
255+ Effect . provideService ( Schedule . CurrentMetadata , meta ) ,
256+ Effect . provideService ( RetryingExecution , instance . executionId ) ,
257+ Effect . exit
258+ )
259+ if ( Exit . isSuccess ( exit ) ) return exit . value
260+ const error = findRecoverableError ( exit . cause )
261+ if ( Result . isFailure ( error ) ) return yield * Effect . failCause ( error . failure )
262+ const key = `Activity.retry/${ name } /${ attempt } `
263+ const now = yield * make ( { name : key , success : Schema . Number , execute : Clock . currentTimeMillis } )
264+ const next = yield * step ( now , error . success ) . pipe (
265+ Effect . provideService ( Random , seededRandom ( `${ instance . executionId } /${ key } ` ) ) ,
266+ Pull . catchDone ( ( ) => Effect . succeed ( undefined ) )
267+ )
268+ if ( next === undefined ) return yield * exit
269+ const start = meta . attempt === 0 ? now : meta . start
270+ meta = {
271+ input : error . success ,
272+ output : next [ 0 ] ,
273+ duration : next [ 1 ] ,
274+ attempt,
275+ start,
276+ now,
277+ elapsed : now - start ,
278+ elapsedSincePrevious : meta . attempt === 0 ? 0 : now - meta . now
279+ }
280+ yield * DurableClock . sleep ( { name : key , duration : next [ 1 ] } )
281+ }
282+ } )
283+
284+ // Mulberry32 seeded with a hash of `seed`.
285+ const seededRandom = ( seed : string ) : RandomService . Random => {
286+ let state = Hash . string ( seed )
287+ const nextDoubleUnsafe = ( ) => {
288+ state = ( state + 0x6D2B79F5 ) | 0
289+ let t = Math . imul ( state ^ ( state >>> 15 ) , 1 | state )
290+ t = ( t + Math . imul ( t ^ ( t >>> 7 ) , 61 | t ) ) ^ t
291+ return ( ( t ^ ( t >>> 14 ) ) >>> 0 ) / 4294967296
292+ }
293+ return {
294+ nextDoubleUnsafe,
295+ nextIntUnsafe : ( ) =>
296+ Math . floor ( nextDoubleUnsafe ( ) * ( Number . MAX_SAFE_INTEGER - Number . MIN_SAFE_INTEGER + 1 ) ) +
297+ Number . MIN_SAFE_INTEGER
298+ }
299+ }
300+
254301/**
255302 * Context reference containing the current activity retry attempt, defaulting
256303 * to `1`.
@@ -259,10 +306,7 @@ export const retry: {
259306 * @category services
260307 * @since 4.0.0
261308 */
262- export const CurrentAttempt = Context . Reference < number > (
263- "effect/workflow/Activity/CurrentAttempt" ,
264- { defaultValue : ( ) => 1 }
265- )
309+ export const CurrentAttempt : Context . Reference < number > = internal . CurrentAttempt
266310
267311/**
268312 * Computes a deterministic activity idempotency key from the current workflow
@@ -280,7 +324,7 @@ export const idempotencyKey: (
280324) => Effect . Effect < string , never , WorkflowInstance > = Effect . fnUntraced ( function * ( name : string , options ?: {
281325 readonly includeAttempt ?: boolean | undefined
282326} ) {
283- const instance = yield * InstanceTag
327+ const instance = yield * internal . InstanceTag
284328 let key = `${ instance . executionId } `
285329 if ( options ?. includeAttempt ) {
286330 const attempt = yield * CurrentAttempt
@@ -320,39 +364,3 @@ export const raceAll = <const Activities extends NonEmptyReadonlyArray<Any>>(
320364 ) ,
321365 effects : activities . map ( ( activity ) => ( activity as any ) ) as any
322366 } ) as any
323-
324- // -----------------------------------------------------------------------------
325- // internal
326- // -----------------------------------------------------------------------------
327-
328- const EngineTag = Context . Service < WorkflowEngine , WorkflowEngine [ "Service" ] > (
329- "effect/workflow/WorkflowEngine" satisfies typeof WorkflowEngine . key
330- )
331- const InstanceTag = Context . Service < WorkflowInstance , WorkflowInstance [ "Service" ] > (
332- "effect/workflow/WorkflowEngine/WorkflowInstance" satisfies typeof WorkflowInstance . key
333- )
334-
335- const makeExecute = Effect . fnUntraced ( function * <
336- R ,
337- Success extends Schema . Constraint = typeof Schema . Void ,
338- Error extends Schema . Constraint = typeof Schema . Never
339- > ( activity : Activity < Success , Error , R > ) {
340- const engine = yield * EngineTag
341- const instance = yield * InstanceTag
342- const attempt = yield * CurrentAttempt
343- yield * Effect . annotateCurrentSpan ( { executionId : instance . executionId } )
344- const result = yield * Workflow . wrapActivityResult (
345- Effect . map ( engine . activityExecute ( activity , attempt ) , ( result ) => {
346- if ( result . _tag === "Suspended" && result . failed ) instance . failed = true
347- return result
348- } ) ,
349- ( _ ) => _ . _tag === "Suspended"
350- )
351- if ( result . _tag === "Suspended" ) {
352- return yield * Workflow . suspend ( instance )
353- }
354- return yield * result . exit
355- } , ( effect , activity ) =>
356- Effect . withSpan ( effect , activity . name , {
357- captureStackTrace : false
358- } ) )
0 commit comments