The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Clock from "effect/Clock"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | |
| 4 | /** |
| 5 | * Time this process's shutdown in the run log: a Debug record when SIGINT or |
| 6 | * SIGTERM arrives, and one when `effect` has finished (finalizers included), |
| 7 | * with the time since the signal. Silent when the process ends on its own. |
| 8 | */ |
| 9 | export const logShutdown = |
| 10 | (name: string) => |
| 11 | <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => |
| 12 | Effect.gen(function* () { |
| 13 | const context = yield* Effect.context<never>(); |
| 14 | const clock = yield* Clock.Clock; |
| 15 | let signalled: { readonly signal: string; readonly at: number } | undefined; |
| 16 | const onSignal = (signal: NodeJS.Signals) => { |
| 17 | if (signalled !== undefined) return; |
| 18 | signalled = { signal, at: clock.currentTimeMillisUnsafe() }; |
| 19 | Effect.runForkWith(context)(Effect.logDebug(`shutdown: ${name} received ${signal}`)); |
| 20 | }; |
| 21 | // Ahead of the runtime's own handler, which interrupts this fiber and |
| 22 | // can run its whole teardown synchronously before later listeners. |
| 23 | process.prependListener("SIGINT", onSignal); |
| 24 | process.prependListener("SIGTERM", onSignal); |
| 25 | return yield* effect.pipe( |
| 26 | Effect.onExit(() => |
| 27 | Effect.flatMap(Clock.currentTimeMillis, (now) => { |
| 28 | process.off("SIGINT", onSignal); |
| 29 | process.off("SIGTERM", onSignal); |
| 30 | return signalled === undefined |
| 31 | ? Effect.void |
| 32 | : Effect.logDebug( |
| 33 | `shutdown: ${name} finished ${now - signalled.at}ms after ${signalled.signal}`, |
| 34 | ); |
| 35 | }), |
| 36 | ), |
| 37 | ); |
| 38 | }); |
| 39 | |
| 40 | /** Run `effect` and log how long it took, as a step of a shutdown. */ |
| 41 | export const timedShutdownStep = |
| 42 | (step: string) => |
| 43 | <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => |
| 44 | Effect.flatMap(Clock.currentTimeMillis, (start) => |
| 45 | effect.pipe( |
| 46 | Effect.onExit(() => |
| 47 | Effect.flatMap(Clock.currentTimeMillis, (end) => |
| 48 | Effect.logDebug(`shutdown: ${step} in ${end - start}ms`), |
| 49 | ), |
| 50 | ), |
| 51 | ), |
| 52 | ); |