@distilled.cloud/core 1.0.0-rc.17 → 1.0.0-rc.18

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 (259) hide show
  1. package/lib/_bundle/base.js +2 -2
  2. package/lib/_bundle/base.js.map +1 -1
  3. package/lib/_bundle/graphql.js +2 -2
  4. package/lib/_bundle/graphql.js.map +1 -1
  5. package/lib/_bundle/rest.js +1 -1
  6. package/lib/_bundle/rest.js.map +1 -1
  7. package/lib/annotations.d.ts +15 -0
  8. package/lib/annotations.d.ts.map +1 -0
  9. package/lib/annotations.js +2 -0
  10. package/lib/annotations.js.map +1 -0
  11. package/lib/api.d.ts +15 -0
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -1
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/config.d.ts +54 -13
  16. package/lib/config.d.ts.map +1 -1
  17. package/lib/config.js +1 -1
  18. package/lib/debug.d.ts.map +1 -1
  19. package/lib/error-category.d.ts.map +1 -1
  20. package/lib/errors.d.ts +2 -13
  21. package/lib/errors.d.ts.map +1 -1
  22. package/lib/errors.js +1 -1
  23. package/lib/graphql.d.ts +14 -0
  24. package/lib/graphql.d.ts.map +1 -1
  25. package/lib/index.d.ts +3 -2
  26. package/lib/index.d.ts.map +1 -1
  27. package/lib/index.js +1 -0
  28. package/lib/pagination.d.ts +34 -2
  29. package/lib/pagination.d.ts.map +1 -1
  30. package/lib/pagination.js +1 -1
  31. package/lib/protocol-http.d.ts +30 -6
  32. package/lib/protocol-http.d.ts.map +1 -1
  33. package/lib/protocol-http.js +1 -1
  34. package/lib/protocol-rest.d.ts +53 -39
  35. package/lib/protocol-rest.d.ts.map +1 -1
  36. package/lib/protocol-rest.js +1 -1
  37. package/lib/response-validation.d.ts +4 -3
  38. package/lib/response-validation.d.ts.map +1 -1
  39. package/lib/schema-lite-typed.js +1 -2
  40. package/lib/telemetry-debug.d.ts +14 -0
  41. package/lib/telemetry-debug.d.ts.map +1 -0
  42. package/lib/telemetry-debug.js +2 -0
  43. package/lib/telemetry-debug.js.map +1 -0
  44. package/lib/telemetry-hooks.d.ts +32 -0
  45. package/lib/telemetry-hooks.d.ts.map +1 -0
  46. package/lib/telemetry-hooks.js +2 -0
  47. package/lib/telemetry-hooks.js.map +1 -0
  48. package/lib/telemetry-host-rules.d.ts +23 -0
  49. package/lib/telemetry-host-rules.d.ts.map +1 -0
  50. package/lib/telemetry-host-rules.js +2 -0
  51. package/lib/telemetry-host-rules.js.map +1 -0
  52. package/lib/telemetry-lambda-context.d.ts +17 -0
  53. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  54. package/lib/telemetry-lambda-context.js +2 -0
  55. package/lib/telemetry-lambda-context.js.map +1 -0
  56. package/lib/telemetry-message-context.d.ts +52 -0
  57. package/lib/telemetry-message-context.d.ts.map +1 -0
  58. package/lib/telemetry-message-context.js +2 -0
  59. package/lib/telemetry-message-context.js.map +1 -0
  60. package/lib/telemetry-metrics.d.ts +6 -0
  61. package/lib/telemetry-metrics.d.ts.map +1 -0
  62. package/lib/telemetry-metrics.js +2 -0
  63. package/lib/telemetry-metrics.js.map +1 -0
  64. package/lib/telemetry-name-template.d.ts +13 -0
  65. package/lib/telemetry-name-template.d.ts.map +1 -0
  66. package/lib/telemetry-name-template.js +2 -0
  67. package/lib/telemetry-name-template.js.map +1 -0
  68. package/lib/telemetry-stream.d.ts +9 -0
  69. package/lib/telemetry-stream.d.ts.map +1 -0
  70. package/lib/telemetry-stream.js +2 -0
  71. package/lib/telemetry-stream.js.map +1 -0
  72. package/lib/telemetry-xray.d.ts +28 -0
  73. package/lib/telemetry-xray.d.ts.map +1 -0
  74. package/lib/telemetry-xray.js +2 -0
  75. package/lib/telemetry-xray.js.map +1 -0
  76. package/lib/telemetry.d.ts +269 -0
  77. package/lib/telemetry.d.ts.map +1 -0
  78. package/lib/telemetry.js +3 -0
  79. package/lib/telemetry.js.map +1 -0
  80. package/package.json +1 -3
  81. package/src/annotations.ts +37 -0
  82. package/src/api.ts +123 -24
  83. package/src/category.ts +21 -22
  84. package/src/config.ts +58 -29
  85. package/src/debug.ts +9 -6
  86. package/src/error-category.ts +12 -14
  87. package/src/errors.ts +7 -7
  88. package/src/graphql.ts +123 -18
  89. package/src/index.ts +3 -2
  90. package/src/pagination.ts +119 -6
  91. package/src/protocol-http.ts +63 -43
  92. package/src/protocol-rest.ts +201 -140
  93. package/src/response-validation.ts +4 -3
  94. package/src/telemetry-debug.ts +135 -0
  95. package/src/telemetry-hooks.ts +33 -0
  96. package/src/telemetry-host-rules.ts +39 -0
  97. package/src/telemetry-lambda-context.ts +46 -0
  98. package/src/telemetry-message-context.ts +170 -0
  99. package/src/telemetry-metrics.ts +69 -0
  100. package/src/telemetry-name-template.ts +26 -0
  101. package/src/telemetry-stream.ts +91 -0
  102. package/src/telemetry-xray.ts +66 -0
  103. package/src/telemetry.ts +768 -0
  104. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  105. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  106. package/lib/codegen/boolean-string-enums.js +0 -147
  107. package/lib/codegen/boolean-string-enums.js.map +0 -1
  108. package/lib/codegen/chunk.d.ts +0 -7
  109. package/lib/codegen/chunk.d.ts.map +0 -1
  110. package/lib/codegen/chunk.js +0 -139
  111. package/lib/codegen/chunk.js.map +0 -1
  112. package/lib/codegen/cli.d.ts +0 -80
  113. package/lib/codegen/cli.d.ts.map +0 -1
  114. package/lib/codegen/cli.js +0 -166
  115. package/lib/codegen/cli.js.map +0 -1
  116. package/lib/codegen/datafy.d.ts +0 -14
  117. package/lib/codegen/datafy.d.ts.map +0 -1
  118. package/lib/codegen/datafy.js +0 -853
  119. package/lib/codegen/datafy.js.map +0 -1
  120. package/lib/codegen/dedupe.d.ts +0 -5
  121. package/lib/codegen/dedupe.d.ts.map +0 -1
  122. package/lib/codegen/dedupe.js +0 -153
  123. package/lib/codegen/dedupe.js.map +0 -1
  124. package/lib/codegen/emit.d.ts +0 -125
  125. package/lib/codegen/emit.d.ts.map +0 -1
  126. package/lib/codegen/emit.js +0 -99
  127. package/lib/codegen/emit.js.map +0 -1
  128. package/lib/codegen/format.d.ts +0 -11
  129. package/lib/codegen/format.d.ts.map +0 -1
  130. package/lib/codegen/format.js +0 -32
  131. package/lib/codegen/format.js.map +0 -1
  132. package/lib/codegen/generated-at.d.ts +0 -29
  133. package/lib/codegen/generated-at.d.ts.map +0 -1
  134. package/lib/codegen/generated-at.js +0 -78
  135. package/lib/codegen/generated-at.js.map +0 -1
  136. package/lib/codegen/generator.d.ts +0 -353
  137. package/lib/codegen/generator.d.ts.map +0 -1
  138. package/lib/codegen/generator.js +0 -810
  139. package/lib/codegen/generator.js.map +0 -1
  140. package/lib/codegen/graph.d.ts +0 -36
  141. package/lib/codegen/graph.d.ts.map +0 -1
  142. package/lib/codegen/graph.js +0 -136
  143. package/lib/codegen/graph.js.map +0 -1
  144. package/lib/codegen/graphql-client.d.ts +0 -70
  145. package/lib/codegen/graphql-client.d.ts.map +0 -1
  146. package/lib/codegen/graphql-client.js +0 -439
  147. package/lib/codegen/graphql-client.js.map +0 -1
  148. package/lib/codegen/graphql.d.ts +0 -207
  149. package/lib/codegen/graphql.d.ts.map +0 -1
  150. package/lib/codegen/graphql.js +0 -786
  151. package/lib/codegen/graphql.js.map +0 -1
  152. package/lib/codegen/latin1.d.ts +0 -3
  153. package/lib/codegen/latin1.d.ts.map +0 -1
  154. package/lib/codegen/latin1.js +0 -126
  155. package/lib/codegen/latin1.js.map +0 -1
  156. package/lib/codegen/members.d.ts +0 -32
  157. package/lib/codegen/members.d.ts.map +0 -1
  158. package/lib/codegen/members.js +0 -62
  159. package/lib/codegen/members.js.map +0 -1
  160. package/lib/codegen/model-diff.d.ts +0 -10
  161. package/lib/codegen/model-diff.d.ts.map +0 -1
  162. package/lib/codegen/model-diff.js +0 -67
  163. package/lib/codegen/model-diff.js.map +0 -1
  164. package/lib/codegen/naming.d.ts +0 -29
  165. package/lib/codegen/naming.d.ts.map +0 -1
  166. package/lib/codegen/naming.js +0 -74
  167. package/lib/codegen/naming.js.map +0 -1
  168. package/lib/codegen/openapi-cli.d.ts +0 -52
  169. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  170. package/lib/codegen/openapi-cli.js +0 -84
  171. package/lib/codegen/openapi-cli.js.map +0 -1
  172. package/lib/codegen/openapi.d.ts +0 -209
  173. package/lib/codegen/openapi.d.ts.map +0 -1
  174. package/lib/codegen/openapi.js +0 -1548
  175. package/lib/codegen/openapi.js.map +0 -1
  176. package/lib/codegen/operations.d.ts +0 -24
  177. package/lib/codegen/operations.d.ts.map +0 -1
  178. package/lib/codegen/operations.js +0 -56
  179. package/lib/codegen/operations.js.map +0 -1
  180. package/lib/codegen/pagination.d.ts +0 -39
  181. package/lib/codegen/pagination.d.ts.map +0 -1
  182. package/lib/codegen/pagination.js +0 -31
  183. package/lib/codegen/pagination.js.map +0 -1
  184. package/lib/codegen/patch-audit.d.ts +0 -84
  185. package/lib/codegen/patch-audit.d.ts.map +0 -1
  186. package/lib/codegen/patch-audit.js +0 -366
  187. package/lib/codegen/patch-audit.js.map +0 -1
  188. package/lib/codegen/patches.d.ts +0 -129
  189. package/lib/codegen/patches.d.ts.map +0 -1
  190. package/lib/codegen/patches.js +0 -472
  191. package/lib/codegen/patches.js.map +0 -1
  192. package/lib/codegen/prelude.d.ts +0 -15
  193. package/lib/codegen/prelude.d.ts.map +0 -1
  194. package/lib/codegen/prelude.js +0 -60
  195. package/lib/codegen/prelude.js.map +0 -1
  196. package/lib/codegen/privatize.d.ts +0 -21
  197. package/lib/codegen/privatize.d.ts.map +0 -1
  198. package/lib/codegen/privatize.js +0 -176
  199. package/lib/codegen/privatize.js.map +0 -1
  200. package/lib/codegen/proto.d.ts +0 -121
  201. package/lib/codegen/proto.d.ts.map +0 -1
  202. package/lib/codegen/proto.js +0 -960
  203. package/lib/codegen/proto.js.map +0 -1
  204. package/lib/codegen/pure.d.ts +0 -6
  205. package/lib/codegen/pure.d.ts.map +0 -1
  206. package/lib/codegen/pure.js +0 -91
  207. package/lib/codegen/pure.js.map +0 -1
  208. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  209. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  210. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  211. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  212. package/lib/codegen/spec-path.d.ts +0 -16
  213. package/lib/codegen/spec-path.d.ts.map +0 -1
  214. package/lib/codegen/spec-path.js +0 -101
  215. package/lib/codegen/spec-path.js.map +0 -1
  216. package/lib/codegen/table.d.ts +0 -5
  217. package/lib/codegen/table.d.ts.map +0 -1
  218. package/lib/codegen/table.js +0 -249
  219. package/lib/codegen/table.js.map +0 -1
  220. package/lib/json-patch.d.ts +0 -58
  221. package/lib/json-patch.d.ts.map +0 -1
  222. package/lib/json-patch.js +0 -2
  223. package/lib/json-patch.js.map +0 -1
  224. package/lib/schema-lite-typed.js.map +0 -1
  225. package/lib/testing.d.ts +0 -40
  226. package/lib/testing.d.ts.map +0 -1
  227. package/lib/testing.js +0 -2
  228. package/lib/testing.js.map +0 -1
  229. package/src/codegen/boolean-string-enums.ts +0 -155
  230. package/src/codegen/chunk.ts +0 -147
  231. package/src/codegen/cli.ts +0 -293
  232. package/src/codegen/datafy.ts +0 -874
  233. package/src/codegen/dedupe.ts +0 -173
  234. package/src/codegen/emit.ts +0 -200
  235. package/src/codegen/format.ts +0 -49
  236. package/src/codegen/generated-at.ts +0 -88
  237. package/src/codegen/generator.ts +0 -1229
  238. package/src/codegen/graph.ts +0 -151
  239. package/src/codegen/graphql-client.ts +0 -545
  240. package/src/codegen/graphql.ts +0 -1145
  241. package/src/codegen/latin1.ts +0 -131
  242. package/src/codegen/members.ts +0 -79
  243. package/src/codegen/model-diff.ts +0 -67
  244. package/src/codegen/naming.ts +0 -85
  245. package/src/codegen/openapi-cli.ts +0 -141
  246. package/src/codegen/openapi.ts +0 -1845
  247. package/src/codegen/operations.ts +0 -73
  248. package/src/codegen/pagination.ts +0 -64
  249. package/src/codegen/patch-audit.ts +0 -480
  250. package/src/codegen/patches.ts +0 -581
  251. package/src/codegen/prelude.ts +0 -70
  252. package/src/codegen/privatize.ts +0 -200
  253. package/src/codegen/proto.ts +0 -1092
  254. package/src/codegen/pure.ts +0 -94
  255. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  256. package/src/codegen/spec-path.ts +0 -112
  257. package/src/codegen/table.ts +0 -254
  258. package/src/json-patch.ts +0 -273
  259. package/src/testing.ts +0 -74
