effect 4.1.2 → 4.1.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 (465) hide show
  1. package/ai-docs/package.json +1 -1
  2. package/ai-docs/tsconfig.json +2 -1
  3. package/dist/DateTime.d.ts +33 -2
  4. package/dist/DateTime.d.ts.map +1 -1
  5. package/dist/DateTime.js +16 -0
  6. package/dist/DateTime.js.map +1 -1
  7. package/dist/Match.d.ts +6 -6
  8. package/dist/Match.d.ts.map +1 -1
  9. package/dist/Match.js.map +1 -1
  10. package/dist/Queue.d.ts +2 -1
  11. package/dist/Queue.d.ts.map +1 -1
  12. package/dist/Queue.js +16 -9
  13. package/dist/Queue.js.map +1 -1
  14. package/dist/Rational.d.ts +1214 -0
  15. package/dist/Rational.d.ts.map +1 -0
  16. package/dist/Rational.js +880 -0
  17. package/dist/Rational.js.map +1 -0
  18. package/dist/RcMap.d.ts +3 -0
  19. package/dist/RcMap.d.ts.map +1 -1
  20. package/dist/RcMap.js +13 -14
  21. package/dist/RcMap.js.map +1 -1
  22. package/dist/Runtime.d.ts +75 -3
  23. package/dist/Runtime.d.ts.map +1 -1
  24. package/dist/Runtime.js +81 -4
  25. package/dist/Runtime.js.map +1 -1
  26. package/dist/Schema.d.ts +131 -29
  27. package/dist/Schema.d.ts.map +1 -1
  28. package/dist/Schema.js +128 -22
  29. package/dist/Schema.js.map +1 -1
  30. package/dist/SchemaAST.d.ts.map +1 -1
  31. package/dist/SchemaAST.js +24 -12
  32. package/dist/SchemaAST.js.map +1 -1
  33. package/dist/SchemaParser.js +2 -2
  34. package/dist/SchemaParser.js.map +1 -1
  35. package/dist/SchemaRepresentation.d.ts +9 -0
  36. package/dist/SchemaRepresentation.d.ts.map +1 -1
  37. package/dist/SchemaRepresentation.js +9 -0
  38. package/dist/SchemaRepresentation.js.map +1 -1
  39. package/dist/ScopedCache.d.ts +7 -0
  40. package/dist/ScopedCache.d.ts.map +1 -1
  41. package/dist/ScopedCache.js +18 -1
  42. package/dist/ScopedCache.js.map +1 -1
  43. package/dist/ai/AgUi.d.ts +109 -0
  44. package/dist/ai/AgUi.d.ts.map +1 -0
  45. package/dist/ai/AgUi.js +543 -0
  46. package/dist/ai/AgUi.js.map +1 -0
  47. package/dist/ai/AgUiSchema.d.ts +6965 -0
  48. package/dist/ai/AgUiSchema.d.ts.map +1 -0
  49. package/dist/ai/AgUiSchema.js +974 -0
  50. package/dist/ai/AgUiSchema.js.map +1 -0
  51. package/dist/ai/AgUiServer.d.ts +6400 -0
  52. package/dist/ai/AgUiServer.d.ts.map +1 -0
  53. package/dist/ai/AgUiServer.js +309 -0
  54. package/dist/ai/AgUiServer.js.map +1 -0
  55. package/dist/ai/Chat.d.ts +30 -4
  56. package/dist/ai/Chat.d.ts.map +1 -1
  57. package/dist/ai/Chat.js +34 -4
  58. package/dist/ai/Chat.js.map +1 -1
  59. package/dist/ai/LanguageModel.d.ts +1 -1
  60. package/dist/ai/LanguageModel.d.ts.map +1 -1
  61. package/dist/ai/LanguageModel.js +18 -8
  62. package/dist/ai/LanguageModel.js.map +1 -1
  63. package/dist/ai/McpClient.d.ts +5 -0
  64. package/dist/ai/McpClient.d.ts.map +1 -1
  65. package/dist/ai/McpClient.js +11 -1
  66. package/dist/ai/McpClient.js.map +1 -1
  67. package/dist/ai/McpServer.d.ts +18 -1
  68. package/dist/ai/McpServer.d.ts.map +1 -1
  69. package/dist/ai/McpServer.js +214 -34
  70. package/dist/ai/McpServer.js.map +1 -1
  71. package/dist/ai/Prompt.d.ts +6 -2
  72. package/dist/ai/Prompt.d.ts.map +1 -1
  73. package/dist/ai/Prompt.js.map +1 -1
  74. package/dist/ai/Response.d.ts +5 -2
  75. package/dist/ai/Response.d.ts.map +1 -1
  76. package/dist/ai/Response.js +5 -1
  77. package/dist/ai/Response.js.map +1 -1
  78. package/dist/ai/Tool.d.ts +265 -69
  79. package/dist/ai/Tool.d.ts.map +1 -1
  80. package/dist/ai/Tool.js +19 -2
  81. package/dist/ai/Tool.js.map +1 -1
  82. package/dist/ai/Toolkit.d.ts +32 -2
  83. package/dist/ai/Toolkit.d.ts.map +1 -1
  84. package/dist/ai/Toolkit.js +61 -8
  85. package/dist/ai/Toolkit.js.map +1 -1
  86. package/dist/ai/index.d.ts +15 -0
  87. package/dist/ai/index.d.ts.map +1 -1
  88. package/dist/ai/index.js +15 -0
  89. package/dist/ai/index.js.map +1 -1
  90. package/dist/ai/internal/mcpCore.d.ts +0 -2
  91. package/dist/ai/internal/mcpCore.d.ts.map +1 -1
  92. package/dist/ai/internal/mcpCore.js +2 -8
  93. package/dist/ai/internal/mcpCore.js.map +1 -1
  94. package/dist/ai/internal/mcpProtocol/v2024_11_05.js +6 -11
  95. package/dist/ai/internal/mcpProtocol/v2024_11_05.js.map +1 -1
  96. package/dist/ai/internal/mcpProtocol/v2025_03_26.js +6 -11
  97. package/dist/ai/internal/mcpProtocol/v2025_03_26.js.map +1 -1
  98. package/dist/ai/internal/mcpProtocol/v2025_06_18.js +6 -8
  99. package/dist/ai/internal/mcpProtocol/v2025_06_18.js.map +1 -1
  100. package/dist/ai/internal/mcpProtocol/v2025_11_25.js +6 -8
  101. package/dist/ai/internal/mcpProtocol/v2025_11_25.js.map +1 -1
  102. package/dist/ai/internal/mcpProtocol/v2026_07_28.js +60 -51
  103. package/dist/ai/internal/mcpProtocol/v2026_07_28.js.map +1 -1
  104. package/dist/ai/internal/mcpProtocol.js +11 -1
  105. package/dist/ai/internal/mcpProtocol.js.map +1 -1
  106. package/dist/ai/internal/mcpProtocolRegistry.js +4 -0
  107. package/dist/ai/internal/mcpProtocolRegistry.js.map +1 -1
  108. package/dist/ai/internal/mcpRuntime.js +6 -2
  109. package/dist/ai/internal/mcpRuntime.js.map +1 -1
  110. package/dist/ai/internal/mcpSchema/v2024_11_05.js +0 -2
  111. package/dist/ai/internal/mcpSchema/v2024_11_05.js.map +1 -1
  112. package/dist/ai/internal/mcpSchema/v2025_03_26.d.ts.map +1 -1
  113. package/dist/ai/internal/mcpSchema/v2025_03_26.js +0 -2
  114. package/dist/ai/internal/mcpSchema/v2025_03_26.js.map +1 -1
  115. package/dist/ai/internal/mcpSchema/v2025_06_18.d.ts.map +1 -1
  116. package/dist/ai/internal/mcpSchema/v2025_06_18.js +0 -2
  117. package/dist/ai/internal/mcpSchema/v2025_06_18.js.map +1 -1
  118. package/dist/ai/internal/mcpSchema/v2025_11_25.d.ts.map +1 -1
  119. package/dist/ai/internal/mcpSchema/v2025_11_25.js +0 -2
  120. package/dist/ai/internal/mcpSchema/v2025_11_25.js.map +1 -1
  121. package/dist/ai/internal/mcpSchema/v2026_07_28.d.ts.map +1 -1
  122. package/dist/ai/internal/mcpSchema/v2026_07_28.js +0 -2
  123. package/dist/ai/internal/mcpSchema/v2026_07_28.js.map +1 -1
  124. package/dist/ai/internal/mcpSkills.js +3 -93
  125. package/dist/ai/internal/mcpSkills.js.map +1 -1
  126. package/dist/ai/internal/mcpStatefulRuntime.js +0 -2
  127. package/dist/ai/internal/mcpStatefulRuntime.js.map +1 -1
  128. package/dist/ai/internal/structured-output.js +1 -1
  129. package/dist/ai/internal/structured-output.js.map +1 -1
  130. package/dist/cli/Argument.d.ts +81 -0
  131. package/dist/cli/Argument.d.ts.map +1 -1
  132. package/dist/cli/Argument.js +26 -0
  133. package/dist/cli/Argument.js.map +1 -1
  134. package/dist/cli/CliError.d.ts +7 -4
  135. package/dist/cli/CliError.d.ts.map +1 -1
  136. package/dist/cli/CliError.js +7 -4
  137. package/dist/cli/CliError.js.map +1 -1
  138. package/dist/cli/Command.d.ts +241 -22
  139. package/dist/cli/Command.d.ts.map +1 -1
  140. package/dist/cli/Command.js +85 -9
  141. package/dist/cli/Command.js.map +1 -1
  142. package/dist/cli/CommandSpec.d.ts +287 -0
  143. package/dist/cli/CommandSpec.d.ts.map +1 -0
  144. package/dist/cli/CommandSpec.js +277 -0
  145. package/dist/cli/CommandSpec.js.map +1 -0
  146. package/dist/cli/Completions.d.ts +5 -0
  147. package/dist/cli/Completions.d.ts.map +1 -1
  148. package/dist/cli/Completions.js.map +1 -1
  149. package/dist/cli/Flag.d.ts +102 -0
  150. package/dist/cli/Flag.d.ts.map +1 -1
  151. package/dist/cli/Flag.js +47 -0
  152. package/dist/cli/Flag.js.map +1 -1
  153. package/dist/cli/Param.d.ts +154 -1
  154. package/dist/cli/Param.d.ts.map +1 -1
  155. package/dist/cli/Param.js +87 -29
  156. package/dist/cli/Param.js.map +1 -1
  157. package/dist/cli/index.d.ts +5 -0
  158. package/dist/cli/index.d.ts.map +1 -1
  159. package/dist/cli/index.js +5 -0
  160. package/dist/cli/index.js.map +1 -1
  161. package/dist/cli/internal/command.d.ts +2 -2
  162. package/dist/cli/internal/command.d.ts.map +1 -1
  163. package/dist/cli/internal/command.js +1 -1
  164. package/dist/cli/internal/command.js.map +1 -1
  165. package/dist/cli/internal/completions/bash.js +6 -7
  166. package/dist/cli/internal/completions/bash.js.map +1 -1
  167. package/dist/cli/internal/completions/descriptor.js +21 -7
  168. package/dist/cli/internal/completions/descriptor.js.map +1 -1
  169. package/dist/cli/internal/completions/fish.js +3 -3
  170. package/dist/cli/internal/completions/fish.js.map +1 -1
  171. package/dist/cli/internal/completions/powershell.js +2 -2
  172. package/dist/cli/internal/completions/powershell.js.map +1 -1
  173. package/dist/cli/internal/completions/zsh.js +2 -2
  174. package/dist/cli/internal/completions/zsh.js.map +1 -1
  175. package/dist/cluster/ClusterWorkflowEngine.d.ts.map +1 -1
  176. package/dist/cluster/ClusterWorkflowEngine.js +15 -13
  177. package/dist/cluster/ClusterWorkflowEngine.js.map +1 -1
  178. package/dist/cluster/Entity.d.ts +17 -0
  179. package/dist/cluster/Entity.d.ts.map +1 -1
  180. package/dist/cluster/Entity.js +20 -0
  181. package/dist/cluster/Entity.js.map +1 -1
  182. package/dist/cluster/MessageRetention.d.ts +71 -0
  183. package/dist/cluster/MessageRetention.d.ts.map +1 -0
  184. package/dist/cluster/MessageRetention.js +100 -0
  185. package/dist/cluster/MessageRetention.js.map +1 -0
  186. package/dist/cluster/MessageStorage.d.ts +81 -0
  187. package/dist/cluster/MessageStorage.d.ts.map +1 -1
  188. package/dist/cluster/MessageStorage.js +34 -2
  189. package/dist/cluster/MessageStorage.js.map +1 -1
  190. package/dist/cluster/ShardingConfig.d.ts +24 -2
  191. package/dist/cluster/ShardingConfig.d.ts.map +1 -1
  192. package/dist/cluster/ShardingConfig.js.map +1 -1
  193. package/dist/cluster/SqlMessageStorage.d.ts.map +1 -1
  194. package/dist/cluster/SqlMessageStorage.js +187 -29
  195. package/dist/cluster/SqlMessageStorage.js.map +1 -1
  196. package/dist/cluster/index.d.ts +5 -0
  197. package/dist/cluster/index.d.ts.map +1 -1
  198. package/dist/cluster/index.js +5 -0
  199. package/dist/cluster/index.js.map +1 -1
  200. package/dist/encoding/Base64.d.ts +0 -6
  201. package/dist/encoding/Base64.d.ts.map +1 -1
  202. package/dist/encoding/Base64.js +25 -5
  203. package/dist/encoding/Base64.js.map +1 -1
  204. package/dist/encoding/Base64Url.d.ts +0 -6
  205. package/dist/encoding/Base64Url.d.ts.map +1 -1
  206. package/dist/encoding/Base64Url.js +91 -8
  207. package/dist/encoding/Base64Url.js.map +1 -1
  208. package/dist/encoding/Csv.d.ts.map +1 -1
  209. package/dist/encoding/Csv.js +11 -5
  210. package/dist/encoding/Csv.js.map +1 -1
  211. package/dist/encoding/Hex.d.ts.map +1 -1
  212. package/dist/encoding/Hex.js +51 -34
  213. package/dist/encoding/Hex.js.map +1 -1
  214. package/dist/encoding/SchemaBinary.d.ts +14 -2
  215. package/dist/encoding/SchemaBinary.d.ts.map +1 -1
  216. package/dist/encoding/SchemaBinary.js +78 -5
  217. package/dist/encoding/SchemaBinary.js.map +1 -1
  218. package/dist/encoding/Xml.d.ts +25 -0
  219. package/dist/encoding/Xml.d.ts.map +1 -1
  220. package/dist/encoding/Xml.js +44 -19
  221. package/dist/encoding/Xml.js.map +1 -1
  222. package/dist/graphql/GraphQL.d.ts.map +1 -1
  223. package/dist/graphql/GraphQL.js +4 -1
  224. package/dist/graphql/GraphQL.js.map +1 -1
  225. package/dist/http/Headers.d.ts +5 -1
  226. package/dist/http/Headers.d.ts.map +1 -1
  227. package/dist/http/Headers.js +7 -2
  228. package/dist/http/Headers.js.map +1 -1
  229. package/dist/http/HttpClient.d.ts +57 -12
  230. package/dist/http/HttpClient.d.ts.map +1 -1
  231. package/dist/http/HttpClient.js +92 -54
  232. package/dist/http/HttpClient.js.map +1 -1
  233. package/dist/http/HttpClientError.d.ts +22 -8
  234. package/dist/http/HttpClientError.d.ts.map +1 -1
  235. package/dist/http/HttpClientError.js +68 -14
  236. package/dist/http/HttpClientError.js.map +1 -1
  237. package/dist/http/HttpEffect.d.ts +63 -4
  238. package/dist/http/HttpEffect.d.ts.map +1 -1
  239. package/dist/http/HttpEffect.js +89 -9
  240. package/dist/http/HttpEffect.js.map +1 -1
  241. package/dist/http/HttpMiddleware.js +1 -1
  242. package/dist/http/HttpMiddleware.js.map +1 -1
  243. package/dist/http/HttpServer.d.ts +80 -0
  244. package/dist/http/HttpServer.d.ts.map +1 -1
  245. package/dist/http/HttpServer.js +16 -0
  246. package/dist/http/HttpServer.js.map +1 -1
  247. package/dist/http/HttpServerRequest.d.ts.map +1 -1
  248. package/dist/http/HttpServerRequest.js +1 -14
  249. package/dist/http/HttpServerRequest.js.map +1 -1
  250. package/dist/http/HttpStaticServer.js +10 -16
  251. package/dist/http/HttpStaticServer.js.map +1 -1
  252. package/dist/http-api/HttpApiBuilder.js +9 -1
  253. package/dist/http-api/HttpApiBuilder.js.map +1 -1
  254. package/dist/http-api/HttpApiSchema.d.ts +19 -0
  255. package/dist/http-api/HttpApiSchema.d.ts.map +1 -1
  256. package/dist/http-api/HttpApiSchema.js +8 -1
  257. package/dist/http-api/HttpApiSchema.js.map +1 -1
  258. package/dist/index.d.ts +5 -0
  259. package/dist/index.d.ts.map +1 -1
  260. package/dist/index.js +5 -0
  261. package/dist/index.js.map +1 -1
  262. package/dist/internal/base64.d.ts +2 -0
  263. package/dist/internal/base64.d.ts.map +1 -0
  264. package/dist/internal/base64.js +30 -0
  265. package/dist/internal/base64.js.map +1 -0
  266. package/dist/internal/core.js +3 -4
  267. package/dist/internal/core.js.map +1 -1
  268. package/dist/internal/dateTime.js +18 -10
  269. package/dist/internal/dateTime.js.map +1 -1
  270. package/dist/internal/effect.js +41 -17
  271. package/dist/internal/effect.js.map +1 -1
  272. package/dist/internal/equal.js +7 -0
  273. package/dist/internal/equal.js.map +1 -1
  274. package/dist/internal/matcher.js +1 -1
  275. package/dist/internal/matcher.js.map +1 -1
  276. package/dist/internal/schema/codegen.js +7 -7
  277. package/dist/internal/schema/codegen.js.map +1 -1
  278. package/dist/internal/schema/fromJsonSchemaDocument.js +20 -1
  279. package/dist/internal/schema/fromJsonSchemaDocument.js.map +1 -1
  280. package/dist/internal/schema/interpreter.js +10 -10
  281. package/dist/internal/schema/interpreter.js.map +1 -1
  282. package/dist/internal/schema/parser.js +9 -4
  283. package/dist/internal/schema/parser.js.map +1 -1
  284. package/dist/internal/schema/toEquivalence.js +6 -5
  285. package/dist/internal/schema/toEquivalence.js.map +1 -1
  286. package/dist/internal/schema/toFormatter.js +3 -2
  287. package/dist/internal/schema/toFormatter.js.map +1 -1
  288. package/dist/internal/version.js +1 -1
  289. package/dist/observability/OtlpMetrics.js +1 -1
  290. package/dist/observability/OtlpMetrics.js.map +1 -1
  291. package/dist/observability/OtlpTracer.js +2 -2
  292. package/dist/observability/OtlpTracer.js.map +1 -1
  293. package/dist/persistence/PersistedQueue.d.ts +72 -3
  294. package/dist/persistence/PersistedQueue.d.ts.map +1 -1
  295. package/dist/persistence/PersistedQueue.js +142 -29
  296. package/dist/persistence/PersistedQueue.js.map +1 -1
  297. package/dist/persistence/RateLimiter.d.ts +12 -2
  298. package/dist/persistence/RateLimiter.d.ts.map +1 -1
  299. package/dist/persistence/RateLimiter.js +11 -4
  300. package/dist/persistence/RateLimiter.js.map +1 -1
  301. package/dist/process/CommandLine.d.ts +9 -9
  302. package/dist/process/CommandLine.js +6 -6
  303. package/dist/process/index.d.ts +1 -1
  304. package/dist/process/index.js +1 -1
  305. package/dist/reactivity/Atom.d.ts.map +1 -1
  306. package/dist/reactivity/Atom.js +24 -3
  307. package/dist/reactivity/Atom.js.map +1 -1
  308. package/dist/reactivity/AtomRpc.d.ts +24 -6
  309. package/dist/reactivity/AtomRpc.d.ts.map +1 -1
  310. package/dist/reactivity/AtomRpc.js.map +1 -1
  311. package/dist/rpc/OpenRpc.d.ts +384 -0
  312. package/dist/rpc/OpenRpc.d.ts.map +1 -0
  313. package/dist/rpc/OpenRpc.js +490 -0
  314. package/dist/rpc/OpenRpc.js.map +1 -0
  315. package/dist/rpc/Rpc.d.ts +22 -3
  316. package/dist/rpc/Rpc.d.ts.map +1 -1
  317. package/dist/rpc/Rpc.js.map +1 -1
  318. package/dist/rpc/RpcClient.d.ts +20 -21
  319. package/dist/rpc/RpcClient.d.ts.map +1 -1
  320. package/dist/rpc/RpcClient.js.map +1 -1
  321. package/dist/rpc/RpcServer.d.ts +23 -2
  322. package/dist/rpc/RpcServer.d.ts.map +1 -1
  323. package/dist/rpc/RpcServer.js +67 -25
  324. package/dist/rpc/RpcServer.js.map +1 -1
  325. package/dist/rpc/index.d.ts +5 -0
  326. package/dist/rpc/index.d.ts.map +1 -1
  327. package/dist/rpc/index.js +5 -0
  328. package/dist/rpc/index.js.map +1 -1
  329. package/dist/schema/SchemaCompiler/runtime.js +3 -2
  330. package/dist/schema/SchemaCompiler/runtime.js.map +1 -1
  331. package/dist/sql/SqlClient.d.ts +59 -6
  332. package/dist/sql/SqlClient.d.ts.map +1 -1
  333. package/dist/sql/SqlClient.js +64 -17
  334. package/dist/sql/SqlClient.js.map +1 -1
  335. package/dist/sql/Statement.d.ts +1 -1
  336. package/dist/sql/Statement.d.ts.map +1 -1
  337. package/dist/sql/Statement.js +9 -16
  338. package/dist/sql/Statement.js.map +1 -1
  339. package/dist/testing/TestClock.d.ts +2 -12
  340. package/dist/testing/TestClock.d.ts.map +1 -1
  341. package/dist/testing/TestClock.js +177 -169
  342. package/dist/testing/TestClock.js.map +1 -1
  343. package/dist/workflow/DurableClock.d.ts +27 -0
  344. package/dist/workflow/DurableClock.d.ts.map +1 -1
  345. package/dist/workflow/DurableClock.js +18 -2
  346. package/dist/workflow/DurableClock.js.map +1 -1
  347. package/dist/workflow/Workflow.d.ts.map +1 -1
  348. package/dist/workflow/Workflow.js +5 -4
  349. package/dist/workflow/Workflow.js.map +1 -1
  350. package/dist/workflow/WorkflowEngine.d.ts.map +1 -1
  351. package/dist/workflow/WorkflowEngine.js +14 -3
  352. package/dist/workflow/WorkflowEngine.js.map +1 -1
  353. package/package.json +3 -3
  354. package/src/DateTime.ts +35 -2
  355. package/src/Match.ts +10 -8
  356. package/src/Queue.ts +16 -11
  357. package/src/Rational.ts +1549 -0
  358. package/src/RcMap.ts +16 -14
  359. package/src/Runtime.ts +84 -4
  360. package/src/Schema.ts +188 -29
  361. package/src/SchemaAST.ts +29 -13
  362. package/src/SchemaParser.ts +2 -2
  363. package/src/SchemaRepresentation.ts +13 -0
  364. package/src/ScopedCache.ts +18 -1
  365. package/src/ai/AgUi.ts +485 -0
  366. package/src/ai/AgUiSchema.ts +1666 -0
  367. package/src/ai/AgUiServer.ts +451 -0
  368. package/src/ai/Chat.ts +78 -16
  369. package/src/ai/LanguageModel.ts +27 -9
  370. package/src/ai/McpClient.ts +11 -1
  371. package/src/ai/McpServer.ts +247 -50
  372. package/src/ai/Prompt.ts +6 -2
  373. package/src/ai/Response.ts +19 -3
  374. package/src/ai/Tool.ts +426 -110
  375. package/src/ai/Toolkit.ts +71 -10
  376. package/src/ai/index.ts +18 -0
  377. package/src/ai/internal/mcpCore.ts +11 -15
  378. package/src/ai/internal/mcpProtocol/v2024_11_05.ts +9 -14
  379. package/src/ai/internal/mcpProtocol/v2025_03_26.ts +9 -14
  380. package/src/ai/internal/mcpProtocol/v2025_06_18.ts +9 -11
  381. package/src/ai/internal/mcpProtocol/v2025_11_25.ts +9 -11
  382. package/src/ai/internal/mcpProtocol/v2026_07_28.ts +76 -55
  383. package/src/ai/internal/mcpProtocol.ts +22 -3
  384. package/src/ai/internal/mcpProtocolRegistry.ts +5 -0
  385. package/src/ai/internal/mcpRuntime.ts +10 -4
  386. package/src/ai/internal/mcpSchema/v2024_11_05.ts +0 -2
  387. package/src/ai/internal/mcpSchema/v2025_03_26.ts +0 -2
  388. package/src/ai/internal/mcpSchema/v2025_06_18.ts +0 -2
  389. package/src/ai/internal/mcpSchema/v2025_11_25.ts +0 -2
  390. package/src/ai/internal/mcpSchema/v2026_07_28.ts +0 -2
  391. package/src/ai/internal/mcpSkills.ts +3 -86
  392. package/src/ai/internal/mcpStatefulRuntime.ts +0 -2
  393. package/src/ai/internal/structured-output.ts +1 -1
  394. package/src/cli/Argument.ts +86 -0
  395. package/src/cli/CliError.ts +7 -4
  396. package/src/cli/Command.ts +261 -35
  397. package/src/cli/CommandSpec.ts +508 -0
  398. package/src/cli/Completions.ts +5 -0
  399. package/src/cli/Flag.ts +106 -0
  400. package/src/cli/Param.ts +225 -23
  401. package/src/cli/index.ts +6 -0
  402. package/src/cli/internal/command.ts +3 -4
  403. package/src/cli/internal/completions/bash.ts +9 -7
  404. package/src/cli/internal/completions/descriptor.ts +37 -5
  405. package/src/cli/internal/completions/fish.ts +9 -3
  406. package/src/cli/internal/completions/powershell.ts +2 -1
  407. package/src/cli/internal/completions/zsh.ts +2 -2
  408. package/src/cluster/ClusterWorkflowEngine.ts +14 -15
  409. package/src/cluster/Entity.ts +24 -0
  410. package/src/cluster/MessageRetention.ts +111 -0
  411. package/src/cluster/MessageStorage.ts +73 -2
  412. package/src/cluster/ShardingConfig.ts +12 -1
  413. package/src/cluster/SqlMessageStorage.ts +271 -41
  414. package/src/cluster/index.ts +6 -0
  415. package/src/encoding/Base64.ts +26 -5
  416. package/src/encoding/Base64Url.ts +93 -10
  417. package/src/encoding/Csv.ts +11 -5
  418. package/src/encoding/Hex.ts +56 -42
  419. package/src/encoding/SchemaBinary.ts +76 -5
  420. package/src/encoding/Xml.ts +65 -16
  421. package/src/graphql/GraphQL.ts +7 -4
  422. package/src/http/Headers.ts +7 -2
  423. package/src/http/HttpClient.ts +118 -68
  424. package/src/http/HttpClientError.ts +82 -15
  425. package/src/http/HttpEffect.ts +101 -10
  426. package/src/http/HttpMiddleware.ts +2 -2
  427. package/src/http/HttpServer.ts +80 -0
  428. package/src/http/HttpServerRequest.ts +1 -19
  429. package/src/http/HttpStaticServer.ts +10 -16
  430. package/src/http-api/HttpApiBuilder.ts +11 -1
  431. package/src/http-api/HttpApiSchema.ts +22 -1
  432. package/src/index.ts +6 -0
  433. package/src/internal/base64.ts +42 -0
  434. package/src/internal/core.ts +3 -4
  435. package/src/internal/dateTime.ts +27 -13
  436. package/src/internal/effect.ts +45 -18
  437. package/src/internal/equal.ts +8 -0
  438. package/src/internal/matcher.ts +7 -3
  439. package/src/internal/schema/codegen.ts +8 -7
  440. package/src/internal/schema/fromJsonSchemaDocument.ts +21 -1
  441. package/src/internal/schema/interpreter.ts +10 -10
  442. package/src/internal/schema/parser.ts +8 -4
  443. package/src/internal/schema/toEquivalence.ts +7 -5
  444. package/src/internal/schema/toFormatter.ts +3 -2
  445. package/src/internal/version.ts +1 -1
  446. package/src/observability/OtlpMetrics.ts +1 -1
  447. package/src/observability/OtlpTracer.ts +2 -2
  448. package/src/persistence/PersistedQueue.ts +199 -41
  449. package/src/persistence/RateLimiter.ts +17 -5
  450. package/src/process/CommandLine.ts +10 -10
  451. package/src/process/index.ts +1 -1
  452. package/src/reactivity/Atom.ts +25 -3
  453. package/src/reactivity/AtomRpc.ts +61 -45
  454. package/src/rpc/OpenRpc.ts +747 -0
  455. package/src/rpc/Rpc.ts +38 -6
  456. package/src/rpc/RpcClient.ts +45 -82
  457. package/src/rpc/RpcServer.ts +77 -28
  458. package/src/rpc/index.ts +6 -0
  459. package/src/schema/SchemaCompiler/runtime.ts +8 -3
  460. package/src/sql/SqlClient.ts +112 -26
  461. package/src/sql/Statement.ts +19 -23
  462. package/src/testing/TestClock.ts +204 -189
  463. package/src/workflow/DurableClock.ts +20 -3
  464. package/src/workflow/Workflow.ts +5 -3
  465. package/src/workflow/WorkflowEngine.ts +20 -5
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Deletes a persisted cluster entity's completed requests from message storage
3
+ * once they are older than a retention.
4
+ *
5
+ * Persisted entities keep every request and its replies in `MessageStorage` to
6
+ * answer duplicates and resume interrupted work, so without a retention their
7
+ * storage grows without bound.
8
+ *
9
+ * @stability unstable
10
+ * @since 4.1.3
11
+ */
12
+ import * as Clock from "../Clock.ts"
13
+ import * as Duration from "../Duration.ts"
14
+ import * as Effect from "../Effect.ts"
15
+ import type * as Layer from "../Layer.ts"
16
+ import type * as Rpc from "../rpc/Rpc.ts"
17
+ import type { Entity } from "./Entity.ts"
18
+ import { MessageStorage } from "./MessageStorage.ts"
19
+ import type { Sharding } from "./Sharding.ts"
20
+ import * as Singleton from "./Singleton.ts"
21
+
22
+ const batchSize = 1000
23
+
24
+ /**
25
+ * Creates a layer that registers a singleton deleting the entity's completed
26
+ * requests once they are older than `retention`.
27
+ *
28
+ * **When to use**
29
+ *
30
+ * Use when a long-lived persisted entity would otherwise keep one stored
31
+ * request and reply for every message it has ever handled.
32
+ *
33
+ * **Details**
34
+ *
35
+ * Every `interval` (default 1 minute), the singleton deletes in batches each
36
+ * request of the entity type whose final reply is older than `retention`, with
37
+ * its acknowledgements, interrupts and replies. Running requests and requests
38
+ * reset with `MessageStorage.clearReplies` are kept. Failures are logged and
39
+ * retried on the next interval.
40
+ *
41
+ * The singleton runs in `shardGroup` (default `"default"`), not the entity's
42
+ * shard group.
43
+ *
44
+ * **Gotchas**
45
+ *
46
+ * - A request sent again with the same primary key after deletion runs the
47
+ * handler again.
48
+ * - Choose a retention longer than any client retry window or reader of the
49
+ * stored replies.
50
+ * - Do not use it for workflow or `ClusterCron` entities, which rely on stored
51
+ * replies to know what already ran.
52
+ * - Include the layer on every runner that can be assigned `shardGroup`, so it
53
+ * keeps running when shards move.
54
+ * - SQL storage on MySQL needs MySQL 8.0.1+ or MariaDB 10.6+, and
55
+ * `binlog_format` `ROW` or `MIXED`. Otherwise every cleanup fails and is
56
+ * logged.
57
+ *
58
+ * **Example** (Forgetting a week-old request)
59
+ *
60
+ * ```ts
61
+ * import { Effect, Layer, Schema } from "effect"
62
+ * import { ClusterSchema, Entity, MessageRetention } from "effect/cluster"
63
+ * import { Rpc } from "effect/rpc"
64
+ *
65
+ * const Counter = Entity.make("Counter", [
66
+ * Rpc.make("Hit", {
67
+ * payload: { id: Schema.String },
68
+ * primaryKey: ({ id }) => id
69
+ * })
70
+ * ]).annotateRpcs(ClusterSchema.Persisted, true)
71
+ *
72
+ * export const CounterLive = Layer.mergeAll(
73
+ * Counter.toLayer({ Hit: () => Effect.void }),
74
+ * MessageRetention.make({ entity: Counter, retention: "7 days" })
75
+ * )
76
+ * ```
77
+ *
78
+ * @stability unstable
79
+ * @category constructors
80
+ * @since 4.1.3
81
+ */
82
+ export const make = <Type extends string, Rpcs extends Rpc.Any>(options: {
83
+ readonly entity: Entity<Type, Rpcs>
84
+ readonly retention: Duration.Input
85
+ readonly interval?: Duration.Input | undefined
86
+ readonly shardGroup?: string | undefined
87
+ }): Layer.Layer<never, never, Sharding | MessageStorage> => {
88
+ const entityType = options.entity.type
89
+ const retention = Duration.toMillis(options.retention)
90
+ const interval = options.interval ?? Duration.minutes(1)
91
+ return Singleton.make(
92
+ `effect/cluster/MessageRetention/${entityType}`,
93
+ Effect.gen(function*() {
94
+ const storage = yield* MessageStorage
95
+ while (true) {
96
+ yield* Effect.sleep(interval)
97
+ const completedBefore = (yield* Clock.currentTimeMillis) - retention
98
+ yield* storage.deleteProcessed({ entityType, completedBefore, limit: batchSize }).pipe(
99
+ Effect.repeat({ while: (deleted) => deleted >= batchSize }),
100
+ Effect.catchCause((cause) => Effect.logWarning("Message retention failed", cause))
101
+ )
102
+ }
103
+ }).pipe(
104
+ Effect.annotateLogs({
105
+ module: "effect/cluster/MessageRetention",
106
+ entityType
107
+ })
108
+ ),
109
+ { shardGroup: options.shardGroup }
110
+ )
111
+ }
@@ -221,6 +221,29 @@ export class MessageStorage extends Context.Service<MessageStorage, {
221
221
  address: EntityAddress
222
222
  ) => Effect.Effect<void, PersistenceError>
