@wardic/core 1.0.0 → 1.1.0

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 (52) hide show
  1. package/dist/Batch.d.ts +4 -2
  2. package/dist/Batch.d.ts.map +1 -1
  3. package/dist/Batch.js +80 -13
  4. package/dist/Batch.js.map +1 -1
  5. package/dist/DefaultTransition.d.ts.map +1 -1
  6. package/dist/DefaultTransition.js +1 -1
  7. package/dist/DefaultTransition.js.map +1 -1
  8. package/dist/LiveValue.d.ts +61 -0
  9. package/dist/LiveValue.d.ts.map +1 -1
  10. package/dist/LiveValue.js +79 -5
  11. package/dist/LiveValue.js.map +1 -1
  12. package/dist/Machine.d.ts +10 -1
  13. package/dist/Machine.d.ts.map +1 -1
  14. package/dist/Machine.js +18 -1
  15. package/dist/Machine.js.map +1 -1
  16. package/dist/Renderer.js +2 -2
  17. package/dist/Renderer.js.map +1 -1
  18. package/dist/Reorder.d.ts +4 -2
  19. package/dist/Reorder.d.ts.map +1 -1
  20. package/dist/Reorder.js +32 -9
  21. package/dist/Reorder.js.map +1 -1
  22. package/dist/Spans.d.ts +41 -0
  23. package/dist/Spans.d.ts.map +1 -0
  24. package/dist/Spans.js +39 -0
  25. package/dist/Spans.js.map +1 -0
  26. package/dist/index.d.ts +1 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +1 -0
  29. package/dist/index.js.map +1 -1
  30. package/dist/internal/frameLoop.d.ts +1 -1
  31. package/dist/internal/frameLoop.d.ts.map +1 -1
  32. package/dist/internal/frameLoop.js +42 -19
  33. package/dist/internal/frameLoop.js.map +1 -1
  34. package/dist/internal/options.d.ts.map +1 -1
  35. package/dist/internal/options.js +2 -2
  36. package/dist/internal/options.js.map +1 -1
  37. package/dist/internal/tracing.d.ts +34 -14
  38. package/dist/internal/tracing.d.ts.map +1 -1
  39. package/dist/internal/tracing.js +56 -24
  40. package/dist/internal/tracing.js.map +1 -1
  41. package/package.json +1 -1
  42. package/src/Batch.ts +68 -12
  43. package/src/DefaultTransition.ts +1 -1
  44. package/src/LiveValue.ts +129 -5
  45. package/src/Machine.ts +22 -1
  46. package/src/Renderer.ts +2 -2
  47. package/src/Reorder.ts +44 -9
  48. package/src/Spans.ts +50 -0
  49. package/src/index.ts +1 -0
  50. package/src/internal/frameLoop.ts +44 -20
  51. package/src/internal/options.ts +2 -2
  52. package/src/internal/tracing.ts +82 -28