package/src/api.ts CHANGED
@@ -15,6 +15,7 @@ import type * as AST from "effect/SchemaAST";
15
15
  import * as Scope from "effect/Scope";
16
16
  import type * as Stream from "effect/Stream";
17
17
  import { SingleShotGen } from "effect/Utils";
18
+ import { getAnn, rawResponseRootSymbol } from "./annotations.ts";
18
19
  import { isThrottling } from "./category.ts";
19
20
  import * as Pagination from "./pagination.ts";
20
21
  import {
@@ -25,6 +26,7 @@ import {
25
26
  resolveServerRetryHintCapMs,
26
27
  serverHintMillis,
27
28
  } from "./retry.ts";
29
+ import * as Telemetry from "./telemetry.ts";
28
30
 
29
31
  //#region Protocol
30
32
 
@@ -239,6 +241,14 @@ export interface OperationConfig<
239
241
  * {@link ProtocolOperationConfig.endpointHostPrefix}).
240
242
  */
241
243
  endpointHostPrefix?: string;
244
+ /** The service's `com.distilled.telemetry#service` trait (a module const). */
245
+ telemetry?: Telemetry.ServiceTelemetry;
246
+ /**
247
+ * The operation's `com.distilled.telemetry#operation` trait, with its
248
+ * input rules; only what differs from the service's rules when it names
249
+ * its `op` (a string is just the op).
250
+ */
251
+ span?: Telemetry.SpanConfig | string;
242
252
  }