223
223
 
224
+ /**
225
+ * Deletes up to `limit` of an entity type's completed requests with their
226
+ * messages and replies, returning the number of requests deleted.
227
+ *
228
+ * **Details**
229
+ *
230
+ * A request is eligible when its `WithExit` reply id has a timestamp before
231
+ * `completedBefore`, in Unix milliseconds. Requests without one, including
232
+ * ones reset by `clearReplies`, are kept. A request saved again with the same
233
+ * primary key after deletion is a new request.
234
+ *
235
+ * **Gotchas**
236
+ *
237
+ * Inside a caller's transaction on MySQL before 8.0.20 or MariaDB, SQL storage
238
+ * needs that transaction at READ COMMITTED, or the delete can deadlock with a
239
+ * concurrent reply.
240
+ */
241
+ readonly deleteProcessed: (options: {
242
+ readonly entityType: string
243
+ readonly completedBefore: number
244
+ readonly limit: number
245
+ }) => Effect.Effect<number, PersistenceError>
246
+
224
247
  /**
225
248
  * Wraps requests in storage transactions.
226
249
  *
@@ -489,6 +512,22 @@ export type Encoded = {
489
512
  shardIds: Arr.NonEmptyArray<string>
490
513
  ) => Effect.Effect<void, PersistenceError>
491
514
 
515
+ /**
516
+ * Deletes up to `limit` of an entity type's completed requests with every
517
+ * message and reply sharing their request id, returning the number deleted.
518
+ *
519
+ * **Details**
520
+ *
521
+ * A request is eligible when its `WithExit` reply id has a timestamp before
522
+ * `completedBefore`, in Unix milliseconds. Selecting and deleting must be
523
+ * atomic. Requests locked by another transaction may be left for a later call.
524
+ */
525
+ readonly deleteProcessed: (options: {
526
+ readonly entityType: string
527
+ readonly completedBefore: number
528
+ readonly limit: number
529
+ }) => Effect.Effect<number, PersistenceError>
530
+
492
531
  /**
493
532
  * Used to wrap requests with transactions.
494
533
  */
