@wardic/core 1.0.1 → 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 (47) 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/Spans.d.ts +41 -0
  19. package/dist/Spans.d.ts.map +1 -0
  20. package/dist/Spans.js +39 -0
  21. package/dist/Spans.js.map +1 -0
  22. package/dist/index.d.ts +1 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/internal/frameLoop.d.ts +1 -1
  27. package/dist/internal/frameLoop.d.ts.map +1 -1
  28. package/dist/internal/frameLoop.js +42 -19
  29. package/dist/internal/frameLoop.js.map +1 -1
  30. package/dist/internal/options.d.ts.map +1 -1
  31. package/dist/internal/options.js +2 -2
  32. package/dist/internal/options.js.map +1 -1
  33. package/dist/internal/tracing.d.ts +34 -14
  34. package/dist/internal/tracing.d.ts.map +1 -1
  35. package/dist/internal/tracing.js +56 -24
  36. package/dist/internal/tracing.js.map +1 -1
  37. package/package.json +1 -1
  38. package/src/Batch.ts +68 -12
  39. package/src/DefaultTransition.ts +1 -1
  40. package/src/LiveValue.ts +129 -5
  41. package/src/Machine.ts +22 -1
  42. package/src/Renderer.ts +2 -2
  43. package/src/Spans.ts +50 -0
  44. package/src/index.ts +1 -0
  45. package/src/internal/frameLoop.ts +44 -20
  46. package/src/internal/options.ts +2 -2
  47. package/src/internal/tracing.ts +82 -28
@@ -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
  ),