@crvouga/mockingbird-runtime 0.5.0 → 0.7.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.
package/README.md CHANGED
@@ -18,7 +18,7 @@ harness from `@crvouga/mockingbird-runtime/ui`.
18
18
  npm install -D @crvouga/mockingbird-runtime
19
19
  ```
20
20
 
21
- Install it directly when using the system harness without an emulator, or to pin its version.
21
+ Install the runtime as a regular dependency (`npm install @crvouga/mockingbird-runtime`) in a package that implements an emulator. Applications using emulators only in tests can use dev dependencies.
22
22
 
23
23
  ## Usage
24
24
 
@@ -29,8 +29,39 @@ const sqs = createRuntime()
29
29
  const response = await sqs.fetch(new Request("http://sqs.local/__admin/health"))
30
30
  ```
31
31
 
32
+ ## Author a custom HTTP service
33
+
34
+ Use `@crvouga/mockingbird-runtime/authoring` in an application workspace or an independently
35
+ published package. The example below runs directly against Fetch.
36
+
37
+ ```ts
38
+ import { defineHttpService } from "@crvouga/mockingbird-runtime/authoring"
39
+
40
+ const { createRuntime, serveTarget } = defineHttpService({
41
+ name: "rates",
42
+ version: "1.0.0",
43
+ document: {
44
+ openapi: "3.1.0",
45
+ info: { title: "Sample rates", version: "1" },
46
+ paths: { "/rate": { get: {
47
+ operationId: "getRate", responses: { "200": { description: "Current rate" } },
48
+ } } },
49
+ },
50
+ handlers: () => ({ getRate: () => Response.json({ cents: 125 }) }),
51
+ })
52
+ const response = await createRuntime().fetch(new Request("https://rates.example/rate"))
53
+ console.log(await response.json()) // { cents: 125 }
54
+ ```
55
+
56
+ Export `createRuntime` from your package entry and `serveTarget` from its `./server` entry.
57
+ Both can be re-exports from the same module. The runtime adds the standard admin API, namespaces,
58
+ clock, faults, request journal, reset and snapshots. The default port is ephemeral. For a stateful
59
+ service, use the [working job queue](https://github.com/crvouga/mockingbird/blob/main/packages/runtime/examples/jobs.ts)
60
+ and the [authoring and fleet guide](https://github.com/crvouga/mockingbird/blob/main/docs/AUTHORING_A_SERVICE.md#custom-http-services-in-your-own-project).
61
+
32
62
  ## API
33
63
 
64
+ - The supported `/authoring` entry exports `defineHttpService`, `Collection`, `IdSequence`, `bodyIssues`, `defineOperations`, and `jsonResponse`. Its factory and target types can also be used in package declarations.
34
65
  - `RUNTIME_SUBPATHS`: the subpaths this package exports (`core`, `service`, `sqlite`, …), each
35
66
  re-exporting the Mockingbird helper of that name.
36
67
 
@@ -144,6 +144,25 @@ type UpstreamOptions = {
144
144
  rewriteAuth?: (request: Request) => Request | Promise<Request>;
145
145
  };
146
146
 
147
+ /** An admission quota applied on the namespace clock. */
148
+ type FaultLimit = {
149
+ requests: number;
150
+ per: Duration;
151
+ key?: "namespace" | "credential";
152
+ window?: "fixed" | "sliding";
153
+ };
154
+ type LimitState = {
155
+ used: number;
156
+ windowStart: number | null;
157
+ windowResetsAt: number | null;
158
+ };
159
+ type LimitBucket = {
160
+ start: number;
161
+ used: number;
162
+ } | {
163
+ arrivals: number[];
164
+ };
165
+
147
166
  /**
148
167
  * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
149
168
  * request a percentage fault hits — is reproducible from a seed.
@@ -211,6 +230,8 @@ type FaultRule = {
211
230
  * rules added through `POST /__admin/faults` default to the calling namespace.
212
231
  */
213
232
  namespace?: string;
233
+ /** Admit at most this many matching requests per window. */
234
+ limit?: FaultLimit;
214
235
  /** Let this many matching requests through first. */
215
236
  after?: number;
216
237
  /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
@@ -302,13 +323,17 @@ type FaultCandidate = {
302
323
  * `undefined` for a body that is missing or not JSON. It must leave the request readable.
303
324
  */
304
325
  readJson?: () => Promise<unknown>;
326
+ /** The service-specific credential, if it has one. */
327
+ credential?: () => string | undefined;
305
328
  /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
306
329
  now?: number;
330
+ /** Read the clock again after asynchronous request matching. */
331
+ clockNow?: () => number;
307
332
  /** How to spend a delay for this request. Default: the registry's own sleep. */
308
333
  wait?: (ms: number) => Promise<void>;
309
334
  };
310
335
  /** A stored rule and how often it was consulted. */
311
- type FaultListing = FaultRule & {
336
+ type FaultListing = FaultRule & Partial<LimitState> & {
312
337
  /** Faults left before the rule retires. `null` when it has no `count`. */
313
338
  remaining: number | null;
314
339
  /** Times the rule faulted a request. */
@@ -324,6 +349,7 @@ type FaultSnapshot = {
324
349
  */
325
350
  rules: (FaultListing & {
326
351
  position?: number;
352
+ limitBuckets?: [string, LimitBucket][];
327
353
  })[];
328
354
  /** How many `fault_<n>` ids the namespace has handed out. */
329
355
  nextId?: number;
@@ -803,6 +829,8 @@ type WebhookEndpoint = {
803
829
  tags?: Record<string, string>;
804
830
  /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
805
831
  signUrl?: string;
832
+ /** Disable automatic retry attempts for this endpoint. Explicit replay remains available. */
833
+ retry?: false;
806
834
  headers?: Record<string, string>;
807
835
  };
808
836
  type WebhookMessage = {
@@ -853,6 +881,8 @@ type PublishInput = {
853
881
  tags?: Record<string, string>;
854
882
  /** Message-specific delivery headers, captured as part of durable message state. */
855
883
  headers?: Record<string, string>;
884
+ /** Additional delivery endpoint for this message only. */
885
+ endpoint?: WebhookEndpoint;
856
886
  /** Message id; generated when omitted. */
857
887
  id?: string;
858
888
  };
@@ -2,7 +2,7 @@ import {
2
2
  normalizeIdBase,
3
3
  ownedTransport,
4
4
  signV4
5
- } from "./chunk-BK5KDNUE.js";
5
+ } from "./chunk-CIJF35LX.js";
6
6
  import "./chunk-2KDYLZXC.js";
7
7
  import {
8
8
  createClock,
@@ -13,7 +13,7 @@ import {
13
13
  resolveAdminPrefix,
14
14
  restoreClock,
15
15
  upstreamRequest
16
- } from "./chunk-GAIPLMRY.js";
16
+ } from "./chunk-MZMSHIAI.js";
17
17
  import {
18
18
  assertArchiveCompatibility,
19
19
  assertCompatibilityTags,
@@ -3651,7 +3651,7 @@ async function preflightFleet(config, options) {
3651
3651
  break;
3652
3652
  }
3653
3653
  }
3654
- targets.set(name, { ...target, packageVersion: packageVersion ?? "0.5.0" });
3654
+ targets.set(name, { ...target, packageVersion: packageVersion ?? "0.7.0" });
3655
3655
  } catch (error) {
3656
3656
  throw new Error(`service ${name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
3657
3657
  }
@@ -4737,6 +4737,7 @@ async function startFleet(config, options) {
4737
4737
  }
4738
4738
 
4739
4739
  // ../adapters/node/dist/fleet-loader.js
4740
+ import { existsSync, readFileSync } from "node:fs";
4740
4741
  import { createRequire as createRequire2 } from "node:module";
4741
4742
  import { resolve as resolve2 } from "node:path";
4742
4743
  import { pathToFileURL } from "node:url";
@@ -4748,7 +4749,9 @@ function createInstalledServiceLoader(options) {
4748
4749
  for (const name of allowed)
4749
4750
  if (!suffix.test(name))
4750
4751
  throw new Error("invalid service suffix");
4751
- const require2 = createRequire2(resolve2(options.projectRoot, "package.json"));
4752
+ const manifest = resolve2(options.projectRoot, "package.json");
4753
+ const require2 = createRequire2(manifest);
4754
+ const imports = existsSync(manifest) ? JSON.parse(readFileSync(manifest, "utf8")).imports : void 0;
4752
4755
  const targets = new Map((options.targets ?? []).map((target) => [target.name, target]));
4753
4756
  return async (name) => {
4754
4757
  if (!suffix.test(name) || !allowed.has(name))
@@ -4756,11 +4759,15 @@ function createInstalledServiceLoader(options) {
4756
4759
  const own = targets.get(name);
4757
4760
  if (own)
4758
4761
  return own;
4759
- const specifier = `@crvouga/mockingbird-service-${name}/server`;
4762
+ const alias = `#mockingbird/${name}/server`;
4763
+ const registered = imports && Object.hasOwn(imports, alias);
4764
+ const specifier = registered ? alias : `@crvouga/mockingbird-service-${name}/server`;
4760
4765
  let location;
4761
4766
  try {
4762
4767
  location = require2.resolve(specifier);
4763
- } catch {
4768
+ } catch (cause) {
4769
+ if (registered)
4770
+ throw new Error(`cannot resolve registered service "${name}" from ${alias} in ${manifest}`, { cause });
4764
4771
  throw new Error(`cannot load service "${name}": install @crvouga/mockingbird-service-${name} in the consumer project; its /server export is required`);
4765
4772
  }
4766
4773
  const mod = await import(pathToFileURL(location).href);