effect 4.1.5 → 4.1.6

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 (309) hide show
  1. package/ai-docs/package.json +2 -2
  2. package/dist/Channel.d.ts +104 -7
  3. package/dist/Channel.d.ts.map +1 -1
  4. package/dist/Channel.js +73 -4
  5. package/dist/Channel.js.map +1 -1
  6. package/dist/Codegen.d.ts +7 -2
  7. package/dist/Codegen.d.ts.map +1 -1
  8. package/dist/Codegen.js +7 -2
  9. package/dist/Codegen.js.map +1 -1
  10. package/dist/Effect.d.ts +139 -18
  11. package/dist/Effect.d.ts.map +1 -1
  12. package/dist/Effect.js +10 -2
  13. package/dist/Effect.js.map +1 -1
  14. package/dist/Equal.d.ts +4 -4
  15. package/dist/Equal.d.ts.map +1 -1
  16. package/dist/Equal.js +78 -65
  17. package/dist/Equal.js.map +1 -1
  18. package/dist/Hash.d.ts.map +1 -1
  19. package/dist/Hash.js +24 -17
  20. package/dist/Hash.js.map +1 -1
  21. package/dist/LayerRef.d.ts +1 -1
  22. package/dist/LayerRef.d.ts.map +1 -1
  23. package/dist/LayerRef.js +3 -3
  24. package/dist/LayerRef.js.map +1 -1
  25. package/dist/Logger.d.ts +37 -13
  26. package/dist/Logger.d.ts.map +1 -1
  27. package/dist/Logger.js +39 -10
  28. package/dist/Logger.js.map +1 -1
  29. package/dist/Match.d.ts +23 -23
  30. package/dist/Match.d.ts.map +1 -1
  31. package/dist/Match.js.map +1 -1
  32. package/dist/Order.js +1 -1
  33. package/dist/Order.js.map +1 -1
  34. package/dist/Schema.d.ts +41 -0
  35. package/dist/Schema.d.ts.map +1 -1
  36. package/dist/Schema.js +51 -390
  37. package/dist/Schema.js.map +1 -1
  38. package/dist/SchemaAST.d.ts.map +1 -1
  39. package/dist/SchemaAST.js +0 -3
  40. package/dist/SchemaAST.js.map +1 -1
  41. package/dist/ScopedCache.d.ts.map +1 -1
  42. package/dist/ScopedCache.js +6 -4
  43. package/dist/ScopedCache.js.map +1 -1
  44. package/dist/Stream.d.ts +128 -5
  45. package/dist/Stream.d.ts.map +1 -1
  46. package/dist/Stream.js +124 -29
  47. package/dist/Stream.js.map +1 -1
  48. package/dist/String.js +1 -1
  49. package/dist/String.js.map +1 -1
  50. package/dist/Tracer.d.ts +10 -0
  51. package/dist/Tracer.d.ts.map +1 -1
  52. package/dist/Tracer.js +2 -0
  53. package/dist/Tracer.js.map +1 -1
  54. package/dist/ai/McpSchema.d.ts +88 -88
  55. package/dist/ai/McpSchema.d.ts.map +1 -1
  56. package/dist/ai/McpServer.d.ts +152 -2
  57. package/dist/ai/McpServer.d.ts.map +1 -1
  58. package/dist/ai/McpServer.js +8 -2
  59. package/dist/ai/McpServer.js.map +1 -1
  60. package/dist/ai/Prompt.d.ts +3 -1
  61. package/dist/ai/Prompt.d.ts.map +1 -1
  62. package/dist/ai/Prompt.js +17 -3
  63. package/dist/ai/Prompt.js.map +1 -1
  64. package/dist/ai/Skill.d.ts +172 -0
  65. package/dist/ai/Skill.d.ts.map +1 -0
  66. package/dist/ai/Skill.js +209 -0
  67. package/dist/ai/Skill.js.map +1 -0
  68. package/dist/ai/index.d.ts +5 -0
  69. package/dist/ai/index.d.ts.map +1 -1
  70. package/dist/ai/index.js +5 -0
  71. package/dist/ai/index.js.map +1 -1
  72. package/dist/cluster/ClusterWorkflowEngine.d.ts.map +1 -1
  73. package/dist/cluster/ClusterWorkflowEngine.js +155 -83
  74. package/dist/cluster/ClusterWorkflowEngine.js.map +1 -1
  75. package/dist/cluster/MessageStorage.d.ts +56 -0
  76. package/dist/cluster/MessageStorage.d.ts.map +1 -1
  77. package/dist/cluster/MessageStorage.js +18 -2
  78. package/dist/cluster/MessageStorage.js.map +1 -1
  79. package/dist/cluster/SqlMessageStorage.d.ts.map +1 -1
  80. package/dist/cluster/SqlMessageStorage.js +45 -22
  81. package/dist/cluster/SqlMessageStorage.js.map +1 -1
  82. package/dist/cluster/internal/entityActivation.js +2 -0
  83. package/dist/cluster/internal/entityActivation.js.map +1 -1
  84. package/dist/cluster/internal/entityManager.js +8 -5
  85. package/dist/cluster/internal/entityManager.js.map +1 -1
  86. package/dist/encoding/Base64.js +5 -1
  87. package/dist/encoding/Base64.js.map +1 -1
  88. package/dist/encoding/Base64Url.d.ts.map +1 -1
  89. package/dist/encoding/Base64Url.js +6 -1
  90. package/dist/encoding/Base64Url.js.map +1 -1
  91. package/dist/encoding/Xml.d.ts +38 -9
  92. package/dist/encoding/Xml.d.ts.map +1 -1
  93. package/dist/encoding/Xml.js +63 -31
  94. package/dist/encoding/Xml.js.map +1 -1
  95. package/dist/http/FetchHttpClient.d.ts +2 -1
  96. package/dist/http/FetchHttpClient.d.ts.map +1 -1
  97. package/dist/http/FetchHttpClient.js +14 -10
  98. package/dist/http/FetchHttpClient.js.map +1 -1
  99. package/dist/http/Headers.d.ts +201 -3
  100. package/dist/http/Headers.d.ts.map +1 -1
  101. package/dist/http/Headers.js +205 -3
  102. package/dist/http/Headers.js.map +1 -1
  103. package/dist/http/HttpClient.d.ts.map +1 -1
  104. package/dist/http/HttpClient.js +11 -7
  105. package/dist/http/HttpClient.js.map +1 -1
  106. package/dist/http/HttpClientError.d.ts +1 -0
  107. package/dist/http/HttpClientError.d.ts.map +1 -1
  108. package/dist/http/HttpClientError.js +32 -9
  109. package/dist/http/HttpClientError.js.map +1 -1
  110. package/dist/http/HttpClientRequest.d.ts +46 -0
  111. package/dist/http/HttpClientRequest.d.ts.map +1 -1
  112. package/dist/http/HttpClientRequest.js +15 -0
  113. package/dist/http/HttpClientRequest.js.map +1 -1
  114. package/dist/http/HttpClientResponse.d.ts +132 -0
  115. package/dist/http/HttpClientResponse.d.ts.map +1 -1
  116. package/dist/http/HttpClientResponse.js +83 -0
  117. package/dist/http/HttpClientResponse.js.map +1 -1
  118. package/dist/http/HttpMiddleware.js +1 -1
  119. package/dist/http/HttpMiddleware.js.map +1 -1
  120. package/dist/http/HttpServerResponse.d.ts +118 -0
  121. package/dist/http/HttpServerResponse.d.ts.map +1 -1
  122. package/dist/http/HttpServerResponse.js +43 -0
  123. package/dist/http/HttpServerResponse.js.map +1 -1
  124. package/dist/http/Multipart.d.ts.map +1 -1
  125. package/dist/http/Multipart.js +0 -5
  126. package/dist/http/Multipart.js.map +1 -1
  127. package/dist/http/MultipartParser/internal/contentType.d.ts +6 -0
  128. package/dist/http/MultipartParser/internal/contentType.d.ts.map +1 -1
  129. package/dist/http/MultipartParser/internal/contentType.js +1 -1
  130. package/dist/http/MultipartParser/internal/contentType.js.map +1 -1
  131. package/dist/http/internal/clientPath.d.ts +2 -0
  132. package/dist/http/internal/clientPath.d.ts.map +1 -0
  133. package/dist/http/internal/clientPath.js +24 -0
  134. package/dist/http/internal/clientPath.js.map +1 -0
  135. package/dist/http/internal/redactedPath.js +2 -0
  136. package/dist/http/internal/redactedPath.js.map +1 -1
  137. package/dist/http/internal/tracing.js +5 -3
  138. package/dist/http/internal/tracing.js.map +1 -1
  139. package/dist/http-api/HttpApi.d.ts +2 -2
  140. package/dist/http-api/HttpApi.d.ts.map +1 -1
  141. package/dist/http-api/HttpApi.js +30 -7
  142. package/dist/http-api/HttpApi.js.map +1 -1
  143. package/dist/http-api/HttpApiBuilder.d.ts.map +1 -1
  144. package/dist/http-api/HttpApiBuilder.js +5 -2
  145. package/dist/http-api/HttpApiBuilder.js.map +1 -1
  146. package/dist/http-api/HttpApiClient.d.ts.map +1 -1
  147. package/dist/http-api/HttpApiClient.js +23 -6
  148. package/dist/http-api/HttpApiClient.js.map +1 -1
  149. package/dist/http-api/internal/redactedKeys.d.ts +2 -0
  150. package/dist/http-api/internal/redactedKeys.d.ts.map +1 -0
  151. package/dist/http-api/internal/redactedKeys.js +37 -0
  152. package/dist/http-api/internal/redactedKeys.js.map +1 -0
  153. package/dist/internal/base64.js +34 -2
  154. package/dist/internal/base64.js.map +1 -1
  155. package/dist/internal/dateTime.js +35 -17
  156. package/dist/internal/dateTime.js.map +1 -1
  157. package/dist/internal/effect.js +9 -1
  158. package/dist/internal/effect.js.map +1 -1
  159. package/dist/internal/equal.js +14 -13
  160. package/dist/internal/equal.js.map +1 -1
  161. package/dist/internal/hash.js +4 -1
  162. package/dist/internal/hash.js.map +1 -1
  163. package/dist/internal/matcher.js +17 -17
  164. package/dist/internal/matcher.js.map +1 -1
  165. package/dist/internal/schema/schemaCodegen.js +3 -2
  166. package/dist/internal/schema/schemaCodegen.js.map +1 -1
  167. package/dist/internal/schema/schemaCodegenBuiltIns.d.ts +2 -0
  168. package/dist/internal/schema/schemaCodegenBuiltIns.d.ts.map +1 -0
  169. package/dist/internal/schema/schemaCodegenBuiltIns.js +425 -0
  170. package/dist/internal/schema/schemaCodegenBuiltIns.js.map +1 -0
  171. package/dist/internal/schema/toEquivalence.js +3 -4
  172. package/dist/internal/schema/toEquivalence.js.map +1 -1
  173. package/dist/internal/version.js +1 -1
  174. package/dist/jose/JoseError.d.ts +51 -1
  175. package/dist/jose/JoseError.d.ts.map +1 -1
  176. package/dist/jose/JoseError.js +25 -18
  177. package/dist/jose/JoseError.js.map +1 -1
  178. package/dist/jose/internal/compact.js +10 -5
  179. package/dist/jose/internal/compact.js.map +1 -1
  180. package/dist/observability/Otlp.d.ts +19 -0
  181. package/dist/observability/Otlp.d.ts.map +1 -1
  182. package/dist/observability/Otlp.js +10 -0
  183. package/dist/observability/Otlp.js.map +1 -1
  184. package/dist/observability/OtlpExporter.d.ts +49 -13
  185. package/dist/observability/OtlpExporter.d.ts.map +1 -1
  186. package/dist/observability/OtlpExporter.js +135 -54
  187. package/dist/observability/OtlpExporter.js.map +1 -1
  188. package/dist/observability/OtlpLogger.d.ts +14 -0
  189. package/dist/observability/OtlpLogger.d.ts.map +1 -1
  190. package/dist/observability/OtlpLogger.js +10 -2
  191. package/dist/observability/OtlpLogger.js.map +1 -1
  192. package/dist/observability/OtlpMetrics.d.ts.map +1 -1
  193. package/dist/observability/OtlpMetrics.js +2 -0
  194. package/dist/observability/OtlpMetrics.js.map +1 -1
  195. package/dist/observability/OtlpTracer.d.ts +14 -0
  196. package/dist/observability/OtlpTracer.d.ts.map +1 -1
  197. package/dist/observability/OtlpTracer.js +10 -2
  198. package/dist/observability/OtlpTracer.js.map +1 -1
  199. package/dist/persistence/KeyValueStore.d.ts.map +1 -1
  200. package/dist/persistence/KeyValueStore.js +6 -4
  201. package/dist/persistence/KeyValueStore.js.map +1 -1
  202. package/dist/reactivity/Atom.d.ts.map +1 -1
  203. package/dist/reactivity/Atom.js +10 -9
  204. package/dist/reactivity/Atom.js.map +1 -1
  205. package/dist/rpc/RpcClient.d.ts.map +1 -1
  206. package/dist/rpc/RpcClient.js +32 -1
  207. package/dist/rpc/RpcClient.js.map +1 -1
  208. package/dist/rpc/RpcGroup.d.ts +1 -1
  209. package/dist/rpc/RpcGroup.d.ts.map +1 -1
  210. package/dist/rpc/RpcGroup.js +4 -0
  211. package/dist/rpc/RpcGroup.js.map +1 -1
  212. package/dist/sql/Migrator.d.ts.map +1 -1
  213. package/dist/sql/Migrator.js +2 -5
  214. package/dist/sql/Migrator.js.map +1 -1
  215. package/dist/sql/SqlClient.d.ts.map +1 -1
  216. package/dist/sql/SqlClient.js +5 -1
  217. package/dist/sql/SqlClient.js.map +1 -1
  218. package/dist/workflow/Activity.d.ts +18 -0
  219. package/dist/workflow/Activity.d.ts.map +1 -1
  220. package/dist/workflow/Activity.js +13 -4
  221. package/dist/workflow/Activity.js.map +1 -1
  222. package/dist/workflow/Workflow.d.ts +10 -9
  223. package/dist/workflow/Workflow.d.ts.map +1 -1
  224. package/dist/workflow/Workflow.js +33 -22
  225. package/dist/workflow/Workflow.js.map +1 -1
  226. package/dist/workflow/WorkflowEngine.d.ts.map +1 -1
  227. package/dist/workflow/WorkflowEngine.js +26 -12
  228. package/dist/workflow/WorkflowEngine.js.map +1 -1
  229. package/dist/workflow/internal/retry.d.ts +2 -0
  230. package/dist/workflow/internal/retry.d.ts.map +1 -0
  231. package/dist/workflow/internal/retry.js +11 -0
  232. package/dist/workflow/internal/retry.js.map +1 -0
  233. package/dist/workflow/internal/scope.d.ts +2 -0
  234. package/dist/workflow/internal/scope.d.ts.map +1 -0
  235. package/dist/workflow/internal/scope.js +26 -0
  236. package/dist/workflow/internal/scope.js.map +1 -0
  237. package/package.json +3 -3
  238. package/src/Channel.ts +105 -8
  239. package/src/Codegen.ts +7 -2
  240. package/src/Effect.ts +224 -48
  241. package/src/Equal.ts +85 -79
  242. package/src/Hash.ts +30 -22
  243. package/src/LayerRef.ts +6 -4
  244. package/src/Logger.ts +68 -25
  245. package/src/Match.ts +78 -50
  246. package/src/Order.ts +1 -1
  247. package/src/Schema.ts +79 -296
  248. package/src/SchemaAST.ts +0 -1
  249. package/src/ScopedCache.ts +6 -4
  250. package/src/Stream.ts +167 -33
  251. package/src/String.ts +1 -1
  252. package/src/Tracer.ts +10 -0
  253. package/src/ai/McpServer.ts +161 -4
  254. package/src/ai/Prompt.ts +20 -3
  255. package/src/ai/Skill.ts +236 -0
  256. package/src/ai/index.ts +6 -0
  257. package/src/cluster/ClusterWorkflowEngine.ts +172 -96
  258. package/src/cluster/MessageStorage.ts +51 -2
  259. package/src/cluster/SqlMessageStorage.ts +81 -34
  260. package/src/cluster/internal/entityActivation.ts +6 -0
  261. package/src/cluster/internal/entityManager.ts +8 -4
  262. package/src/encoding/Base64.ts +5 -1
  263. package/src/encoding/Base64Url.ts +6 -1
  264. package/src/encoding/Xml.ts +96 -26
  265. package/src/http/FetchHttpClient.ts +8 -5
  266. package/src/http/Headers.ts +309 -3
  267. package/src/http/HttpClient.ts +19 -7
  268. package/src/http/HttpClientError.ts +42 -9
  269. package/src/http/HttpClientRequest.ts +51 -0
  270. package/src/http/HttpClientResponse.ts +156 -0
  271. package/src/http/HttpMiddleware.ts +1 -1
  272. package/src/http/HttpServerResponse.ts +126 -0
  273. package/src/http/Multipart.ts +0 -5
  274. package/src/http/MultipartParser/internal/contentType.ts +1 -1
  275. package/src/http/internal/clientPath.ts +39 -0
  276. package/src/http/internal/redactedPath.ts +4 -0
  277. package/src/http/internal/tracing.ts +6 -3
  278. package/src/http-api/HttpApi.ts +29 -8
  279. package/src/http-api/HttpApiBuilder.ts +7 -2
  280. package/src/http-api/HttpApiClient.ts +30 -7
  281. package/src/http-api/internal/redactedKeys.ts +40 -0
  282. package/src/internal/base64.ts +57 -2
  283. package/src/internal/dateTime.ts +43 -24
  284. package/src/internal/effect.ts +31 -102
  285. package/src/internal/equal.ts +37 -17
  286. package/src/internal/hash.ts +5 -1
  287. package/src/internal/matcher.ts +34 -113
  288. package/src/internal/schema/schemaCodegen.ts +5 -4
  289. package/src/internal/schema/schemaCodegenBuiltIns.ts +343 -0
  290. package/src/internal/schema/toEquivalence.ts +3 -5
  291. package/src/internal/version.ts +1 -1
  292. package/src/jose/JoseError.ts +34 -0
  293. package/src/jose/internal/compact.ts +14 -5
  294. package/src/observability/Otlp.ts +29 -0
  295. package/src/observability/OtlpExporter.ts +206 -75
  296. package/src/observability/OtlpLogger.ts +24 -2
  297. package/src/observability/OtlpMetrics.ts +2 -0
  298. package/src/observability/OtlpTracer.ts +24 -3
  299. package/src/persistence/KeyValueStore.ts +17 -14
  300. package/src/reactivity/Atom.ts +12 -18
  301. package/src/rpc/RpcClient.ts +26 -1
  302. package/src/rpc/RpcGroup.ts +4 -1
  303. package/src/sql/Migrator.ts +2 -11
  304. package/src/sql/SqlClient.ts +14 -8
  305. package/src/workflow/Activity.ts +28 -4
  306. package/src/workflow/Workflow.ts +68 -44
  307. package/src/workflow/WorkflowEngine.ts +38 -15
  308. package/src/workflow/internal/retry.ts +12 -0
  309. package/src/workflow/internal/scope.ts +36 -0
