@smthrs/journal 0.0.0-stage → 1.0.0-rc.12

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 (257) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/LICENSE +21 -0
  3. package/README.md +208 -2
  4. package/dist/cjs/CallFact.d.ts +129 -0
  5. package/dist/cjs/CallFact.d.ts.map +1 -0
  6. package/dist/cjs/CallFact.js +106 -0
  7. package/dist/cjs/CallFact.js.map +7 -0
  8. package/dist/cjs/Consensus.d.ts +492 -0
  9. package/dist/cjs/Consensus.d.ts.map +1 -0
  10. package/dist/cjs/Consensus.js +308 -0
  11. package/dist/cjs/Consensus.js.map +7 -0
  12. package/dist/cjs/EngineEvent.d.ts +890 -0
  13. package/dist/cjs/EngineEvent.d.ts.map +1 -0
  14. package/dist/cjs/EngineEvent.js +383 -0
  15. package/dist/cjs/EngineEvent.js.map +7 -0
  16. package/dist/cjs/ExecutionFact.d.ts +216 -0
  17. package/dist/cjs/ExecutionFact.d.ts.map +1 -0
  18. package/dist/cjs/ExecutionFact.js +303 -0
  19. package/dist/cjs/ExecutionFact.js.map +7 -0
  20. package/dist/cjs/Journal.d.ts +617 -0
  21. package/dist/cjs/Journal.d.ts.map +1 -0
  22. package/dist/cjs/Journal.js +190 -0
  23. package/dist/cjs/Journal.js.map +7 -0
  24. package/dist/cjs/JournalEvent.d.ts +421 -0
  25. package/dist/cjs/JournalEvent.d.ts.map +1 -0
  26. package/dist/cjs/JournalEvent.js +281 -0
  27. package/dist/cjs/JournalEvent.js.map +7 -0
  28. package/dist/cjs/JournalGeneration.d.ts +34 -0
  29. package/dist/cjs/JournalGeneration.d.ts.map +1 -0
  30. package/dist/cjs/JournalGeneration.js +73 -0
  31. package/dist/cjs/JournalGeneration.js.map +7 -0
  32. package/dist/cjs/JournalMetrics.d.ts +72 -0
  33. package/dist/cjs/JournalMetrics.d.ts.map +1 -0
  34. package/dist/cjs/JournalMetrics.js +55 -0
  35. package/dist/cjs/JournalMetrics.js.map +7 -0
  36. package/dist/cjs/Migrations.d.ts +42 -0
  37. package/dist/cjs/Migrations.d.ts.map +1 -0
  38. package/dist/cjs/Migrations.js +58 -0
  39. package/dist/cjs/Migrations.js.map +7 -0
  40. package/dist/cjs/OwnerId.d.ts +40 -0
  41. package/dist/cjs/OwnerId.d.ts.map +1 -0
  42. package/dist/cjs/OwnerId.js +40 -0
  43. package/dist/cjs/OwnerId.js.map +7 -0
  44. package/dist/cjs/Projection.d.ts +29 -0
  45. package/dist/cjs/Projection.d.ts.map +1 -0
  46. package/dist/cjs/Projection.js +25 -0
  47. package/dist/cjs/Projection.js.map +7 -0
  48. package/dist/cjs/RedactedLogger.d.ts +121 -0
  49. package/dist/cjs/RedactedLogger.d.ts.map +1 -0
  50. package/dist/cjs/RedactedLogger.js +235 -0
  51. package/dist/cjs/RedactedLogger.js.map +7 -0
  52. package/dist/cjs/Redaction.d.ts +350 -0
  53. package/dist/cjs/Redaction.d.ts.map +1 -0
  54. package/dist/cjs/Redaction.js +955 -0
  55. package/dist/cjs/Redaction.js.map +7 -0
  56. package/dist/cjs/SqlConsensus.d.ts +44 -0
  57. package/dist/cjs/SqlConsensus.d.ts.map +1 -0
  58. package/dist/cjs/SqlConsensus.js +273 -0
  59. package/dist/cjs/SqlConsensus.js.map +7 -0
  60. package/dist/cjs/SqlJournal.d.ts +173 -0
  61. package/dist/cjs/SqlJournal.d.ts.map +1 -0
  62. package/dist/cjs/SqlJournal.js +1568 -0
  63. package/dist/cjs/SqlJournal.js.map +7 -0
  64. package/dist/cjs/StepFact.d.ts +66 -0
  65. package/dist/cjs/StepFact.d.ts.map +1 -0
  66. package/dist/cjs/StepFact.js +68 -0
  67. package/dist/cjs/StepFact.js.map +7 -0
  68. package/dist/cjs/index.d.ts +95 -0
  69. package/dist/cjs/index.d.ts.map +1 -0
  70. package/dist/cjs/index.js +63 -0
  71. package/dist/cjs/index.js.map +7 -0
  72. package/dist/cjs/internal/JournalInternalFault.d.ts +37 -0
  73. package/dist/cjs/internal/JournalInternalFault.d.ts.map +1 -0
  74. package/dist/cjs/internal/JournalInternalFault.js +43 -0
  75. package/dist/cjs/internal/JournalInternalFault.js.map +7 -0
  76. package/dist/cjs/migrations/0001_initial.d.ts +15 -0
  77. package/dist/cjs/migrations/0001_initial.d.ts.map +1 -0
  78. package/dist/cjs/migrations/0001_initial.js +54 -0
  79. package/dist/cjs/migrations/0001_initial.js.map +7 -0
  80. package/dist/cjs/migrations/0002_checkpoints.d.ts +27 -0
  81. package/dist/cjs/migrations/0002_checkpoints.d.ts.map +1 -0
  82. package/dist/cjs/migrations/0002_checkpoints.js +48 -0
  83. package/dist/cjs/migrations/0002_checkpoints.js.map +7 -0
  84. package/dist/cjs/migrations/0003_startup_index.d.ts +15 -0
  85. package/dist/cjs/migrations/0003_startup_index.d.ts.map +1 -0
  86. package/dist/cjs/migrations/0003_startup_index.js +40 -0
  87. package/dist/cjs/migrations/0003_startup_index.js.map +7 -0
  88. package/dist/cjs/migrations/0004_dedup.d.ts +15 -0
  89. package/dist/cjs/migrations/0004_dedup.d.ts.map +1 -0
  90. package/dist/cjs/migrations/0004_dedup.js +57 -0
  91. package/dist/cjs/migrations/0004_dedup.js.map +7 -0
  92. package/dist/cjs/migrations/0005_run_event_type.d.ts +15 -0
  93. package/dist/cjs/migrations/0005_run_event_type.d.ts.map +1 -0
  94. package/dist/cjs/migrations/0005_run_event_type.js +40 -0
  95. package/dist/cjs/migrations/0005_run_event_type.js.map +7 -0
  96. package/dist/cjs/migrations/0006_consensus.d.ts +22 -0
  97. package/dist/cjs/migrations/0006_consensus.d.ts.map +1 -0
  98. package/dist/cjs/migrations/0006_consensus.js +84 -0
  99. package/dist/cjs/migrations/0006_consensus.js.map +7 -0
  100. package/dist/cjs/package.json +1 -0
  101. package/dist/cjs/test/Notifying.d.ts +65 -0
  102. package/dist/cjs/test/Notifying.d.ts.map +1 -0
  103. package/dist/cjs/test/Notifying.js +62 -0
  104. package/dist/cjs/test/Notifying.js.map +7 -0
  105. package/dist/cjs/test/TestJournal.d.ts +43 -0
  106. package/dist/cjs/test/TestJournal.d.ts.map +1 -0
  107. package/dist/cjs/test/TestJournal.js +43 -0
  108. package/dist/cjs/test/TestJournal.js.map +7 -0
  109. package/dist/esm/CallFact.d.ts +129 -0
  110. package/dist/esm/CallFact.d.ts.map +1 -0
  111. package/dist/esm/CallFact.js +96 -0
  112. package/dist/esm/CallFact.js.map +1 -0
  113. package/dist/esm/Consensus.d.ts +492 -0
  114. package/dist/esm/Consensus.d.ts.map +1 -0
  115. package/dist/esm/Consensus.js +536 -0
  116. package/dist/esm/Consensus.js.map +1 -0
  117. package/dist/esm/EngineEvent.d.ts +890 -0
  118. package/dist/esm/EngineEvent.d.ts.map +1 -0
  119. package/dist/esm/EngineEvent.js +614 -0
  120. package/dist/esm/EngineEvent.js.map +1 -0
  121. package/dist/esm/ExecutionFact.d.ts +216 -0
  122. package/dist/esm/ExecutionFact.d.ts.map +1 -0
  123. package/dist/esm/ExecutionFact.js +374 -0
  124. package/dist/esm/ExecutionFact.js.map +1 -0
  125. package/dist/esm/Journal.d.ts +617 -0
  126. package/dist/esm/Journal.d.ts.map +1 -0
  127. package/dist/esm/Journal.js +323 -0
  128. package/dist/esm/Journal.js.map +1 -0
  129. package/dist/esm/JournalEvent.d.ts +421 -0
  130. package/dist/esm/JournalEvent.d.ts.map +1 -0
  131. package/dist/esm/JournalEvent.js +517 -0
  132. package/dist/esm/JournalEvent.js.map +1 -0
  133. package/dist/esm/JournalGeneration.d.ts +34 -0
  134. package/dist/esm/JournalGeneration.d.ts.map +1 -0
  135. package/dist/esm/JournalGeneration.js +71 -0
  136. package/dist/esm/JournalGeneration.js.map +1 -0
  137. package/dist/esm/JournalMetrics.d.ts +72 -0
  138. package/dist/esm/JournalMetrics.d.ts.map +1 -0
  139. package/dist/esm/JournalMetrics.js +79 -0
  140. package/dist/esm/JournalMetrics.js.map +1 -0
  141. package/dist/esm/Migrations.d.ts +42 -0
  142. package/dist/esm/Migrations.d.ts.map +1 -0
  143. package/dist/esm/Migrations.js +59 -0
  144. package/dist/esm/Migrations.js.map +1 -0
  145. package/dist/esm/OwnerId.d.ts +40 -0
  146. package/dist/esm/OwnerId.d.ts.map +1 -0
  147. package/dist/esm/OwnerId.js +33 -0
  148. package/dist/esm/OwnerId.js.map +1 -0
  149. package/dist/esm/Projection.d.ts +29 -0
  150. package/dist/esm/Projection.d.ts.map +1 -0
  151. package/dist/esm/Projection.js +13 -0
  152. package/dist/esm/Projection.js.map +1 -0
  153. package/dist/esm/RedactedLogger.d.ts +121 -0
  154. package/dist/esm/RedactedLogger.d.ts.map +1 -0
  155. package/dist/esm/RedactedLogger.js +445 -0
  156. package/dist/esm/RedactedLogger.js.map +1 -0
  157. package/dist/esm/Redaction.d.ts +350 -0
  158. package/dist/esm/Redaction.d.ts.map +1 -0
  159. package/dist/esm/Redaction.js +1619 -0
  160. package/dist/esm/Redaction.js.map +1 -0
  161. package/dist/esm/SqlConsensus.d.ts +44 -0
  162. package/dist/esm/SqlConsensus.d.ts.map +1 -0
  163. package/dist/esm/SqlConsensus.js +273 -0
  164. package/dist/esm/SqlConsensus.js.map +1 -0
  165. package/dist/esm/SqlJournal.d.ts +173 -0
  166. package/dist/esm/SqlJournal.d.ts.map +1 -0
  167. package/dist/esm/SqlJournal.js +1858 -0
  168. package/dist/esm/SqlJournal.js.map +1 -0
  169. package/dist/esm/StepFact.d.ts +66 -0
  170. package/dist/esm/StepFact.d.ts.map +1 -0
  171. package/dist/esm/StepFact.js +50 -0
  172. package/dist/esm/StepFact.js.map +1 -0
  173. package/dist/esm/index.d.ts +95 -0
  174. package/dist/esm/index.d.ts.map +1 -0
  175. package/dist/esm/index.js +95 -0
  176. package/dist/esm/index.js.map +1 -0
  177. package/dist/esm/internal/JournalInternalFault.d.ts +37 -0
  178. package/dist/esm/internal/JournalInternalFault.d.ts.map +1 -0
  179. package/dist/esm/internal/JournalInternalFault.js +28 -0
  180. package/dist/esm/internal/JournalInternalFault.js.map +1 -0
  181. package/dist/esm/migrations/0001_initial.d.ts +15 -0
  182. package/dist/esm/migrations/0001_initial.d.ts.map +1 -0
  183. package/dist/esm/migrations/0001_initial.js +32 -0
  184. package/dist/esm/migrations/0001_initial.js.map +1 -0
  185. package/dist/esm/migrations/0002_checkpoints.d.ts +27 -0
  186. package/dist/esm/migrations/0002_checkpoints.d.ts.map +1 -0
  187. package/dist/esm/migrations/0002_checkpoints.js +38 -0
  188. package/dist/esm/migrations/0002_checkpoints.js.map +1 -0
  189. package/dist/esm/migrations/0003_startup_index.d.ts +15 -0
  190. package/dist/esm/migrations/0003_startup_index.d.ts.map +1 -0
  191. package/dist/esm/migrations/0003_startup_index.js +18 -0
  192. package/dist/esm/migrations/0003_startup_index.js.map +1 -0
  193. package/dist/esm/migrations/0004_dedup.d.ts +15 -0
  194. package/dist/esm/migrations/0004_dedup.d.ts.map +1 -0
  195. package/dist/esm/migrations/0004_dedup.js +38 -0
  196. package/dist/esm/migrations/0004_dedup.js.map +1 -0
  197. package/dist/esm/migrations/0005_run_event_type.d.ts +15 -0
  198. package/dist/esm/migrations/0005_run_event_type.d.ts.map +1 -0
  199. package/dist/esm/migrations/0005_run_event_type.js +18 -0
  200. package/dist/esm/migrations/0005_run_event_type.js.map +1 -0
  201. package/dist/esm/migrations/0006_consensus.d.ts +22 -0
  202. package/dist/esm/migrations/0006_consensus.d.ts.map +1 -0
  203. package/dist/esm/migrations/0006_consensus.js +69 -0
  204. package/dist/esm/migrations/0006_consensus.js.map +1 -0
  205. package/dist/esm/test/Notifying.d.ts +65 -0
  206. package/dist/esm/test/Notifying.d.ts.map +1 -0
  207. package/dist/esm/test/Notifying.js +62 -0
  208. package/dist/esm/test/Notifying.js.map +1 -0
  209. package/dist/esm/test/TestJournal.d.ts +43 -0
  210. package/dist/esm/test/TestJournal.d.ts.map +1 -0
  211. package/dist/esm/test/TestJournal.js +27 -0
  212. package/dist/esm/test/TestJournal.js.map +1 -0
  213. package/docs/README.md +166 -0
  214. package/docs/api.md +650 -0
  215. package/docs/concepts/compaction.md +157 -0
  216. package/docs/concepts/idempotency.md +127 -0
  217. package/docs/concepts/owner-fence.md +128 -0
  218. package/docs/concepts/redaction.md +222 -0
  219. package/docs/concepts/state-event-authority.md +159 -0
  220. package/docs/concepts/two-channels.md +167 -0
  221. package/docs/guides/commit-state-and-entry.md +114 -0
  222. package/docs/guides/compact-a-run.md +134 -0
  223. package/docs/guides/fold-a-projection.md +106 -0
  224. package/docs/guides/read-a-run.md +139 -0
  225. package/docs/guides/redact-log-output.md +94 -0
  226. package/docs/guides/testing.md +124 -0
  227. package/docs/guides/write-lifecycle-events.md +110 -0
  228. package/docs/installation.md +137 -0
  229. package/docs/quickstart.md +146 -0
  230. package/docs/troubleshooting.md +214 -0
  231. package/package.json +263 -3
  232. package/src/CallFact.ts +117 -0
  233. package/src/Consensus.ts +800 -0
  234. package/src/EngineEvent.ts +823 -0
  235. package/src/ExecutionFact.ts +433 -0
  236. package/src/Journal.ts +688 -0
  237. package/src/JournalEvent.ts +654 -0
  238. package/src/JournalGeneration.ts +83 -0
  239. package/src/JournalMetrics.ts +89 -0
  240. package/src/Migrations.ts +62 -0
  241. package/src/OwnerId.ts +42 -0
  242. package/src/Projection.ts +31 -0
  243. package/src/RedactedLogger.ts +483 -0
  244. package/src/Redaction.ts +1820 -0
  245. package/src/SqlConsensus.ts +384 -0
  246. package/src/SqlJournal.ts +2732 -0
  247. package/src/StepFact.ts +69 -0
  248. package/src/index.ts +109 -0
  249. package/src/internal/JournalInternalFault.ts +40 -0
  250. package/src/migrations/0001_initial.ts +41 -0
  251. package/src/migrations/0002_checkpoints.ts +46 -0
  252. package/src/migrations/0003_startup_index.ts +19 -0
  253. package/src/migrations/0004_dedup.ts +43 -0
  254. package/src/migrations/0005_run_event_type.ts +19 -0
  255. package/src/migrations/0006_consensus.ts +83 -0
  256. package/src/test/Notifying.ts +101 -0
  257. package/src/test/TestJournal.ts +52 -0