243
253
 
244
254
  /**
@@ -264,6 +274,26 @@ const backoffDelay = (b: Backoff, attempt: number, error: unknown): Effect.Effec
264
274
 
265
275
  const NO_BACKOFF: Backoff = { baseMs: 0, factor: 1, capMs: 0 };
266
276
 
277
+ /**
278
+ * BRAINSTORM: the sleep before retry `attempt` (1-based). The retry is
279
+ * recorded on the operation span; debug mode also makes the sleep a span.
280
+ */
281
+ const backoffSleep = (
282
+ delay: Duration.Input,
283
+ attempt: number,
284
+ error: unknown,
285
+ ): Effect.Effect<void> =>
286
+ Effect.withFiber((fiber) => {
287
+ const context = fiber.context as Context.Context<any>;
288
+ const delayMs = typeof delay === "number" ? delay : 0;
289
+ Telemetry.retried(context, attempt, error, delayMs);
290
+ return Telemetry.phase(context, "distilled.retry.backoff", Effect.sleep(delay), {
291
+ "distilled.retry.attempt": attempt,
292
+ "distilled.retry.delay_ms": Math.round(delayMs),
293
+ "distilled.retry.reason": (error as { _tag?: string } | null)?._tag,
294
+ });
295
+ });
296
+
267
297
  /**
268
298
  * Wrap one operation call with the caller-provided retry policy, if the
269
299
  * operation declares a retry tag. The call runs once with no retry
@@ -271,35 +301,44 @@ const NO_BACKOFF: Backoff = { baseMs: 0, factor: 1, capMs: 0 };
271
301
  * {@link Backoff} data run by a small loop; a caller-supplied `schedule`
272
302
  * runs under `Effect.retry`, with the first failure replayed as attempt one
273
303
  * so delays and counts match running the whole call under it.
304
+ *
305
+ * With `TelemetryDebug.layer`, every try runs as `Attempt` span n.
274
306
  */