@@ -344,18 +344,24 @@ export const makeEncodedStorage: (options?: {
344
344
  `${messageColumns}, ${idAs("r.id", "reply_reply_id")}, ${replyJoinColumns}`
345
345
  )
346
346
 
347
- const selectByMessageId = (message_id: string): Effect.Effect<ReadonlyArray<Row>, SqlError> =>
347
+ const emptyFragment = sql.literal("")
348
+ const selectByMessageId = (
349
+ message_id: string,
350
+ lock: Fragment = emptyFragment
351
+ ): Effect.Effect<ReadonlyArray<Row>, SqlError> =>
348
352
  sql`
349
353
  SELECT ${duplicateColumns}
350
354
  FROM ${messagesTableSql} m
351
355
  LEFT JOIN ${repliesTableSql} r ON r.id = m.last_reply_id
352
356
  WHERE m.message_id = ${message_id}
357
+ ${lock}
353
358
  `
354
359
  const maxInsertAttempts = 3
355
360
  // Runs an insert that reports whether it stored the row, returning the
356
361
  // existing row with the same message_id when it did not
357
362
  const insertUnlessExists = (
358
- insert: (row: MessageRow, message_id: string) => Effect.Effect<boolean, SqlError>
363
+ insert: (row: MessageRow, message_id: string) => Effect.Effect<boolean, SqlError>,
364
+ lock?: Fragment
359
365
  ) =>
360
366
  (row: MessageRow, message_id: string): Effect.Effect<ReadonlyArray<Row>, SqlError> => {
361
367
  // deleteProcessed can delete the existing row before it is read, so insert
@@ -364,7 +370,7 @@ export const makeEncodedStorage: (options?: {
364
370
  Effect.flatMap(
365
371
  insert(row, message_id),
366
372
  (inserted) =>
367
- inserted ? Effect.succeed([]) : Effect.flatMap(selectByMessageId(message_id), (rows) => {
373
+ inserted ? Effect.succeed([]) : Effect.flatMap(selectByMessageId(message_id, lock), (rows) => {
368
374
  if (rows.length > 0) return Effect.succeed(rows)
369
375
  if (attempt < maxInsertAttempts) return loop(attempt + 1)
370
376
  return Effect.fail(
@@ -397,11 +403,15 @@ export const makeEncodedStorage: (options?: {
397
403
  )
398
404
  ),
399
405
  mysql: () =>
400
- insertUnlessExists((row) =>
401
- Effect.map(
402
- sql`INSERT IGNORE INTO ${messagesTableSql} ${sql.insert(row)}`.raw,
403
- (result: any) => result.affectedRows > 0
404
- )
406
+ insertUnlessExists(
407
+ (row) =>
408
+ Effect.map(
409
+ sql`INSERT IGNORE INTO ${messagesTableSql} ${sql.insert(row)}`.raw,
410
+ (result: any) => result.affectedRows > 0
411
+ ),
412
+ // At MySQL's default REPEATABLE READ, a plain SELECT reads the
413
+ // transaction's snapshot and misses a row committed after it began.
414
+ sql.literal("LOCK IN SHARE MODE")
405
415
  ),
406
416
  mssql: () =>
407
417
  insertUnlessExists((row, message_id) =>
@@ -557,7 +567,6 @@ export const makeEncodedStorage: (options?: {
557
567
  `
558
568
  })
559
569
 
560
- const emptyFragment = sql.literal("")
561
570
  // mssql only limits with OFFSET/FETCH, which requires the ORDER BY that
562
571
  // both queries already have
563
572
  const limitFragment = sql.onDialectOrElse({
@@ -847,6 +856,29 @@ export const makeEncodedStorage: (options?: {
847
856
  withTracerDisabled
848
857
  ),
849
858
 
859
+ requestsForAddress: ({ address, tag }) =>
860
+ sql<MessageRow & ReplyJoinRow>`
861
+ SELECT ${sql.literal(messageColumns)}
862
+ FROM ${messagesTableSql} m
863
+ WHERE m.entity_type = ${address.entityType}
864
+ AND m.entity_id = ${address.entityId}
865
+ AND m.tag = ${tag}
866
+ AND m.kind = ${messageKindRequest}
867
+ `.pipe(
868
+ // The indexed predicates follow the column collation, which may ignore case,
869
+ // accents or trailing spaces, so exact matches are enforced here.
870
+ Effect.map((rows) =>
871
+ rows
872
+ .filter((row) =>
873
+ row.entity_type === address.entityType && row.entity_id === address.entityId && row.tag === tag
874
+ )
875
+ .map((row) => messageFromRow(row).envelope as Envelope.PartialRequestEncoded)
876
+ ),
877
+ Effect.provideService(SqlClient.SafeIntegers, true),
878
+ PersistenceError.refail,
879
+ withTracerDisabled
880
+ ),
881
+
850
882
  repliesForUnfiltered: (requestIds) =>
851
883
  sql<ReplyRow>`
852
884
  SELECT ${replyColumns}
@@ -1045,6 +1077,36 @@ export const migrations = (options?: {
1045
1077
  const messagesTable = table("messages")
1046
1078
  const repliesTable = table("replies")
1047
1079
 
1080
+ const ensureMessagesIndex = Effect.fnUntraced(function*(
1081
+ name: string,
1082
+ columnList: string,
1083
+ mysqlColumnList = columnList
1084
+ ) {
1085
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms()
1086
+ const messagesTableSql = sql(messagesTable)
1087
+ const index = `${messagesTable}_${name}`
1088
+ const columns = sql.literal(columnList)
1089
+ yield* sql.onDialectOrElse({
1090
+ mssql: () =>
1091
+ sql`
1092
+ IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${index} AND object_id = OBJECT_ID(${messagesTable}))
1093
+ CREATE INDEX ${sql(index)} ON ${messagesTableSql} (${columns})
1094
+ `,
1095
+ mysql: () =>
1096
+ sql`
1097
+ SELECT 1 FROM information_schema.statistics
1098
+ WHERE table_schema = DATABASE() AND table_name = ${messagesTable} AND index_name = ${index}
1099
+ `.pipe(
1100
+ Effect.flatMap((rows) =>
1101
+ rows.length > 0
1102
+ ? Effect.void
1103
+ : sql`CREATE INDEX ${sql(index)} ON ${messagesTableSql} (${sql.literal(mysqlColumnList)})`.unprepared
1104
+ )
1105
+ ),
1106
+ orElse: () => sql`CREATE INDEX IF NOT EXISTS ${sql(index)} ON ${messagesTableSql} (${columns})`
1107
+ })
1108
+ })
1109
+
1048
1110
  // The migrator serializes PostgreSQL DDL. Propagate errors: retrying in an
1049
1111
  // aborted transaction cannot succeed.
1050
1112
  return Migrator.fromRecord({
@@ -1353,31 +1415,16 @@ export const migrations = (options?: {
1353
1415
  }),
1354
1416
 
1355
1417
  // Serves deleteProcessed's lookup by entity type and final reply id
1356
- "0005_retention_index": Effect.gen(function*() {
1357
- const sql = (yield* SqlClient.SqlClient).withoutTransforms()
1358
- const messagesTableSql = sql(messagesTable)
1359
- const retentionIndex = `${messagesTable}_retention_idx`
1360
- const columns = sql.literal("entity_type, processed, last_reply_id")
1361
- yield* sql.onDialectOrElse({
1362
- mssql: () =>
1363
- sql`
1364
- IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${retentionIndex} AND object_id = OBJECT_ID(${messagesTable}))
1365
- CREATE INDEX ${sql(retentionIndex)} ON ${messagesTableSql} (${columns})
1366
- `,
1367
- mysql: () =>
1368
- sql`
1369
- SELECT 1 FROM information_schema.statistics
1370
- WHERE table_schema = DATABASE() AND table_name = ${messagesTable} AND index_name = ${retentionIndex}
1371
- `.pipe(
1372
- Effect.flatMap((rows) =>
1373
- rows.length > 0
1374
- ? Effect.void
1375
- : sql`CREATE INDEX ${sql(retentionIndex)} ON ${messagesTableSql} (${columns})`.unprepared
1376
- )
1377
- ),
1378
- orElse: () => sql`CREATE INDEX IF NOT EXISTS ${sql(retentionIndex)} ON ${messagesTableSql} (${columns})`
1379
- })
1380
- })
1418
+ "0005_retention_index": ensureMessagesIndex("retention_idx", "entity_type, processed, last_reply_id"),
1419
+
1420
+ // Serves requestsForAddress and clearAddress. On MySQL, a prefix of
1421
+ // entity_id keeps the utf8mb4 key within 1,536 bytes (8 KiB pages);
1422
+ // lookups still compare the full column.
1423
+ "0006_address_index": ensureMessagesIndex(
1424
+ "address_idx",
1425
+ "entity_type, entity_id, tag",
1426
+ "entity_type, entity_id(128), tag"
1427
+ )
1381
1428
  })
1382
1429
  }
1383
1430
 
@@ -1,7 +1,13 @@
1
1
  import * as Context from "../../Context.ts"
2
+ import type * as Latch from "../../Latch.ts"
2
3
  import type * as Scope from "../../Scope.ts"
3
4
 
4
5
  /** The entity lifetime, shared by all handler rebuilds within an activation. @internal */
5
6
  export class CurrentActivationScope extends Context.Service<CurrentActivationScope, Scope.Scope>()(
6
7
  "effect/cluster/internal/CurrentActivationScope"
7
8
  ) {}
9
+
10
+ /** Opens when the activation retires and stops accepting new requests. @internal */
11
+ export class CurrentRetirementLatch extends Context.Service<CurrentRetirementLatch, Latch.Latch>()(
12
+ "effect/cluster/internal/CurrentRetirementLatch"
13
+ ) {}
@@ -39,7 +39,7 @@ import type { Sharding } from "../Sharding.ts"
39
39
  import { ShardingConfig } from "../ShardingConfig.ts"
40
40
  import * as Snowflake from "../Snowflake.ts"
41
41
  import * as ClusterAbandon from "./clusterAbandon.ts"
42
- import { CurrentActivationScope } from "./entityActivation.ts"
42
+ import { CurrentActivationScope, CurrentRetirementLatch } from "./entityActivation.ts"
43
43
  import { EntityReaper } from "./entityReaper.ts"
44
44
  import { acquireEntity, releaseEntity } from "./interruptors.ts"
45
45
  import { ResourceMap } from "./resourceMap.ts"
@@ -343,6 +343,7 @@ export const make = Effect.fnUntraced(function*<
343
343
  Context.add(CurrentRunnerAddress, options.runnerAddress),
344
344
  Context.add(KeepAliveLatch, keepAliveLatch),
345
345
  Context.add(CurrentActivationScope, scope),
346
+ Context.add(CurrentRetirementLatch, retired),
346
347
  Context.add(Scope.Scope, handlerScope),
347
348
  Context.add(CurrentLogAnnotations, {})
348
349
  )
@@ -643,9 +644,9 @@ export const make = Effect.fnUntraced(function*<
643
644
  scope,
644
645
  Effect.suspend(() => {
645
646
  activeServers.delete(address.entityId)
646
- retired.openUnsafe()
647
647
  closeLatches.closing = true
648
648
  acquireEntity(address)
649
+ retired.openUnsafe()
649
650
  drainingServers.set(address.entityId, state)
650
651
  return Effect.raceFirst(
651
652
  Effect.gen(function*() {
@@ -801,10 +802,13 @@ export const make = Effect.fnUntraced(function*<
801
802
  if (server.keepAliveRequestId === message.envelope.requestId) return Effect.void
802
803
  if (server.keepAliveRequestId !== undefined) return reply
803
804
  server.keepAliveRequestId = message.envelope.requestId
804
- return server.keepAliveLatch.whenOpen(Effect.suspend(() => {
805
+ // Re-check: the latch may close again before this fiber runs.
806
+ const release: Effect.Effect<void> = server.keepAliveLatch.whenOpen(Effect.suspend(() => {
807
+ if (!server.keepAliveLatch.isOpen()) return release
805
808
  server.keepAliveRequestId = undefined
806
809
  return reply
807
- })).pipe(
810
+ }))
811
+ return release.pipe(
808
812
  Effect.forkIn(server.scope, { startImmediately: true }),
809
813
  Effect.asVoid
810
814
  )
@@ -252,7 +252,11 @@ const encodeBytes = (bytes: Uint8Array): string => {
252
252
  // Looked up on the prototype at call time, so own or subclass overrides are ignored.
253
253
  const toBase64 = (Uint8Array.prototype as { readonly toBase64?: (this: Uint8Array) => string }).toBase64
254
254
  // The size guard also keeps detached buffers (length 0) away from native `toBase64`, which throws on them.
255
- if (length >= 32 && typeof toBase64 === "function") return toBase64.call(bytes)
255
+ if (length >= 32) {
256
+ if (typeof toBase64 === "function") return toBase64.call(bytes)
257
+ const encoded = base64.encodeBuffer(bytes, "base64")
258
+ if (encoded !== undefined) return encoded
259
+ }
256
260
  // Below ~128 bytes, appending to a string beats filling a byte array and decoding it once.
257
261
  return length < 128 ? encodeShort(bytes) : encodeLong(bytes)
258
262
  }
@@ -173,7 +173,11 @@ const encodeBytes = (bytes: Uint8Array, pad: boolean): string => {
173
173
  readonly toBase64?: (this: Uint8Array, options: NativeEncodeOptions) => string
174
174
  }).toBase64
175
175
  // The size guard also keeps detached buffers (length 0) away from native `toBase64`, which throws on them.
176
- if (length >= 32 && typeof toBase64 === "function") return toBase64.call(bytes, pad ? paddedOptions : unpaddedOptions)
176
+ if (length >= 32) {
177
+ if (typeof toBase64 === "function") return toBase64.call(bytes, pad ? paddedOptions : unpaddedOptions)
178
+ const encoded = base64.encodeBuffer(bytes, "base64url")
179
+ if (encoded !== undefined) return pad ? encoded + padding[encoded.length & 3] : encoded
180
+ }
177
181
  // Below ~128 bytes, appending to a string beats filling a byte array and decoding it once.
178
182
  return length < 128 ? encodeShort(bytes, pad) : encodeLong(bytes, pad)
179
183
  }
@@ -235,6 +239,7 @@ const nativeDecodeOptions: base64.NativeDecodeOptions = { alphabet: "base64url"
235
239
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
236
240
  const alphabetCodes = encoder.encode(alphabet)
237
241
  const paddingCode = "=".charCodeAt(0)
242
+ const padding = ["", "", "==", "="]
238
243
  const codes = new Uint8Array(128)
239
244
  for (let i = 0; i < alphabet.length; i++) codes[alphabet.charCodeAt(i)] = i
240
245
 
@@ -277,12 +277,28 @@ export type Event =
277
277
  * Adjacent text is merged into one string; comments and processing
278
278
  * instructions are dropped.
279
279
  *
280
+ * When the events were decoded with `namespaces: "strict"`, `namespace` and
281
+ * `localName` give the element's resolved name. Otherwise they are absent.
282
+ *
280
283
  * @stability experimental
281
284
  * @category models
282
285
  * @since 4.0.6
283
286
  */
284
287
  export interface Element {
285
288
  readonly name: string
289
+ /**
290
+ * Namespace name of the element, or `""` for none, with
291
+ * `namespaces: "strict"`.
292
+ *
293
+ * @since 4.1.5
294
+ */
295
+ readonly namespace?: string | undefined
296
+ /**
297
+ * Local part of the element name, with `namespaces: "strict"`.
298
+ *
299
+ * @since 4.1.5
300
+ */
301
+ readonly localName?: string | undefined
286
302
  readonly attributes: Readonly<Record<string, string>>
287
303
  readonly children: ReadonlyArray<Element | string>
288
304
  }
@@ -342,8 +358,8 @@ export interface DecodeOptions {
342
358
  *
343
359
  * `maxElementSize` is the maximum size of one collected element, counted as
344
360
  * the UTF-16 code units of its names, attribute names and values, and text.
345
- * Defaults to 16 MiB; `Infinity` disables the limit. Invalid options throw when
346
- * the channel is created.
361
+ * `namespace` and `localName` are not counted. Defaults to 16 MiB; `Infinity`
362
+ * disables the limit. Invalid options throw when the channel is created.
347
363
  *
348
364
  * @stability experimental
349
365
  * @category configuration
@@ -474,17 +490,21 @@ export const decode = <IE = never, Done = unknown>(options?: DecodeOptions): Cha
474
490
  *
475
491
  * **Details**
476
492
  *
477
- * `path` lists element names from the root, and `"*"` matches any name. Each
478
- * element whose ancestors and own name match the path is emitted once its end
479
- * tag arrives, with all of its descendants; everything outside the matched
480
- * elements is skipped. Because paths start at the root, an element nested in a
481
- * matched element is part of its tree and is not emitted separately.
493
+ * `path` lists element names from the root, and `"*"` matches any name. A name
494
+ * in Clark notation, `{uri}local`, matches an element with that namespace and
495
+ * local name, `{*}local` matches the local name in any namespace or none, and
496
+ * `{}local` matches it in no namespace. Each element whose ancestors and own
497
+ * name match the path is emitted once its end tag arrives, with all of its
498
+ * descendants; everything outside the matched elements is skipped. Because
499
+ * paths start at the root, an element nested in a matched element is part of
500
+ * its tree and is not emitted separately.
482
501
  *
483
502
  * **Gotchas**
484
503
  *
485
504
  * - A path that does not start at the root element matches nothing.
486
- * - Paths and `Element` names are names as written, including prefixes, even
487
- * with `namespaces: "strict"`, which only adds namespaces to events.
505
+ * - Except in Clark notation, names in a path are matched as written,
506
+ * including prefixes, even with `namespaces: "strict"`. `Element` names are
507
+ * always as written.
488
508
  * - Whitespace between child elements, such as indentation, is kept as string
489
509
  * children.
490
510
  * - A collected element larger than `maxElementSize` fails with a `Limit`
@@ -493,6 +513,11 @@ export const decode = <IE = never, Done = unknown>(options?: DecodeOptions): Cha
493
513
  * limit for untrusted input.
494
514
  * - Events that end inside an element, or end an element that was never
495
515
  * started, fail with an `InvalidEvent` `XmlError`.
516
+ * - A path with a name in Clark notation needs events decoded with
517
+ * `namespaces: "strict"`. Any start tag without `localName` fails with an
518
+ * `InvalidEvent` `XmlError`, even outside a matched subtree.
519
+ * - Clark notation requires an unprefixed local name. A wildcard in that
520
+ * position, such as `{uri}*`, is not supported.
496
521
  * - A path that is empty or contains an invalid name throws when the channel is
497
522
  * created.
498
523
  *
@@ -539,13 +564,8 @@ export const elements = <IE = never, Done = unknown>(
539
564
  if (path.length === 0) {
540
565
  throw new Error("Xml: elements path must not be empty")
541
566
  }
542
- for (const name of path) {
543
- if (name !== "*" && !isName(name)) {
544
- throw new Error(`Xml: invalid element name in path: ${JSON.stringify(name)}`)
545
- }
546
- }
567
+ const segments = Array.from(path, parseSegment)
547
568
  const maxElementSize = checkLimit("maxElementSize", options?.maxElementSize, defaultMaxElementSize)
548
- const segments = Array.from(path)
549
569
  return makeChannel<Event, Element, IE, Done>(() => new Collector(segments, maxElementSize))
550
570
  }
551
571
 
@@ -645,6 +665,10 @@ export const encode = <IE = never, Done = unknown>(): Channel.Channel<
645
665
  * empty one. Names and characters are not checked; `encode` and
646
666
  * `encodeString` check them.
647
667
  *
668
+ * An element with a `localName`, such as one collected from events decoded
669
+ * with `namespaces: "strict"`, keeps its `namespace` and `localName` on its
670
+ * start and end events, so paths in Clark notation still match them.
671
+ *
648
672
  * **Gotchas**
649
673
  *
650
674
  * A collected subtree does not carry `xmlns` declarations inherited from its
@@ -678,12 +702,12 @@ export const encode = <IE = never, Done = unknown>(): Channel.Channel<
678
702
  * @since 4.1.5
679
703
  */
680
704
  export const toEvents = (element: Element): Arr.NonEmptyReadonlyArray<Event> => {
681
- const out: Arr.NonEmptyArray<Event> = [{ _tag: "StartElement", name: element.name, attributes: element.attributes }]
705
+ const out: Arr.NonEmptyArray<Event> = [startEvent(element)]
682
706
  const stack = [{ element, index: 0 }]
683
707
  while (stack.length > 0) {
684
708
  const frame = stack[stack.length - 1]
685
709
  if (frame.index === frame.element.children.length) {
686
- out.push({ _tag: "EndElement", name: frame.element.name })
710
+ out.push(endEvent(frame.element))
687
711
  stack.pop()
688
712
  continue
689
713
  }
@@ -691,13 +715,32 @@ export const toEvents = (element: Element): Arr.NonEmptyReadonlyArray<Event> =>
691
715
  if (typeof child === "string") {
692
716
  out.push({ _tag: "Text", text: child })
693
717
  } else {
694
- out.push({ _tag: "StartElement", name: child.name, attributes: child.attributes })
718
+ out.push(startEvent(child))
695
719
  stack.push({ element: child, index: 0 })
696
720
  }
697
721
  }
698
722
  return out
699
723
  }
700
724
 
725
+ interface ResolvedName {
726
+ namespace?: string | undefined
727
+ localName?: string | undefined
728
+ }
729
+
730
+ const withResolvedName = <A extends ResolvedName>(to: A, from: Readonly<ResolvedName>): A => {
731
+ if (from.localName !== undefined) {
732
+ to.namespace = from.namespace
733
+ to.localName = from.localName
734
+ }
735
+ return to
736
+ }
737
+
738
+ const startEvent = (element: Element): StartElement =>
739
+ withResolvedName<StartElement>({ _tag: "StartElement", name: element.name, attributes: element.attributes }, element)
740
+
741
+ const endEvent = (element: Element): EndElement =>
742
+ withResolvedName<EndElement>({ _tag: "EndElement", name: element.name }, element)
743
+
701
744
  const defaultMaxTokenSize = 10 * 1024 * 1024
702
745
  const defaultMaxDepth = 1024
703
746
  const defaultMaxElementSize = 16 * 1024 * 1024
@@ -2110,12 +2153,30 @@ class Utf8Input implements Machine<Uint8Array, Event> {
2110
2153
  }
2111
2154
  }
2112
2155
 
2113
- interface MutableElement {
2114
- readonly name: string
2115
- readonly attributes: Readonly<Record<string, string>>
2156
+ interface MutableElement extends Element {
2116
2157
  readonly children: Array<MutableElement | string>
2117
2158
  }
2118
2159
 
2160
+ // `string` is "*" or a literal name; `namespace: undefined` matches any namespace
2161
+ type Segment = string | { readonly namespace: string | undefined; readonly localName: string }
2162
+
2163
+ const parseSegment = (segment: string): Segment => {
2164
+ if (segment === "*" || isName(segment)) return segment
2165
+ // The last "}" ends the namespace: a namespace can contain "}", a local name cannot
2166
+ const close = segment.lastIndexOf("}")
2167
+ const localName = segment.slice(close + 1)
2168
+ if (segment.startsWith("{") && isName(localName) && !localName.includes(":")) {
2169
+ const namespace = segment.slice(1, close)
2170
+ return { namespace: namespace === "*" ? undefined : namespace, localName }
2171
+ }
2172
+ throw new Error(`Xml: invalid element name in path: ${JSON.stringify(segment)}`)
2173
+ }
2174
+
2175
+ const matches = (segment: Segment, event: StartElement): boolean =>
2176
+ typeof segment === "string" ?
2177
+ segment === "*" || segment === event.name :
2178
+ segment.localName === event.localName && (segment.namespace === undefined || segment.namespace === event.namespace)
2179
+
2119
2180
  class Collector implements Machine<Event, Element> {
2120
2181
  out: Array<Element> = []
2121
2182
  private depth = 0
@@ -2124,25 +2185,34 @@ class Collector implements Machine<Event, Element> {
2124
2185
  // The element being collected and its open descendants
2125
2186
  private readonly stack: Array<MutableElement> = []
2126
2187
  private size = 0
2127
- private readonly path: ReadonlyArray<string>
2188
+ private readonly path: ReadonlyArray<Segment>
2128
2189
  private readonly maxElementSize: number
2190
+ private readonly clark: boolean
2129
2191
 
2130
- constructor(path: ReadonlyArray<string>, maxElementSize: number) {
2192
+ constructor(path: ReadonlyArray<Segment>, maxElementSize: number) {
2131
2193
  this.path = path
2132
2194
  this.maxElementSize = maxElementSize
2195
+ this.clark = path.some((segment) => typeof segment !== "string")
2133
2196
  }
2134
2197
 
2135
2198
  push(event: Event): void {
2136
2199
  switch (event._tag) {
2137
2200
  case "StartElement": {
2201
+ if (this.clark && event.localName === undefined) {
2202
+ throw invalidEvent(
2203
+ `start tag <${event.name}> without localName for a path in Clark notation: decode with namespaces: "strict"`
2204
+ )
2205
+ }
2138
2206
  const depth = this.depth++
2139
2207
  if (this.stack.length === 0) {
2140
- const segment = this.path[depth]
2141
- if (this.matched !== depth || (segment !== "*" && segment !== event.name)) return
2208
+ if (this.matched !== depth || !matches(this.path[depth], event)) return
2142
2209
  if (++this.matched < this.path.length) return
2143
2210
  this.size = 0
2144
2211
  }
2145
- const element: MutableElement = { name: event.name, attributes: event.attributes, children: [] }
2212
+ const element = withResolvedName<MutableElement>(
2213
+ { name: event.name, attributes: event.attributes, children: [] },
2214
+ event
2215
+ )
2146
2216
  if (this.stack.length > 0) this.stack[this.stack.length - 1].children.push(element)
2147
2217
  this.stack.push(element)
2148
2218
  let size = event.name.length
@@ -26,7 +26,8 @@ import * as HttpClientResponse from "./HttpClientResponse.ts"
26
26
  *
27
27
  * **Details**
28
28
  *
29
- * Defaults to `globalThis.fetch`.
29
+ * Defaults to `globalThis.fetch`. When not explicitly provided in context,
30
+ * `FetchHttpClient` uses the current `globalThis.fetch` on each request.
30
31
  *
31
32
  * @stability unstable
32
33
  * @category services
@@ -116,7 +117,7 @@ const fetch: HttpClient.HttpClient = HttpClient.make((request, url, signal, fibe
116
117
  })
117
118
  )
118
119
  }
119
- const fetch = fiber.getRef(Fetch)
120
+ const fetch = Context.getOrUndefined(fiber.context, Fetch)
120
121
  const options: globalThis.RequestInit = Context.getOrUndefined(fiber.context, RequestInit) ?? {}
121
122
  let headers = options.headers
122
123
  ? Headers.merge(Headers.fromInput(options.headers as Headers.Input), request.headers)
@@ -129,15 +130,17 @@ const fetch: HttpClient.HttpClient = HttpClient.make((request, url, signal, fibe
129
130
  const send = (body: BodyInit | undefined) =>
130
131
  Effect.map(
131
132
  Effect.tryPromise({
132
- try: () =>
133
- fetch(url, {
133
+ try: () => {
134
+ const init: any = {
134
135
  ...options,
135
136
  method: request.method,
136
137
  headers,
137
138
  body,
138
139
  duplex: typeof ReadableStream !== "undefined" && body instanceof ReadableStream ? "half" : undefined,
139
140
  signal: uploadController ? AbortSignal.any([signal, uploadController.signal]) : signal
140
- } as any),
141
+ }
142
+ return fetch ? fetch(url, init) : globalThis.fetch(url, init)
143
+ },
141
144
  catch: (cause) =>
142
145
  new HttpClientError.HttpClientError({
143
146
  reason: new HttpClientError.TransportError({