@zyro-sec/util 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/docs/layer-node.md +155 -155
  2. package/package.json +1 -1
  3. package/script/build.ts +9 -9
  4. package/script/pack.ts +5 -5
  5. package/src/abort.ts +9 -9
  6. package/src/activity-calendar.ts +50 -50
  7. package/src/artifact.ts +95 -95
  8. package/src/base64.ts +29 -29
  9. package/src/binary.ts +30 -30
  10. package/src/bom.ts +46 -46
  11. package/src/cross-spawn-spawner.ts +694 -694
  12. package/src/duration.ts +22 -22
  13. package/src/effect/app-node-platform.ts +40 -40
  14. package/src/effect/app-node.ts +14 -14
  15. package/src/effect/layer-node.ts +360 -360
  16. package/src/effect-flock.ts +313 -313
  17. package/src/encode.ts +39 -39
  18. package/src/execute-output.ts +23 -23
  19. package/src/flock.ts +346 -346
  20. package/src/fs-util.ts +271 -271
  21. package/src/glob.ts +38 -38
  22. package/src/global-roots.ts +19 -19
  23. package/src/global-roots.workerd.ts +16 -16
  24. package/src/global.ts +88 -88
  25. package/src/hash.ts +11 -11
  26. package/src/heap-snapshot.ts +44 -44
  27. package/src/no-timeout-fetch.ts +5 -5
  28. package/src/npm-config.ts +41 -41
  29. package/src/npm.ts +557 -557
  30. package/src/observability/logging.ts +179 -179
  31. package/src/observability/otlp.ts +109 -109
  32. package/src/observability/shared.ts +8 -8
  33. package/src/observability.ts +60 -60
  34. package/src/open.ts +12 -12
  35. package/src/patch.ts +382 -382
  36. package/src/path.ts +149 -149
  37. package/src/process-signal.ts +23 -23
  38. package/src/process.ts +270 -270
  39. package/src/qr.ts +323 -323
  40. package/src/record.ts +3 -3
  41. package/src/retry.ts +51 -51
  42. package/src/runtime/import.bun.ts +10 -10
  43. package/src/runtime/import.node.ts +61 -61
  44. package/src/runtime/import.workerd.ts +9 -9
  45. package/src/runtime-import.ts +1 -1
  46. package/src/session-mention.ts +24 -24
  47. package/src/session-title-fallback.ts +36 -36
  48. package/src/session-turn.ts +82 -82
  49. package/src/teardown.ts +19 -19
  50. package/src/text-boundary.ts +36 -36
  51. package/src/uuid.ts +15 -15
  52. package/test/fixtures/qr.json +625 -625
  53. package/tsconfig.build.json +12 -12
  54. package/tsconfig.dist.json +10 -10
  55. package/tsconfig.json +14 -14
  56. package/src/abort.test.ts +0 -16
  57. package/src/activity-calendar.test.ts +0 -136
  58. package/src/artifact.test.ts +0 -29
  59. package/src/base64.test.ts +0 -12
  60. package/src/binary.test.ts +0 -19
  61. package/src/bom.test.ts +0 -21
  62. package/src/encode.test.ts +0 -32
  63. package/src/execute-output.test.ts +0 -36
  64. package/src/no-timeout-fetch.test.ts +0 -33
  65. package/src/open.test.ts +0 -16
  66. package/src/path.test.ts +0 -89
  67. package/src/process-signal.test.ts +0 -38
  68. package/src/retry.test.ts +0 -87
  69. package/src/session-mention.test.ts +0 -19
  70. package/src/session-turn.test.ts +0 -131
  71. package/src/text-boundary.test.ts +0 -39
  72. package/src/uuid.test.ts +0 -80
  73. package/test/glob.test.ts +0 -11
  74. package/test/global-roots.test.ts +0 -62
  75. package/test/global.test.ts +0 -99
  76. package/test/observability-otlp.test.ts +0 -45
  77. package/test/qr.test.ts +0 -113
  78. package/test/session-title-fallback.test.ts +0 -49