275
307
  const applyRetry = (
276
308
  base: Effect.Effect<any, any, any>,
277
309
  retryKey: Context.Key<any, RetryPolicy> | undefined,
278
- ): Effect.Effect<any, any, any> =>
279
- retryKey === undefined
280
- ? base
281
- : Effect.catch(base, (error) =>
310
+ debug: Telemetry.DebugHooks | undefined,
311
+ ): Effect.Effect<any, any, any> => {
312
+ const first = debug === undefined ? base : debug.attempt(base, 1);
313
+ return retryKey === undefined
314
+ ? first
315
+ : Effect.catch(first, (error) =>
282
316
  Effect.flatMap(Effect.serviceOption(retryKey), (opt) => {
283
- if (Option.isNone(opt)) return retryWith(base, defaultOptions, error);
317
+ if (Option.isNone(opt)) return retryWith(base, defaultOptions, error, debug);
284
318
  const policy = opt.value;
285
- if (typeof policy !== "function") return retryWith(base, policy, error);
319
+ if (typeof policy !== "function") return retryWith(base, policy, error, debug);
286
320
  return Effect.flatMap(Ref.make<unknown>(error), (lastError) =>
287
321
  retryWith(
288
322
  Effect.tapError(base, (e) => Ref.set(lastError, e)),
289
323
  policy(lastError),
290
324
  error,
325
+ debug,
291
326
  ),
292
327
  );
293
328
  }),
294
329
  );
330
+ };
295
331
 
