@mark1russell7/service 0.6.3 → 0.6.4

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.
@@ -1,6 +1,6 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
2
  import { $ as UncaughtOrigin, G as ExitTrigger, W as ExitSignal, X as ProcessPort, c as Logger, i as LogEntry, s as LogLevel } from "./logger-DhFgh48y.js";
3
- import { D as CheckFn, F as Outcome, d as TransportImpl, r as Lifecycle } from "./lifecycle-Ks9Yd5CM.js";
3
+ import { D as CheckFn, F as Outcome, _ as RequestFn, d as TransportImpl, h as RequestEnd, r as Lifecycle } from "./lifecycle-Ks9Yd5CM.js";
4
4
  import { n as ServiceBuilder } from "./builder-bXJqMe2p.js";
5
5
  import { c as ProcessMark, d as StopSignal, i as CommandResult, n as CommandOptions, o as HostPorts, t as ChildHandle, u as SpawnRequest } from "./ports-CZLzYK5d.js";
6
6
  //#region src/fakes.d.ts
@@ -52,7 +52,10 @@ interface FakeProcessOptions {
52
52
  }
53
53
  /** This function makes a fake process. */
54
54
  export declare const fakeProcess: (options?: FakeProcessOptions) => FakeProcess;
55
- /** This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). */
55
+ /**
56
+ * This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). It is
57
+ * `mulberry32` of @mark1russell7/rigor-generators.
58
+ */
56
59
  export declare const seeded: (seed: number) => (() => number);
57
60
  //#endregion
58
61
  //#region src/contract.d.ts
@@ -104,9 +107,42 @@ interface TransportSubject {
104
107
  offer(): Promise<boolean>;
105
108
  /** This method starts one unit of work that stays in flight until its release. The promise ends when the transport has it. */
106
109
  hold(): Promise<HeldWork>;
110
+ /**
111
+ * This method sends one call through the transport, for the stream cases (option `streams`). The
112
+ * handler of the call gives `call.work` to `life.request(call.controller, call.route, ...)` of the
113
+ * lifecycle of the start, and writes its stream to the caller. It gives what the caller sees.
114
+ */
115
+ call?(call: StreamCall): CallerView | Promise<CallerView>;
107
116
  /** This method frees what the subject holds outside the transport: its clients and their sockets. */
108
117
  dispose?(): Promise<void> | void;
109
118
  }
119
+ /** A stream call is one request of the stream cases. The kit gives its work, and the subject sends it. */
120
+ interface StreamCall {
121
+ /** This name is the controller of the request in the lifecycle of the kit. */
122
+ readonly controller: string;
123
+ /** This name is the route of the request in the lifecycle of the kit. */
124
+ readonly route: string;
125
+ /** This function is the work of the request: one value, or a stream of values. */
126
+ readonly work: RequestFn<unknown>;
127
+ /** True tells that the answer is a stream of items. False tells that the answer is unary: one status and one value. */
128
+ readonly stream: boolean;
129
+ }
130
+ /** A seen end is the end of a call, as its caller read it. */
131
+ interface SeenEnd {
132
+ readonly kind: RequestEnd["kind"];
133
+ /**
134
+ * True tells that the end came in the body of the answer, after its status, for example as the
135
+ * last line of a stream. False tells that the end came as the status of the answer.
136
+ */
137
+ readonly inBand: boolean;
138
+ }
139
+ /** A caller view is what the caller of a call has read so far. The kit reads it again until it changes. */
140
+ interface CallerView {
141
+ /** These values are the items that the caller read, in their sequence. */
142
+ readonly items: readonly unknown[];
143
+ /** This end is the end that the caller read, or null while the call is open. */
144
+ readonly end: SeenEnd | null;
145
+ }
110
146
  /**
111
147
  * This function gives a detached lifecycle: a lifecycle with no service, for the start of a
112
148
  * transport in a test. Its state is `running`, it keeps each connection, and nothing is in flight. Each request
@@ -140,6 +176,11 @@ interface ConformanceOptions {
140
176
  readonly cooperative?: boolean | undefined;
141
177
  /** This count is the number of works that the count case holds. The default is 3. */
142
178
  readonly holds?: number | undefined;