@@ -0,0 +1,800 @@
1
+ /**
2
+ * The injectable consensus strategy arbitrating the journal's ownership rules.
3
+ *
4
+ * The journal owns the consensus rules — single writer per run, fenced and
5
+ * unfenced appends, commit-time admission, the generation fence, and steal
6
+ * only on staleness plus liveness evidence, or on a same-host probe that
7
+ * proves the owner's process gone — and this service is how a deployment chooses *how* those rules are
8
+ * arbitrated: where the lease lives, how liveness is probed, and how the
9
+ * fence is checked at commit time. `Consensus` lives here beside `OwnerId`
10
+ * for the same reason `OwnerId` does: the journal is what it fences.
11
+ * `@smthrs/run-store`'s `Ownership` keeps its public API and rules but
12
+ * delegates arbitration to this strategy.
13
+ *
14
+ * Every operation that reasons about staleness takes the caller's clock
15
+ * reading (`nowMs`) rather than reading a clock itself: staleness (R5) and
16
+ * the monotonic lease stamp are defined against the arbitrating caller's
17
+ * reading, exactly as `RunStore`'s compare-and-swap operations always were,
18
+ * so the recorded lease never differs from the outcome the caller observed.
19
+ *
20
+ * Governing design: `packages/smithers/flows/journal/docs/concepts/owner-fence.md`.
21
+ * Rule constants and their provenance:
22
+ * `packages/smithers/flows/run-store/docs/concepts/leases.md`.
23
+ *
24
+ * Prior art: Effect `EventJournal` (`reference/effect` `unstable/eventlog`)
25
+ * resolves multi-writer by merge with conflict surfacing; driving a run is not
26
+ * mergeable, so this surface deviates to exclusive-writer admission. The
27
+ * fencing and generation semantics follow Temporal's shard `rangeID`
28
+ * (`reference/temporal/service/history/shard/context_impl.go`).
29
+ *
30
+ * @since 1.0.0
31
+ */
32
+
33
+ import * as Clock from "effect/Clock"
34
+ import * as Context from "effect/Context"
35
+ import * as Duration from "effect/Duration"
36
+ import * as Effect from "effect/Effect"
37
+ import * as Layer from "effect/Layer"
38
+ import * as Schema from "effect/Schema"
39
+ import { OwnerId } from "./OwnerId.ts"
40
+
41
+ /**
42
+ * How often the supervision loop pulses to renew the owner's lease.
43
+ *
44
+ * @since 1.0.0
45
+ * @category constants
46
+ */
47
+ export const heartbeatInterval: Duration.Duration = Duration.seconds(1)
48
+
49
+ /**
50
+ * How old a persisted heartbeat must be before a peer may steal the run.
51
+ * Every strategy judges R5 staleness against this one definition.
52
+ *
53
+ * @since 1.0.0
54
+ * @category constants
55
+ */
56
+ export const heartbeatStaleAfter: Duration.Duration = Duration.seconds(30)
57
+
58
+ /**
59
+ * How far the owner's wall clock may run behind a peer's before the lease
60
+ * reasoning stops holding.
61
+ *
62
+ * The owner stamps its heartbeat from *its* clock and a would-be stealer
63
+ * compares that stamp against *its own*, so the two hosts' clock offset is
64
+ * subtracted directly from the owner's real safety margin. This constant names
65
+ * that allowance instead of leaving it implicit in a "two ticks" arithmetic
66
+ * accident, and it is a budgeted allowance, not a guarantee: see
67
+ * {@link heartbeatWriteTolerance} for what happens once it is exceeded.
68
+ *
69
+ * @since 1.0.0
70
+ * @category constants
71
+ */
72
+ export const heartbeatSkewAllowance: Duration.Duration = Duration.seconds(10)
73
+
74
+ /**
75
+ * How long heartbeat writes may go unconfirmed before ownership must be reconfirmed.
76
+ *
77
+ * A peer judges staleness by the persisted heartbeat and may steal the run the
78
+ * instant it is {@link heartbeatStaleAfter} old, so an owner that tolerated
79
+ * write failures for exactly that long would still be executing side effects
80
+ * when the steal is admitted. The budget is therefore
81
+ * {@link heartbeatStaleAfter} minus {@link heartbeatSkewAllowance} (the peer's
82
+ * clock may already read that much later than the owner's) minus one
83
+ * {@link heartbeatInterval} (reserved for one bounded compare-and-swap
84
+ * reconfirmation before the owner interrupts).
85
+ *
86
+ * This bounds, but does not eliminate, overlap. Beyond
87
+ * {@link heartbeatSkewAllowance} of clock offset a peer can be admitted while
88
+ * the old owner is still running. *Durable* writes stay safe regardless — they
89
+ * are fenced by the strategy's commit-time admission, so the displaced owner's
90
+ * writes fail rather than corrupt. Non-durable external side effects (an HTTP
91
+ * call, a spawned process) can genuinely overlap. That is inherent to any
92
+ * wall-clock lease and is stated here rather than asserted away; a caller that
93
+ * cannot tolerate any overlap needs an external fencing token at the side
94
+ * effect itself, not a larger timeout.
95
+ *
96
+ * @since 1.0.0
97
+ * @category constants
98
+ */
99
+ export const heartbeatWriteTolerance: Duration.Duration = Duration.millis(
100
+ Duration.toMillis(heartbeatStaleAfter) -
101
+ Duration.toMillis(heartbeatSkewAllowance) -
102
+ Duration.toMillis(heartbeatInterval)
103
+ )
104
+
105
+ const staleAfterMs = Duration.toMillis(heartbeatStaleAfter)
106
+
107
+ /**
108
+ * Evidence that the owner in an exact run snapshot is no longer live.
109
+ *
110
+ * Defined here because R5 — steal requires staleness plus liveness evidence —
111
+ * is a consensus rule every strategy validates. `@smthrs/run-store`'s
112
+ * `Ownership` re-exports it alongside the probes that mint it.
113
+ *
114
+ * Two of the three kinds are collected outside the strategy:
115
+ * `same-host-pid-dead` is a local process probe, and
116
+ * `cross-host-unreachable-stale` is a reachability judgement the deployment
117
+ * makes. `lease-expired` is different — it asserts only that the persisted
118
+ * heartbeat is older than the staleness cutoff, which is the one claim a
119
+ * strategy can check for itself, and `steal` checks it: the takeover refuses
120
+ * any lease whose heartbeat is still inside the window. It is therefore
121
+ * accepted from a claimant on any host, while the other two stay bound to the
122
+ * host relation that makes them meaningful. `same-host-pid-dead` alone also
123
+ * admits a steal inside the window; see {@link provesDeath}. The observation must carry the
124
+ * exact instant supplied to the consuming operation: `checkedAtMs` must equal
125
+ * that operation's `nowMs`. A caller that probes at T and calls at T+1 is
126
+ * refused and must build fresh evidence.
127
+ *
128
+ * @since 1.0.0
129
+ * @category models
130
+ */
131
+ export const LivenessEvidence = Schema.Struct({
132
+ expectedOwner: OwnerId,
133
+ checkedAtMs: Schema.Number,
134
+ kind: Schema.Literals(["same-host-pid-dead", "cross-host-unreachable-stale", "lease-expired"])
135
+ })
136
+
137
+ /**
138
+ * Evidence that the owner in an exact run snapshot is no longer live.
139
+ *
140
+ * @since 1.0.0
141
+ * @category models
142
+ */
143
+ export type LivenessEvidence = typeof LivenessEvidence.Type
144
+
145
+ /**
146
+ * Structural equality on the process identity tuple.
147
+ *
148
+ * @since 1.0.0
149
+ * @category predicates
150
+ */
151
+ export const sameOwner = (left: OwnerId, right: OwnerId): boolean =>
152
+ left.hostId === right.hostId && left.pid === right.pid && left.nonce === right.nonce
153
+
154
+ /**
155
+ * Validates liveness evidence against the owner it claims to disprove.
156
+ *
157
+ * The evidence must name the expected owner, carry the observer's current
158
+ * clock reading, and respect the host rule: a `same-host-pid-dead` probe is
159
+ * only meaningful from the same host, a `cross-host-unreachable-stale`
160
+ * observation only from a different one, and `lease-expired` is host-neutral
161
+ * because the strategy verifies the cutoff it names for itself.
162
+ *
163
+ * @since 1.0.0
164
+ * @category predicates
165
+ */
166
+ export const matchesEvidence = (
167
+ expectedOwner: OwnerId,
168
+ observer: OwnerId,
169
+ nowMs: number,
170
+ evidence: LivenessEvidence
171
+ ): boolean => {
172
+ if (!sameOwner(expectedOwner, evidence.expectedOwner) || evidence.checkedAtMs !== nowMs) return false
173
+ switch (evidence.kind) {
174
+ // A pid means nothing outside the host that owns the process namespace.
175
+ case "same-host-pid-dead":
176
+ return expectedOwner.hostId === observer.hostId
177
+ // Unreachability is what a peer host observes; on the owner's own host it
178
+ // would be an unprobed guess dressed as evidence.
179
+ case "cross-host-unreachable-stale":
180
+ return expectedOwner.hostId !== observer.hostId
181
+ // The lease is host-neutral, and the strategy verifies the same
182
+ // caller-clock cutoff named by this evidence.
183
+ case "lease-expired":
184
+ return true
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Whether evidence proves the owner gone, so a steal need not wait for its
190
+ * lease to go stale.
191
+ *
192
+ * The lease stands in for a question a peer cannot ask directly: is the owner
193
+ * still running? A `same-host-pid-dead` probe asks it. The claimant read its
194
+ * own host's process table and found no process behind the owner's pid, and a
195
+ * process that does not exist renews no lease and writes nothing, so waiting
196
+ * out `heartbeatStaleAfter` adds no safety. A run whose owner was killed with
197
+ * `SIGKILL` is therefore reclaimed by the next process on the same host at
198
+ * once.
199
+ *
200
+ * The evidence must still pass {@link matchesEvidence}, which binds the kind
201
+ * to the same host. One more case is excluded here: an owner recorded with the
202
+ * claimant's own pid names the claimant's process, which is running, so a
203
+ * probe of that pid cannot report it gone. Such evidence keeps the staleness
204
+ * cutoff.
205
+ *
206
+ * The other kinds never waive the cutoff. `cross-host-unreachable-stale` is a
207
+ * judgement about a host this process cannot inspect, and `lease-expired` is
208
+ * the cutoff itself.
209
+ *
210
+ * @since 1.0.0
211
+ * @category predicates
212
+ */
213
+ export const provesDeath = (evidence: LivenessEvidence, claimant: OwnerId): boolean =>
214
+ evidence.kind === "same-host-pid-dead" && evidence.expectedOwner.pid !== claimant.pid
215
+
216
+ /**
217
+ * Why a strategy refused a claim, steal, or recovery.
218
+ *
219
+ * @since 1.0.0
220
+ * @category models
221
+ */
222
+ export const RejectionReason = Schema.Literals([
223
+ "already_claimed",
224
+ "owner_held",
225
+ "owner_live",
226
+ "evidence_invalid",
227
+ "claim_fresh",
228
+ "claim_changed",
229
+ "unavailable"
230
+ ])
231
+
232
+ /**
233
+ * Why a strategy refused a claim, steal, or recovery.
234
+ *
235
+ * @since 1.0.0
236
+ * @category models
237
+ */
238
+ export type RejectionReason = typeof RejectionReason.Type
239
+
240
+ /**
241
+ * A granted claim, carrying the grant timestamp the later activation must
242
+ * present (R4 — the generation fence).
243
+ *
244
+ * @since 1.0.0
245
+ * @category models
246
+ */
247
+ export const Claimed = Schema.TaggedStruct("Claimed", {
248
+ grantedAtMs: Schema.Number
249
+ })
250
+
251
+ /**
252
+ * A granted claim.
253
+ *
254
+ * @since 1.0.0
255
+ * @category models
256
+ */
257
+ export type Claimed = typeof Claimed.Type
258
+
259
+ /**
260
+ * A refused claim, steal, or recovery, with the strategy's typed reason.
261
+ *
262
+ * @since 1.0.0
263
+ * @category models
264
+ */
265
+ export const Rejected = Schema.TaggedStruct("Rejected", {
266
+ reason: RejectionReason
267
+ })
268
+
269
+ /**
270
+ * A refused claim, steal, or recovery.
271
+ *
272
+ * @since 1.0.0
273
+ * @category models
274
+ */
275
+ export type Rejected = typeof Rejected.Type
276
+
277
+ /**
278
+ * Outcome of `claim` and `steal`.
279
+ *
280
+ * @since 1.0.0
281
+ * @category models
282
+ */
283
+ export const ClaimOutcome = Schema.Union([Claimed, Rejected])
284
+
285
+ /**
286
+ * Outcome of `claim` and `steal`.
287
+ *
288
+ * @since 1.0.0
289
+ * @category models
290
+ */
291
+ export type ClaimOutcome = typeof ClaimOutcome.Type
292
+
293
+ /**
294
+ * A claim promoted to ownership.
295
+ *
296
+ * @since 1.0.0
297
+ * @category models
298
+ */
299
+ export const Activated = Schema.TaggedStruct("Activated", {})
300
+
301
+ /**
302
+ * A claim promoted to ownership.
303
+ *
304
+ * @since 1.0.0
305
+ * @category models
306
+ */
307
+ export type Activated = typeof Activated.Type
308
+
309
+ /**
310
+ * The claim or lease the caller presented no longer exists.
311
+ *
312
+ * @since 1.0.0
313
+ * @category models
314
+ */
315
+ export const Lost = Schema.TaggedStruct("Lost", {})
316
+
317
+ /**
318
+ * The claim or lease the caller presented no longer exists.
319
+ *
320
+ * @since 1.0.0
321
+ * @category models
322
+ */
323
+ export type Lost = typeof Lost.Type
324
+
325
+ /**
326
+ * Outcome of `activate`.
327
+ *
328
+ * @since 1.0.0
329
+ * @category models
330
+ */
331
+ export const ActivateOutcome = Schema.Union([Activated, Lost])
332
+
333
+ /**
334
+ * Outcome of `activate`.
335
+ *
336
+ * @since 1.0.0
337
+ * @category models
338
+ */
339
+ export type ActivateOutcome = typeof ActivateOutcome.Type
340
+
341
+ /**
342
+ * A renewed lease, carrying the monotonic heartbeat stamp the strategy
343
+ * recorded — the maximum of the stored stamp and the caller's reading, so a
344
+ * late pulse never moves the lease backwards.
345
+ *
346
+ * @since 1.0.0
347
+ * @category models
348
+ */
349
+ export const Renewed = Schema.TaggedStruct("Renewed", {
350
+ heartbeatAtMs: Schema.Number
351
+ })
352
+
353
+ /**
354
+ * A renewed lease.
355
+ *
356
+ * @since 1.0.0
357
+ * @category models
358
+ */
359
+ export type Renewed = typeof Renewed.Type
360
+
361
+ /**
362
+ * Outcome of `heartbeat` and `reconfirm`.
363
+ *
364
+ * @since 1.0.0
365
+ * @category models
366
+ */
367
+ export const HeartbeatOutcome = Schema.Union([Renewed, Lost])
368
+
369
+ /**
370
+ * Outcome of `heartbeat` and `reconfirm`.
371
+ *
372
+ * @since 1.0.0
373
+ * @category models
374
+ */
375
+ export type HeartbeatOutcome = typeof HeartbeatOutcome.Type
376
+
377
+ /**
378
+ * A stale claim cleared after its claimant was proven dead.
379
+ *
380
+ * @since 1.0.0
381
+ * @category models
382
+ */
383
+ export const Recovered = Schema.TaggedStruct("Recovered", {})
384
+
385
+ /**
386
+ * A stale claim cleared after its claimant was proven dead.
387
+ *
388
+ * @since 1.0.0
389
+ * @category models
390
+ */
391
+ export type Recovered = typeof Recovered.Type
392
+
393
+ /**
394
+ * Outcome of `recover`.
395
+ *
396
+ * @since 1.0.0
397
+ * @category models
398
+ */
399
+ export const RecoverOutcome = Schema.Union([Recovered, Rejected])
400
+
401
+ /**
402
+ * Outcome of `recover`.
403
+ *
404
+ * @since 1.0.0
405
+ * @category models
406
+ */
407
+ export type RecoverOutcome = typeof RecoverOutcome.Type
408
+
409
+ /**
410
+ * Failure raised by a consensus strategy.
411
+ *
412
+ * `fence_lost` is `guard`'s refusal: the supplied owner no longer holds the
413
+ * run, so the fenced write it joins must not commit. `persistence_failed`
414
+ * wraps a strategy's storage failure; the original cause is preserved so the
415
+ * durable writer's retry classification still sees a transient conflict
416
+ * through the wrapper.
417
+ *
418
+ * @since 1.0.0
419
+ * @category errors
420
+ */
421
+ export class ConsensusError extends Schema.TaggedError<ConsensusError>()("@smthrs/journal/ConsensusError", {
422
+ code: Schema.Literals(["fence_lost", "persistence_failed"]),
423
+ message: Schema.String,
424
+ cause: Schema.optional(Schema.Unknown)
425
+ }) {}
426
+
427
+ /**
428
+ * Consensus operations.
429
+ *
430
+ * The rules being arbitrated are strategy-independent; a strategy
431
+ * chooses where the lease lives and how the fence is checked at commit time.
432
+ * The claim lifecycle is two-phase, exactly as `RunStore`'s always was:
433
+ * `claim` (or `steal`, its evidence-gated form) reserves the run and returns
434
+ * the grant timestamp, `activate` presents that grant to take ownership, and
435
+ * `release` clears whichever of the caller's claim or ownership still stands.
436
+ * `recover` clears a *third party's* stale claim after its claimant was proven
437
+ * dead — the relocated `recoverClaim` mechanic. `guard` is the commit-time
438
+ * admission check (R3) `Journal.emitDurable`, `checkpoint`, and `compact`
439
+ * join: it succeeds while the owner holds the run and fails with `fence_lost`
440
+ * otherwise.
441
+ *
442
+ * Heartbeats and lease state are the strategy's private evidence and never
443
+ * enter the journal.
444
+ *
445
+ * @since 1.0.0
446
+ * @category models
447
+ */
448
+ export interface Service {
449
+ /** Holds a named durable resource lease through work, with heartbeat supervision. */
450
+ readonly withPermit: <A, E, R>(
451
+ key: string,
452
+ owner: OwnerId,
453
+ isAlive: (
454
+ owner: OwnerId,
455
+ context: { readonly claimant: OwnerId; readonly heartbeatAtMs: number | null; readonly nowMs: number }
456
+ ) => Effect.Effect<boolean>,
457
+ effect: Effect.Effect<A, E, R>
458
+ ) => Effect.Effect<A, E | ConsensusError, R>
459
+
460
+ readonly claim: (
461
+ runId: string,
462
+ claimant: OwnerId,
463
+ nowMs: number
464
+ ) => Effect.Effect<ClaimOutcome, ConsensusError>
465
+ readonly activate: (
466
+ runId: string,
467
+ owner: OwnerId,
468
+ grantedAtMs: number,
469
+ nowMs: number
470
+ ) => Effect.Effect<ActivateOutcome, ConsensusError>
471
+ readonly heartbeat: (
472
+ runId: string,
473
+ owner: OwnerId,
474
+ nowMs: number
475
+ ) => Effect.Effect<HeartbeatOutcome, ConsensusError>
476
+ /** Renews only while this owner holds the lease and no takeover claim is pending. */
477
+ readonly reconfirm: (
478
+ runId: string,
479
+ owner: OwnerId,
480
+ nowMs: number
481
+ ) => Effect.Effect<HeartbeatOutcome, ConsensusError>
482
+ readonly release: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>
483
+ readonly steal: (
484
+ runId: string,
485
+ claimant: OwnerId,
486
+ nowMs: number,
487
+ evidence: LivenessEvidence
488
+ ) => Effect.Effect<ClaimOutcome, ConsensusError>
489
+ readonly recover: (
490
+ runId: string,
491
+ staleClaimant: OwnerId,
492
+ grantedAtMs: number,
493
+ observer: OwnerId,
494
+ nowMs: number,
495
+ evidence: LivenessEvidence
496
+ ) => Effect.Effect<RecoverOutcome, ConsensusError>
497
+ readonly guard: (runId: string, owner: OwnerId) => Effect.Effect<void, ConsensusError>
498
+ }
499
+
500
+ /**
501
+ * Context service for the injected consensus strategy.
502
+ *
503
+ * @since 1.0.0
504
+ * @category services
505
+ */
506
+ export class Consensus extends Context.Service<Consensus, Service>()("@smthrs/journal/Consensus") {}
507
+
508
+ /**
509
+ * Constructs a consensus service from an implementation.
510
+ *
511
+ * @since 1.0.0
512
+ * @category constructors
513
+ */
514
+ export const make = (implementation: Service): Service => Consensus.of(implementation)
515
+
516
+ const rejected = (reason: RejectionReason): Rejected => ({ _tag: "Rejected", reason })
517
+ const claimed = (grantedAtMs: number): Claimed => ({ _tag: "Claimed", grantedAtMs })
518
+ const lost: Lost = { _tag: "Lost" }
519
+ const activated: Activated = { _tag: "Activated" }
520
+ const recovered: Recovered = { _tag: "Recovered" }
521
+
522
+ /**
523
+ * The refusal `guard` raises for an owner that no longer holds the run.
524
+ *
525
+ * @since 1.0.0
526
+ * @category errors
527
+ */
528
+ export const fenceLost = (runId: string, owner: OwnerId): ConsensusError =>
529
+ new ConsensusError({
530
+ code: "fence_lost",
531
+ message: `run ${runId} is no longer owned by ${owner.hostId}:${owner.pid}:${owner.nonce}`
532
+ })
533
+
534
+ /**
535
+ * Constructs a strategy that arbitrates nothing: claims are refused, leases
536
+ * are never held, and every fenced write is rejected.
537
+ *
538
+ * @since 1.0.0
539
+ * @category constructors
540
+ */
541
+ export const makeNoop = (overrides: Partial<Service> = {}): Service =>
542
+ Consensus.of({
543
+ claim: Effect.fn("Consensus.claim")(() => Effect.succeed(rejected("unavailable"))),
544
+ activate: Effect.fn("Consensus.activate")(() => Effect.succeed(lost)),
545
+ heartbeat: Effect.fn("Consensus.heartbeat")(() => Effect.succeed(lost)),
546
+ reconfirm: Effect.fn("Consensus.reconfirm")(() => Effect.succeed(lost)),
547
+ release: Effect.fn("Consensus.release")(() => Effect.void),
548
+ steal: Effect.fn("Consensus.steal")(() => Effect.succeed(rejected("unavailable"))),
549
+ recover: Effect.fn("Consensus.recover")(() => Effect.succeed(rejected("unavailable"))),
550
+ guard: Effect.fn("Consensus.guard")((runId: string, owner: OwnerId) => Effect.fail(fenceLost(runId, owner))),
551
+ withPermit: () =>
552
+ Effect.fail(new ConsensusError({ code: "persistence_failed", message: "resource leases unavailable" })),
553
+ ...overrides
554
+ })
555
+
556
+ /**
557
+ * Provides the refusing strategy stub.
558
+ *
559
+ * @since 1.0.0
560
+ * @category layers
561
+ */
562
+ export const layerNoop = (overrides: Partial<Service> = {}): Layer.Layer<Consensus> =>
563
+ Layer.succeed(Consensus)(makeNoop(overrides))
564
+
565
+ interface LocalLease {
566
+ owner: { readonly id: OwnerId; readonly grantedAtMs: number; heartbeatAtMs: number } | undefined
567
+ claim: { readonly id: OwnerId; readonly claimedAtMs: number } | undefined
568
+ }
569
+
570
+ /**
571
+ * Constructs the in-memory single-process strategy.
572
+ *
573
+ * @since 1.0.0
574
+ * @category constructors
575
+ */
576
+ export const makeLocal: Effect.Effect<Service> = Effect.sync(() => {
577
+ const leases = new Map<string, LocalLease>()
578
+
579
+ const leaseOf = (runId: string): LocalLease => {
580
+ const existing = leases.get(runId)
581
+ if (existing !== undefined) return existing
582
+ const fresh: LocalLease = { owner: undefined, claim: undefined }
583
+ leases.set(runId, fresh)
584
+ return fresh
585
+ }
586
+
587
+ const prune = (runId: string, lease: LocalLease): void => {
588
+ if (lease.owner === undefined && lease.claim === undefined) {
589
+ leases.delete(runId)
590
+ }
591
+ }
592
+
593
+ const service: Service = Consensus.of({
594
+ withPermit: (key, owner, isAlive, effect) =>
595
+ resourcePermit(service, () => Effect.sync(() => leases.get(key)), key, owner, isAlive, effect),
596
+ claim: Effect.fn("Consensus.claim")((runId: string, claimant: OwnerId, nowMs: number) =>
597
+ Effect.sync(() => {
598
+ const lease = leaseOf(runId)
599
+ if (lease.claim !== undefined) return rejected("already_claimed")
600
+ if (lease.owner !== undefined) return rejected("owner_held")
601
+ lease.claim = { id: claimant, claimedAtMs: nowMs }
602
+ return claimed(nowMs)
603
+ })
604
+ ),
605
+ activate: Effect.fn("Consensus.activate")((
606
+ runId: string,
607
+ owner: OwnerId,
608
+ grantedAtMs: number,
609
+ nowMs: number
610
+ ) =>
611
+ Effect.sync(() => {
612
+ const lease = leaseOf(runId)
613
+ if (
614
+ lease.claim === undefined ||
615
+ !sameOwner(lease.claim.id, owner) ||
616
+ lease.claim.claimedAtMs !== grantedAtMs
617
+ ) {
618
+ prune(runId, lease)
619
+ return lost
620
+ }
621
+ lease.claim = undefined
622
+ lease.owner = { id: owner, grantedAtMs, heartbeatAtMs: nowMs }
623
+ return activated
624
+ })
625
+ ),
626
+ heartbeat: Effect.fn("Consensus.heartbeat")((runId: string, owner: OwnerId, nowMs: number) =>
627
+ Effect.sync(() => {
628
+ const lease = leases.get(runId)
629
+ if (lease?.owner === undefined || !sameOwner(lease.owner.id, owner)) return lost
630
+ lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)
631
+ return ({ _tag: "Renewed", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)
632
+ })
633
+ ),
634
+ reconfirm: Effect.fn("Consensus.reconfirm")((runId: string, owner: OwnerId, nowMs: number) =>
635
+ Effect.sync(() => {
636
+ const lease = leases.get(runId)
637
+ if (lease?.owner === undefined || lease.claim !== undefined || !sameOwner(lease.owner.id, owner)) return lost
638
+ lease.owner.heartbeatAtMs = Math.max(lease.owner.heartbeatAtMs, nowMs)
639
+ return ({ _tag: "Renewed", heartbeatAtMs: lease.owner.heartbeatAtMs } satisfies Renewed)
640
+ })
641
+ ),
642
+ release: Effect.fn("Consensus.release")((runId: string, owner: OwnerId) =>
643
+ Effect.sync(() => {
644
+ const lease = leases.get(runId)
645
+ if (lease === undefined) return
646
+ if (lease.claim !== undefined && sameOwner(lease.claim.id, owner)) {
647
+ lease.claim = undefined
648
+ }
649
+ if (lease.owner !== undefined && sameOwner(lease.owner.id, owner)) {
650
+ lease.owner = undefined
651
+ }
652
+ prune(runId, lease)
653
+ })
654
+ ),
655
+ steal: Effect.fn("Consensus.steal")((
656
+ runId: string,
657
+ claimant: OwnerId,
658
+ nowMs: number,
659
+ evidence: LivenessEvidence
660
+ ) =>
661
+ Effect.sync(() => {
662
+ if (!matchesEvidence(evidence.expectedOwner, claimant, nowMs, evidence)) {
663
+ return rejected("evidence_invalid")
664
+ }
665
+ const lease = leases.get(runId)
666
+ if (lease?.claim !== undefined) return rejected("already_claimed")
667
+ if (lease?.owner === undefined || !sameOwner(lease.owner.id, evidence.expectedOwner)) {
668
+ return rejected("evidence_invalid")
669
+ }
670
+ if (!provesDeath(evidence, claimant) && lease.owner.heartbeatAtMs >= nowMs - staleAfterMs) {
671
+ return rejected("owner_live")
672
+ }
673
+ lease.claim = { id: claimant, claimedAtMs: nowMs }
674
+ return claimed(nowMs)
675
+ })
676
+ ),
677
+ recover: Effect.fn("Consensus.recover")((
678
+ runId: string,
679
+ staleClaimant: OwnerId,
680
+ grantedAtMs: number,
681
+ observer: OwnerId,
682
+ nowMs: number,
683
+ evidence: LivenessEvidence
684
+ ) =>
685
+ Effect.sync(() => {
686
+ if (!matchesEvidence(staleClaimant, observer, nowMs, evidence)) return rejected("evidence_invalid")
687
+ const lease = leases.get(runId)
688
+ if (
689
+ lease?.claim === undefined ||
690
+ !sameOwner(lease.claim.id, staleClaimant) ||
691
+ lease.claim.claimedAtMs !== grantedAtMs
692
+ ) {
693
+ return rejected("claim_changed")
694
+ }
695
+ if (lease.claim.claimedAtMs >= nowMs - staleAfterMs) return rejected("claim_fresh")
696
+ lease.claim = undefined
697
+ prune(runId, lease)
698
+ return recovered
699
+ })
700
+ ),
701
+ guard: Effect.fn("Consensus.guard")((runId: string, owner: OwnerId) =>
702
+ Effect.suspend(() => {
703
+ const lease = leases.get(runId)
704
+ return lease?.owner !== undefined && sameOwner(lease.owner.id, owner)
705
+ ? Effect.void
706
+ : Effect.fail(fenceLost(runId, owner))
707
+ })
708
+ )
709
+ })
710
+ return service
711
+ })
712
+
713
+ /**
714
+ * Provides the in-memory single-process strategy.
715
+ *
716
+ * The lease lives in process memory, so R3 is exact within the process — the
717
+ * strategy's transitions and the serialized append transactions interleave
718
+ * atomically on one event loop — and browser support needs nothing beyond
719
+ * this layer plus the browser-safe journal. State is per layer build: provide
720
+ * one instance to every service that must agree on it, which is what
721
+ * `SqlJournal.layerWith` and `RunStore.layerWith` exist for.
722
+ *
723
+ * The lease is not part of any database transaction: a transition made inside
724
+ * a `Journal.transact` that later rolls back stays applied in memory, so the
725
+ * lease and a rolled-back run row can disagree until the next transition.
726
+ * `SqlConsensus` keeps the two in one transaction; prefer it wherever a
727
+ * database is present.
728
+ *
729
+ * @since 1.0.0
730
+ * @category layers
731
+ */
732
+ export const layerLocal: Layer.Layer<Consensus> = Layer.effect(Consensus, makeLocal)
733
+
734
+ /**
735
+ * Shares the existing consensus lease lifecycle with named engine resources.
736
+ * The reader is private to the strategy; resource leases never create runs.
737
+ * @since 1.0.0
738
+ * @category constructors
739
+ */
740
+ export const resourcePermit = <A, E, R>(
741
+ strategy: Omit<Service, "withPermit">,
742
+ read: () => Effect.Effect<LocalLease | undefined, ConsensusError>,
743
+ key: string,
744
+ owner: OwnerId,
745
+ isAlive: Parameters<Service["withPermit"]>[2],
746
+ effect: Effect.Effect<A, E, R>
747
+ ): Effect.Effect<A, E | ConsensusError, R> =>
748
+ Effect.uninterruptibleMask((restore) => {
749
+ const acquire = Effect.gen(function*() {
750
+ while (true) {
751
+ const admitted = yield* Effect.uninterruptible(Effect.gen(function*() {
752
+ const nowMs = yield* Clock.currentTimeMillis
753
+ let grant = yield* strategy.claim(key, owner, nowMs)
754
+ if (grant._tag === "Rejected") {
755
+ const lease = yield* read()
756
+ const held = lease?.claim === undefined
757
+ ? lease?.owner
758
+ : { id: lease.claim.id, heartbeatAtMs: lease.claim.claimedAtMs }
759
+ if (
760
+ held !== undefined && held.heartbeatAtMs < nowMs - staleAfterMs &&
761
+ !(yield* isAlive(held.id, { claimant: owner, heartbeatAtMs: held.heartbeatAtMs, nowMs }))
762
+ ) {
763
+ const evidence = { expectedOwner: held.id, checkedAtMs: nowMs, kind: "lease-expired" as const }
764
+ if (lease?.claim !== undefined) {
765
+ yield* strategy.recover(key, held.id, lease.claim.claimedAtMs, owner, nowMs, evidence)
766
+ } else {
767
+ grant = yield* strategy.steal(key, owner, nowMs, evidence)
768
+ }
769
+ }
770
+ }
771
+ if (grant._tag !== "Claimed") return false
772
+ const activated = yield* strategy.activate(key, owner, grant.grantedAtMs, nowMs).pipe(
773
+ Effect.onError(() => strategy.release(key, owner).pipe(Effect.orDie))
774
+ )
775
+ if (activated._tag === "Activated") return true
776
+ yield* strategy.release(key, owner)
777
+ return false
778
+ }))
779
+ if (admitted) return
780
+ yield* restore(Effect.sleep("50 millis"))
781
+ }
782
+ })
783
+ const pulse = Effect.forever(
784
+ Effect.sleep(heartbeatInterval).pipe(
785
+ Effect.andThen(Effect.gen(function*() {
786
+ const nowMs = yield* Clock.currentTimeMillis
787
+ const renewed = yield* strategy.reconfirm(key, owner, nowMs).pipe(Effect.timeout(heartbeatInterval))
788
+ if (renewed._tag !== "Renewed") return yield* Effect.fail(fenceLost(key, owner))
789
+ })),
790
+ Effect.mapError(() => fenceLost(key, owner))
791
+ )
792
+ )
793
+ return acquire.pipe(
794
+ Effect.andThen(() =>
795
+ restore(Effect.raceFirst(effect, pulse)).pipe(
796
+ Effect.ensuring(strategy.release(key, owner).pipe(Effect.orDie))
797
+ )
798
+ )
799
+ )
800
+ })