package/src/Machine.ts CHANGED
@@ -701,7 +701,8 @@ export const clampDt: {
701
701
 
702
702
  /**
703
703
  * `self` under the span `name`, with `options.attributes`, in place of its own: its runs' traces and
704
- * logs carry that name.
704
+ * logs carry that name, in the spans its runs open when the app gives `Spans.layer` (`WardicSpans`)
705
+ * and a tracer reads them.
705
706
  *
706
707
  * @example
707
708
  * const bounce = Machine.spring(1).pipe(Machine.withSpan("app.bounce", { attributes: { card: id } }))
@@ -1669,3 +1670,23 @@ export const keyframesValues: (
1669
1670
  })
1670
1671
  },
1671
1672
  )
1673
+
1674
+ /** `nextFrame`'s one Frame: settled at its first step. */
1675
+ const SETTLED_AT_ONCE: Frame.Frame<number> = { value: 0, done: true }
1676
+
1677
+ /** `nextFrame`'s sink: it keeps nothing. */
1678
+ const keepNothing = (): undefined => undefined
1679
+
1680
+ /**
1681
+ * Succeeds at the Frame loop's next tick, once its runs have stepped: a run of one Frame, settled at its
1682
+ * first step. It keeps the loop ticking for that one tick, though nothing else runs. Added in a tick's Late
1683
+ * window, it succeeds in that tick's Late round. Interrupted first, it leaves the loop at once.
1684
+ *
1685
+ * @internal
1686
+ */
1687
+ // #714: for a binding's write that must wait a frame on the Frame loop, as a Batch Reorder group's own size
1688
+ // does. Here, not beside `LiveValue.eachFrame`: every app that animates has `Machine`, where importing
1689
+ // `LiveValue` cost a Batch Reorder app 3.6 KB gzipped (ADR-0072, *Amendment (#714)*, decision 5).
1690
+ export const nextFrame: Effect.Effect<void, never, FrameLoop.FrameLoop> = /*#__PURE__*/ Effect.asVoid(
1691
+ /*#__PURE__*/ run(/*#__PURE__*/ make({ settles: true, span: { name: "wardic.nextFrame", attributes: {} }, start: () => () => SETTLED_AT_ONCE }), keepNothing),
1692
+ )
package/src/Renderer.ts CHANGED
@@ -57,11 +57,11 @@ export const applyTo: {
57
57
  stream: Stream.Stream<Frame.Frame<Record<string, unknown>>, E, R>,
58
58
  ) => Effect.Effect<void, E, R | Renderer>
59
59
  <T, E, R>(stream: Stream.Stream<Frame.Frame<Record<string, unknown>>, E, R>, target: T): Effect.Effect<void, E, R | Renderer>
60
- } = dual(
60
+ } = /*#__PURE__*/ dual(
61
61
  // The target is any value: told apart by the stream (#460).
62
62
  Stream.isStream,
63
63
  // Not `Effect.fn`, which always captures a call-site stack (ADR-0040, decision 2).
64
- Effect.fnUntraced(
64
+ /*#__PURE__*/ Effect.fnUntraced(
65
65
  function* <T, E, R>(stream: Stream.Stream<Frame.Frame<Record<string, unknown>>, E, R>, target: T): Effect.fn.Return<void, E, R | Renderer> {
66
66
  yield* Effect.annotateCurrentSpan({ target: typeof target })
67
67
  const renderer = yield* Renderer
package/src/Reorder.ts CHANGED
@@ -84,8 +84,10 @@ const indexOf = <V>(order: ReadonlyArray<ItemData<V>>, value: V): Option.Option<
84
84
  * The order after the item holding `value` has been dragged `offset` from its place, moving at
85
85
  * `velocity`: the rule for when a dragged item swaps places. The same `order` when nothing moves, so a
86
86
  * caller can compare by reference.
87
- * - **One axis** moves the item one place at most: toward the neighbour, of the two next to it, whose
88
- * centre lies the way it's moving, once its edge facing that neighbour crosses the neighbour's centre.
87
+ * - **One axis** moves the item toward the neighbour, of the two next to it, whose centre lies the way
88
+ * it's moving, once its edge facing that neighbour crosses the neighbour's centre, and on past each
89
+ * further item on that side whose centre the edge has crossed too, as one-place moves would over many
90
+ * samples: a sample that carries it several places, as Auto-scroll can, leaves no order trailing it.
89
91
  * No velocity on the axis moves nothing.
90
92
  * - **A grid** (`"xy"`), as Motion's: the dragged centre picks the nearest row. In another row, the item
91
93
  * goes before the first item whose centre is past it in `direction`; in its own, it steps one place
@@ -144,20 +146,53 @@ const checkReorderOnAxis = <V>(
144
146
  const centre = centreOf(own)
145
147
  const neighbour = (n: number) =>
146
148
  Option.map(centreOnSide(order, n, axis, centre, forward), (nextCentre) => [n, nextCentre] as const)
149
+ // The item's edge facing the way it moves, where the drag holds it.
150
+ const edge = Bool.match(forward, { onTrue: () => own.max + offset[axis], onFalse: () => own.min + offset[axis] })
151
+ const passes = (nextCentre: number): boolean => Bool.match(forward, { onTrue: () => edge > nextCentre, onFalse: () => edge < nextCentre })
147
152
  // The neighbour on the side the item moves toward: index - 1, else index + 1.
148
153
  return Option.match(Option.orElse(neighbour(index - 1), () => neighbour(index + 1)), {
149
154
  onNone: () => order,
150
- onSome: ([n, nextCentre]) => {
151
- const crossed = Bool.match(forward, {
152
- onTrue: () => own.max + offset[axis] > nextCentre,
153
- onFalse: () => own.min + offset[axis] < nextCentre,
154
- })
155
- return Bool.match(crossed, { onTrue: () => moveItem(order, index, n), onFalse: () => order })
156
- },
155
+ onSome: ([n, nextCentre]) =>
156
+ Bool.match(passes(nextCentre), {
157
+ onTrue: () => moveItem(order, index, farthestPassed(order, index, n - index, axis, centre, forward, passes)),
158
+ onFalse: () => order,
159
+ }),
157
160
  })
158
161
  },
159
162
  })
160
163
 
164
+ /**
165
+ * Past the neighbour at `index + step`, the farthest place on that side whose centre the item's edge has
166
+ * passed too: where one-place moves, each over the order laid out again, would take it, since the items past
167
+ * the ones it passes stay where they were. A sample can carry the item past several, as Auto-scroll past a
168
+ * scroller's edge does; a place a sample would leave the order trailing the item, and its release there.
169
+ */
170
+ // Per drag sample (an input event): Arr's searches from the dragged index, no copy of the order.
171
+ const farthestPassed = <V>(
172
+ order: ReadonlyArray<ItemData<V>>,
173
+ index: number,
174
+ step: number,
175
+ axis: "x" | "y",
176
+ centre: number,
177
+ forward: boolean,
178
+ passes: (nextCentre: number) => boolean,
179
+ ): number => {
180
+ /** Whether the item at `i`, past the dragged one on the walk's side, stops the walk: its centre not passed. */
181
+ const stops = (_: ItemData<V>, i: number): boolean =>
182
+ Bool.match(Bool.match(step > 0, { onTrue: () => i > index, onFalse: () => i < index }), {
183
+ onTrue: () =>
184
+ Option.match(centreOnSide(order, i, axis, centre, forward), {
185
+ onNone: () => true,
186
+ onSome: (c) => Bool.not(passes(c)),
187
+ }),
188
+ onFalse: () => false,
189
+ })
190
+ return Bool.match(step > 0, {
191
+ onTrue: () => Option.match(Arr.findFirstIndex(order, stops), { onNone: () => order.length - 1, onSome: (stop) => stop - 1 }),
192
+ onFalse: () => Option.match(Arr.findLastIndex(order, stops), { onNone: () => 0, onSome: (stop) => stop + 1 }),
193
+ })
194
+ }
195
+
161
196
  /** `order[n]`'s centre on `axis` if it lies past `centre` in the direction of motion, else NaN. */
162
197
  const centreOnSide = <V>(
163
198
  order: ReadonlyArray<ItemData<V>>,
package/src/Spans.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Wardic's spans, an app's to give: with {@link layer} and a tracer installed (the devtools', an
3
+ * OpenTelemetry exporter's), each animation runs in a span named for what it is, and each burst of
4
+ * frames, gesture, layout pass and exit in one of its own. Without `layer`, Wardic opens none, and an
5
+ * app ships none of their code. With `layer` and no tracer, it opens none either.
6
+ *
7
+ * @example
8
+ * const env = Layer.mergeAll(DomLive, devtools, Spans.layer)
9
+ *
10
+ * @module
11
+ */
12
+ // #746, ADR-0067 *Amendment (#746)*, decision 8: the span code was every app's, a tracer or not (Effect
13
+ // 4.1.4's runtime no longer keeps `Tracer` and `Hex`; opening a span brings them). What opens them is a
14
+ // Reference in `internal/tracing.ts`, as `FrameLoop`'s metrics are given (#518): its default opens none.
15
+ import * as Effect from "effect/Effect"
16
+ import * as Layer from "effect/Layer"
17
+ import { dual } from "./internal/dual.ts"
18
+ import * as internal from "./internal/tracing.ts"
19
+
20
+ /** A span's options: its attributes, and whether it's a root, with no parent. */
21
+ export interface Options {
22
+ readonly attributes?: Readonly<Record<string, unknown>> | undefined
23
+ readonly root?: boolean | undefined
24
+ }
25
+
26
+ /**
27
+ * Wardic's spans, given: merged beside an Environment, each animation, burst of frames, gesture,
28
+ * layout pass and exit opens its span under the tracer installed. `@wardic/dom` gives it as
29
+ * `WardicSpans`.
30
+ */
31
+ export const layer: Layer.Layer<never> = /*#__PURE__*/ Layer.succeed(internal.SpansGiven, internal.opening)
32
+
33
+ /**
34
+ * `self` under the span `name`, opened as Wardic's own are: when the app gives {@link layer} and a
35
+ * tracer reads it, with no call-site stack. As it is otherwise. For a binding's own spans.
36
+ *
37
+ * @example
38
+ * const measured = pass.pipe(Spans.withSpan("app.measure", { attributes: { nodes: 3 } }))
39
+ */
40
+ // `dual` as `Effect.withSpan` is, told apart by its first argument.
41
+ export const withSpan: {
42
+ (name: string, options?: Options): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
43
+ <A, E, R>(self: Effect.Effect<A, E, R>, name: string, options?: Options): Effect.Effect<A, E, R>
44
+ } = /*#__PURE__*/ dual(Effect.isEffect, internal.traced)
45
+
46
+ /**
47
+ * Whether a tracer reads the running fiber's spans while the app gives no {@link layer}: what a
48
+ * binding warns of in development, as it builds its Environment.
49
+ */
50
+ export const missing: Effect.Effect<boolean> = internal.missing
package/src/index.ts CHANGED
@@ -51,6 +51,7 @@ export * as Scalar from "./Scalar.ts"
51
51
  export * as ScrollSource from "./ScrollSource.ts"
52
52
  export * as Sequence from "./Sequence.ts"
53
53
  export * as SharedSource from "./SharedSource.ts"
54
+ export * as Spans from "./Spans.ts"
54
55
  export * as Spring from "./Spring.ts"
55
56
  export * as Stagger from "./Stagger.ts"
56
57
  export * as Supersede from "./Supersede.ts"
@@ -11,7 +11,7 @@
11
11
  * given a token (`run(machine, sink, { supersede })`, #200) joins it, and `Supersede.end` takes
12
12
  * it off at once too, completing its fiber with `Superseded`: no interrupt, and no interrupt
13
13
  * cause for every finalizer to combine (ADR-0027, *Amendment (#200)*).
14
- * - **A burst** is the loop's one `Clock.ticks` subscription, held in a `FiberHandle` and forked
14
+ * - **A burst** is the loop's one `Clock.ticks` subscription, held in a field of the loop's (#746) and forked
15
15
  * under the Layer's build context (never a caller's scheduler or span, the Clock's own rule,
16
16
  * ADR-0017). The first run starts it; it ends itself at the first tick with nothing left, so
17
17
  * a Retarget (a removal, then an add, in one call) keeps it, and the Clock goes idle at its
@@ -64,8 +64,7 @@ import * as Data from "effect/Data"
64
64
  import * as Deferred from "effect/Deferred"
65
65
  import * as Effect from "effect/Effect"
66
66
  import * as Exit from "effect/Exit"
67
- import type * as Fiber from "effect/Fiber"
68
- import * as FiberHandle from "effect/FiberHandle"
67
+ import * as Fiber from "effect/Fiber"
69
68
  import { constUndefined, identity } from "effect/Function"
70
69
  import * as LogLevel from "effect/LogLevel"
71
70
  import type * as Metric from "effect/Metric"
@@ -74,14 +73,14 @@ import * as Predicate from "effect/Predicate"
74
73
  import * as References from "effect/References"
75
74
  import type * as Scope from "effect/Scope"
76
75
  import * as Stream from "effect/Stream"
77
- import * as Tracer from "effect/Tracer"
76
+ import type * as Tracer from "effect/Tracer"
78
77
  import * as UndefinedOr from "effect/UndefinedOr"
79
78
  import * as Clock from "../Clock.ts"
80
79
  import type * as Frame from "../Frame.ts"
81
80
  import * as Supersede from "../Supersede.ts"
82
81
  import type * as FrameLoop from "../FrameLoop.ts"
83
82
  import type * as Machine from "../Machine.ts"
84
- import { isTraced, traced } from "./tracing.ts"
83
+ import { none, SpansGiven, traced } from "./tracing.ts"
85
84
 
86
85
  // @wardic/core compiles against ES2022 alone, which does not declare `performance` (see
87
86
  // refresh-frame-clock.ts). It is a host global in every Environment Wardic targets.
@@ -280,9 +279,12 @@ const joinSupersede = (token: Supersede.Supersede, run: Supersede.Run): void =>
280
279
  runs.push(run)
281
280
  }
282
281
 
282
+ /** A burst's fork: started at once, inline, as `FiberHandle.run` started it (#746). */
283
+ const START_NOW = { startImmediately: true } as const
284
+
283
285
  /**
284
286
  * Build the Frame loop over the Environment's `Clock`. Needs a `Scope` (the burst's
285
- * `FiberHandle` lives in it), so the `FrameLoop` module wraps it as its `layer`. Its span
287
+ * fiber ends with it), so the `FrameLoop` module wraps it as its `layer`. Its span
286
288
  * captures no call-site stack (ADR-0040, decision 2), so not `Effect.fn`, which always does:
287
289
  * `Effect.fnUntraced`, the span its pipeable (#460, Q6).
288
290
  */
@@ -291,7 +293,29 @@ export const make = Effect.fnUntraced(
291
293
  const clock = yield* Clock.Clock
292
294
  // The burst runs here, under the Layer's build context, never in a caller's.
293
295
  const buildContext = yield* Effect.context<Clock.Clock | Scope.Scope>()
294
- const burst = yield* FiberHandle.make<void>()
296
+ // The burst's fiber (#746: what a `FiberHandle` held, in a field, so an app ships no FiberHandle): a
297
+ // new burst's replaces it, interrupting it, and the loop's Scope interrupts it and lets it go. Once
298
+ // that Scope has closed, the loop takes no run (`entered`), as the handle's closed state had it.
299
+ let held: Fiber.Fiber<void> | undefined
300
+ let closed = false
301
+ yield* Effect.addFinalizer(() =>
302
+ Effect.suspend(() => {
303
+ closed = true
304
+ const last = held
305
+ held = undefined
306
+ return UndefinedOr.match(last, { onUndefined: () => Effect.void, onDefined: Fiber.interrupt })
307
+ }),
308
+ )
309
+ /** Hold `fiber`, the burst just forked: the one before it, still ending its runs, is interrupted. */
310
+ const hold = (fiber: Fiber.Fiber<void>): void => {
311
+ const previous = held
312
+ // Held before the interruption, which may re-enter through a finalizer, as FiberHandle does.
313
+ held = fiber
314
+ if (Predicate.isNotUndefined(previous)) previous.interruptUnsafe()
315
+ fiber.addObserver(() => {
316
+ if (held === fiber) held = undefined
317
+ })
318
+ }
295
319
  const entries: Array<Entry> = []
296
320
  // The runs `runLast` added, stepped after `entries` in each tick.
297
321
  const lastEntries: Array<Entry> = []
@@ -300,8 +324,8 @@ export const make = Effect.fnUntraced(
300
324
  // removes.
301
325
  let hooks: ReadonlyArray<Hook> = []
302
326
  // Whether a burst holds the loop's subscription. A run's continuation runs inline while the
303
- // ending burst is still in `burst`, so the loop tracks its burst itself rather than asking the
304
- // handle (#81).
327
+ // ending burst is still `held`, so the loop tracks its burst here rather than asking whether one
328
+ // is held (#81).
305
329
  let bursting = false
306
330
  // The Late window (ADR-0027 *Amendment (#680)*): open from a tick's first step until the microtask
307
331
  // queued at its end has run. `windowQueued` keeps one microtask per window, however many ticks open
@@ -529,11 +553,7 @@ export const make = Effect.fnUntraced(
529
553
  }
530
554
 
531
555
  /** The burst's fiber, if one holds the subscription. */
532
- const burstFiber = (): Fiber.Fiber<void, unknown> | undefined => {
533
- const state = burst.state
534
- if (state._tag === "Closed") return undefined
535
- return state.fiber
536
- }
556
+ const burstFiber = (): Fiber.Fiber<void, unknown> | undefined => held
537
557
 
538
558
  const afterTick = (hook: (dt: number) => undefined): Effect.Effect<void, never, Scope.Scope> => {
539
559
  const added: Hook = { hook }
@@ -585,14 +605,17 @@ export const make = Effect.fnUntraced(
585
605
 
586
606
  /**
587
607
  * Start a burst unless one holds the subscription, inline: no scheduler hop before the
588
- * subscription. While a burst ends its runs, the new one replaces it in `burst` (#81).
608
+ * subscription. While a burst ends its runs, the new one replaces it as the one `held` (#81). A
609
+ * closed loop never gets here: it takes no run (`entered`).
589
610
  */
590
611
  const startBurst: Effect.Effect<unknown> = Effect.suspend(() =>
591
612
  Bool.match(bursting, {
592
613
  onTrue: () => Effect.void,
593
614
  onFalse: () => {
594
615
  bursting = true
595
- return FiberHandle.run(burst, ticking)
616
+ // Detached and started at once, as `FiberHandle.run` forks: no scheduler hop before the
617
+ // subscription, and no caller's fiber its parent.
618
+ return Effect.map(Effect.forkDetach(ticking, START_NOW), hold)
596
619
  },
597
620
  }),
598
621
  )
@@ -610,9 +633,10 @@ export const make = Effect.fnUntraced(
610
633
  const logged = !LogLevel.isGreaterThan(fiber.getRef(References.MinimumLogLevel), "Debug")
611
634
  // The metrics from the first run whose fiber has them (#518); none is read once they're in.
612
635
  if (Predicate.isUndefined(metrics)) metrics = fiber.getRef(MetricsGiven)
613
- if (!isTraced(fiber)) return added(lane, late, machine, sink, options, undefined, logged)
614
- return Effect.useSpan(machine.span.name, { attributes: machine.span.attributes }, (span) =>
615
- Effect.provideService(added(lane, late, machine, sink, options, span, logged), Tracer.ParentSpan, span))
636
+ // Its span, the app's to give (#746): none without `Spans.layer`, and no closure for it.
637
+ const spans = fiber.getRef(SpansGiven)
638
+ if (spans === none) return added(lane, late, machine, sink, options, undefined, logged)
639
+ return spans.run(fiber, machine.span.name, machine.span.attributes, (span) => added(lane, late, machine, sink, options, span, logged))
616
640
  })) as Run
617
641
 
618
642
  /**
@@ -659,7 +683,7 @@ export const make = Effect.fnUntraced(
659
683
  span: Tracer.Span | undefined,
660
684
  ): Effect.Effect<Entry> => {
661
685
  // A closed Environment takes no runs: nothing would tick them.
662
- if (burst.state._tag === "Closed") return Effect.interrupt
686
+ if (closed) return Effect.interrupt
663
687
  let checkedSink: FrameLoop.Sink<F> = sink
664
688
  if (check) checkedSink = checked(sink)
665
689
  const entry: Entry = {
@@ -131,10 +131,10 @@ export const checked = <A>(check: Check<A>, value: unknown, name?: string): A =>
131
131
  throw new OptionError({ message: under(`["${name}"]`, failure) })
132
132
  }
133
133
 
134
- const NO_STEPS = expected("a count of 1 or more")
134
+ const NO_STEPS = /*#__PURE__*/ expected("a count of 1 or more")
135
135
 
136
136
  /** A count of steps: a finite number, 1 or more. */
137
- export const stepCount: Check<number> = refine(finite, (n) => n >= 1 || NO_STEPS)
137
+ export const stepCount: Check<number> = /*#__PURE__*/ refine(finite, (n) => n >= 1 || NO_STEPS)
138
138
 
139
139
  /** A finite number above 0. */
140
140
  export const positive: Check<number> = refine(finite, (n) => n > 0 || NOT_POSITIVE)
@@ -1,58 +1,112 @@
1
1
  /**
2
- * Core's spans, opened only where something reads them (#460, ADR-0040 *Amendment (#460)*): a tracer
3
- * installed other than Effect's default `nativeTracer` (the comparison Effect's `Tracer` documents
4
- * for this), with `TracerEnabled` on. The devtools, an app's OpenTelemetry exporter and the tests each
5
- * install one; with Effect's default, a span is recorded that nothing reads, and its `ParentSpan` gives
6
- * the fiber a new context root. No span captures a call-site stack (ADR-0040, decision 2).
2
+ * Core's spans (#746, ADR-0067 *Amendment (#746)*, decision 8): opened through what the app gives,
3
+ * `Spans.layer`, read from the fiber where each would open. With nothing given, `none` opens none, and
4
+ * no module an app imports names Effect's `Tracer`. Given, each opens only where something reads it
5
+ * (#460, ADR-0040 *Amendment (#460)*): a tracer installed other than Effect's default, tracing on. No
6
+ * span captures a call-site stack (ADR-0040, decision 2).
7
7
  */
8
8
  import * as Channel from "effect/Channel"
9
+ import * as Context from "effect/Context"
9
10
  import * as Effect from "effect/Effect"
10
11
  import type * as Fiber from "effect/Fiber"
11
12
  import * as References from "effect/References"
12
13
  import type * as Scope from "effect/Scope"
13
14
  import * as Stream from "effect/Stream"
14
15
  import * as Tracer from "effect/Tracer"
16
+ import type * as Spans from "../Spans.ts"
15
17
 
16
- /** A span's options: Effect's, with no call-site stack. */
17
- export interface SpanOptions {
18
- readonly attributes?: Record<string, unknown> | undefined
19
- readonly root?: boolean | undefined
18
+ /** What opens Wardic's spans, read from the fiber where each would open. */
19
+ export interface Shape {
20
+ /** `self` under the span `name`, when `fiber` is traced. */
21
+ readonly traced: <A, E, R>(fiber: Fiber.Fiber<unknown, unknown>, self: Effect.Effect<A, E, R>, name: string, options: Spans.Options) => Effect.Effect<A, E, R>
22
+ /** `self` under the span `name` for its Scope's life, when `fiber` is traced. */
23
+ readonly tracedScoped: <A, E, R>(
24
+ fiber: Fiber.Fiber<unknown, unknown>,
25
+ self: Effect.Effect<A, E, R>,
26
+ name: string,
27
+ options: Spans.Options,
28
+ ) => Effect.Effect<A, E, R | Scope.Scope>
29
+ /** `self` under the span `name`, when `fiber`, the one running it, is traced; `self` itself, the same Stream, otherwise. */
30
+ readonly tracedStream: <A, E, R>(fiber: Fiber.Fiber<unknown, unknown>, self: Stream.Stream<A, E, R>, name: string, options: Spans.Options) => Stream.Stream<A, E, R>
31
+ /**
32
+ * `body` under the span `name`, the `ParentSpan` of what runs inside it, with no stack frame
33
+ * (ADR-0040, decision 3), when `fiber` is traced: what a Frame loop run opens. `body` is given the
34
+ * span, or `undefined` with none.
35
+ */
36
+ readonly run: <A, E, R>(
37
+ fiber: Fiber.Fiber<unknown, unknown>,
38
+ name: string,
39
+ attributes: Readonly<Record<string, unknown>>,
40
+ body: (span: Tracer.Span | undefined) => Effect.Effect<A, E, R>,
41
+ ) => Effect.Effect<A, E, R>
20
42
  }
21
43
 
22
- /** Whether a fiber's spans reach anything: a tracer installed, not Effect's default, and tracing on. */
23
- export const isTraced = (fiber: Fiber.Fiber<unknown, unknown>): boolean =>
44
+ /** Opens no span: what's read without `Spans.layer`. */
45
+ export const none: Shape = {
46
+ traced: (_, self) => self,
47
+ tracedScoped: (_, self) => self,
48
+ tracedStream: (_, self) => self,
49
+ run: (_, __, ___, body) => body(undefined),
50
+ }
51
+
52
+ /**
53
+ * Whether a fiber's spans reach anything: a tracer installed, not Effect's default `nativeTracer` (the
54
+ * comparison Effect's `Tracer` documents for this), and tracing on. With Effect's default, a span is
55
+ * recorded that nothing reads, and its `ParentSpan` gives the fiber a new context root.
56
+ */
57
+ const isTraced = (fiber: Fiber.Fiber<unknown, unknown>): boolean =>
24
58
  fiber.getRef(Tracer.Tracer) !== Tracer.nativeTracer && fiber.getRef(References.TracerEnabled)
25
59
 
26
- /** `self` under the span `name` when its fiber is traced; as it is otherwise. */
27
- export const traced = <A, E, R>(self: Effect.Effect<A, E, R>, name: string, options: SpanOptions = {}): Effect.Effect<A, E, R> =>
28
- Effect.withFiber((fiber) => {
60
+ /** Opens each span where its fiber is traced: what `Spans.layer` gives. */
61
+ export const opening: Shape = {
62
+ traced: (fiber, self, name, options) => {
29
63
  if (!isTraced(fiber)) return self
30
64
  return Effect.withSpan(self, name, { ...options, captureStackTrace: false })
31
- })
65
+ },
66
+ tracedScoped: (fiber, self, name, options) => {
67
+ if (!isTraced(fiber)) return self
68
+ return Effect.withSpanScoped(self, name, { ...options, captureStackTrace: false })
69
+ },
70
+ tracedStream: (fiber, self, name, options) => {
71
+ if (!isTraced(fiber)) return self
72
+ return Stream.withSpan(self, name, { ...options, captureStackTrace: false })
73
+ },
74
+ run: (fiber, name, attributes, body) => {
75
+ if (!isTraced(fiber)) return body(undefined)
76
+ return Effect.useSpan(name, { attributes }, (span) => Effect.provideService(body(span), Tracer.ParentSpan, span))
77
+ },
78
+ }
79
+
80
+ /** What opens Wardic's spans: {@link none} unless the app gives `Spans.layer`, as `FrameLoop`'s metrics are given (#518). */
81
+ export const SpansGiven: Context.Reference<Shape> = /*#__PURE__*/ Context.Reference<Shape>("@wardic/core/Spans", { defaultValue: () => none })
82
+
83
+ /** Whether a tracer reads the running fiber's spans while the app gives none: what development warns of. */
84
+ export const missing: Effect.Effect<boolean> = /*#__PURE__*/ Effect.withFiber((fiber) => Effect.succeed(isTraced(fiber) && fiber.getRef(SpansGiven) === none))
32
85
 
33
- /** `self` under the span `name` for its Scope's life when its fiber is traced; as it is otherwise. */
86
+ /** `self` under the span `name` when its fiber is traced and the app gives spans; as it is otherwise. */
87
+ export const traced = <A, E, R>(self: Effect.Effect<A, E, R>, name: string, options: Spans.Options = {}): Effect.Effect<A, E, R> =>
88
+ Effect.withFiber((fiber) => fiber.getRef(SpansGiven).traced(fiber, self, name, options))
89
+
90
+ /** `self` under the span `name` for its Scope's life when its fiber is traced and the app gives spans; as it is otherwise. */
34
91
  export const tracedScoped = <A, E, R>(
35
92
  self: Effect.Effect<A, E, R>,
36
93
  name: string,
37
- options: SpanOptions = {},
38
- ): Effect.Effect<A, E, R | Scope.Scope> =>
39
- Effect.withFiber((fiber): Effect.Effect<A, E, R | Scope.Scope> => {
40
- if (!isTraced(fiber)) return self
41
- return Effect.withSpanScoped(self, name, { ...options, captureStackTrace: false })
42
- })
94
+ options: Spans.Options = {},
95
+ ): Effect.Effect<A, E, R | Scope.Scope> => Effect.withFiber((fiber) => fiber.getRef(SpansGiven).tracedScoped(fiber, self, name, options))
43
96
 
44
97
  /**
45
- * `self` under the span `name` when the fiber running it is traced; as it is otherwise. Decided once,
46
- * when the stream is run, and the pull handed on is `self`'s own: a `Stream.unwrap` here suspended
47
- * every pull, per element per frame for a Stream consumer (+4–6% on Bun's `ticksOnly`).
98
+ * `self` under the span `name` when the fiber running it is traced and the app gives spans; as it is
99
+ * otherwise. Decided once, when the stream is run, and the pull handed on is `self`'s own: a
100
+ * `Stream.unwrap` here suspended every pull, per element per frame for a Stream consumer (+4–6% on
101
+ * Bun's `ticksOnly`). `Shape.tracedStream` hands `self` back untraced, which is how it's told.
48
102
  */
49
- export const tracedStream = <A, E, R>(self: Stream.Stream<A, E, R>, name: string, options: SpanOptions = {}): Stream.Stream<A, E, R> => {
103
+ export const tracedStream = <A, E, R>(self: Stream.Stream<A, E, R>, name: string, options: Spans.Options = {}): Stream.Stream<A, E, R> => {
50
104
  const channel = Stream.toChannel(self)
51
105
  return Stream.fromChannel(
52
106
  Channel.fromTransform((upstream, scope) =>
53
107
  Effect.withFiber((fiber) => {
54
- if (!isTraced(fiber)) return Channel.toTransform(channel)(upstream, scope)
55
- const spanned = Stream.withSpan(self, name, { ...options, captureStackTrace: false })
108
+ const spanned = fiber.getRef(SpansGiven).tracedStream(fiber, self, name, options)
109
+ if (spanned === self) return Channel.toTransform(channel)(upstream, scope)
56
110
  return Channel.toTransform(Stream.toChannel(spanned))(upstream, scope)
57
111
  }),
58
112
  ),