179
+ /**
180
+ * True adds the stream cases (S6 D4). Then the subject gives `call`, and the kit gives the
181
+ * transport a lifecycle with request tracking. The default is false.
182
+ */
183
+ readonly streams?: boolean | undefined;
143
184
  /** This function receives each measurement, for the raw records of a run. */
144
185
  readonly record?: ((record: ConformanceRecord) => void) | undefined;
145
186
  }
@@ -153,6 +194,16 @@ interface ConformanceOptions {
153
194
  * past it. It gives the cooperative abort to the work, and it does not throw.
154
195
  * - `close` ends the work in flight in its bound, and a second close has no effect.
155
196
  * - The stages in their sequence, as the lifecycle does them.
197
+ *
198
+ * The option `streams` adds the cases of the streams (S6 D4). Each request is a stream, and a
199
+ * unary call is a stream of one item. The kit gives the transport a lifecycle with request
200
+ * tracking. It also does the stages of the shutdown on the tracker, as the lifecycle does them.
201
+ * - A unary call gives one value, and its end comes as the status of the answer.
202
+ * - A stream stays in flight until its end, not until its first item.
203
+ * - A failure after the first item ends the stream with an error line in the body, not a status.
204
+ * A failure before the first item gets a status.
205
+ * - `drain` waits for an open stream. The cooperative abort ends the stream, and its caller gets the end.
206
+ * - At the deadline of the drain, the cut ends an open stream, and its caller gets the end.
156
207
  */
157
208
  export declare const transportConformance: (make: SubjectFactory, options?: ConformanceOptions) => ContractCase[];
158
209
  //#endregion
@@ -287,5 +338,5 @@ export interface QuietServer {
287
338
  */
288
339
  export declare const quietServer: () => Promise<QuietServer>;
289
340
  //#endregion
290
- export type { ConformanceOptions, ConformanceRecord, ContractCase, ContractOptions, FakeChild, FakeClock, FakeHost, FakeHostOptions, FakeProcess, FakeProcessOptions, HeldWork, RecordedCommand, RecordedSignal, SubjectFactory, TransportSubject };
341
+ export type { CallerView, ConformanceOptions, ConformanceRecord, ContractCase, ContractOptions, FakeChild, FakeClock, FakeHost, FakeHostOptions, FakeProcess, FakeProcessOptions, HeldWork, RecordedCommand, RecordedSignal, SeenEnd, StreamCall, SubjectFactory, TransportSubject };
291
342
  //# sourceMappingURL=testing.d.ts.map
package/build/testing.js CHANGED
@@ -1,7 +1,11 @@
1
1
  import { realClock } from "./clock.js";
2
2
  import { a as recoverSpan, r as failSpan } from "./timing-DGRi3XCI.js";
3
+ import { s as ownStream } from "./knobs-D2ClI68I.js";
4
+ import { t as tracker } from "./requests-BIq9Tr4P.js";
3
5
  import { valueIn } from "@mark1russell7/quantity";
4
6
  import { createServer } from "node:net";
7
+ import { mulberry32 } from "@mark1russell7/rigor-generators";
8
+ import "node:events";
5
9
  //#region src/fakes.ts
6
10
  /** This function lets the promises that are ready continue, before the clock moves again. */
7
11
  const settle = async () => {
@@ -136,17 +140,11 @@ const fakeProcess = (options = {}) => {
136
140
  }
137
141
  };
138
142
  };
139
- /** This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). */
140
- const seeded = (seed) => {
141
- let state = seed >>> 0;
142
- return () => {
143
- state = state + 1831565813 >>> 0;
144
- let t = state;
145
- t = Math.imul(t ^ t >>> 15, t | 1);
146
- t ^= t + Math.imul(t ^ t >>> 7, t | 61);
147
- return ((t ^ t >>> 14) >>> 0) / 4294967296;
148
- };
149
- };
143
+ /**
144
+ * This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). It is
145
+ * `mulberry32` of @mark1russell7/rigor-generators.
146
+ */
147
+ const seeded = (seed) => mulberry32(seed);
150
148
  //#endregion
151
149
  //#region src/contract.ts
152
150
  const ms = (amount) => valueIn(amount, "ms");
@@ -327,6 +325,64 @@ const contractCases = (declare, options = {}) => {
327
325
  return cases;
328
326
  };
329
327
  //#endregion
328
+ //#region src/http/fake-server.ts
329
+ /** This function makes a pushed source, a stream of a work for the tests of a stream. */
330
+ const pushedSource = () => {
331
+ const queue = [];
332
+ let wake = null;
333
+ let failure = null;
334
+ let returned = false;
335
+ const poke = () => {
336
+ wake?.();
337
+ wake = null;
338
+ };
339
+ return {
340
+ iterable: { [Symbol.asyncIterator]: () => ({
341
+ async next() {
342
+ for (;;) {
343
+ if (failure !== null) throw failure;
344
+ if (returned) return {
345
+ value: void 0,
346
+ done: true
347
+ };
348
+ const step = queue.shift();
349
+ if (step !== void 0) return step;
350
+ await new Promise((resolve) => wake = resolve);
351
+ }
352
+ },
353
+ async return() {
354
+ returned = true;
355
+ poke();
356
+ return {
357
+ value: void 0,
358
+ done: true
359
+ };
360
+ }
361
+ }) },
362
+ push: (value) => {
363
+ queue.push({
364
+ value,
365
+ done: false
366
+ });
367
+ poke();
368
+ },
369
+ finish: () => {
370
+ queue.push({
371
+ value: void 0,
372
+ done: true
373
+ });
374
+ poke();
375
+ },
376
+ fail: (error) => {
377
+ failure = error;
378
+ poke();
379
+ },
380
+ get returned() {
381
+ return returned;
382
+ }
383
+ };
384
+ };
385
+ //#endregion
330
386
  //#region src/conformance.ts
331
387
  /**
332
388
  * This function gives a detached lifecycle: a lifecycle with no service, for the start of a
@@ -359,6 +415,32 @@ const detachedLifecycle = () => {
359
415
  keepAlive: () => true
360
416
  };
361
417
  };
418
+ /** These names are the controller and the route of each call of the stream cases. */
419
+ const CALLS = {
420
+ controller: "conformance",
421
+ route: "call"
422
+ };
423
+ /**
424
+ * This function gives a lifecycle with request tracking for the stream cases, and its tracker. The
425
+ * kit uses the tracker for the stages of the shutdown, as the lifecycle of a service does. Its
426
+ * requests are not idempotent, and it admits each request until the stop of its intake.
427
+ */
428
+ const trackedLifecycle = (clock) => {
429
+ const requests = tracker([{
430
+ name: CALLS.controller,
431
+ requires: [],
432
+ routes: { [CALLS.route]: { idempotent: false } }
433
+ }], clock, () => null);
434
+ const life = {
435
+ ...detachedLifecycle(),
436
+ request: (controller, route, work, options) => ownStream(requests.request(controller, route, work, options), life),
437
+ inFlight: (controller) => requests.inFlight(controller)
438
+ };
439
+ return {
440
+ life,
441
+ requests
442
+ };
443
+ };
362
444
  const realNow = () => performance.now();
363
445
  const turn = () => new Promise((resolve) => setTimeout(resolve, 0));
364
446
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -408,6 +490,16 @@ const track = (promise) => {
408
490
  * past it. It gives the cooperative abort to the work, and it does not throw.
409
491
  * - `close` ends the work in flight in its bound, and a second close has no effect.
410
492
  * - The stages in their sequence, as the lifecycle does them.
493
+ *
494
+ * The option `streams` adds the cases of the streams (S6 D4). Each request is a stream, and a
495
+ * unary call is a stream of one item. The kit gives the transport a lifecycle with request
496
+ * tracking. It also does the stages of the shutdown on the tracker, as the lifecycle does them.
497
+ * - A unary call gives one value, and its end comes as the status of the answer.
498
+ * - A stream stays in flight until its end, not until its first item.
499
+ * - A failure after the first item ends the stream with an error line in the body, not a status.
500
+ * A failure before the first item gets a status.
501
+ * - `drain` waits for an open stream. The cooperative abort ends the stream, and its caller gets the end.
502
+ * - At the deadline of the drain, the cut ends an open stream, and its caller gets the end.
411
503
  */
412
504
  const transportConformance = (make, options = {}) => {
413
505
  const name = options.name ?? "transport";
@@ -463,7 +555,7 @@ const transportConformance = (make, options = {}) => {
463
555
  check(inBound, `close did not end in its bound of ${closeBound} ms`);
464
556
  check(!closed.failed, `close threw: ${String(closed.error)}`);
465
557
  };
466
- return [
558
+ const cases = [
467
559
  each("nothing is in flight after the start, and it takes new work", async (subject) => {
468
560
  check(subject.impl.inFlight() === 0, `inFlight() gives ${subject.impl.inFlight()} after the start, not 0`);
469
561
  check(await subject.offer(), "the transport refused new work after its start");
@@ -596,6 +688,161 @@ const transportConformance = (make, options = {}) => {
596
688
  await count(subject, 0, "close left work in flight");
597
689
  })
598
690
  ];
691
+ if (!(options.streams ?? false)) return cases;
692
+ const eachStream = (title, body) => ({
693
+ name: `${name}: ${title}`,
694
+ async run() {
695
+ const time = timeOf();
696
+ const subject = await make(time.clock);
697
+ const { life, requests } = trackedLifecycle(time.clock);
698
+ try {
699
+ await subject.impl.start(new AbortController().signal, life);
700
+ check(subject.call !== void 0, "the option streams needs a subject that gives call()");
701
+ await body(subject, time, requests);
702
+ } finally {
703
+ requests.stopIntake();
704
+ requests.cooperativeAbort();
705
+ try {
706
+ await subject.impl.close();
707
+ } finally {
708
+ await subject.dispose?.();
709
+ }
710
+ }
711
+ }
712
+ });
713
+ const call = (subject, given) => Promise.resolve(subject.call(given));
714
+ const openStream = async (subject) => {
715
+ const source = pushedSource();
716
+ let started = false;
717
+ let signal = null;
718
+ const view = await call(subject, {
719
+ ...CALLS,
720
+ stream: true,
721
+ work: (given) => {
722
+ started = true;
723
+ signal = given;
724
+ return source.iterable;
725
+ }
726
+ });
727
+ check(await within(slack, () => started), "the work of a stream call did not start");
728
+ return {
729
+ view,
730
+ push: (value) => source.push(value),
731
+ finish: () => source.finish(),
732
+ fail: (error) => source.fail(error),
733
+ get aborted() {
734
+ return signal?.aborted === true;
735
+ }
736
+ };
737
+ };
738
+ const pushes = async (fed, value, what) => {
739
+ const before = fed.view.items.length;
740
+ fed.push(value);
741
+ check(await within(slack, () => fed.view.items.length > before), `${what}: the caller did not get the item ${value}`);
742
+ };
743
+ const ends = async (view, kind, inBand, what) => {
744
+ check(await within(slack, () => view.end !== null), `${what}: the caller got no end`);
745
+ const end = view.end;
746
+ const where = (body) => body ? "in the body" : "as a status";
747
+ check(end.kind === kind && end.inBand === inBand, `${what}: the caller got the end ${end.kind} ${where(end.inBand)}, not ${kind} ${where(inBand)}`);
748
+ };
749
+ /** This function stops the intake of the tracker and of the transport, as the stage `stop intake` does. */
750
+ const stopBoth = async (subject, requests) => {
751
+ requests.stopIntake();
752
+ await subject.impl.stopIntake();
753
+ };
754
+ /**
755
+ * This function starts the drain of the transport and of the tracker, as the stage `drain` does.
756
+ * The abort of `signal` is also the cooperative abort of the tracker. It tracks the drain of the transport.
757
+ */
758
+ const drainBoth = (subject, requests, deadline, signal) => {
759
+ if (signal.aborted) requests.cooperativeAbort();
760
+ else signal.addEventListener("abort", () => requests.cooperativeAbort(), { once: true });
761
+ requests.drain(deadline);
762
+ return track(attempt(() => subject.impl.drain(deadline, signal)));
763
+ };
764
+ const failure = () => /* @__PURE__ */ new Error("the failure of the conformance kit");
765
+ const streamCases = [
766
+ eachStream("a unary call is a stream of one item: one value, and its end as the status", async (subject) => {
767
+ let started = false;
768
+ let give = () => {};
769
+ const view = await call(subject, {
770
+ ...CALLS,
771
+ stream: false,
772
+ work: () => {
773
+ started = true;
774
+ return new Promise((resolve) => {
775
+ give = resolve;
776
+ });
777
+ }
778
+ });
779
+ check(await within(slack, () => started), "the work of a unary call did not start");
780
+ await count(subject, 1, "a unary call is in flight");
781
+ give(7);
782
+ await ends(view, "done", false, "a unary call");
783
+ check(view.items.length === 1 && view.items[0] === 7, `a unary call gave the items ${JSON.stringify(view.items)}, not [7]`);
784
+ await count(subject, 0, "a unary call ended");
785
+ }),
786
+ eachStream("a stream stays in flight until its end, not until its first item", async (subject) => {
787
+ const fed = await openStream(subject);
788
+ await count(subject, 1, "a stream is open");
789
+ for (const value of [1, 2]) {
790
+ await pushes(fed, value, "an open stream");
791
+ await count(subject, 1, `a stream is open after its item ${value}`);
792
+ }
793
+ check(fed.view.end === null, "the caller got an end before the end of the stream");
794
+ fed.finish();
795
+ await ends(fed.view, "done", true, "a stream that ended");
796
+ check(JSON.stringify(fed.view.items) === "[1,2]", `a stream gave the items ${JSON.stringify(fed.view.items)}, not [1,2]`);
797
+ await count(subject, 0, "a stream ended");
798
+ }),
799
+ eachStream("a failure after the first item ends the stream with an error line, not a status", async (subject) => {
800
+ const fed = await openStream(subject);
801
+ await pushes(fed, 1, "a stream before its failure");
802
+ fed.fail(failure());
803
+ await ends(fed.view, "failed", true, "a stream that failed after its first item");
804
+ await count(subject, 0, "a stream failed");
805
+ }),
806
+ eachStream("a failure before the first item gets a status, not an error line", async (subject) => {
807
+ const fed = await openStream(subject);
808
+ fed.fail(failure());
809
+ await ends(fed.view, "failed", false, "a stream that failed before its first item");
810
+ check(fed.view.items.length === 0, `a stream that failed before its first item gave ${fed.view.items.length} items`);
811
+ await count(subject, 0, "a stream failed");
812
+ }),
813
+ eachStream("drain waits for an open stream, and the cooperative abort ends the stream with its end", async (subject, time, requests) => {
814
+ const fed = await openStream(subject);
815
+ await pushes(fed, 1, "a stream before the drain");
816
+ await stopBoth(subject, requests);
817
+ const abort = new AbortController();
818
+ const deadline = time.clock.now() + cap;
819
+ const drained = drainBoth(subject, requests, deadline, abort.signal);
820
+ await time.pass(cap / 4);
821
+ await quiet();
822
+ check(!drained.settled, "drain ended while a stream was open, before its deadline");
823
+ check(fed.view.end === null, "the caller got an end before the cooperative abort");
824
+ await count(subject, 1, "a stream is open in the drain");
825
+ abort.abort(/* @__PURE__ */ new Error("the cooperative abort of the conformance kit"));
826
+ check(await within(slack, () => fed.aborted), "the work of the stream did not get the cooperative abort");
827
+ await ends(fed.view, "cut", true, "a stream after the cooperative abort");
828
+ check(await within(slack, () => drained.settled), "drain did not end when the stream ended");
829
+ check(!drained.failed, `drain threw: ${String(drained.error)}`);
830
+ check(time.clock.now() < deadline, "drain waited until its deadline after the stream ended");
831
+ await count(subject, 0, "the cooperative abort left a stream in flight");
832
+ }),
833
+ eachStream("drain cuts an open stream at its deadline, and the caller gets the end of the cut", async (subject, time, requests) => {
834
+ const fed = await openStream(subject);
835
+ await pushes(fed, 1, "a stream before the drain");
836
+ await stopBoth(subject, requests);
837
+ const drained = drainBoth(subject, requests, time.clock.now() + cap, new AbortController().signal);
838
+ await time.pass(cap);
839
+ await ends(fed.view, "cut", true, "a stream at the deadline of the drain");
840
+ check(await within(slack, () => drained.settled), "drain did not end after the cut of the stream");
841
+ check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);
842
+ await count(subject, 0, "the cut left a stream in flight");
843
+ })
844
+ ];
845
+ return [...cases, ...streamCases];
599
846
  };
600
847
  //#endregion
601
848
  //#region src/host/fakes.ts