@@ -1,313 +1,313 @@
1
- import path from "path"
2
- import os from "os"
3
- import { randomUUID } from "crypto"
4
- import { Context, Effect, Function, Layer, Option, Schedule, Schema } from "effect"
5
- import type { FileSystem, Scope } from "effect"
6
- import type { PlatformError } from "effect/PlatformError"
7
- import { FSUtil } from "./fs-util.js"
8
- import { Global } from "./global.js"
9
- import { makeGlobalNode } from "./effect/app-node.js"
10
- import { Hash } from "./hash.js"
11
-
12
- export namespace EffectFlock {
13
- // ---------------------------------------------------------------------------
14
- // Errors
15
- // ---------------------------------------------------------------------------
16
-
17
- export class LockTimeoutError extends Schema.TaggedError<LockTimeoutError>()("LockTimeoutError", {
18
- key: Schema.String,
19
- }) {}
20
-
21
- export class LockCompromisedError extends Schema.TaggedError<LockCompromisedError>()("LockCompromisedError", {
22
- detail: Schema.String,
23
- }) {}
24
-
25
- class ReleaseError extends Schema.TaggedError<ReleaseError>()("ReleaseError", {
26
- detail: Schema.String,
27
- cause: Schema.optional(Schema.Defect()),
28
- }) {
29
- override get message() {
30
- return this.detail
31
- }
32
- }
33
-
34
- /** Internal: signals "lock is held, retry later". Never leaks to callers. */
35
- class NotAcquired extends Schema.TaggedError<NotAcquired>()("NotAcquired", {}) {}
36
-
37
- export type LockError = LockTimeoutError | LockCompromisedError
38
-
39
- export interface Options {
40
- readonly staleMs?: number
41
- readonly timeoutMs?: number
42
- }
43
-
44
- // ---------------------------------------------------------------------------
45
- // Timing defaults
46
- // ---------------------------------------------------------------------------
47
-
48
- const DEFAULT_STALE_MS = 60_000
49
- const DEFAULT_TIMEOUT_MS = 5 * 60_000
50
- const BASE_DELAY_MS = 100
51
- const MAX_DELAY_MS = 2_000
52
-
53
- const retrySchedule = (timeoutMs: number) =>
54
- Schedule.min([
55
- Schedule.exponential(BASE_DELAY_MS, 1.7),
56
- Schedule.spaced(Math.min(MAX_DELAY_MS, Math.max(BASE_DELAY_MS, Math.floor(timeoutMs / 10)))),
57
- ]).pipe(
58
- Schedule.jittered,
59
- Schedule.while((meta) => meta.elapsed < timeoutMs),
60
- )
61
-
62
- // ---------------------------------------------------------------------------
63
- // Lock metadata schema
64
- // ---------------------------------------------------------------------------
65
-
66
- const LockMetaJson = Schema.fromJsonString(
67
- Schema.Struct({
68
- token: Schema.String,
69
- pid: Schema.Number,
70
- hostname: Schema.String,
71
- createdAt: Schema.String,
72
- }),
73
- )
74
-
75
- const decodeMeta = Schema.decodeUnknownSync(LockMetaJson)
76
- const encodeMeta = Schema.encodeSync(LockMetaJson)
77
-
78
- // ---------------------------------------------------------------------------
79
- // Service
80
- // ---------------------------------------------------------------------------
81
-
82
- export interface Interface {
83
- readonly acquire: (key: string, dir?: string, options?: Options) => Effect.Effect<void, LockError, Scope.Scope>
84
- readonly withLock: {
85
- (key: string, dir?: string): <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | LockError, R>
86
- <A, E, R>(body: Effect.Effect<A, E, R>, key: string, dir?: string): Effect.Effect<A, E | LockError, R>
87
- }
88
- }
89
-
90
- export class Service extends Context.Service<Service, Interface>()("EffectFlock") {}
91
-
92
- // ---------------------------------------------------------------------------
93
- // Layer
94
- // ---------------------------------------------------------------------------
95
-
96
- function wall() {
97
- return performance.timeOrigin + performance.now()
98
- }
99
-
100
- const mtimeMs = (info: FileSystem.File.Info) => Option.getOrElse(info.mtime, () => new Date(0)).getTime()
101
-
102
- const isPathGone = (e: PlatformError) => e.reason._tag === "NotFound" || e.reason._tag === "Unknown"
103
-
104
- const layer: Layer.Layer<Service, never, Global.Service | FSUtil.Service> = Layer.effect(
105
- Service,
106
- Effect.gen(function* () {
107
- const global = yield* Global.Service
108
- const fs = yield* FSUtil.Service
109
- const lockRoot = path.join(global.state, "locks")
110
- const hostname = os.hostname()
111
- const ensuredDirs = new Set<string>()
112
-
113
- // -- helpers (close over fs) --
114
-
115
- const safeStat = (file: string) =>
116
- fs.stat(file).pipe(
117
- Effect.catchIf(isPathGone, () => Effect.void),
118
- Effect.orDie,
119
- )
120
-
121
- const forceRemove = (target: string) => fs.remove(target, { recursive: true }).pipe(Effect.ignore)
122
-
123
- /** Atomic mkdir — returns true if created, false if already exists, dies on other errors. */
124
- const atomicMkdir = (dir: string) =>
125
- fs.makeDirectory(dir, { mode: 0o700 }).pipe(
126
- Effect.as(true),
127
- Effect.catchIf(
128
- (e) => e.reason._tag === "AlreadyExists",
129
- () => Effect.succeed(false),
130
- ),
131
- Effect.orDie,
132
- )
133
-
134
- /** Write with exclusive create — compromised error if file already exists. */
135
- const exclusiveWrite = (filePath: string, content: string, lockDir: string, detail: string) =>
136
- fs.writeFileString(filePath, content, { flag: "wx" }).pipe(
137
- Effect.catch(() =>
138
- Effect.gen(function* () {
139
- yield* forceRemove(lockDir)
140
- return yield* new LockCompromisedError({ detail })
141
- }),
142
- ),
143
- )
144
-
145
- const cleanStaleBreaker = Effect.fnUntraced(function* (breakerPath: string, staleMs: number) {
146
- const bs = yield* safeStat(breakerPath)
147
- if (bs && wall() - mtimeMs(bs) > staleMs) yield* forceRemove(breakerPath)
148
- return false
149
- })
150
-
151
- const ensureDir = Effect.fnUntraced(function* (dir: string) {
152
- if (ensuredDirs.has(dir)) return
153
- yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.orDie)
154
- ensuredDirs.add(dir)
155
- })
156
-
157
- const isStale = Effect.fnUntraced(function* (
158
- lockDir: string,
159
- heartbeatPath: string,
160
- metaPath: string,
161
- staleMs: number,
162
- ) {
163
- const now = wall()
164
-
165
- const hb = yield* safeStat(heartbeatPath)
166
- if (hb) return now - mtimeMs(hb) > staleMs
167
-
168
- const meta = yield* safeStat(metaPath)
169
- if (meta) return now - mtimeMs(meta) > staleMs
170
-
171
- const dir = yield* safeStat(lockDir)
172
- if (!dir) return false
173
-
174
- return now - mtimeMs(dir) > staleMs
175
- })
176
-
177
- // -- single lock attempt --
178
-
179
- type Handle = { token: string; metaPath: string; heartbeatPath: string; lockDir: string }
180
-
181
- const tryAcquireLockDir = (lockDir: string, key: string, staleMs: number) =>
182
- Effect.gen(function* () {
183
- const token = randomUUID()
184
- const metaPath = path.join(lockDir, "meta.json")
185
- const heartbeatPath = path.join(lockDir, "heartbeat")
186
-
187
- // Atomic mkdir — the POSIX lock primitive
188
- const created = yield* atomicMkdir(lockDir)
189
-
190
- if (!created) {
191
- if (!(yield* isStale(lockDir, heartbeatPath, metaPath, staleMs))) return yield* new NotAcquired()
192
-
193
- // Stale — race for breaker ownership
194
- const breakerPath = lockDir + ".breaker"
195
-
196
- const claimed = yield* fs.makeDirectory(breakerPath, { mode: 0o700 }).pipe(
197
- Effect.as(true),
198
- Effect.catchIf(
199
- (e) => e.reason._tag === "AlreadyExists",
200
- () => cleanStaleBreaker(breakerPath, staleMs),
201
- ),
202
- Effect.catchIf(isPathGone, () => Effect.succeed(false)),
203
- Effect.orDie,
204
- )
205
-
206
- if (!claimed) return yield* new NotAcquired()
207
-
208
- // We own the breaker — double-check staleness, nuke, recreate
209
- const recreated = yield* Effect.gen(function* () {
210
- if (!(yield* isStale(lockDir, heartbeatPath, metaPath, staleMs))) return false
211
- yield* forceRemove(lockDir)
212
- return yield* atomicMkdir(lockDir)
213
- }).pipe(Effect.ensuring(forceRemove(breakerPath)))
214
-
215
- if (!recreated) return yield* new NotAcquired()
216
- }
217
-
218
- // We own the lock dir — write heartbeat + meta with exclusive create
219
- yield* exclusiveWrite(heartbeatPath, "", lockDir, "heartbeat already existed")
220
-
221
- const metaJson = encodeMeta({ token, pid: process.pid, hostname, createdAt: new Date().toISOString() })
222
- yield* exclusiveWrite(metaPath, metaJson, lockDir, "meta.json already existed")
223
-
224
- return { token, metaPath, heartbeatPath, lockDir } satisfies Handle
225
- }).pipe(
226
- Effect.withSpan("EffectFlock.tryAcquire", {
227
- attributes: { key },
228
- }),
229
- )
230
-
231
- // -- retry wrapper (preserves Handle type) --
232
-
233
- const acquireHandle = (
234
- lockfile: string,
235
- key: string,
236
- options: { staleMs: number; timeoutMs: number },
237
- ): Effect.Effect<Handle, LockError> =>
238
- tryAcquireLockDir(lockfile, key, options.staleMs).pipe(
239
- Effect.retry({
240
- while: (err) => err._tag === "NotAcquired",
241
- schedule: retrySchedule(options.timeoutMs),
242
- }),
243
- Effect.catchTag("NotAcquired", () => Effect.fail(new LockTimeoutError({ key }))),
244
- Effect.timeoutOrElse({
245
- duration: options.timeoutMs,
246
- orElse: () => Effect.fail(new LockTimeoutError({ key })),
247
- }),
248
- )
249
-
250
- // -- release --
251
-
252
- const release = (handle: Handle) =>
253
- Effect.gen(function* () {
254
- const raw = yield* fs.readFileString(handle.metaPath).pipe(
255
- Effect.catch((err) => {
256
- if (isPathGone(err)) return Effect.die(new ReleaseError({ detail: "metadata missing" }))
257
- return Effect.die(err)
258
- }),
259
- )
260
-
261
- const parsed = yield* Effect.try({
262
- try: () => decodeMeta(raw),
263
- catch: (cause) => new ReleaseError({ detail: "metadata invalid", cause }),
264
- }).pipe(Effect.orDie)
265
-
266
- if (parsed.token !== handle.token) return yield* Effect.die(new ReleaseError({ detail: "token mismatch" }))
267
-
268
- yield* forceRemove(handle.lockDir)
269
- })
270
-
271
- // -- build service --
272
-
273
- const acquire = Effect.fn("EffectFlock.acquire")(function* (key: string, dir?: string, options: Options = {}) {
274
- const lockDir = dir ?? lockRoot
275
- const staleMs = options.staleMs ?? DEFAULT_STALE_MS
276
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
277
- yield* ensureDir(lockDir)
278
-
279
- const lockfile = path.join(lockDir, Hash.fast(key) + ".lock")
280
-
281
- // acquireRelease: acquire is uninterruptible, release is guaranteed
282
- const handle = yield* Effect.acquireRelease(acquireHandle(lockfile, key, { staleMs, timeoutMs }), (handle) =>
283
- release(handle),
284
- )
285
-
286
- // Heartbeat fiber — scoped, so it's interrupted before release runs
287
- yield* Effect.suspend(() => {
288
- const now = new Date()
289
- return fs.utimes(handle.heartbeatPath, now, now)
290
- }).pipe(
291
- Effect.ignore,
292
- Effect.repeat(Schedule.spaced(Math.max(100, Math.floor(staleMs / 3)))),
293
- Effect.forkScoped,
294
- )
295
- })
296
-
297
- const withLock: Interface["withLock"] = Function.dual(
298
- (args) => Effect.isEffect(args[0]),
299
- <A, E, R>(body: Effect.Effect<A, E, R>, key: string, dir?: string): Effect.Effect<A, E | LockError, R> =>
300
- Effect.scoped(
301
- Effect.gen(function* () {
302
- yield* acquire(key, dir)
303
- return yield* body
304
- }),
305
- ),
306
- )
307
-
308
- return Service.of({ acquire, withLock })
309
- }),
310
- )
311
-
312
- export const node = makeGlobalNode({ service: Service, layer: layer, deps: [Global.node, FSUtil.node] })
313
- }
1
+ import path from "path"
2
+ import os from "os"
3
+ import { randomUUID } from "crypto"
4
+ import { Context, Effect, Function, Layer, Option, Schedule, Schema } from "effect"
5
+ import type { FileSystem, Scope } from "effect"
6
+ import type { PlatformError } from "effect/PlatformError"
7
+ import { FSUtil } from "./fs-util.js"
8
+ import { Global } from "./global.js"
9
+ import { makeGlobalNode } from "./effect/app-node.js"
10
+ import { Hash } from "./hash.js"
11
+
12
+ export namespace EffectFlock {
13
+ // ---------------------------------------------------------------------------
14
+ // Errors
15
+ // ---------------------------------------------------------------------------
16
+
17
+ export class LockTimeoutError extends Schema.TaggedError<LockTimeoutError>()("LockTimeoutError", {
18
+ key: Schema.String,
19
+ }) {}
20
+
21
+ export class LockCompromisedError extends Schema.TaggedError<LockCompromisedError>()("LockCompromisedError", {
22
+ detail: Schema.String,
23
+ }) {}
24
+
25
+ class ReleaseError extends Schema.TaggedError<ReleaseError>()("ReleaseError", {
26
+ detail: Schema.String,
27
+ cause: Schema.optional(Schema.Defect()),
28
+ }) {
29
+ override get message() {
30
+ return this.detail
31
+ }
32
+ }
33
+
34
+ /** Internal: signals "lock is held, retry later". Never leaks to callers. */
35
+ class NotAcquired extends Schema.TaggedError<NotAcquired>()("NotAcquired", {}) {}
36
+
37
+ export type LockError = LockTimeoutError | LockCompromisedError
38
+
39
+ export interface Options {
40
+ readonly staleMs?: number
41
+ readonly timeoutMs?: number
42
+ }
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Timing defaults
46
+ // ---------------------------------------------------------------------------
47
+
48
+ const DEFAULT_STALE_MS = 60_000
49
+ const DEFAULT_TIMEOUT_MS = 5 * 60_000
50
+ const BASE_DELAY_MS = 100
51
+ const MAX_DELAY_MS = 2_000
52
+
53
+ const retrySchedule = (timeoutMs: number) =>
54
+ Schedule.min([
55
+ Schedule.exponential(BASE_DELAY_MS, 1.7),
56
+ Schedule.spaced(Math.min(MAX_DELAY_MS, Math.max(BASE_DELAY_MS, Math.floor(timeoutMs / 10)))),
57
+ ]).pipe(
58
+ Schedule.jittered,
59
+ Schedule.while((meta) => meta.elapsed < timeoutMs),
60
+ )
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Lock metadata schema
64
+ // ---------------------------------------------------------------------------
65
+
66
+ const LockMetaJson = Schema.fromJsonString(
67
+ Schema.Struct({
68
+ token: Schema.String,
69
+ pid: Schema.Number,
70
+ hostname: Schema.String,
71
+ createdAt: Schema.String,
72
+ }),
73
+ )
74
+
75
+ const decodeMeta = Schema.decodeUnknownSync(LockMetaJson)
76
+ const encodeMeta = Schema.encodeSync(LockMetaJson)
77
+
78
+ // ---------------------------------------------------------------------------
79
+ // Service
80
+ // ---------------------------------------------------------------------------
81
+
82
+ export interface Interface {
83
+ readonly acquire: (key: string, dir?: string, options?: Options) => Effect.Effect<void, LockError, Scope.Scope>
84
+ readonly withLock: {
85
+ (key: string, dir?: string): <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | LockError, R>
86
+ <A, E, R>(body: Effect.Effect<A, E, R>, key: string, dir?: string): Effect.Effect<A, E | LockError, R>
87
+ }
88
+ }
89
+
90
+ export class Service extends Context.Service<Service, Interface>()("EffectFlock") {}
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // Layer
94
+ // ---------------------------------------------------------------------------
95
+
96
+ function wall() {
97
+ return performance.timeOrigin + performance.now()
98
+ }
99
+
100
+ const mtimeMs = (info: FileSystem.File.Info) => Option.getOrElse(info.mtime, () => new Date(0)).getTime()
101
+
102
+ const isPathGone = (e: PlatformError) => e.reason._tag === "NotFound" || e.reason._tag === "Unknown"
103
+
104
+ const layer: Layer.Layer<Service, never, Global.Service | FSUtil.Service> = Layer.effect(
105
+ Service,
106
+ Effect.gen(function* () {
107
+ const global = yield* Global.Service
108
+ const fs = yield* FSUtil.Service
109
+ const lockRoot = path.join(global.state, "locks")
110
+ const hostname = os.hostname()
111
+ const ensuredDirs = new Set<string>()
112
+
113
+ // -- helpers (close over fs) --
114
+
115
+ const safeStat = (file: string) =>
116
+ fs.stat(file).pipe(
117
+ Effect.catchIf(isPathGone, () => Effect.void),
118
+ Effect.orDie,
119
+ )
120
+
121
+ const forceRemove = (target: string) => fs.remove(target, { recursive: true }).pipe(Effect.ignore)
122
+
123
+ /** Atomic mkdir — returns true if created, false if already exists, dies on other errors. */
124
+ const atomicMkdir = (dir: string) =>
125
+ fs.makeDirectory(dir, { mode: 0o700 }).pipe(
126
+ Effect.as(true),
127
+ Effect.catchIf(
128
+ (e) => e.reason._tag === "AlreadyExists",
129
+ () => Effect.succeed(false),
130
+ ),
131
+ Effect.orDie,
132
+ )
133
+
134
+ /** Write with exclusive create — compromised error if file already exists. */
135
+ const exclusiveWrite = (filePath: string, content: string, lockDir: string, detail: string) =>
136
+ fs.writeFileString(filePath, content, { flag: "wx" }).pipe(
137
+ Effect.catch(() =>
138
+ Effect.gen(function* () {
139
+ yield* forceRemove(lockDir)
140
+ return yield* new LockCompromisedError({ detail })
141
+ }),
142
+ ),
143
+ )
144
+
145
+ const cleanStaleBreaker = Effect.fnUntraced(function* (breakerPath: string, staleMs: number) {
146
+ const bs = yield* safeStat(breakerPath)
147
+ if (bs && wall() - mtimeMs(bs) > staleMs) yield* forceRemove(breakerPath)
148
+ return false
149
+ })
150
+
151
+ const ensureDir = Effect.fnUntraced(function* (dir: string) {
152
+ if (ensuredDirs.has(dir)) return
153
+ yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.orDie)
154
+ ensuredDirs.add(dir)
155
+ })
156
+
157
+ const isStale = Effect.fnUntraced(function* (
158
+ lockDir: string,
159
+ heartbeatPath: string,
160
+ metaPath: string,
161
+ staleMs: number,
162
+ ) {
163
+ const now = wall()
164
+
165
+ const hb = yield* safeStat(heartbeatPath)
166
+ if (hb) return now - mtimeMs(hb) > staleMs
167
+
168
+ const meta = yield* safeStat(metaPath)
169
+ if (meta) return now - mtimeMs(meta) > staleMs
170
+
171
+ const dir = yield* safeStat(lockDir)
172
+ if (!dir) return false
173
+
174
+ return now - mtimeMs(dir) > staleMs
175
+ })
176
+
177
+ // -- single lock attempt --
178
+
179
+ type Handle = { token: string; metaPath: string; heartbeatPath: string; lockDir: string }
180
+
181
+ const tryAcquireLockDir = (lockDir: string, key: string, staleMs: number) =>
182
+ Effect.gen(function* () {
183
+ const token = randomUUID()
184
+ const metaPath = path.join(lockDir, "meta.json")
185
+ const heartbeatPath = path.join(lockDir, "heartbeat")
186
+
187
+ // Atomic mkdir — the POSIX lock primitive
188
+ const created = yield* atomicMkdir(lockDir)
189
+
190
+ if (!created) {
191
+ if (!(yield* isStale(lockDir, heartbeatPath, metaPath, staleMs))) return yield* new NotAcquired()
192
+
193
+ // Stale — race for breaker ownership
194
+ const breakerPath = lockDir + ".breaker"
195
+
196
+ const claimed = yield* fs.makeDirectory(breakerPath, { mode: 0o700 }).pipe(
197
+ Effect.as(true),
198
+ Effect.catchIf(
199
+ (e) => e.reason._tag === "AlreadyExists",
200
+ () => cleanStaleBreaker(breakerPath, staleMs),
201
+ ),
202
+ Effect.catchIf(isPathGone, () => Effect.succeed(false)),
203
+ Effect.orDie,
204
+ )
205
+
206
+ if (!claimed) return yield* new NotAcquired()
207
+
208
+ // We own the breaker — double-check staleness, nuke, recreate
209
+ const recreated = yield* Effect.gen(function* () {
210
+ if (!(yield* isStale(lockDir, heartbeatPath, metaPath, staleMs))) return false
211
+ yield* forceRemove(lockDir)
212
+ return yield* atomicMkdir(lockDir)
213
+ }).pipe(Effect.ensuring(forceRemove(breakerPath)))
214
+
215
+ if (!recreated) return yield* new NotAcquired()
216
+ }
217
+
218
+ // We own the lock dir — write heartbeat + meta with exclusive create
219
+ yield* exclusiveWrite(heartbeatPath, "", lockDir, "heartbeat already existed")
220
+
221
+ const metaJson = encodeMeta({ token, pid: process.pid, hostname, createdAt: new Date().toISOString() })
222
+ yield* exclusiveWrite(metaPath, metaJson, lockDir, "meta.json already existed")
223
+
224
+ return { token, metaPath, heartbeatPath, lockDir } satisfies Handle
225
+ }).pipe(
226
+ Effect.withSpan("EffectFlock.tryAcquire", {
227
+ attributes: { key },
228
+ }),
229
+ )
230
+
231
+ // -- retry wrapper (preserves Handle type) --
232
+
233
+ const acquireHandle = (
234
+ lockfile: string,
235
+ key: string,
236
+ options: { staleMs: number; timeoutMs: number },
237
+ ): Effect.Effect<Handle, LockError> =>
238
+ tryAcquireLockDir(lockfile, key, options.staleMs).pipe(
239
+ Effect.retry({
240
+ while: (err) => err._tag === "NotAcquired",
241
+ schedule: retrySchedule(options.timeoutMs),
242
+ }),
243
+ Effect.catchTag("NotAcquired", () => Effect.fail(new LockTimeoutError({ key }))),
244
+ Effect.timeoutOrElse({
245
+ duration: options.timeoutMs,
246
+ orElse: () => Effect.fail(new LockTimeoutError({ key })),
247
+ }),
248
+ )
249
+
250
+ // -- release --
251
+
252
+ const release = (handle: Handle) =>
253
+ Effect.gen(function* () {
254
+ const raw = yield* fs.readFileString(handle.metaPath).pipe(
255
+ Effect.catch((err) => {
256
+ if (isPathGone(err)) return Effect.die(new ReleaseError({ detail: "metadata missing" }))
257
+ return Effect.die(err)
258
+ }),
259
+ )
260
+
261
+ const parsed = yield* Effect.try({
262
+ try: () => decodeMeta(raw),
263
+ catch: (cause) => new ReleaseError({ detail: "metadata invalid", cause }),
264
+ }).pipe(Effect.orDie)
265
+
266
+ if (parsed.token !== handle.token) return yield* Effect.die(new ReleaseError({ detail: "token mismatch" }))
267
+
268
+ yield* forceRemove(handle.lockDir)
269
+ })
270
+
271
+ // -- build service --
272
+
273
+ const acquire = Effect.fn("EffectFlock.acquire")(function* (key: string, dir?: string, options: Options = {}) {
274
+ const lockDir = dir ?? lockRoot
275
+ const staleMs = options.staleMs ?? DEFAULT_STALE_MS
276
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
277
+ yield* ensureDir(lockDir)
278
+
279
+ const lockfile = path.join(lockDir, Hash.fast(key) + ".lock")
280
+
281
+ // acquireRelease: acquire is uninterruptible, release is guaranteed
282
+ const handle = yield* Effect.acquireRelease(acquireHandle(lockfile, key, { staleMs, timeoutMs }), (handle) =>
283
+ release(handle),
284
+ )
285
+
286
+ // Heartbeat fiber — scoped, so it's interrupted before release runs
287
+ yield* Effect.suspend(() => {
288
+ const now = new Date()
289
+ return fs.utimes(handle.heartbeatPath, now, now)
290
+ }).pipe(
291
+ Effect.ignore,
292
+ Effect.repeat(Schedule.spaced(Math.max(100, Math.floor(staleMs / 3)))),
293
+ Effect.forkScoped,
294
+ )
295
+ })
296
+
297
+ const withLock: Interface["withLock"] = Function.dual(
298
+ (args) => Effect.isEffect(args[0]),
299
+ <A, E, R>(body: Effect.Effect<A, E, R>, key: string, dir?: string): Effect.Effect<A, E | LockError, R> =>
300
+ Effect.scoped(
301
+ Effect.gen(function* () {
302
+ yield* acquire(key, dir)
303
+ return yield* body
304
+ }),
305
+ ),
306
+ )
307
+
308
+ return Service.of({ acquire, withLock })
309
+ }),
310
+ )
311
+
312
+ export const node = makeGlobalNode({ service: Service, layer: layer, deps: [Global.node, FSUtil.node] })
313
+ }