296
332
  const retryWith = (
297
333
  base: Effect.Effect<any, any, any>,
298
334
  opts: RetryOptions,
299
335
  error: unknown,
336
+ debug: Telemetry.DebugHooks | undefined,
300
337
  ): Effect.Effect<any, any, any> => {
301
338
  const keepGoing = opts.while;
302
339
  if (!keepGoing || !keepGoing(error)) return Effect.fail(error);
340
+ // Attempt n (2, 3, ...) of the call.
341
+ const again = (n: number) => (debug === undefined ? base : debug.attempt(base, n));
303
342
  if (opts.schedule) {
304
343
  // Drive the caller's schedule through its own `step`, as Effect.retry
305
344
  // does, without importing the Schedule module into every bundle: the
@@ -311,6 +350,7 @@ const retryWith = (
311
350
  >;
312
351
  };
313
352
  return Effect.flatMap(schedule.step, (next) => {
353
+ let attempt = 0;
314
354
  const loop = (e: unknown): Effect.Effect<any, any, any> =>
315
355
  !keepGoing(e)
316
356
  ? Effect.fail(e)
@@ -318,7 +358,9 @@ const retryWith = (
318
358
  Effect.matchEffect(next(clock.currentTimeMillisUnsafe(), e), {
319
359
  onFailure: () => Effect.fail(e),
320
360
  onSuccess: ([, delay]) =>
321
- Effect.flatMap(Effect.sleep(delay), () => Effect.catch(base, loop)),
361
+ Effect.flatMap(backoffSleep(delay, ++attempt, e), () =>
362
+ Effect.catch(again(attempt + 1), loop),
363
+ ),
322
364
  }),
323
365
  );
324
366
  return loop(error);
@@ -329,7 +371,9 @@ const retryWith = (
329
371
  !keepGoing(e) || (b.maxRetries !== undefined && n >= b.maxRetries)
330
372
  ? Effect.fail(e)
331
373
  : Effect.flatMap(backoffDelay(b, n, e), (ms) =>
332
- Effect.flatMap(Effect.sleep(ms), () => Effect.catch(base, (next) => step(next, n + 1))),
374
+ Effect.flatMap(backoffSleep(ms, n + 1, e), () =>
375
+ Effect.catch(again(n + 2), (next) => step(next, n + 1)),
376
+ ),
333
377
  );
334
378
  return step(error, 0);
335
379
  };
@@ -351,8 +395,18 @@ interface Prepared extends PreparedOperation {
351
395
  readonly cfg: OperationConfig<any, any, any, any, any>;
352
396
  /** The built protocol service, once its layer has been built. */
353
397
  service?: ProtocolShape;
398
+ /** The operation span's facts, from the telemetry traits; built on the first traced call. */
399
+ info?: Telemetry.OperationInfo;
354
400
  }
355
401
 
402
+ const infoOf = (p: Prepared): Telemetry.OperationInfo =>
403
+ (p.info ??= Telemetry.operationInfo(
404
+ p.cfg.telemetry,
405
+ p.cfg.span,
406
+ p.cfg.operationName,
407
+ p.inputAst,
408
+ ));
409
+
356
410
  const stateKey = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/OperationState");
357
411
 
358
412
  // Lazily resolve the operation config + schema ASTs on first call, not at
@@ -377,6 +431,14 @@ const prepare = (state: OperationState): Prepared => {
377
431
 
378
432
  const stateOf = (op: unknown): OperationState => (op as Record<symbol, OperationState>)[stateKey]!;
379
433
 
434
+ /**
435
+ * The span facts an operation's calls carry (name, kind, fixed attributes,
436
+ * input rules), as the runtime builds them from its generated config. For
437
+ * tests and tooling.
438
+ */
439
+ export const describeOperation = (op: unknown): Telemetry.OperationInfo =>
440
+ infoOf(prepare(stateOf(op)));
441
+
380
442
  const defineState = (op: unknown, state: OperationState): OperationState => {
381
443
  Object.defineProperty(op, stateKey, { value: state });
382
444
  return state;
@@ -389,27 +451,59 @@ const runWith = (
389
451
  ): Effect.Effect<any, any, any> => {
390
452
  if (protocol.call !== undefined) return protocol.call(p, input);
391
453
  const { cfg, inputAst, outputAst, errors } = p;
392
- return Effect.flatMap(HttpClient.HttpClient, (client) =>
393
- Effect.flatMap(protocol.encode({ input, inputAst, config: cfg }), (request) =>
394
- Effect.flatMap(client.execute(request), (response) =>
454
+ return Effect.withFiber((fiber) => {
455
+ const context = fiber.context as Context.Context<any>;
456
+ const client = Context.get(context, HttpClient.HttpClient);
457
+ return Effect.flatMap(protocol.encode({ input, inputAst, config: cfg }), (request) =>
458
+ Effect.flatMap(Telemetry.execute(context, client, request), (response) =>
395
459
  protocol.decode({ response, outputAst, errors, config: cfg }),
396
460
  ),
397
- ),
398
- );
461
+ );
462
+ });
399
463
  };
400
464
 
401
- const callOperation = (state: OperationState, input: unknown): Effect.Effect<any, any, any> => {
465
+ const callUntraced = (
466
+ state: OperationState,
467
+ input: unknown,
468
+ debug: Telemetry.DebugHooks | undefined,
469
+ ): Effect.Effect<any, any, any> => {
402
470
  // Warm path: the operation is prepared and its protocol built, so the call
403
471
  // is whatever the protocol returns, with no wrapper effects around it.
404
472
  const p = state.prepared;
405
- if (p?.service !== undefined) return applyRetry(runWith(p, p.service, input), p.cfg.retry);
473
+ if (p?.service !== undefined) return applyRetry(runWith(p, p.service, input), p.cfg.retry, debug);
406
474
  return Effect.suspend(() => {
407
475
  const prepared = prepare(state);
408
- const call = Effect.flatMap(protocolContext(prepared.cfg.protocol), (protocolCtx) => {
409
- const service = (prepared.service = Context.get(protocolCtx, Protocol));
410
- return runWith(prepared, service, input);
411
- });
412
- return applyRetry(call, prepared.cfg.retry);
476
+ const call = Effect.flatMap(
477
+ debug === undefined
478
+ ? protocolContext(prepared.cfg.protocol)
479
+ : debug.phase("distilled.setup", protocolContext(prepared.cfg.protocol), {
480
+ "distilled.setup.first_call": true,
481
+ }),
482
+ (protocolCtx) => {
483
+ const service = (prepared.service = Context.get(protocolCtx, Protocol));
484
+ return runWith(prepared, service, input);
485
+ },
486
+ );
487
+ return applyRetry(call, prepared.cfg.retry, debug);
488
+ });
489
+ };
490
+
491
+ /**
492
+ * BRAINSTORM: the call in its operation span (recorded only when an
493
+ * exporter is installed), whose stack frame is the caller (captured here,
494
+ * synchronously, while the caller is still on the JS stack).
495
+ */
496
+ const callOperation = (
497
+ state: OperationState,
498
+ input: unknown,
499
+ entry: Function,
500
+ ): Effect.Effect<any, any, any> => {
501
+ const callSite = Telemetry.captureCallSite(entry);
502
+ return Effect.withFiber((fiber) => {
503
+ const debug = fiber.getRef(Telemetry.Debug);
504
+ return Telemetry.operationSpan(fiber, debug, infoOf(prepare(state)), callSite, input, (sent) =>
505
+ callUntraced(state, sent, debug),
506
+ );
413
507
  });
414
508
  };
415
509
 
@@ -474,7 +568,7 @@ const OperationProto: object = /*@__PURE__*/ Object.setPrototypeOf(
474
568
  );
475
569
 
476
570
  const makeOperation = (state: OperationState, proto: object): any => {
477
- const fn = (input: unknown) => callOperation(state, input);
571
+ const fn = (input: unknown) => callOperation(state, input, fn);
478
572
  defineState(fn, state);
479
573
  return Object.setPrototypeOf(fn, proto);
480
574
  };
@@ -571,7 +665,12 @@ const streamsOf = (state: OperationState, call: (input: any) => Effect.Effect<an
571
665
  const pages = (input: Record<string, unknown>) => paginate(call, input, pag());
572
666
  const items = (input: Record<string, unknown>) => {
573
667
  const p = pag();
574
- return p.items ? Pagination.extractItems(pages(input), p.items) : pages(input);
668
+ if (!p.items) return pages(input);
669
+ // A bare-array response's schema is its sole member's value
670
+ // (`RawResponseRoot`), so the member `items` names is the page itself.
671
+ return getAnn(prepare(state).outputAst, rawResponseRootSymbol) !== undefined
672
+ ? Pagination.extractArrayItems(pages(input))
673
+ : Pagination.extractItems(pages(input), p.items);
575
674
  };
576
675
  return { pages, items };
577
676
  };
@@ -830,7 +929,7 @@ export const opPaginated = (fn: DataFn): any => (definer ? definer(fn, 1) : asOp
830
929
 
831
930
  /** The call path of a data operation. */
832
931
  export const call = (op: unknown, input: unknown): Effect.Effect<any, any, any> =>
833
- callOperation(stateOf(op), input);
932
+ callOperation(stateOf(op), input, op as Function);
834
933
 
835
934
  /**
836
935
  * Generated error classes described by data:
@@ -1272,7 +1371,7 @@ export const lazyService = (
1272
1371
  len?: number,
1273
1372
  ): { readonly o: () => any; readonly e: (name: string) => any; readonly E: any } => {
1274
1373
  const svc: LazyService = { url, spec, kinds, ns, at, len, o: [], e: [], oi: 0, ei: 0 };
1275
- if (!primed && at !== undefined && !(globalThis as any).process?.env?.NOPRIME) prime(svc);
1374
+ if (!primed && at !== undefined) prime(svc);
1276
1375
  return {
1277
1376
  o: () => {
1278
1377
  const paginated = kinds[svc.o.length] === "p";
package/src/category.ts CHANGED
@@ -320,19 +320,19 @@ const makeCatcher =
320
320
  * )
321
321
  * ```
322
322
  */
323
- export const catchErrors =
324
- <Categories extends Category[], A2, E2, R2>(
325
- ...args: [...Categories, (err: any) => Effect.Effect<A2, E2, R2>]
326
- ) =>
327
- <A, E, R>(effect: Effect.Effect<A, E, R>) => {
328
- const handler = args.pop() as (err: any) => Effect.Effect<A2, E2, R2>;
329
- const categories = args as unknown as Categories;
330
- return Effect.catchIf(
323
+ export const catchErrors = <Categories extends Category[], A2, E2, R2>(
324
+ ...args: [...Categories, (err: any) => Effect.Effect<A2, E2, R2>]
325
+ ) => {
326
+ // Split once, without mutating `args`, so one catcher can be reused.
327
+ const handler = args[args.length - 1] as (err: any) => Effect.Effect<A2, E2, R2>;
328
+ const categories = args.slice(0, -1) as unknown as Categories;
329
+ return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
330
+ Effect.catchIf(
331
331
  effect,
332
332
  (e) => categories.some((cat) => hasCategory(e, cat)),
333
333
  handler,
334
334
  ) as Effect.Effect<A | A2, E | E2, R | R2>;
335
- };
335
+ };
336
336
 
337
337
  // Alias for convenience
338
338
  export { catchErrors as catch };
@@ -364,19 +364,18 @@ export const catchDependencyViolationError = /*@__PURE__*/ makeCatcher(Dependenc
364
364
  * )
365
365
  * ```
366
366
  */
367
- export const catchCategory =
368
- <E, const Categories extends Array<AllKeys<E>>, A2, E2, R2>(
369
- ...args: [
370
- ...Categories,
371
- f: (err: ExtractAll<E, Categories[number]>) => Effect.Effect<A2, E2, R2>,
372
- ]
373
- ) =>
374
- <A, R>(
367
+ export const catchCategory = <E, const Categories extends Array<AllKeys<E>>, A2, E2, R2>(
368
+ ...args: [...Categories, f: (err: ExtractAll<E, Categories[number]>) => Effect.Effect<A2, E2, R2>]
369
+ ) => {
370
+ // Split once, without mutating `args`, so one catcher can be reused.
371
+ const f = args[args.length - 1] as (
372
+ err: ExtractAll<E, Categories[number]>,
373
+ ) => Effect.Effect<A2, E2, R2>;
374
+ const categories = args.slice(0, -1) as unknown as Categories;
375
+ return <A, R>(
375
376
  effect: Effect.Effect<A, E, R>,
376
- ): Effect.Effect<A | A2, E2 | Exclude<E, ExtractAll<E, Categories[number]>>, R | R2> => {
377
- const f = args.pop()!;
378
- const categories = args;
379
- return Effect.catchIf(
377
+ ): Effect.Effect<A | A2, E2 | Exclude<E, ExtractAll<E, Categories[number]>>, R | R2> =>
378
+ Effect.catchIf(
380
379
  effect,
381
380
  (e) => {
382
381
  if (Predicate.isObject(e) && Predicate.hasProperty(categoriesKey)(e)) {
@@ -392,4 +391,4 @@ export const catchCategory =
392
391
  // @ts-expect-error - type narrowing limitation
393
392
  (e) => f(e),
394
393
  ) as any;
395
- };
394
+ };
package/src/config.ts CHANGED
@@ -13,8 +13,9 @@
13
13
  * - Otherwise the value comes from `process.env`, which is what Effect's
14
14
  * default provider reads.
15
15
  *
16
- * A missing variable fails with {@link ConfigMissing} (tag `ConfigError`, like
17
- * Effect's), which `withDefault`, `option` and `orElse` handle.
16
+ * A missing variable fails with {@link ConfigError} (with its `key`), which `withDefault`, `option` and `orElse` handle. A provided
17
+ * `ConfigProvider` that cannot read its source fails with its `SourceError`,
18
+ * which those helpers pass through.
18
19
  *
19
20
  * Credentials read these on every request, so without a provider a whole
20
21
  * reader tree (`all`, `withDefault`, `orElse`, ...) runs as one synchronous
@@ -23,25 +24,30 @@
23
24
  * A missing value inside the tree is a plain marker; the tagged error is
24
25
  * only built if the whole tree fails.
25
26
  */
27
+ import type { SourceError } from "effect/ConfigProvider";
26
28
  import * as Context from "effect/Context";
27
- import * as Data from "effect/Data";
28
29
  import * as Effect from "effect/Effect";
29
30
  import * as Option from "effect/Option";
30
31
  import * as Redact from "effect/Redacted";
32
+ import * as Category from "./category.ts";
33
+ import * as Schema from "./schema-lite-typed.ts";
31
34
 
32
- /** A required configuration value is missing. */
33
- export class ConfigMissing
34
- extends /*@__PURE__*/ Data.TaggedError("ConfigError")<{
35
- readonly name: string;
36
- readonly message: string;
37
- }> {}
35
+ /**
36
+ * Configuration error - missing or invalid configuration. `key` is the
37
+ * configuration value (e.g. an environment variable) when one is missing.
38
+ */
39
+ export class ConfigError
40
+ extends /*@__PURE__*/ Schema.TaggedError<ConfigError>()("ConfigError", {
41
+ message: Schema.String,
42
+ key: /*@__PURE__*/ Schema.optional(Schema.String),
43
+ }).pipe(Category.withConfigurationError) {}
38
44
 
39
45
  const CONFIG_PROVIDER_KEY = "effect/ConfigProvider";
40
46
 
41
47
  interface ProvidedConfigProvider {
42
48
  readonly load: (
43
49
  path: ReadonlyArray<string>,
44
- ) => Effect.Effect<{ readonly _tag: string; readonly value?: string } | undefined, unknown>;
50
+ ) => Effect.Effect<{ readonly _tag: string; readonly value?: string } | undefined, SourceError>;
45
51
  }
46
52
 
47
53
  const fromEnv = (name: string): string | undefined =>
@@ -81,7 +87,7 @@ const hasProvider = (context: Context.Context<never>): boolean =>
81
87
  Context.getOrUndefined(context, providerKey) !== undefined;
82
88
 
83
89
  const missingError = (m: Missing) =>
84
- new ConfigMissing({ name: m.name, message: `Expected ${m.name} to be set` });
90
+ new ConfigError({ key: m.name, message: `Expected ${m.name} to be set` });
85
91
 
86
92
  const fromReader = <A>(reader: Reader<A>): Effect.Effect<A, any, any> => {
87
93
  const effect = Effect.withFiber((fiber) => {
@@ -94,41 +100,62 @@ const fromReader = <A>(reader: Reader<A>): Effect.Effect<A, any, any> => {
94
100
  return effect;
95
101
  };
96
102
 
97
- /** The raw value of `name` from the provided `ConfigProvider`, or undefined when unset. */
98
- const lookup = (name: string): Effect.Effect<string | undefined> =>
103
+ /**
104
+ * The raw value of `name` from the provided `ConfigProvider`, or undefined
105
+ * when unset. A provider that cannot read its source fails with `SourceError`.
106
+ */
107
+ const lookup = (name: string): Effect.Effect<string | undefined, SourceError> =>
99
108
  Effect.flatMap(Effect.context<never>(), (context) => {
100
109
  const provider = context.mapUnsafe.get(CONFIG_PROVIDER_KEY) as
101
110
  | ProvidedConfigProvider
102
111
  | undefined;
103
112
  if (!provider) return Effect.succeed(fromEnv(name));
104
- return provider.load([name]).pipe(
105
- Effect.map((node) => (node?._tag === "Value" ? node.value : undefined)),
106
- Effect.orElseSucceed(() => undefined),
113
+ return Effect.map(provider.load([name]), (node) =>
114
+ node?._tag === "Value" ? node.value : undefined,
107
115
  );
108
116
  });
109
117
 
110
- const required = (name: string): Effect.Effect<string, ConfigMissing> =>
118
+ const required = (name: string): Effect.Effect<string, ConfigError | SourceError> =>
111
119
  fromReader({
112
120
  read: () => fromEnv(name) ?? new Missing(name),
113
121
  viaEffect: () =>
114
122
  Effect.flatMap(lookup(name), (value) =>
115
123
  value === undefined ? Effect.fail(missingError(new Missing(name))) : Effect.succeed(value),
116
124
  ),
117
- }) as Effect.Effect<string, ConfigMissing>;
125
+ }) as Effect.Effect<string, ConfigError | SourceError>;
118
126
 
119
127
  /** The string value of environment variable `name`. */
120
- export const String = (name: string): Effect.Effect<string, ConfigMissing> => required(name);
128
+ export const String = (name: string): Effect.Effect<string, ConfigError | SourceError> =>
129
+ required(name);
121
130
 
122
131
  /** The value of `name`, redacted. */
123
- export const Redacted = (name: string): Effect.Effect<Redact.Redacted<string>, ConfigMissing> =>
132
+ export const Redacted = (
133
+ name: string,
134
+ ): Effect.Effect<Redact.Redacted<string>, ConfigError | SourceError> =>
124
135
  map((value: string) => Redact.make(value))(required(name));
125
136
 
137
+ /**
138
+ * The failure of a missing value: {@link ConfigError}, matched by its tag
139
+ * (Effect's own config errors share it). `option`, `withDefault` and `orElse` handle
140
+ * only this failure; any other failure of `self` propagates.
141
+ */
142
+ type Missed = { readonly _tag: "ConfigError" };
143
+
144
+ const isMissed = (error: unknown): boolean =>
145
+ typeof error === "object" && error !== null && (error as Missed)._tag === "ConfigError";
146
+
147
+ const catchMissed = <A, E, R, A2, E2, R2>(
148
+ self: Effect.Effect<A, E, R>,
149
+ f: () => Effect.Effect<A2, E2, R2>,
150
+ ): Effect.Effect<A | A2, Exclude<E, Missed> | E2, R | R2> =>
151
+ Effect.catchIf(self, isMissed, f) as Effect.Effect<A | A2, Exclude<E, Missed> | E2, R | R2>;
152
+
126
153
  /** The value as an `Option`: `None` when missing. */
127
154
  export const option = <A, E, R>(
128
155
  self: Effect.Effect<A, E, R>,
129
- ): Effect.Effect<Option.Option<A>, never, R> => {
156
+ ): Effect.Effect<Option.Option<A>, Exclude<E, Missed>, R> => {
130
157
  const viaEffect = () =>
131
- Effect.catch(Effect.map(self, Option.some), () => Effect.succeed(Option.none<A>()));
158
+ catchMissed(Effect.map(self, Option.some), () => Effect.succeed(Option.none<A>()));
132
159
  const reader = readerOf(self);
133
160
  if (!reader) return viaEffect();
134
161
  return fromReader({
@@ -138,14 +165,14 @@ export const option = <A, E, R>(
138
165
  return value instanceof Missing ? Option.none<A>() : Option.some(value);
139
166
  },
140
167
  viaEffect,
141
- }) as Effect.Effect<Option.Option<A>, never, R>;
168
+ }) as Effect.Effect<Option.Option<A>, Exclude<E, Missed>, R>;
142
169
  };
143
170
 
144
171
  /** Use `value` when missing. */
145
172
  export const withDefault =
146
173
  <B>(value: B) =>
147
- <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A | B, never, R> => {
148
- const viaEffect = () => Effect.catch(self, () => Effect.succeed(value));
174
+ <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A | B, Exclude<E, Missed>, R> => {
175
+ const viaEffect = () => catchMissed(self, () => Effect.succeed(value));
149
176
  const reader = readerOf(self);
150
177
  if (!reader) return viaEffect();
151
178
  return fromReader<A | B>({
@@ -154,14 +181,16 @@ export const withDefault =
154
181
  return v instanceof Missing ? value : v;
155
182
  },
156
183
  viaEffect,
157
- }) as Effect.Effect<A | B, never, R>;
184
+ }) as Effect.Effect<A | B, Exclude<E, Missed>, R>;
158
185
  };
159
186
 
160
187
  /** Try `that` when missing. */
161
188
  export const orElse =
162
189
  <A2, E2, R2>(that: () => Effect.Effect<A2, E2, R2>) =>
163
- <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A | A2, E2, R | R2> => {
164
- const viaEffect = () => Effect.catch(self, () => that());
190
+ <A, E, R>(
191
+ self: Effect.Effect<A, E, R>,
192
+ ): Effect.Effect<A | A2, Exclude<E, Missed> | E2, R | R2> => {
193
+ const viaEffect = () => catchMissed(self, that);
165
194
  const reader = readerOf(self);
166
195
  if (!reader) return viaEffect();
167
196
  return fromReader<A | A2>({
@@ -172,7 +201,7 @@ export const orElse =
172
201
  return fallback ? fallback.read() : DEFER;
173
202
  },
174
203
  viaEffect,
175
- }) as Effect.Effect<A | A2, E2, R | R2>;
204
+ }) as Effect.Effect<A | A2, Exclude<E, Missed> | E2, R | R2>;
176
205
  };
177
206
 
178
207
  export const map =
package/src/debug.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  /**
2
- * `DISTILLED_DEBUG_HTTP`, read once. Protocols check it on every request,
3
- * and a `process.env` read is a C++ getter call: about 1 us each.
2
+ * Whether the call running on this fiber logs its requests and responses to
3
+ * stderr (`[distilled] -> GET /zones/{zone_id}`, `[distilled] <- 200 ...`):
4
+ * `TelemetryDebug.layerWith({ logRequests: true })` from
5
+ * `./telemetry-debug.ts`. Protocols check it on every request; outside a
6
+ * fiber, or without that layer, it is false.
4
7
  */
5
- let flag: boolean | undefined;
6
- export const debugHttp = (): boolean =>
7
- (flag ??= !!(globalThis as { process?: { env?: Record<string, string | undefined> } }).process
8
- ?.env?.DISTILLED_DEBUG_HTTP);
8
+ import * as Fiber from "effect/Fiber";
9
+ import { Debug } from "./telemetry.ts";
10
+
11
+ export const debugHttp = (): boolean => Fiber.getCurrent()?.getRef(Debug)?.logRequests === true;
@@ -56,18 +56,16 @@ export const hasAnyCategory =
56
56
  return false;
57
57
  };
58
58
 
59
- export const catchCategory =
60
- <E, const Categories extends Array<AllKeys<E>>, A2, E2, R2>(
61
- ...args: [
62
- ...Categories,
63
- f: (err: ExtractAll<E, Categories[number]>) => Effect.Effect<A2, E2, R2>,
64
- ]
65
- ) =>
66
- <A, R>(
59
+ export const catchCategory = <E, const Categories extends Array<AllKeys<E>>, A2, E2, R2>(
60
+ ...args: [...Categories, f: (err: ExtractAll<E, Categories[number]>) => Effect.Effect<A2, E2, R2>]
61
+ ) => {
62
+ // Split once, without mutating `args`, so one catcher can be reused.
63
+ const f = args[args.length - 1] as (
64
+ err: ExtractAll<E, Categories[number]>,
65
+ ) => Effect.Effect<A2, E2, R2>;
66
+ const matches = hasAnyCategory(...(args.slice(0, -1) as Array<PropertyKey>));
67
+ return <A, R>(
67
68
  effect: Effect.Effect<A, E, R>,
68
- ): Effect.Effect<A | A2, E2 | Exclude<E, ExtractAll<E, Categories[number]>>, R | R2> => {
69
- const f = args.pop()! as (err: ExtractAll<E, Categories[number]>) => Effect.Effect<A2, E2, R2>;
70
- const categories = args as Array<PropertyKey>;
71
- const matches = hasAnyCategory(...categories);
72
- return Effect.catchIf(effect, matches, (e) => f(e as ExtractAll<E, Categories[number]>)) as any;
73
- };
69
+ ): Effect.Effect<A | A2, E2 | Exclude<E, ExtractAll<E, Categories[number]>>, R | R2> =>
70
+ Effect.catchIf(effect, matches, (e) => f(e as ExtractAll<E, Categories[number]>)) as any;
71
+ };
package/src/errors.ts CHANGED
@@ -139,13 +139,13 @@ export class GatewayTimeout
139
139
  retryAfter: /*@__PURE__*/ Schema.optional(DurationSchema),
140
140
  }).pipe(Category.withServerError, /*@__PURE__*/ Category.withRetryable()) {}
141
141
 
142
- /**
143
- * Configuration error - missing or invalid configuration.
144
- */
145
- export class ConfigError
146
- extends /*@__PURE__*/ Schema.TaggedError<ConfigError>()("ConfigError", {
147
- message: Schema.String,
148
- }).pipe(Category.withConfigurationError) {}
142
+ // Defined with the config readers (core's `base` bundle group, which every
143
+ // program loads) so they can fail with it without importing this module.
144
+ export { ConfigError } from "./config.ts";
145
+
146
+ // Defined with the label check (`protocol-http.ts`), so protocols can fail
147
+ // with it without importing every class in this module.
148
+ export { InvalidInput } from "./protocol-http.ts";
149
149
 
150
150
  // ============================================================================
151
151
  // Error Maps