@@ -799,6 +838,7 @@ export const makeEncoded: (encoded: Encoded) => Effect.Effect<
799
838
  resetRequests: (requestIds) => requestIds.length === 0 ? Effect.void : encoded.resetRequests(requestIds),
800
839
  resetAddresses: (addresses) => addresses.length === 0 ? Effect.void : encoded.resetAddresses(addresses),
801
840
  clearAddress: encoded.clearAddress,
841
+ deleteProcessed: encoded.deleteProcessed,
802
842
  resetShards: (shardIds) => {
803
843
  const shards = Array.from(shardIds, (id) => id.toString())
804
844
  if (!Arr.isArrayNonEmpty(shards)) return Effect.void
@@ -931,6 +971,7 @@ export const noop: MessageStorage["Service"] = Effect.runSync(make({
931
971
  resetRequests: () => Effect.void,
932
972
  resetAddresses: () => Effect.void,
933
973
  clearAddress: () => Effect.void,
974
+ deleteProcessed: () => Effect.succeed(0),
934
975
  resetShards: () => Effect.void,
935
976
  withTransaction: identity
936
977
  }))
@@ -1083,9 +1124,11 @@ export class MemoryDriver extends Context.Service<MemoryDriver>()("effect/cluste
1083
1124
  if (primaryKey) {
1084
1125
  requestsByPrimaryKey.set(primaryKey, entry)
1085
1126
  }
1086
- } else if (envelope._tag === "AckChunk") {
1127
+ } else {
1087
1128
  const entry = requests.get(envelope.requestId)
1088
- if (entry) {
1129
+ // the request was deleted, so there is nothing left to acknowledge or interrupt
1130
+ if (!entry) return SaveResultEncoded.Success()
1131
+ if (envelope._tag === "AckChunk") {
1089
1132
  entry.lastReceivedChunk = entry.replies.find((r): r is Reply.ChunkEncoded =>
1090
1133
  r._tag === "Chunk" && r.id === envelope.replyId
1091
1134
  ) ?? entry.lastReceivedChunk
@@ -1224,6 +1267,34 @@ export class MemoryDriver extends Context.Service<MemoryDriver>()("effect/cluste
1224
1267
  journal.splice(i, 1)
1225
1268
  }
1226
1269
  }),
1270
+ deleteProcessed: ({ completedBefore, entityType, limit }) =>
1271
+ Effect.sync(() => {
1272
+ const deleted = new Set<string>()
1273
+ for (const [requestId, entry] of requests) {
1274
+ if (deleted.size >= limit) break
1275
+ const exit = entry.replies.find((reply) => reply._tag === "WithExit")
1276
+ if (
1277
+ entry.envelope.address.entityType === entityType && exit !== undefined &&
1278
+ Snowflake.timestamp(Snowflake.Snowflake(exit.id)) < completedBefore
1279
+ ) {
1280
+ deleted.add(requestId)
1281
+ for (const reply of entry.replies) replyIds.delete(reply.id)
1282
+ }
1283
+ }
1284
+ if (deleted.size === 0) return 0
1285
+ for (const requestId of deleted) requests.delete(requestId)
1286
+ for (const [primaryKey, entry] of requestsByPrimaryKey) {
1287
+ if (deleted.has(entry.envelope.requestId)) requestsByPrimaryKey.delete(primaryKey)
1288
+ }
1289
+ for (let i = journal.length - 1; i >= 0; i--) {
1290
+ const envelope = journal[i]
1291
+ if (!deleted.has(envelope.requestId)) continue
1292
+ unprocessed.delete(envelope)
1293
+ lastRead.delete(envelope)
1294
+ journal.splice(i, 1)
1295
+ }
1296
+ return deleted.size
1297
+ }),
1227
1298
  resetShards: (shardIds) =>
1228
1299
  Effect.sync(() => {
1229
1300
  const shards = new Set(shardIds)
@@ -203,7 +203,18 @@ export class ShardingConfig extends Context.Service<ShardingConfig, {
203
203
  */
204
204
  readonly sendRetryInterval: Duration.Input
205
205
  /**
206
- * The interval at which to check for unhealthy runners and report them
206
+ * The interval at which runners are health checked. Unhealthy runners are
207
+ * removed from shard assignments.
208
+ *
209
+ * The checks run on one runner, the host of the runner health singleton, so
210
+ * they cannot detect a crash of that runner. It leaves shard assignments
211
+ * only once runner storage stops listing it, which for `SqlRunnerStorage`
212
+ * is when its last heartbeat is older than `shardLockExpiration`. Lowering
213
+ * this interval detects crashes of other runners sooner, but not a crash of
214
+ * the singleton's host. For that, lower `shardLockExpiration`, at the cost
215
+ * of less tolerance for slow or unavailable lock storage.
216
+ *
217
+ * Defaults to 1 minute.
207
218
  */
208
219
  readonly runnerHealthCheckInterval: Duration.Input
209
220
  /**
@@ -18,6 +18,12 @@
18
18
  * composed keys of any length are supported; shorter keys are stored as
19
19
  * plaintext, byte-compatible with rows written by previous versions.
20
20
  *
21
+ * On MySQL, `deleteProcessed` needs MySQL 8.0.1+ or MariaDB 10.6+ for
22
+ * `SKIP LOCKED`. It runs at READ COMMITTED, which needs `binlog_format` `ROW`
23
+ * or `MIXED`. Inside a caller's transaction it keeps that transaction's
24
+ * isolation level, which must also be READ COMMITTED on MySQL before 8.0.20
25
+ * and on MariaDB, or it can deadlock with a concurrent reply.
26
+ *
21
27
  * @stability unstable
22
28
  * @since 4.0.0
23
29
  */
@@ -25,16 +31,18 @@
25
31
  import * as Arr from "../Array.ts"
26
32
  import * as Digest from "../crypto/Digest.ts"
27
33
  import * as Effect from "../Effect.ts"
34
+ import { identity } from "../Function.ts"
28
35
  import * as Layer from "../Layer.ts"
29
36
  import * as Option from "../Option.ts"
30
37
  import * as Migrator from "../sql/Migrator.ts"
31
38
  import * as SqlClient from "../sql/SqlClient.ts"
32
39
  import type { Row } from "../sql/SqlConnection.ts"
33
- import { isSqlError, type SqlError } from "../sql/SqlError.ts"
40
+ import { isSqlError, SqlError, UnknownError } from "../sql/SqlError.ts"
34
41
  import type { Fragment } from "../sql/Statement.ts"
35
42
  import { PersistenceError } from "./ClusterError.ts"
36
43
  import type * as EntityAddress from "./EntityAddress.ts"
37
44
  import type * as Envelope from "./Envelope.ts"
45
+ import * as MachineId from "./MachineId.ts"
38
46
  import * as MessageStorage from "./MessageStorage.ts"
39
47
  import { SaveResultEncoded } from "./MessageStorage.ts"
40
48
  import type * as Reply from "./Reply.ts"
@@ -121,6 +129,7 @@ export const makeEncodedStorage: (options?: {
121
129
  const prefix = options?.prefix ?? "cluster"
122
130
  const table = (name: string) => `${prefix}_${name}`
123
131
 
132
+ const messageKindRequest = sql.literal(String(messageKind.Request))
124
133
  const messageKindAckChunk = sql.literal(String(messageKind.AckChunk))
125
134
  const messageKindInterrupt = sql.literal(String(messageKind.Interrupt))
126
135
  const replyKindWithExit = sql.literal(String(replyKind.WithExit))
@@ -342,39 +351,73 @@ export const makeEncodedStorage: (options?: {
342
351
  LEFT JOIN ${repliesTableSql} r ON r.id = m.last_reply_id
343
352
  WHERE m.message_id = ${message_id}
344
353
  `
345
- // an insert that returned no rows hit an existing message_id
346
- const selectUnlessInserted = (message_id: string) => (inserted: ReadonlyArray<unknown>) =>
347
- inserted.length > 0 ? Effect.succeed([]) : selectByMessageId(message_id)
354
+ const maxInsertAttempts = 3
355
+ // Runs an insert that reports whether it stored the row, returning the
356
+ // existing row with the same message_id when it did not
357
+ const insertUnlessExists = (
358
+ insert: (row: MessageRow, message_id: string) => Effect.Effect<boolean, SqlError>
359
+ ) =>
360
+ (row: MessageRow, message_id: string): Effect.Effect<ReadonlyArray<Row>, SqlError> => {
361
+ // deleteProcessed can delete the existing row before it is read, so insert
362
+ // again rather than report a save that stored nothing
363
+ const loop = (attempt: number): Effect.Effect<ReadonlyArray<Row>, SqlError> =>
364
+ Effect.flatMap(
365
+ insert(row, message_id),
366
+ (inserted) =>
367
+ inserted ? Effect.succeed([]) : Effect.flatMap(selectByMessageId(message_id), (rows) => {
368
+ if (rows.length > 0) return Effect.succeed(rows)
369
+ if (attempt < maxInsertAttempts) return loop(attempt + 1)
370
+ return Effect.fail(
371
+ new SqlError({
372
+ reason: new UnknownError({
373
+ cause: undefined,
374
+ message: `Message ${message_id} conflicted with a row that was deleted before it could be read`,
375
+ operation: "saveEnvelope"
376
+ })
377
+ })
378
+ )
379
+ })
380
+ )
381
+ return loop(1)
382
+ }
348
383
 
349
384
  const insertEnvelope: (
350
385
  row: MessageRow,
351
386
  message_id: string
352
387
  ) => Effect.Effect<ReadonlyArray<Row>, SqlError> = sql.onDialectOrElse({
353
- pg: () => (row, message_id) =>
354
- sql`
355
- INSERT INTO ${messagesTableSql} ${sql.insert(row)}
356
- ON CONFLICT (message_id) DO NOTHING
357
- RETURNING id
358
- `.pipe(Effect.flatMap(selectUnlessInserted(message_id))),
359
- mysql: () => (row, message_id) =>
360
- Effect.flatMap(
361
- sql`INSERT IGNORE INTO ${messagesTableSql} ${sql.insert(row)}`.raw,
362
- (row: any) => {
363
- if (row.affectedRows > 0) {
364
- return Effect.succeed([])
365
- }
366
- return selectByMessageId(message_id)
367
- }
388
+ pg: () =>
389
+ insertUnlessExists((row) =>
390
+ Effect.map(
391
+ sql`
392
+ INSERT INTO ${messagesTableSql} ${sql.insert(row)}
393
+ ON CONFLICT (message_id) DO NOTHING
394
+ RETURNING id
395
+ `,
396
+ (rows) => rows.length > 0
397
+ )
368
398
  ),
369
- mssql: () => (row, message_id) =>
370
- sql`
371
- MERGE ${messagesTableSql} WITH (HOLDLOCK) AS target
372
- USING (SELECT ${message_id} as message_id) AS source
373
- ON target.message_id = source.message_id
374
- WHEN NOT MATCHED THEN
375
- INSERT ${sql.insert(row)}
376
- OUTPUT inserted.id;
377
- `.pipe(Effect.flatMap(selectUnlessInserted(message_id))),
399
+ mysql: () =>
400
+ insertUnlessExists((row) =>
401
+ Effect.map(
402
+ sql`INSERT IGNORE INTO ${messagesTableSql} ${sql.insert(row)}`.raw,
403
+ (result: any) => result.affectedRows > 0
404
+ )
405
+ ),
406
+ mssql: () =>
407
+ insertUnlessExists((row, message_id) =>
408
+ Effect.map(
409
+ sql`
410
+ MERGE ${messagesTableSql} WITH (HOLDLOCK) AS target
411
+ USING (SELECT ${message_id} as message_id) AS source
412
+ ON target.message_id = source.message_id
413
+ WHEN NOT MATCHED THEN
414
+ INSERT ${sql.insert(row)}
415
+ OUTPUT inserted.id;
416
+ `,
417
+ (rows) => rows.length > 0
418
+ )
419
+ ),
420
+ // SQLite has a single writer, so no delete can run between read and insert
378
421
  orElse: () => (row, message_id) =>
379
422
  selectByMessageId(message_id).pipe(
380
423
  Effect.tap(sql`INSERT OR IGNORE INTO ${messagesTableSql} ${sql.insert(row)}`),
@@ -411,6 +454,107 @@ export const makeEncodedStorage: (options?: {
411
454
  mssql: () => sql.literal("WITH (UPDLOCK)"),
412
455
  orElse: () => sql.literal("")
413
456
  })
457
+ // Like updateLock and forUpdate, but skips locked rows. REPEATABLEREAD keeps
458
+ // mssql's READPAST valid at any session isolation level.
459
+ const skipLockedHint = sql.onDialectOrElse({
460
+ mssql: () => sql.literal("WITH (UPDLOCK, READPAST, REPEATABLEREAD)"),
461
+ orElse: () => sql.literal("")
462
+ })
463
+ const forUpdateSkipLocked = sql.onDialectOrElse({
464
+ mssql: () => sql.literal(""),
465
+ sqlite: () => sql.literal(""),
466
+ orElse: () => sql.literal("FOR UPDATE SKIP LOCKED")
467
+ })
468
+ // Writes to a request's replies lock its row first, in deleteProcessed's
469
+ // order, so they cannot deadlock. An empty result means it was deleted.
470
+ const lockRequest = (requestId: string) =>
471
+ sql`SELECT 1 FROM ${messagesTableSql} ${updateLock} WHERE id = ${requestId} ${forUpdate}`
472
+ // mssql can scan the clustered index on small tables and deadlock on other
473
+ // requests' rows, so these statements force the request_id indexes
474
+ const markAcksProcessed: (requestId: string) => Effect.Effect<unknown, SqlError> = sql.onDialectOrElse({
475
+ mssql: () => (requestId) =>
476
+ sql`
477
+ UPDATE m SET processed = ${sqlTrue}
478
+ FROM ${messagesTableSql} m WITH (INDEX(${sql(messagesTable + "_request_id_idx")}))
479
+ WHERE m.processed = ${sqlFalse} AND m.request_id = ${requestId} AND m.kind = ${messageKindAckChunk}
480
+ `,
481
+ orElse: () => (requestId) =>
482
+ sql`
483
+ UPDATE ${messagesTableSql} SET processed = ${sqlTrue}
484
+ WHERE processed = ${sqlFalse} AND request_id = ${requestId} AND kind = ${messageKindAckChunk}
485
+ `
486
+ })
487
+ const deleteRequests: (ids: Fragment) => Effect.Effect<unknown, SqlError> = sql.onDialectOrElse({
488
+ mssql: () => (ids) =>
489
+ Effect.andThen(
490
+ sql`
491
+ DELETE r FROM ${repliesTableSql} r WITH (INDEX(${sql(repliesTable + "_request_lookup_idx")}))
492
+ WHERE r.request_id IN (${ids})
493
+ `,
494
+ sql`
495
+ DELETE m FROM ${messagesTableSql} m WITH (INDEX(${sql(messagesTable + "_request_id_idx")}))
496
+ WHERE m.request_id IN (${ids})
497
+ `
498
+ ),
499
+ // A scanning DELETE locks every row it reads and can deadlock. MySQL
500
+ // ignores FORCE INDEX here, so an optimizer hint keeps it on the index.
501
+ // Servers without hints (before 8.0.20, MariaDB) rely on cleanupIsolation.
502
+ mysql: () => (ids) =>
503
+ Effect.andThen(
504
+ sql`
505
+ DELETE /*+ INDEX(${repliesTableSql} ${sql(repliesTable + "_request_lookup_idx")}) */
506
+ FROM ${repliesTableSql} WHERE request_id IN (${ids})
507
+ `,
508
+ sql`
509
+ DELETE /*+ INDEX(${messagesTableSql} ${sql(messagesTable + "_request_id_idx")}) */
510
+ FROM ${messagesTableSql} WHERE request_id IN (${ids})
511
+ `
512
+ ),
513
+ orElse: () => (ids) =>
514
+ Effect.andThen(
515
+ sql`DELETE FROM ${repliesTableSql} WHERE request_id IN (${ids})`,
516
+ sql`DELETE FROM ${messagesTableSql} WHERE request_id IN (${ids})`
517
+ )
518
+ })
519
+ // Gap locks at MySQL's default REPEATABLE READ let a scanning DELETE
520
+ // deadlock with saveReply. READ COMMITTED takes none, but the server rejects
521
+ // it with binlog_format STATEMENT. A caller's transaction keeps its level.
522
+ const cleanupIsolation: <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> = sql
523
+ .onDialectOrElse({
524
+ mysql: () => Effect.provideService(SqlClient.BeginTransaction, "SET TRANSACTION ISOLATION LEVEL READ COMMITTED"),
525
+ orElse: () => identity
526
+ })
527
+ // Locks up to limit eligible requests, skipping locked ones, since waiting
528
+ // can deadlock on MySQL gap locks. Ordering by last_reply_id keeps the
529
+ // query on the retention index.
530
+ const lockDeletable: (
531
+ eligible: Fragment,
532
+ limit: number
533
+ ) => Effect.Effect<ReadonlyArray<{ id: string | bigint }>, SqlError> = sql.onDialectOrElse({
534
+ // A MySQL locking scan also locks ineligible rows, in the opposite order
535
+ // to lockRequest, so find candidates unlocked, then lock them by id and
536
+ // recheck them
537
+ mysql: () => (eligible, limit) =>
538
+ Effect.flatMap(
539
+ sql<{ id: string | bigint }>`
540
+ SELECT id FROM ${messagesTableSql} WHERE ${eligible} ORDER BY last_reply_id ASC ${limitFragment(limit)}
541
+ `,
542
+ (candidates) =>
543
+ candidates.length === 0 ? Effect.succeed(candidates) : sql<{ id: string | bigint }>`
544
+ SELECT id FROM ${messagesTableSql} FORCE INDEX (id)
545
+ WHERE id IN (${sql.literal(candidates.map((row) => String(row.id)).join(","))}) AND ${eligible}
546
+ FOR UPDATE SKIP LOCKED
547
+ `
548
+ ),
549
+ orElse: () => (eligible, limit) =>
550
+ sql<{ id: string | bigint }>`
551
+ SELECT ${idColumn} FROM ${messagesTableSql} ${skipLockedHint}
552
+ WHERE ${eligible}
553
+ ORDER BY last_reply_id ASC
554
+ ${limitFragment(limit)}
555
+ ${forUpdateSkipLocked}
556
+ `
557
+ })
414
558
 
415
559
  const emptyFragment = sql.literal("")
416
560
  // mssql only limits with OFFSET/FETCH, which requires the ORDER BY that
@@ -571,16 +715,21 @@ export const makeEncodedStorage: (options?: {
571
715
  })
572
716
  } else {
573
717
  const row = envelopeToRow(envelope, null, deliverAt)
574
- insert = Effect.as(sql`INSERT INTO ${messagesTableSql} ${sql.insert(row)}`.unprepared, [])
575
- if (envelope._tag === "AckChunk") {
576
- insert = sql`UPDATE ${repliesTableSql} SET acked = ${sqlTrue} WHERE id = ${envelope.replyId}`.pipe(
577
- Effect.andThen(
578
- sql`UPDATE ${messagesTableSql} SET processed = ${sqlTrue} WHERE processed = ${sqlFalse} AND request_id = ${envelope.requestId} AND kind = ${messageKindAckChunk}`
579
- ),
580
- Effect.andThen(insert),
581
- sql.withTransaction
582
- )
583
- }
718
+ const insertRow = Effect.as(sql`INSERT INTO ${messagesTableSql} ${sql.insert(row)}`.unprepared, [])
719
+ insert = envelope._tag === "Request" ? insertRow : lockRequest(envelope.requestId).pipe(
720
+ Effect.flatMap((request) =>
721
+ // the request was deleted, so there is nothing left to acknowledge or interrupt
722
+ request.length === 0 ?
723
+ Effect.succeed([]) :
724
+ envelope._tag === "Interrupt" ?
725
+ insertRow :
726
+ sql`UPDATE ${repliesTableSql} SET acked = ${sqlTrue} WHERE id = ${envelope.replyId}`.pipe(
727
+ Effect.andThen(markAcksProcessed(envelope.requestId)),
728
+ Effect.andThen(insertRow)
729
+ )
730
+ ),
731
+ sql.withTransaction
732
+ )
584
733
  }
585
734
  return insert.pipe(
586
735
  Effect.map((rows) => {
@@ -638,6 +787,7 @@ export const makeEncodedStorage: (options?: {
638
787
  clearReplies: Effect.fnUntraced(
639
788
  function*(requestId, options) {
640
789
  const expectedReplyId = options?.expectedReplyId
790
+ yield* lockRequest(String(requestId))
641
791
  if (expectedReplyId === undefined) {
642
792
  yield* sql`DELETE FROM ${repliesTableSql} WHERE request_id = ${String(requestId)} AND kind = 0`
643
793
  yield* sql`DELETE FROM ${messagesTableSql} WHERE request_id = ${
@@ -815,6 +965,39 @@ export const makeEncodedStorage: (options?: {
815
965
  withTracerDisabled
816
966
  ),
817
967
 
968
+ deleteProcessed: Effect.fnUntraced(
969
+ function*({ completedBefore, entityType, limit }) {
970
+ // No signed snowflake id is at or before this. Also covers -Infinity and NaN.
971
+ if (!(completedBefore > Snowflake.constEpochMillis - 2 ** 41)) return 0
972
+ // Reply timestamps are whole milliseconds, so round up. Every signed
973
+ // snowflake id is below the cap, which also covers Infinity.
974
+ const cutoff = Snowflake.make({
975
+ timestamp: Math.min(Math.ceil(completedBefore), Snowflake.constEpochMillis + 2 ** 41),
976
+ machineId: MachineId.make(0),
977
+ sequence: 0
978
+ })
979
+ // Locked so a concurrent clearReplies cannot reset them first
980
+ const rows = yield* lockDeletable(
981
+ sql`
982
+ entity_type = ${entityType}
983
+ AND kind = ${messageKindRequest}
984
+ AND processed = ${sqlTrue}
985
+ AND last_reply_id < ${sql.literal(String(cutoff))}
986
+ `,
987
+ limit
988
+ )
989
+ if (rows.length === 0) return 0
990
+ const ids = sql.literal(rows.map((row) => String(row.id)).join(","))
991
+ yield* deleteRequests(ids)
992
+ return rows.length
993
+ },
994
+ sql.withTransaction,
995
+ cleanupIsolation,
996
+ Effect.provideService(SqlClient.SafeIntegers, true),
997
+ PersistenceError.refail,
998
+ withTracerDisabled
999
+ ),
1000
+
818
1001
  resetShards: (shardIds) =>
819
1002
  resetUnprocessed(sql`shard_id IN (${sql.literal(shardIds.map(wrapString).join(","))})`).pipe(
820
1003
  Effect.asVoid,
@@ -987,11 +1170,11 @@ export const migrations = (options?: {
987
1170
  yield* sql.onDialectOrElse({
988
1171
  mssql: () =>
989
1172
  sql`
990
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${shardLookupIndex})
1173
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${shardLookupIndex} AND object_id = OBJECT_ID(${messagesTable}))
991
1174
  CREATE INDEX ${sql(shardLookupIndex)}
992
1175
  ON ${messagesTableSql} (shard_id, processed, last_read, deliver_at);
993
1176
 
994
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${requestIdLookupIndex})
1177
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${requestIdLookupIndex} AND object_id = OBJECT_ID(${messagesTable}))
995
1178
  CREATE INDEX ${sql(requestIdLookupIndex)}
996
1179
  ON ${messagesTableSql} (request_id);
997
1180
  `,
@@ -1093,7 +1276,7 @@ export const migrations = (options?: {
1093
1276
  yield* sql.onDialectOrElse({
1094
1277
  mssql: () =>
1095
1278
  sql`
1096
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${replyLookupIndex})
1279
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${replyLookupIndex} AND object_id = OBJECT_ID(${repliesTable}))
1097
1280
  CREATE INDEX ${sql(replyLookupIndex)}
1098
1281
  ON ${repliesTableSql} (request_id, kind, acked);
1099
1282
  `,
@@ -1151,6 +1334,53 @@ export const migrations = (options?: {
1151
1334
  `,
1152
1335
  orElse: () => Effect.void
1153
1336
  })
1337
+ }),
1338
+
1339
+ // 0001 looked mssql indexes up by name alone, so a same-named index on
1340
+ // another table skipped them. Writes force them, so create any missing.
1341
+ "0004_mssql_lookup_indexes": Effect.gen(function*() {
1342
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms()
1343
+ const ensureIndex = (index: string, table: string, columns: string) =>
1344
+ sql`
1345
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${index} AND object_id = OBJECT_ID(${table}))
1346
+ CREATE INDEX ${sql(index)} ON ${sql(table)} (${sql.literal(columns)})
1347
+ `
1348
+ yield* sql.onDialectOrElse({
1349
+ mssql: () =>
1350
+ Effect.all([
1351
+ ensureIndex(`${messagesTable}_shard_idx`, messagesTable, "shard_id, processed, last_read, deliver_at"),
1352
+ ensureIndex(`${messagesTable}_request_id_idx`, messagesTable, "request_id"),
1353
+ ensureIndex(`${repliesTable}_request_lookup_idx`, repliesTable, "request_id, kind, acked")
1354
+ ], { discard: true }),
1355
+ orElse: () => Effect.void
1356
+ })
1357
+ }),
1358
+
1359
+ // Serves deleteProcessed's lookup by entity type and final reply id
1360
+ "0005_retention_index": Effect.gen(function*() {
1361
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms()
1362
+ const messagesTableSql = sql(messagesTable)
1363
+ const retentionIndex = `${messagesTable}_retention_idx`
1364
+ const columns = sql.literal("entity_type, processed, last_reply_id")
1365
+ yield* sql.onDialectOrElse({
1366
+ mssql: () =>
1367
+ sql`
1368
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${retentionIndex} AND object_id = OBJECT_ID(${messagesTable}))
1369
+ CREATE INDEX ${sql(retentionIndex)} ON ${messagesTableSql} (${columns})
1370
+ `,
1371
+ mysql: () =>
1372
+ sql`
1373
+ SELECT 1 FROM information_schema.statistics
1374
+ WHERE table_schema = DATABASE() AND table_name = ${messagesTable} AND index_name = ${retentionIndex}
1375
+ `.pipe(
1376
+ Effect.flatMap((rows) =>
1377
+ rows.length > 0
1378
+ ? Effect.void
1379
+ : sql`CREATE INDEX ${sql(retentionIndex)} ON ${messagesTableSql} (${columns})`.unprepared
1380
+ )
1381
+ ),
1382
+ orElse: () => sql`CREATE INDEX IF NOT EXISTS ${sql(retentionIndex)} ON ${messagesTableSql} (${columns})`
1383
+ })
1154
1384
  })
1155
1385
  })
1156
1386
  }
@@ -119,6 +119,12 @@ export * as MachineId from "./MachineId.ts"
119
119
  */
120
120
  export * as Message from "./Message.ts"
121
121
 
122
+ /**
123
+ * @stability unstable
124
+ * @since 4.1.3
125
+ */
126
+ export * as MessageRetention from "./MessageRetention.ts"
127
+
122
128
  /**
123
129
  * @stability unstable
124
130
  * @since 4.0.0