diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 7c9e760..672c116 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -23,7 +23,9 @@
- Write code for readers ranging from junior developers to experienced maintainers. Prefer straightforward control flow, descriptive names, and explicit intermediate steps over terse, clever, or densely composed syntax.
- Keep functions cohesive and small enough to understand without tracing unrelated state. Extract a well-named local or helper when it reveals intent, but do not fragment a simple operation across unnecessary abstractions.
- Make behavior and ownership visible in the code. Avoid hidden side effects, ambiguous Boolean parameters, unexplained constants, and conditionals whose meaning must be reconstructed by the reader.
-- Explain why non-obvious behavior is necessary, especially for security, protocol, concurrency, lifecycle, compatibility, and accessibility constraints. Place concise comments near the relevant code, keep them current, and do not narrate statements that are already clear.
+- Explain non-obvious intent and tradeoffs in the source files, not only in pull requests, commit messages, or external documentation. Place concise comments beside the relevant security, protocol, concurrency, lifecycle, compatibility, accessibility, and performance decisions, including the invariants future changes must preserve.
+- For performance-sensitive code, explain what work or allocation is avoided and any ownership, parallel-request safety, bounded-retention, or cleanup requirements. Distinguish reduced allocation/GC pressure from guaranteed lower resident memory; keep environment-specific benchmark results in tests or documentation rather than presenting them as source-code guarantees.
+- Review comments when changing behavior: update or remove stale explanations, prefer clear names and control flow for obvious operations, and avoid line-by-line narration or mandatory comments on every helper.
- Prefer readability over micro-optimization. Use a less obvious implementation only when measurements or a hard platform constraint justify it, and document the reason and invariant that future changes must preserve.
- Make tests readable specifications: use behavior-focused names, arrange setup and assertions clearly, and favor expected outcomes over implementation details.
- Prefer the .NET platform and `System.Text.Json` over new dependencies. Justify added packages by concrete functionality or risk reduction.
diff --git a/.github/instructions/dotnet.instructions.md b/.github/instructions/dotnet.instructions.md
index d5b827e..536a04f 100644
--- a/.github/instructions/dotnet.instructions.md
+++ b/.github/instructions/dotnet.instructions.md
@@ -13,6 +13,7 @@ applyTo: "**/*.{cs,csproj,sln,props,targets}"
- Map reserved management routes before the dispatcher fallback, keep management edits in a domain service, and require strong revision ETags on every management write.
- Keep management API, dashboard, OpenAPI document, and Swagger UI exposure independently configurable. OpenAPI must describe only reserved management operations, never runtime-defined mock routes.
- Represent the active document, revision, persistence status, and endpoint registry as one immutable configuration snapshot and publish replacements atomically.
+- Reuse only unchanged immutable response bytes and ordered headers by stable endpoint ID. Keep fresh runtime endpoints and limiter permits on every applied replacement; never retain prior registries or extra UTF-16 bodies merely for reuse.
- Route every runtime or management configuration mutation through `ConfigurationState`; do not publish routes independently of the active document and revision.
- Load persisted configuration before serving requests, fail startup for required malformed or invalid files, and save by replacing a flushed same-directory temporary file.
- Capture one configuration snapshot per save and clear its dirty state only when that revision is still current.
@@ -31,13 +32,18 @@ applyTo: "**/*.{cs,csproj,sln,props,targets}"
protection. Existing settings, rotations, and explicit opt-outs take precedence over the deployment value.
Invalid keys, unreadable settings, or failed persistence fail startup without exposing secrets.
- Use cancellation tokens for asynchronous I/O and propagate them through application boundaries.
+- Publish the predecoded API-key digest with its security revision and enforcement flag. Verify requests using independent bounded stack buffers, clear scratch storage, preserve constant-time comparison, and never cache plaintext request keys.
- Use UTC timestamps through `TimeProvider` where behavior depends on time.
- Use source-generated `System.Text.Json` contexts for application-owned request, response, and persistence types.
- Document public C# contracts with XML documentation comments. Cover parameters, return values, exceptions, wire semantics, concurrency guarantees, and persistence behavior when they are not obvious from the signature; use ` ` when a contract is inherited.
-- Do not add narration to trivial private helpers. Use implementation comments only for invariants, security decisions, protocol constraints, or reasoning the code cannot express clearly.
+- Do not add narration to trivial private helpers. Use implementation comments for reasoning the code cannot express clearly, including invariants, security decisions, protocol constraints, and performance tradeoffs. Explain pooled/shared/stack storage ownership, concurrent-use safety, retention, and cleanup where relevant; do not imply that fewer allocations guarantee lower resident memory.
- Give every management operation a stable OpenAPI operation ID, concise summary, request-body metadata, typed success responses, and applicable problem responses. Document strong `If-Match` requirements in the operation description and test the generated document.
- Return problem details for management API errors and avoid exposing exceptions or filesystem details.
- Design concurrent statistics structures with bounded memory and test their rollover and contention behavior.
+- Keep dashboard deltas opt-in and absolute, with SSE sequence/base guards and full baselines after resets,
+ reconnects, or missed frames. Retain one shared frame without replay history; preserve legacy full delivery
+ and keep comparison/serialization locks off the recording path.
+- Keep minute buckets and counters contiguous value types. Access stored elements and atomic fields by reference; avoid struct copies or readonly defensive copies that bypass volatile reads or discard updates.
- Account for every matched dispatch exactly once, including delay cancellation. Failed attempts retain the
selected response status, or no status before response selection, and contribute zero completed bytes.
Keep intentional connection aborts distinct and preserve logical-request retry coalescing.
diff --git a/.github/instructions/frontend.instructions.md b/.github/instructions/frontend.instructions.md
index 188ff7c..b0c984f 100644
--- a/.github/instructions/frontend.instructions.md
+++ b/.github/instructions/frontend.instructions.md
@@ -43,6 +43,10 @@ applyTo: "src/MockAPI/wwwroot/**/*.{js,html,css},tests/{frontend,browser}/**/*.j
- Keep event, timer, request, and subscription lifecycles visible. Co-locate setup with cleanup where practical, and explain ordering or stale-update protections when they are not apparent from the control flow.
- Dispose page-owned controllers on non-persisted `pagehide`, not `beforeunload` (which also fires for downloads). Suspend synchronization for back-forward cached pages and resume it on persisted `pageshow`.
- Use one `/__mockapi/api/dashboard/events` stream for configuration and statistics. Poll only for recovery or unsupported SSE; abort work while hidden and reject obsolete responses. Cache endpoint definitions in memory by revision, never in browser storage. Preserve endpoint row controls during statistics-only updates.
+- Opt the dashboard into interval statistics deltas. Maintain its sequenced stream baseline independently
+ of HTTP refreshes, apply absolute updates immutably, and recover sequence gaps without aborting commands.
+ Retain Statistics rows and UTC-minute chart columns, bound their caches, and dispose removed listeners
+ while preserving focus, scroll, and current tooltip data.
- Route management requests through `dashboard-management.js`. Configuration commands pass an explicit captured ETag; editor drafts and confirmations keep their reviewed revision despite live updates. Keep the single-flight guard through the authoritative refresh, surface failures, and never automatically replay rejected writes.
- Consume the synchronizer's explicit completed/failed/inactive refresh result at the command boundary. Background recovery may continue after failure, but a command must not treat a failed or interrupted refresh as successful.
- Serve scripts and styles with private, content-validated caching; keep dashboard HTML and administrative data non-storable. Do not use immutable caching for unversioned asset URLs.
@@ -50,7 +54,7 @@ applyTo: "src/MockAPI/wwwroot/**/*.{js,html,css},tests/{frontend,browser}/**/*.j
- Prefer reusable `@typedef` contracts for shared object shapes. Keep annotations specific enough to help editors and reviewers; do not use `Object` when a meaningful shape is known.
- Keep shared endpoint, configuration, management-problem, and statistics wire shapes in `dashboard-core.js`, aligned with the backend's nullable and omitted fields. Keep named controller/lifecycle types in their owning modules and reuse shared contracts rather than duplicating payload shapes.
- Declare required DOM IDs with their expected HTML tags through `getDashboardElements`; the lookup validates markup and infers precise control types. Preserve concrete element and request-entry types through generic helpers. Keep narrowing assertions at validated or statically owned DOM/JSON boundaries rather than casting whole controllers.
-- Do not require comments on trivial private helpers. Add concise comments only for accessibility behavior, synchronization invariants, storage fallbacks, security boundaries, or non-obvious browser behavior.
+- Do not require comments on trivial private helpers. Add concise source comments for non-obvious accessibility behavior, synchronization invariants, storage fallbacks, security boundaries, browser behavior, or performance tradeoffs. Explain node reuse and listener/cache ownership when they affect cleanup, current data, focus, or scroll preservation; update those explanations with the behavior.
- Keep pure transformation logic in importable modules with direct Vitest coverage. Inject browser APIs into stateful controllers when doing so makes lifecycle and failure behavior deterministic to test.
- Preserve WCAG 2.2 AA contrast, keyboard access, focus order, dialog semantics, reduced-motion behavior, and light, dark, and high-contrast states.
- Gate side-by-side dashboard panels on the measured command-group width, including gaps; never wrap command groups within a column. Fall back to stacked without overwriting the saved layout preference. Keep endpoint search compact and the collapse control aligned with the first filter row.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 90a397e..4e1c9e1 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -109,6 +109,10 @@ methods remain unchanged. These are global runtime rules, not new endpoint confi
remains independent and unchanged. Validation responses are counted against the matched endpoint without retaining
the request content.
+Validation reuses bounded byte buffers and reads JSON tokens without building a document tree.
+All rented buffers are cleared before being returned to the pool, including after failed or cancelled reads.
+These are internal allocation optimizations; payload limits, accepted JSON, and error responses are unchanged.
+
The test blade and all portable request exports provide optional illustrative JSON samples for
`POST`, `PUT`, and `PATCH`. Trailhead inventory reservation routes use a SKU, quantity, and warehouse;
shipping creation routes use a service, parcel weight, and line items. Other routes use a general
@@ -190,6 +194,24 @@ and API description edits. File persistence writes and flushes a temporary file
atomically replaces the configured path. Blob persistence uploads the complete deterministic document as one
replacement operation. Concurrent saves are serialized and converge on the latest active revision.
+File saves, Blob uploads, and unfiltered native exports stream the canonical bytes of one captured
+immutable snapshot without first copying the complete document. Public snapshot exports still return
+independent byte arrays; filtered native exports and generated formats retain their existing serialization.
+
+Every applied replacement still validates the complete candidate and creates fresh runtime endpoint
+instances. For matching stable endpoint IDs, compilation reuses unchanged immutable UTF-8 response
+bodies and ordered header projections, including the pre-limit success response. Body comparison
+uses bounded stack storage rather than retaining a second UTF-16 copy. Route and metadata edits can
+reuse wire data, but status, content type, reason phrase, and delay always come from the new definition.
+Rate-limit permits are never shared between revisions: every successful configuration replacement
+starts fresh limiters, as before. Rejected or stale candidates leave the active snapshot and its
+limiter state untouched. The reuse index is owned by the snapshot, not an unbounded cross-revision cache.
+
+Single-endpoint management mutation responses deserialize only the selected endpoint from the applied
+snapshot's canonical JSON. Unrelated endpoint bodies are skipped without materialization. Returned
+data stays detached, with canonical header ordering and body text; complete candidate validation,
+atomic publication, ETags, and autosave behavior are unchanged.
+
If automatic saving fails, changes remain active but unsaved. The dashboard displays an error and enables
**Retry save**; the management API returns a `500` `autosave-failed` problem with the current ETag.
Retry persistence through **Retry save** or `POST /__mockapi/api/configuration/save` with that ETag, not by
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index e1f62ca..298dcfb 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -61,6 +61,12 @@ pnpm run test:site
pnpm run test:browser:smoke
```
+The site tests check that common-use card headings, descriptions, and links align across desktop
+widths and enlarged text, while narrow viewports retain naturally sized, stacked cards.
+The hero's Docker Hub version badge uses the same Shields.io source as the README and links to the
+published image. Browser tests stub the badge service and verify keyboard access and an accessible
+link name even when the image cannot load.
+
`pnpm run validate:dependency-security` audits pnpm and direct and transitive NuGet
dependencies. Dependency findings are warning-only: the reports remain visible,
but builds and validation continue even when vulnerabilities are found.
diff --git a/docs/MANAGEMENT_API.md b/docs/MANAGEMENT_API.md
index 41b8112..bc79548 100644
--- a/docs/MANAGEMENT_API.md
+++ b/docs/MANAGEMENT_API.md
@@ -99,20 +99,43 @@ classes. If writing fails after response selection, statistics retain the select
the success status of a rate-limited endpoint, with zero completed bytes. Intentional connection aborts
remain separate `aborted` outcomes. Existing logical-request retry coalescing applies to failures too.
+Rolling statistics use contiguous value-type buckets with six packed atomic counters per minute,
+avoiding separate heap objects for every bucket and counter. Recording, snapshot reads, and reset
+operate on the stored counters by reference. This changes storage only: the 60-minute history,
+counter saturation, bounded endpoint tracking, concurrent non-transactional snapshots, and JSON
+contract remain unchanged. No new recording locks or sharded counters are introduced.
+
## Dashboard Synchronization and Caching
-The dashboard opens one authenticated `GET /dashboard/events` connection. It receives a
+The dashboard opens one authenticated `GET /dashboard/events?deltas=true` connection. It receives a
`configuration` event containing the same JSON shape as `/configuration`, followed by a
`statistics` event containing the same shape as `/statistics`. Configuration events are
triggered by atomic snapshot publication, including saves that clear the dirty flag without
incrementing the revision. Invalid or conflicting writes do not publish events.
Statistics are coalesced to at most one update every two seconds and serialized once per
-changed snapshot across connected dashboards. Idle statistics are not retransmitted, except
+shared interval frame across connected dashboards. Idle statistics are not retransmitted, except
at minute boundaries to advance the rolling window. Idle streams send keepalive comments
approximately every 16 seconds. Disable proxy buffering and allow long-lived SSE responses.
The existing `/statistics/events` route remains available with its original behavior.
+All three statistics delivery paths share one bounded management-side cache keyed by the
+collector's version and UTC minute: GET reuses the immutable snapshot, while both SSE routes
+reuse its compact JSON. GET retains its indented JSON formatting and serializer options;
+the standalone statistics stream still transmits every two seconds even when unchanged.
+Recording, retries, and successful resets invalidate the version; an idle minute rollover
+advances both aggregate and endpoint histories. The cache reads the version before capturing
+counters so a recording or reset completing during capture invalidates the next read.
+Snapshots retain the collector's existing concurrent, non-transactional read semantics.
+
+Only management readers acquire the cache lock. Recording never waits for serialization.
+The snapshot cache retains one snapshot and, when requested, one compact string. The delta
+cache additionally retains one current interval frame, its bounded patch, and lazy serializations;
+it does not retain a chain of previous snapshots or a replay queue. A slow connection can hold
+its currently transmitting frame until the write completes.
+SSE framing writes its prefix, compact JSON, and terminator separately, avoiding a second
+full-payload string without changing the event bytes.
+
Reconnects receive current state; there is no replay queue or `Last-Event-ID` history. The
dashboard reloads endpoint definitions only when their revision changes or after reconnecting
(a restart can reuse a numeric revision). Saves at the same revision update the Save button
@@ -120,6 +143,46 @@ without reloading endpoints. Unsupported or failed SSE uses a 15-second completi
poll, which stops after stream recovery. Hidden pages close the stream and abort requests;
returning pages reconnect. Explicit mutations still refresh immediately.
+### Interval Statistics Deltas
+
+The optional Boolean `deltas=true` query selects interval **state patches**, not raw request-event
+replay. Omit it or set it to `false` for the original full `statistics` events without SSE IDs.
+The full `/statistics` API and standalone `/statistics/events` stream are unchanged.
+
+Opt-in statistics frames carry an SSE `id`. The initial `statistics` event contains a complete
+baseline. Subsequent `statistics-delta` JSON has these fields:
+
+| Field | Meaning |
+| -------------------- | ------------------------------------------------------------------------ |
+| `baseSequence` | Sequence of the full view this patch updates |
+| `sequence` | New sequence, also carried by the SSE `id` |
+| `windowStartUtc` | Oldest UTC minute in the retained 60-minute window |
+| `totals` | All eleven absolute aggregate counters, not increments |
+| `recentMinutes` | Only changed aggregate minute buckets, with absolute counts |
+| `endpoints` | Changed endpoint scalar summaries with only their changed minute buckets |
+| `removedEndpointIds` | Stable IDs whose counters must be removed |
+| `recentRequests` | Complete bounded replacement feed, or `null` when unchanged |
+
+Clients discard minutes outside the window, initialize missing minutes to zero, and retain
+unchanged buckets and endpoint summaries. A newly tracked endpoint therefore needs only its
+nonzero buckets. The request feed is replaced atomically, including an empty replacement:
+logical retries can update an existing summary rather than append a new request.
+
+Successful overall or endpoint resets, reconnects, and clients missing an intermediate server
+frame receive a fresh full baseline. Clamped duplicate UTC minute identities also require a
+baseline. SSE IDs guard continuity; they do not enable `Last-Event-ID` replay. The dashboard
+ignores duplicate sequences and closes an unusable stream before recovering at the normal
+15-second polling interval. It keeps its stream baseline separate from immediate HTTP refreshes,
+and retiring a broken stream does not abort an authoritative management refresh.
+
+This reduces repeated serialization, wire traffic, and browser parsing, not the initial baseline
+or full snapshot capture. Local managed Release tests on Windows ARM64/.NET 10.0.13, with
+**256 tracked endpoints and 100 recent summaries**, measured **2,811,112 bytes** for a full
+snapshot versus **21,938 bytes** for one changed endpoint and the replacement feed:
+**99.22% smaller**. The regression test requires a sparse interval to use less than 2% of the full
+payload. Busy intervals touching every endpoint can be larger; these are not throughput,
+container-memory, or universal compression guarantees.
+
Endpoint definitions stay only in page memory, never local storage. Administrative JSON and
dashboard HTML use `Cache-Control: no-store`. The HTML references scripts, styles, and images with
one SHA-256 version derived from the complete dashboard asset set. Matching versioned URLs use
@@ -129,6 +192,12 @@ proxies must not cache authenticated dashboard assets.
Statistics-only updates preserve endpoint row controls and focus unless the selected sort changes
row order. Collapsed panels and inactive statistics views are rendered when shown.
+The Statistics table retains rows by stable endpoint ID or aggregate measure and changes only
+different cell text. The graph retains UTC-keyed columns, their six status segments, and one tooltip.
+It replaces a column only when its button/non-button behavior changes, clears listeners on removed
+or replaced columns, and bounds the cache to the current minute window. Surviving focused columns,
+manual horizontal scroll, and follow-newest behavior are preserved; removed focus returns to the
+timeline. Endpoint switching still uses complete histories already held in page memory.
The Endpoints table offers **Collapse all groups**, switching to **Expand all groups** when all API
groups in the current filtered result are collapsed. With a mixture of expanded and collapsed groups,
the action collapses them all. Groups hidden by filters retain their state; new API groups start
@@ -141,6 +210,138 @@ current buckets are collapsed. New minute buckets start expanded; additional req
existing bucket retain its state. Table columns use stable widths and reserved scrollbar space,
with long values wrapping and horizontal scrolling available on narrow panels.
+### Statistics Allocation Diagnostic
+
+The opt-in [statistics delivery diagnostic](../tests/MockAPI.Tests/Management/StatisticsDeliveryDiagnostics.cs)
+measures the actual GET and SSE handlers against synchronous non-retaining sinks, plus an
+uncached snapshot/serialization reference. Normal regression tests separately pin exact GET
+and SSE bytes, cache invalidation, refreshes, concurrent recording/readers/resets, cancellation,
+and warmed allocation bounds.
+
+On 2026-10-21, local Windows ARM64 managed Release runs on .NET 10.0.13 used **256 tracked
+endpoints**, **100 recent summaries**, and **2,811,113 compact JSON characters**. Tiered
+compilation was disabled. Each allocation result below is the median of five samples of ten
+calls after ten warmups; fixture creation is outside measurement.
+
+| Idle controlling path | Allocated bytes/call before | Allocated bytes/call after |
+| -------------------------------------- | --------------------------- | -------------------------- |
+| GET statistics, indented serialization | 2,301,002 | 1,265,032 |
+| Standalone SSE, one statistics event | 9,650,524 | 1,317,408 |
+| Dashboard SSE, initial two events | 8,794,341 | 1,454,212 |
+| Dashboard compact JSON cache lookup | 0 | 0 |
+
+GET still allocates serializer traversal state; it does not cache a second indented payload.
+The shared cache retains approximately 1 MiB of snapshot data at this fixture size in addition
+to the compact string. Changed versions still require snapshot capture and serialization;
+no improvement is claimed for continuously changing, single-consumer traffic. Array-pool and
+GC behavior affected individual samples, especially full serialization and framing, so these
+figures describe this local experiment, not HTTP throughput, network latency, container memory,
+or cross-environment guarantees. The diagnostic also reports elapsed-time samples.
+
+Repeat against the same fixture, runtime, build configuration, and environment for both revisions:
+
+```powershell
+pwsh -NoProfile -Command {
+ $env:MOCKAPI_STATISTICS_DIAGNOSTICS = '1'
+ $env:DOTNET_TieredCompilation = '0'
+ dotnet test .\tests\MockAPI.Tests\MockAPI.Tests.csproj --no-restore `
+ --configuration Release --filter "FullyQualifiedName~StatisticsDeliveryDiagnostics" `
+ --logger "console;verbosity=detailed"
+ exit $LASTEXITCODE
+}
+```
+
+```bash
+MOCKAPI_STATISTICS_DIAGNOSTICS=1 DOTNET_TieredCompilation=0 \
+ dotnet test ./tests/MockAPI.Tests/MockAPI.Tests.csproj --no-restore \
+ --configuration Release --filter "FullyQualifiedName~StatisticsDeliveryDiagnostics" \
+ --logger "console;verbosity=detailed"
+```
+
+### Recording Contention Diagnostic
+
+The opt-in [recording diagnostic](../tests/MockAPI.Tests/Runtime/StatisticsRecordingDiagnostics.cs)
+runs five fixed-work samples of 120,000 requests with 1, 2, 4, or 8 dedicated workers. Run it
+alone because `Monitor.LockContentionCount` is process-wide. A local Windows ARM64 managed Release
+run on .NET 10.0.13, with tiered compilation disabled, produced these medians:
+
+| Workers | Matched requests/s with bounded feed | Unmatched requests/s without logical ID | Matched monitor contentions/sample |
+| ------- | ------------------------------------ | --------------------------------------- | ---------------------------------- |
+| 1 | 2.59 million | 6.41 million | 0 |
+| 2 | 2.85 million | 5.70 million | 18 |
+| 4 | 2.96 million | 6.00 million | 45 |
+| 8 | 2.57 million | 5.70 million | 53 |
+
+These paths do different work. Monitor counts do not attribute contention to one gate and do not
+measure spinning, cache-line traffic, or HTTP throughput. The probe does not isolate a bottleneck
+that justifies sharding counters or replacing synchronization, so recording locks remain unchanged.
+Use attributable profiling under a representative deployment load before such a redesign.
+
+```powershell
+pwsh -NoProfile -Command {
+ $env:MOCKAPI_RECORDING_DIAGNOSTICS = '1'
+ $env:DOTNET_TieredCompilation = '0'
+ dotnet test .\tests\MockAPI.Tests\MockAPI.Tests.csproj --no-restore `
+ --configuration Release --filter "FullyQualifiedName~StatisticsRecordingDiagnostics" `
+ --logger "console;verbosity=detailed"
+ exit $LASTEXITCODE
+}
+```
+
+```bash
+MOCKAPI_RECORDING_DIAGNOSTICS=1 DOTNET_TieredCompilation=0 \
+ dotnet test ./tests/MockAPI.Tests/MockAPI.Tests.csproj --no-restore \
+ --configuration Release --filter "FullyQualifiedName~StatisticsRecordingDiagnostics" \
+ --logger "console;verbosity=detailed"
+```
+
+### Backend Allocation Diagnostic
+
+The opt-in [backend diagnostic](../tests/MockAPI.Tests/Runtime/BackendRefactoringDiagnostics.cs)
+measures repeated unchanged configuration replacement, population of all 256 tracked endpoint
+counters, and valid and invalid API-key verification. Regression tests separately enforce compiled
+body/header reuse, independent limiter permits, bounded population allocations, and allocation-free
+warmed key verification with minimum, generated-length, and maximum-length keys.
+
+Local Windows ARM64 managed Release measurements on .NET 10.0.13, with tiered compilation disabled,
+produced these medians of five samples after ten warmups:
+
+| Operation | Allocated bytes/call before | Allocated bytes/call after |
+| ------------------------------------------------------ | --------------------------- | -------------------------- |
+| Full replacement, four unchanged 960 KiB bodies | 10,394,519 | 6,045,249 |
+| Populate 256 endpoint counters | 3,513,888 | 858,784 |
+| Verify a valid 43-character key, existing HTTP context | 216 | 0 |
+| Verify an invalid 43-character key, existing context | 216 | 0 |
+
+Configuration and population samples contain ten operations; authentication samples contain 1,000.
+Fixture documents, endpoint IDs, keys, and HTTP contexts are created outside measurement. Full
+configuration replacement still clones, validates, and serializes the complete document. Serializer
+pooling and GC introduce allocation variation; response-data reuse saves body/header recompilation,
+not those required document operations. The stable-ID index adds bounded per-snapshot bookkeeping,
+and authentication retains one decoded digest alongside the persisted hexadecimal representation.
+
+These are allocation measurements, not retained-heap, RSS, contention, HTTP-throughput, or Native AOT
+results. Counter synchronization is unchanged; do not infer parallel throughput gains from the
+smaller object graph. The diagnostic also reports elapsed-time samples.
+
+```powershell
+pwsh -NoProfile -Command {
+ $env:MOCKAPI_BACKEND_DIAGNOSTICS = '1'
+ $env:DOTNET_TieredCompilation = '0'
+ dotnet test .\tests\MockAPI.Tests\MockAPI.Tests.csproj --no-restore `
+ --configuration Release --filter "FullyQualifiedName~BackendRefactoringDiagnostics" `
+ --logger "console;verbosity=detailed"
+ exit $LASTEXITCODE
+}
+```
+
+```bash
+MOCKAPI_BACKEND_DIAGNOSTICS=1 DOTNET_TieredCompilation=0 \
+ dotnet test ./tests/MockAPI.Tests/MockAPI.Tests.csproj --no-restore \
+ --configuration Release --filter "FullyQualifiedName~BackendRefactoringDiagnostics" \
+ --logger "console;verbosity=detailed"
+```
+
## Configuration Read Efficiency
Configuration status reads and SSE configuration-event projections use an owned, immutable
@@ -148,6 +349,15 @@ API-description projection from the captured snapshot. They do not deserialize e
or response bodies just to retrieve metadata. Persistence-status-only updates share this projection
while keeping descriptions, revision, and ETag consistent.
+Single-endpoint mutation responses scan the captured canonical JSON and deserialize only the
+selected endpoint, skipping unrelated endpoint bodies. They still return detached, canonical data
+from the applied revision, and complete candidate validation and atomic publication are unchanged.
+The opt-in backend allocation diagnostic compares this with materializing the entire document.
+With four unrelated 960 KiB bodies and one small selected endpoint, five ten-call managed Release
+samples measured a median **7,869,780 bytes/read** for the full-document path versus
+**1,343 bytes/read** for targeted extraction. The scan remains proportional to the bytes preceding
+the selected endpoint; this does not make configuration writes allocation-free.
+
Unfiltered native exports, including requests with omitted or empty endpoint IDs, use the snapshot's
canonical serialized bytes without first materializing a configuration document. This removes a
redundant parse and object graph, not the allocation needed to return detached export bytes. Selected
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 4d2ffd5..1067888 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -99,6 +99,11 @@ configuration volume or private Blob container. Endpoint import/export/save neve
document restores the fail-closed default unless a deployment key seeds it again; otherwise generate a
replacement key as an administrator.
+The hexadecimal digest is decoded once when security state is loaded or successfully committed,
+and published together with its revision and enforcement setting. Request verification uses
+independent bounded stack buffers, compares hashes in constant time, and clears its scratch storage
+before returning. It does not cache plaintext request keys or change the persisted security format.
+
For a deliberately unauthenticated local fixture, set `MockApi__RequireApiKey=false` before the first security
document is saved. Persisted security settings take precedence over this bootstrap setting. Operators can also
explicitly disable enforcement in Settings after confirming the exposure warning. Do not opt a shared or
diff --git a/docs/PLAN.md b/docs/PLAN.md
index b9d5f57..cf018d3 100644
--- a/docs/PLAN.md
+++ b/docs/PLAN.md
@@ -84,6 +84,11 @@ Use one ASP.NET Core application and one deployable container.
A catch-all dispatcher is preferred over adding conventional ASP.NET endpoints after startup. Configuration mutations build and validate a replacement snapshot, then swap it atomically so in-flight requests continue against a consistent prior snapshot.
+Compilation may share unchanged immutable response bytes and ordered headers by stable endpoint ID
+with the prior snapshot, but never shares mutable rate limiters. Every applied configuration
+replacement retains the existing fresh-permit behavior, including replacements that only edit
+metadata. Reuse remains snapshot-owned and does not retain a chain of prior registries.
+
### Suggested project boundaries
Keep a single deployable web project, but separate responsibilities in code:
@@ -396,6 +401,19 @@ The UI must be keyboard usable and responsive, with WCAG 2.2 AA as the design an
status, including rate-limit success responses. Intentional connection aborts remain a distinct outcome.
- Attribute attempts by stable endpoint ID, not path, so edits do not corrupt identity.
- Use atomic counters for totals and a bounded ring buffer of 60 one-minute buckets, retaining 60 minutes of recent rate data.
+- Store minute buckets and packed atomic counters contiguously as value types. Read and update
+ the stored counters by reference, preserving volatile access, rollover, saturation, and reset semantics.
+- Share one immutable statistics snapshot and lazy compact SSE serialization across management
+ delivery paths while the collector version and UTC minute are unchanged. Keep cache locks off
+ recorders, retain non-transactional concurrent snapshot semantics, preserve indented GET JSON,
+ and keep dashboard coalescing distinct from the standalone stream's two-second refresh.
+- Let the dashboard opt into sequenced interval state deltas after a full baseline, while retaining
+ full GET and default stream compatibility. Send absolute counter and changed-minute values,
+ replace the bounded request feed only when changed, and require full baselines after resets,
+ reconnects, or missed bases. Keep one shared current frame, not request-event replay history.
+- Retain Statistics rows by stable endpoint ID or aggregate measure and chart columns by UTC minute.
+ Bound rendering caches to the current data, dispose replaced listeners, and preserve focus,
+ timeline scroll, and immediate endpoint-history switching.
- Retain at most 100 newest-first request summaries containing only timestamp, method, normalized path, stable endpoint ID, outcome, status, and response byte count.
- Do not retain request or response bodies, authorization headers, cookies, or query values.
- Treat statistics as process-local and reset them on restart in the initial release.
@@ -436,6 +454,8 @@ The initial ARM64 experiment measured 26.83 MB for Alpine CoreCLR and 27.11 MB f
- Generate 32-byte random keys, compare SHA-256 hashes in constant time, and keep only the hash in a separate
security document beside the configuration file or blob. Persist before atomic activation; use an independent
strong ETag for security writes. Rotation enables protection and immediately revokes the previous key.
+- Decode the persisted digest once per published security state. Use independently owned bounded
+ stack storage for request verification, clear it before return, and preserve constant-time comparison.
- Support fully automatic initial key setup through the optional secret-backed `MockApi__ApiKey` setting
and secure `mockApiKey` Bicep parameter (`AZURE_MOCKAPI_KEY` in both developer CLIs). Accept 32-256 ASCII
letters, digits, hyphens, or underscores. If no security document exists, persist only the supplied key's
diff --git a/site/index.html b/site/index.html
index 7a70a8b..ff87031 100644
--- a/site/index.html
+++ b/site/index.html
@@ -188,6 +188,15 @@
Make your first request
Common uses
Mock API examples for development and testing
-
+
Develop against an unavailable API
@@ -479,6 +488,18 @@
Live request view
Understand request statistics
+
+ APIM Samples integration
+
+ Easily connect APIM Samples to your custom mock APIs. Import live OpenAPI definitions into Azure API
+ Management and use MockAPI as the backend for your scenarios.
+
+
+ Connect custom APIs to APIM
+
+
diff --git a/site/site.css b/site/site.css
index 1851143..9c5c85b 100644
--- a/site/site.css
+++ b/site/site.css
@@ -168,6 +168,17 @@ figcaption {
.actions {
margin-block: 2rem;
}
+.docker-hub-badge {
+ display: inline-flex;
+ align-items: center;
+ max-width: 100%;
+ min-height: 36px;
+}
+.docker-hub-badge img {
+ display: block;
+ max-width: 100%;
+ height: auto;
+}
.button,
.icon-button {
display: inline-flex;
@@ -407,6 +418,23 @@ footer {
font-size: 0.9rem;
}
+@media (min-width: 951px) {
+ .example-cards {
+ row-gap: 0;
+ }
+ .example-cards > .card {
+ display: grid;
+ grid-template-rows: subgrid;
+ grid-row: span 3;
+ }
+ .example-cards > .card > p {
+ margin-top: 0;
+ }
+ .example-cards > .card > :last-child {
+ align-self: start;
+ }
+}
+
@media (max-width: 950px) {
.cards,
.start-cards,
diff --git a/src/MockAPI/Configuration/ConfigurationBlobStore.cs b/src/MockAPI/Configuration/ConfigurationBlobStore.cs
index f77dd62..cf528ed 100644
--- a/src/MockAPI/Configuration/ConfigurationBlobStore.cs
+++ b/src/MockAPI/Configuration/ConfigurationBlobStore.cs
@@ -11,7 +11,7 @@ public sealed class ConfigurationBlobStore : IConfigurationStore
{
private readonly MockApiOptions _options;
private readonly Func> _download;
- private readonly Func, CancellationToken, Task> _upload;
+ private readonly Func _upload;
private readonly ConfigurationPersistenceCoordinator _coordinator;
/// Initializes an Azure Blob configuration store.
@@ -38,7 +38,7 @@ public ConfigurationBlobStore(MockApiOptions options, BlobClient blobClient)
async (content, cancellationToken) =>
{
await blobClient.UploadAsync(
- BinaryData.FromBytes(content),
+ content,
overwrite: true,
cancellationToken);
})
@@ -48,7 +48,7 @@ await blobClient.UploadAsync(
internal ConfigurationBlobStore(
MockApiOptions options,
Func> download,
- Func, CancellationToken, Task> upload,
+ Func upload,
Func? onSnapshotCaptured = null,
Func? onDocumentLoaded = null)
{
@@ -146,7 +146,8 @@ public async Task SaveAsync(
{
try
{
- await _upload(snapshot.ExportUtf8(), saveCancellationToken);
+ using var content = snapshot.OpenRead();
+ await _upload(content, saveCancellationToken);
}
catch (RequestFailedException exception)
{
diff --git a/src/MockAPI/Configuration/ConfigurationFileStore.cs b/src/MockAPI/Configuration/ConfigurationFileStore.cs
index ae7abdc..ff23418 100644
--- a/src/MockAPI/Configuration/ConfigurationFileStore.cs
+++ b/src/MockAPI/Configuration/ConfigurationFileStore.cs
@@ -154,7 +154,7 @@ public async Task SaveAsync(
bufferSize: 64 * 1024,
FileOptions.Asynchronous | FileOptions.WriteThrough))
{
- await stream.WriteAsync(snapshot.ExportUtf8(), saveCancellationToken);
+ await snapshot.WriteToAsync(stream, saveCancellationToken);
await stream.FlushAsync(saveCancellationToken);
stream.Flush(flushToDisk: true);
}
diff --git a/src/MockAPI/Configuration/ConfigurationState.cs b/src/MockAPI/Configuration/ConfigurationState.cs
index 366ea11..efbae5e 100644
--- a/src/MockAPI/Configuration/ConfigurationState.cs
+++ b/src/MockAPI/Configuration/ConfigurationState.cs
@@ -69,7 +69,8 @@ private ConfigurationUpdateResult TryReplace(
ArgumentNullException.ThrowIfNull(candidate);
ArgumentOutOfRangeException.ThrowIfNegative(expectedRevision);
- if (Current.Revision != expectedRevision)
+ var observed = Current;
+ if (observed.Revision != expectedRevision)
{
return ConfigurationUpdateResult.RevisionConflict();
}
@@ -81,7 +82,7 @@ private ConfigurationUpdateResult TryReplace(
return ConfigurationUpdateResult.ValidationFailed(validation);
}
- var endpoints = EndpointRegistrySnapshot.Create(canonicalDocument);
+ var endpoints = EndpointRegistrySnapshot.Create(canonicalDocument, observed.Endpoints);
_beforeWriteLock?.Invoke();
lock (_writeGate)
{
@@ -170,10 +171,62 @@ private ConfigurationStateSnapshot(
public MockApiConfigurationDocument GetDocument() =>
DeserializeDocument(_serializedDocument);
+ internal MockEndpointDefinition GetEndpoint(Guid endpointId)
+ {
+ var reader = new Utf8JsonReader(_serializedDocument);
+ while (reader.Read())
+ {
+ if (reader.TokenType != JsonTokenType.PropertyName || reader.CurrentDepth != 1 ||
+ !reader.ValueTextEquals("endpoints"))
+ {
+ continue;
+ }
+
+ reader.Read();
+ while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
+ {
+ if (HasEndpointId(reader, endpointId))
+ {
+ // Deserialize from the captured canonical bytes, but do not materialize unrelated bodies.
+ return JsonSerializer.Deserialize(ref reader, MockApiJsonContext.Default.MockEndpointDefinition)!;
+ }
+ reader.Skip();
+ }
+ break;
+ }
+
+ throw new InvalidOperationException("The captured configuration does not contain the requested endpoint.");
+ }
+
+ private static bool HasEndpointId(Utf8JsonReader reader, Guid endpointId)
+ {
+ // Probe a value copy so the caller can still deserialize from the object's opening token.
+ while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
+ {
+ if (reader.ValueTextEquals("id"))
+ {
+ reader.Read();
+ return reader.GetGuid() == endpointId;
+ }
+ reader.Skip();
+ }
+ return false;
+ }
+
/// Copies the deterministic UTF-8 JSON representation of this snapshot.
/// A new byte array that callers may modify without affecting this snapshot.
public byte[] ExportUtf8() => [.. _serializedDocument];
+ internal ValueTask WriteToAsync(Stream destination, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(destination);
+ return destination.WriteAsync(_serializedDocument.AsMemory(), cancellationToken);
+ }
+
+ // SDK consumers may seek and retry reads, but cannot write or expose the owned buffer.
+ internal Stream OpenRead() => new MemoryStream(
+ _serializedDocument, 0, _serializedDocument.Length, writable: false, publiclyVisible: false);
+
internal static MockApiConfigurationDocument DeserializeDocument(ReadOnlySpan serializedDocument) =>
JsonSerializer.Deserialize(
serializedDocument,
diff --git a/src/MockAPI/Management/ApiKeySecurity.cs b/src/MockAPI/Management/ApiKeySecurity.cs
index f036203..5a8623f 100644
--- a/src/MockAPI/Management/ApiKeySecurity.cs
+++ b/src/MockAPI/Management/ApiKeySecurity.cs
@@ -38,7 +38,7 @@ internal sealed class ApiKeySecurity(MockApiOptions options, BlobClient? blobCli
internal const string HeaderName = "X-MockAPI-Key";
private const int MaximumSecurityDocumentBytes = 4096;
private readonly SemaphoreSlim _writes = new(1, 1);
- private ApiSecurityDocument _current = new(options.RequireApiKey, null, 0);
+ private ApiSecuritySnapshot _current = new(new ApiSecurityDocument(options.RequireApiKey, null, 0));
private readonly string _path = options.ConfigurationPath + ".security.json";
private readonly BlobClient? _blobClient = blobClient ?? (options.ConfigurationBlobUri is null ? null : CreateBlobClient(options));
@@ -46,7 +46,7 @@ internal ApiSecurityStatus Status
{
get
{
- var snapshot = Volatile.Read(ref _current);
+ var snapshot = Volatile.Read(ref _current).Document;
return new(snapshot.Enabled, snapshot.KeyHash is not null, $"\"{snapshot.Revision}\"");
}
}
@@ -54,7 +54,7 @@ internal ApiSecurityStatus Status
internal bool Authorizes(HttpContext context)
{
var snapshot = Volatile.Read(ref _current);
- if (!snapshot.Enabled)
+ if (!snapshot.Document.Enabled)
{
return true;
}
@@ -65,8 +65,20 @@ internal bool Authorizes(HttpContext context)
return false;
}
- var suppliedHash = SHA256.HashData(Encoding.UTF8.GetBytes(key));
- return CryptographicOperations.FixedTimeEquals(suppliedHash, Convert.FromHexString(snapshot.KeyHash));
+ // Each call owns its stack buffers; concurrent requests never share plaintext or hash scratch storage.
+ Span encodedKey = stackalloc byte[256];
+ Span suppliedHash = stackalloc byte[SHA256.HashSizeInBytes];
+ try
+ {
+ var written = Encoding.UTF8.GetBytes(key.AsSpan(), encodedKey);
+ SHA256.HashData(encodedKey[..written], suppliedHash);
+ return CryptographicOperations.FixedTimeEquals(suppliedHash, snapshot.KeyHash);
+ }
+ finally
+ {
+ CryptographicOperations.ZeroMemory(encodedKey);
+ CryptographicOperations.ZeroMemory(suppliedHash);
+ }
}
internal async Task LoadAsync(CancellationToken cancellationToken)
@@ -120,7 +132,7 @@ internal async Task LoadAsync(CancellationToken cancellationToken)
throw new InvalidOperationException("API security settings contain an invalid revision or key hash.");
}
- Volatile.Write(ref _current, document);
+ Volatile.Write(ref _current, new ApiSecuritySnapshot(document));
}
internal async Task UpdateAsync(
@@ -140,7 +152,7 @@ internal async Task LoadAsync(CancellationToken cancellationToken)
var key = rotate
? Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
: null;
- var previous = Volatile.Read(ref _current);
+ var previous = Volatile.Read(ref _current).Document;
var hash = key is null ? previous.KeyHash : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key)));
var candidate = new ApiSecurityDocument(enabled, hash, checked(previous.Revision + 1));
await CommitAsync(candidate, cancellationToken);
@@ -152,9 +164,23 @@ internal async Task LoadAsync(CancellationToken cancellationToken)
}
}
- private static bool IsValidKey(string key) =>
- key.Length is >= 32 and <= 256 &&
- key.All(character => char.IsAsciiLetterOrDigit(character) || character is '-' or '_');
+ private static bool IsValidKey(string key)
+ {
+ if (key.Length is < 32 or > 256)
+ {
+ return false;
+ }
+
+ foreach (var character in key)
+ {
+ if (!char.IsAsciiLetterOrDigit(character) && character is not '-' and not '_')
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
private async Task InitializeAsync(CancellationToken cancellationToken)
{
@@ -169,10 +195,19 @@ private async Task InitializeAsync(CancellationToken cancellationToken)
private async Task CommitAsync(ApiSecurityDocument candidate, CancellationToken cancellationToken)
{
+ var replacement = new ApiSecuritySnapshot(candidate);
var content = JsonSerializer.SerializeToUtf8Bytes(candidate, ApiSecurityJsonContext.Default.ApiSecurityDocument);
await PersistAsync(content, cancellationToken);
// Publish only after durable replacement; failed saves never change request authorization.
- Volatile.Write(ref _current, candidate);
+ Volatile.Write(ref _current, replacement);
+ }
+
+ private sealed class ApiSecuritySnapshot(ApiSecurityDocument document)
+ {
+ internal ApiSecurityDocument Document { get; } = document;
+
+ // Decode once, publishing the digest together with its revision and enforcement flag.
+ internal byte[]? KeyHash { get; } = document.KeyHash is { } hash ? Convert.FromHexString(hash) : null;
}
private static BlobClient CreateBlobClient(MockApiOptions options)
diff --git a/src/MockAPI/Management/DashboardEventStream.cs b/src/MockAPI/Management/DashboardEventStream.cs
index 1447c21..91cb812 100644
--- a/src/MockAPI/Management/DashboardEventStream.cs
+++ b/src/MockAPI/Management/DashboardEventStream.cs
@@ -5,23 +5,47 @@
namespace MockAPI.Management;
/// Streams configuration invalidations and coalesced statistics without per-client event queues.
-public sealed class DashboardEventStream(
- ConfigurationState configuration,
- RequestStatisticsCollector statistics,
- TimeProvider? timeProvider = null)
+public sealed class DashboardEventStream
{
private static readonly ManagementJsonContext JsonContext = new(
new JsonSerializerOptions(ManagementJsonContext.Default.Options) { WriteIndented = false });
- private readonly TimeProvider _timeProvider = timeProvider ?? TimeProvider.System;
- private readonly object _cacheGate = new();
- private (long Version, long Minute) _statisticsKey = (-1, -1);
- private string _statisticsJson = string.Empty;
+ private readonly ConfigurationState _configuration;
+ private readonly StatisticsSnapshotCache _statistics;
+ private readonly TimeProvider _timeProvider;
+ private readonly StatisticsDeltaCache _deltas;
+
+ /// Initializes a dashboard stream with a bounded statistics cache shared by its connections.
+ /// The configuration source for invalidation events.
+ /// The collector whose UTC clock determines statistics minute rollover.
+ /// The stream timer and keepalive clock, or for the system clock.
+ public DashboardEventStream(
+ ConfigurationState configuration,
+ RequestStatisticsCollector statistics,
+ TimeProvider? timeProvider = null)
+ : this(configuration, new StatisticsSnapshotCache(statistics), timeProvider)
+ {
+ }
+
+ internal DashboardEventStream(
+ ConfigurationState configuration,
+ StatisticsSnapshotCache statistics,
+ TimeProvider? timeProvider = null)
+ {
+ _configuration = configuration;
+ _statistics = statistics;
+ _timeProvider = timeProvider ?? TimeProvider.System;
+ _deltas = new StatisticsDeltaCache(statistics, _timeProvider);
+ }
/// Writes initial state, immediate configuration changes, and at most one statistics update every two seconds.
/// The authenticated management request; disconnecting cancels all stream work.
/// A task that completes when the client disconnects.
/// Reconnects receive current state, not replayed history. Idle streams send keepalive comments.
- public async Task WriteAsync(HttpContext context)
+ public Task WriteAsync(HttpContext context) => WriteAsync(context, useDeltas: false);
+
+ // Delta delivery is opt-in; legacy clients continue receiving complete statistics events.
+ // Every connection starts from current state, irrespective of an EventSource Last-Event-ID resume hint.
+ internal async Task WriteAsync(HttpContext context, bool useDeltas)
{
var cancellation = context.RequestAborted;
context.Response.ContentType = "text/event-stream";
@@ -30,18 +54,19 @@ public async Task WriteAsync(HttpContext context)
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2), _timeProvider);
ConfigurationStateSnapshot? observed = null;
string? sentStatistics = null;
+ long? sentSequence = null;
var lastWrite = _timeProvider.GetUtcNow();
Task tick = Task.CompletedTask;
try
{
while (!cancellation.IsCancellationRequested)
{
- var current = configuration.Current;
+ var current = _configuration.Current;
var wrote = false;
if (!ReferenceEquals(observed, current))
{
var status = ConfigurationStatusResponse.FromSnapshot(current);
- await WriteEventAsync(context, "configuration", JsonSerializer.Serialize(status, JsonContext.ConfigurationStatusResponse));
+ await ManagementEventWriter.WriteAsync(context, "configuration", JsonSerializer.Serialize(status, JsonContext.ConfigurationStatusResponse));
observed = current;
wrote = true;
}
@@ -49,12 +74,30 @@ public async Task WriteAsync(HttpContext context)
if (tick.IsCompleted)
{
await tick;
- var json = GetStatisticsJson();
- if (!ReferenceEquals(sentStatistics, json))
+ if (useDeltas)
+ {
+ var frame = _deltas.GetFrame();
+ if (sentSequence != frame.Sequence)
+ {
+ // A patch is valid only against the state this connection last received. First delivery,
+ // resets, and slow clients that missed a frame get a full baseline, not a partial patch.
+ var canApplyDelta = frame.Delta is { } delta && delta.BaseSequence == sentSequence;
+ await ManagementEventWriter.WriteAsync(context,
+ canApplyDelta ? "statistics-delta" : "statistics",
+ canApplyDelta ? frame.GetDeltaJson() : frame.GetSnapshotJson(), frame.Sequence);
+ sentSequence = frame.Sequence;
+ wrote = true;
+ }
+ }
+ else
{
- await WriteEventAsync(context, "statistics", json);
- sentStatistics = json;
- wrote = true;
+ var json = GetStatisticsJson();
+ if (!ReferenceEquals(sentStatistics, json))
+ {
+ await ManagementEventWriter.WriteAsync(context, "statistics", json);
+ sentStatistics = json;
+ wrote = true;
+ }
}
tick = timer.WaitForNextTickAsync(cancellation).AsTask();
}
@@ -70,7 +113,7 @@ public async Task WriteAsync(HttpContext context)
lastWrite = _timeProvider.GetUtcNow();
}
- await Task.WhenAny(configuration.WaitForChangeAsync(observed), tick);
+ await Task.WhenAny(_configuration.WaitForChangeAsync(observed), tick);
}
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
@@ -79,20 +122,5 @@ public async Task WriteAsync(HttpContext context)
}
}
- internal string GetStatisticsJson()
- {
- lock (_cacheGate)
- {
- var key = (statistics.Version, _timeProvider.GetUtcNow().ToUnixTimeSeconds() / 60);
- if (_statisticsKey != key)
- {
- _statisticsJson = JsonSerializer.Serialize(statistics.GetSnapshot(), JsonContext.RequestStatisticsSnapshot);
- _statisticsKey = key;
- }
- return _statisticsJson;
- }
- }
-
- private static Task WriteEventAsync(HttpContext context, string name, string json) =>
- context.Response.WriteAsync($"event: {name}\ndata: {json}\n\n", context.RequestAborted);
+ internal string GetStatisticsJson() => _statistics.GetCompactJson();
}
diff --git a/src/MockAPI/Management/EndpointManagementService.cs b/src/MockAPI/Management/EndpointManagementService.cs
index 655ac1d..739a750 100644
--- a/src/MockAPI/Management/EndpointManagementService.cs
+++ b/src/MockAPI/Management/EndpointManagementService.cs
@@ -180,7 +180,7 @@ private ManagementOperationResult Apply(
return FromUpdate(update, endpoint: null);
}
- var endpoint = update.Snapshot!.GetDocument().Endpoints.Single(candidate => candidate.Id == endpointId);
+ var endpoint = update.Snapshot!.GetEndpoint(endpointId);
return ManagementOperationResult.Applied(update.Snapshot, endpoint);
}
diff --git a/src/MockAPI/Management/ManagementApiEndpoints.cs b/src/MockAPI/Management/ManagementApiEndpoints.cs
index 642ee28..b4bedc5 100644
--- a/src/MockAPI/Management/ManagementApiEndpoints.cs
+++ b/src/MockAPI/Management/ManagementApiEndpoints.cs
@@ -16,8 +16,6 @@ public static class ManagementApiEndpoints
private const string BasePath = "/__mockapi/api";
private const string ProblemBase = "https://mockapi.local/problems/";
private const string AutoSaveDescription = " Changes activate immediately and are saved automatically. A 500 autosave-failed problem means the change is active but unsaved; retry persistence with configuration/save, not the mutation.";
- private static readonly ManagementJsonContext CompactJsonContext = new(
- new JsonSerializerOptions(ManagementJsonContext.Default.Options) { WriteIndented = false });
/// Maps all management configuration, endpoint, and statistics routes under /__mockapi/api .
/// The application receiving the routes.
@@ -42,12 +40,14 @@ public static void Map(
MapConfigurationEndpoints(group, service, configuration);
MapEndpointEndpoints(group, service, configuration);
- MapStatisticsEndpoints(group, statistics);
- var dashboardEvents = new DashboardEventStream(app.Services.GetRequiredService(), statistics);
- group.MapGet("/dashboard/events", (HttpContext context, CancellationToken _) => dashboardEvents.WriteAsync(context))
+ var statisticsCache = new StatisticsSnapshotCache(statistics);
+ MapStatisticsEndpoints(group, statistics, statisticsCache);
+ var dashboardEvents = new DashboardEventStream(app.Services.GetRequiredService(), statisticsCache);
+ group.MapGet("/dashboard/events", (HttpContext context, bool? deltas, CancellationToken _) =>
+ dashboardEvents.WriteAsync(context, useDeltas: deltas is true))
.WithName("StreamDashboardEvents")
.WithSummary("Stream configuration changes and live statistics")
- .WithDescription("Sends current configuration status and statistics on connect, configuration events after edits or saves, coalesced statistics events, and idle keepalive comments. Reconnect to resynchronize; no event history is retained.")
+ .WithDescription("Sends current configuration status and statistics on connect, configuration events after edits or saves, coalesced statistics events, and idle keepalive comments. Opt in with deltas=true for sequenced statistics-delta events after a full statistics baseline. Resets, reconnects, and missed bases receive a full baseline; no replay queue is retained. Default payloads remain full snapshots.")
.Produces(StatusCodes.Status200OK, "text/event-stream");
}
@@ -241,14 +241,17 @@ private static void MapEndpointEndpoints(
StatusCodes.Status500InternalServerError);
}
- private static void MapStatisticsEndpoints(RouteGroupBuilder group, RequestStatisticsCollector statistics)
+ private static void MapStatisticsEndpoints(
+ RouteGroupBuilder group,
+ RequestStatisticsCollector statistics,
+ StatisticsSnapshotCache statisticsCache)
{
- group.MapGet("/statistics", (HttpContext context, CancellationToken _) => WriteStatisticsAsync(context, statistics))
+ group.MapGet("/statistics", (HttpContext context, CancellationToken _) => WriteStatisticsAsync(context, statisticsCache))
.WithName("GetStatistics")
.WithSummary("Get aggregate and per-endpoint request statistics")
.Produces(StatusCodes.Status200OK, "application/json");
- group.MapGet("/statistics/events", (HttpContext context, CancellationToken _) => StreamStatisticsAsync(context, statistics))
+ group.MapGet("/statistics/events", (HttpContext context, CancellationToken _) => StreamStatisticsAsync(context, statisticsCache))
.WithName("StreamStatisticsEvents")
.WithSummary("Stream request statistics as server-sent events")
.Produces(StatusCodes.Status200OK, "text/event-stream");
@@ -515,11 +518,15 @@ await WriteProblemAsync(
context.Response.StatusCode = StatusCodes.Status200OK;
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Headers.ContentDisposition = "attachment; filename=mockapi.json";
- var content = endpointIds is null or { Length: 0 }
- ? snapshot.ExportUtf8()
- : JsonSerializer.SerializeToUtf8Bytes(
- FilterExportDocument(snapshot.GetDocument(), endpointIds),
- MockApiJsonContext.Default.MockApiConfigurationDocument);
+ if (endpointIds is null or { Length: 0 })
+ {
+ await snapshot.WriteToAsync(context.Response.Body, context.RequestAborted);
+ return;
+ }
+
+ var content = JsonSerializer.SerializeToUtf8Bytes(
+ FilterExportDocument(snapshot.GetDocument(), endpointIds),
+ MockApiJsonContext.Default.MockApiConfigurationDocument);
await context.Response.Body.WriteAsync(content, context.RequestAborted);
}
@@ -604,7 +611,7 @@ await WriteProblemAsync(
}
}
- private static Task WriteStatisticsAsync(HttpContext context, RequestStatisticsCollector statistics) =>
+ internal static Task WriteStatisticsAsync(HttpContext context, StatisticsSnapshotCache statistics) =>
WriteJsonAsync(
context,
StatusCodes.Status200OK,
@@ -613,24 +620,26 @@ private static Task WriteStatisticsAsync(HttpContext context, RequestStatisticsC
internal static async Task StreamStatisticsAsync(
HttpContext context,
- RequestStatisticsCollector statistics)
+ StatisticsSnapshotCache statistics)
{
context.Response.StatusCode = StatusCodes.Status200OK;
context.Response.ContentType = "text/event-stream";
context.Response.Headers.CacheControl = "no-cache";
context.Response.Headers.Connection = "keep-alive";
- while (!context.RequestAborted.IsCancellationRequested)
- {
- var json = JsonSerializer.Serialize(
- statistics.GetSnapshot(),
- CompactJsonContext.RequestStatisticsSnapshot);
- await context.Response.WriteAsync("event: statistics\ndata: ", context.RequestAborted);
- await context.Response.WriteAsync(json, context.RequestAborted);
- await context.Response.WriteAsync("\n\n", context.RequestAborted);
- await context.Response.Body.FlushAsync(context.RequestAborted);
- await Task.Delay(TimeSpan.FromSeconds(2), context.RequestAborted)
- .ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
+ try
+ {
+ while (!context.RequestAborted.IsCancellationRequested)
+ {
+ await ManagementEventWriter.WriteAsync(context, "statistics", statistics.GetCompactJson());
+ await context.Response.Body.FlushAsync(context.RequestAborted);
+ await Task.Delay(TimeSpan.FromSeconds(2), context.RequestAborted)
+ .ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
+ }
+ }
+ catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
+ {
+ // A disconnect during framing or flushing is as normal as cancellation between events.
}
}
diff --git a/src/MockAPI/Management/ManagementEventWriter.cs b/src/MockAPI/Management/ManagementEventWriter.cs
new file mode 100644
index 0000000..5b2b46f
--- /dev/null
+++ b/src/MockAPI/Management/ManagementEventWriter.cs
@@ -0,0 +1,17 @@
+namespace MockAPI.Management;
+
+/// Writes compact JSON SSE frames without copying the payload into a second full-size string.
+internal static class ManagementEventWriter
+{
+ internal static async Task WriteAsync(HttpContext context, string name, string json, long? sequence = null)
+ {
+ var cancellation = context.RequestAborted;
+ if (sequence is { } value)
+ {
+ await context.Response.WriteAsync($"id: {value.ToString(System.Globalization.CultureInfo.InvariantCulture)}\n", cancellation);
+ }
+ await context.Response.WriteAsync($"event: {name}\ndata: ", cancellation);
+ await context.Response.WriteAsync(json, cancellation);
+ await context.Response.WriteAsync("\n\n", cancellation);
+ }
+}
diff --git a/src/MockAPI/Management/StatisticsDeltaCache.cs b/src/MockAPI/Management/StatisticsDeltaCache.cs
new file mode 100644
index 0000000..4e882ed
--- /dev/null
+++ b/src/MockAPI/Management/StatisticsDeltaCache.cs
@@ -0,0 +1,181 @@
+using System.Collections.Immutable;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using MockAPI.Runtime;
+
+namespace MockAPI.Management;
+
+/// Shares interval state patches instead of resending every endpoint's sixty-minute history.
+///
+/// This is not request-event replay: each patch compares two bounded snapshots. The cache owns only the current
+/// frame, so slow clients recover with a full baseline instead of requiring an ever-growing delivery queue.
+///
+internal sealed class StatisticsDeltaCache(StatisticsSnapshotCache statistics, TimeProvider clock)
+{
+ private readonly object _gate = new();
+ private StatisticsDeltaFrame? _current;
+ private DateTimeOffset _lastCapture;
+ private DateTimeOffset _nextCapture;
+
+ internal StatisticsDeltaFrame GetFrame()
+ {
+ // Coalesce comparison work across clients once per interval. Request recording never takes this gate.
+ lock (_gate)
+ {
+ var now = clock.GetUtcNow();
+ if (_current is not null && now >= _lastCapture && now < _nextCapture)
+ {
+ return _current;
+ }
+
+ var view = statistics.GetView();
+ _lastCapture = now;
+ _nextCapture = now.AddSeconds(2);
+ if (_current is not null && ReferenceEquals(view.Snapshot, _current.Snapshot))
+ {
+ return _current;
+ }
+
+ var sequence = (_current?.Sequence ?? 0) + 1;
+ // Resets invalidate the client's accumulated state even when the resulting totals happen to match.
+ var delta = _current is not null && _current.ResetVersion == view.ResetVersion
+ ? StatisticsDelta.Create(_current.Snapshot, view.Snapshot, _current.Sequence, sequence)
+ : null;
+ // Retain one frame, not a replay queue or a chain of prior snapshots.
+ _current = new StatisticsDeltaFrame(statistics, view.Snapshot, view.ResetVersion, sequence, delta);
+ return _current;
+ }
+ }
+}
+
+// Each frame owns its captured snapshot and lazily shares its JSON across clients. Keeping serialization here
+// avoids per-client payload allocations and lets an in-flight write finish safely after the cache advances.
+internal sealed class StatisticsDeltaFrame(
+ StatisticsSnapshotCache cache,
+ RequestStatisticsSnapshot snapshot,
+ long resetVersion,
+ long sequence,
+ StatisticsDelta? delta)
+{
+ private readonly object _gate = new();
+ private string? _snapshotJson;
+ private string? _deltaJson;
+
+ internal RequestStatisticsSnapshot Snapshot { get; } = snapshot;
+ internal long ResetVersion { get; } = resetVersion;
+ internal long Sequence { get; } = sequence;
+ internal StatisticsDelta? Delta { get; } = delta;
+
+ internal string GetSnapshotJson()
+ {
+ lock (_gate)
+ {
+ return _snapshotJson ??= cache.GetCompactJson(Snapshot);
+ }
+ }
+
+ internal string GetDeltaJson()
+ {
+ lock (_gate)
+ {
+ return _deltaJson ??= JsonSerializer.Serialize(
+ Delta ?? throw new InvalidOperationException("A baseline frame has no statistics delta."),
+ StatisticsDeltaJsonContext.Default.StatisticsDelta);
+ }
+ }
+}
+
+/// Absolute state replacements that require the client's exact .
+///
+/// Aggregate totals are always included; endpoint summaries and minute buckets are sent only when changed.
+/// Omission means unchanged, not zero. The client advances every history to WindowStartUtc and fills new
+/// minutes with zeros. RecentRequests is a complete bounded replacement when present, including an empty array.
+///
+internal sealed record StatisticsDelta(
+ long BaseSequence,
+ long Sequence,
+ DateTimeOffset WindowStartUtc,
+ StatisticsTotals Totals,
+ ImmutableArray RecentMinutes,
+ ImmutableArray Endpoints,
+ ImmutableArray RemovedEndpointIds,
+ ImmutableArray? RecentRequests)
+{
+ internal static StatisticsDelta? Create(
+ RequestStatisticsSnapshot previous, RequestStatisticsSnapshot current, long baseSequence, long sequence)
+ {
+ // UTC-minimum clamping can produce duplicate minute identities. Send a baseline rather than an ambiguous patch.
+ if (current.RecentMinutes[0].MinuteUtc == current.RecentMinutes[1].MinuteUtc ||
+ previous.RecentMinutes[0].MinuteUtc == previous.RecentMinutes[1].MinuteUtc)
+ {
+ return null;
+ }
+
+ var oldEndpoints = previous.Endpoints.ToDictionary(endpoint => endpoint.EndpointId);
+ var changed = ImmutableArray.CreateBuilder();
+ foreach (var endpoint in current.Endpoints)
+ {
+ oldEndpoints.Remove(endpoint.EndpointId, out var old);
+ var minutes = ChangedMinutes(old?.RecentMinutes ?? [], endpoint.RecentMinutes);
+ if (old is null || endpoint.TotalRequests != old.TotalRequests || endpoint.LastRequestUtc != old.LastRequestUtc ||
+ endpoint.LastStatusCode != old.LastStatusCode || endpoint.ResponseBytes != old.ResponseBytes || !minutes.IsEmpty)
+ {
+ changed.Add(new EndpointStatisticsDelta(endpoint.EndpointId, endpoint.TotalRequests, endpoint.LastRequestUtc,
+ endpoint.LastStatusCode, endpoint.ResponseBytes, minutes));
+ }
+ }
+
+ // Retry coalescing can update an existing request summary without appending a request. Replace the bounded
+ // feed on any change rather than treating it as append-only or retaining raw request events for replay.
+ return new StatisticsDelta(baseSequence, sequence, current.RecentMinutes[0].MinuteUtc,
+ StatisticsTotals.FromSnapshot(current), ChangedMinutes(previous.RecentMinutes, current.RecentMinutes),
+ changed.ToImmutable(), [.. oldEndpoints.Keys],
+ previous.RecentRequests.SequenceEqual(current.RecentRequests) ? null : current.RecentRequests);
+ }
+
+ private static ImmutableArray ChangedMinutes(
+ ImmutableArray previous, ImmutableArray current)
+ {
+ var changed = ImmutableArray.CreateBuilder();
+ // Match UTC minutes across sliding windows, not array positions; backward clock changes can make this negative.
+ var offset = previous.IsEmpty ? 0 : (current[0].MinuteUtc - previous[0].MinuteUtc).Ticks / TimeSpan.TicksPerMinute;
+ for (var index = 0; index < current.Length; index++)
+ {
+ var oldIndex = index + offset;
+ var bucket = current[index];
+ if (previous.IsEmpty)
+ {
+ // New endpoint histories start at zero on the client; only nonzero buckets need transmission.
+ if (bucket.Requests != 0 || bucket.InformationalResponses != 0 || bucket.SuccessResponses != 0 ||
+ bucket.RedirectionResponses != 0 || bucket.ClientErrorResponses != 0 || bucket.ServerErrorResponses != 0)
+ {
+ changed.Add(bucket);
+ }
+ }
+ else if (oldIndex < 0 || oldIndex >= previous.Length || previous[(int)oldIndex] != bucket)
+ {
+ changed.Add(bucket);
+ }
+ }
+ return changed.ToImmutable();
+ }
+}
+
+internal sealed record EndpointStatisticsDelta(
+ Guid EndpointId, long TotalRequests, DateTimeOffset? LastRequestUtc, int? LastStatusCode,
+ long ResponseBytes, ImmutableArray RecentMinutes);
+
+internal sealed record StatisticsTotals(
+ long TotalRequests, long MatchedRequests, long UnmatchedRequests, long FailedWrites, long AbortedConnections,
+ long InformationalResponses, long SuccessResponses, long RedirectionResponses, long ClientErrorResponses,
+ long ServerErrorResponses, long ResponseBytes)
+{
+ internal static StatisticsTotals FromSnapshot(RequestStatisticsSnapshot snapshot) => new(
+ snapshot.TotalRequests, snapshot.MatchedRequests, snapshot.UnmatchedRequests, snapshot.FailedWrites,
+ snapshot.AbortedConnections, snapshot.InformationalResponses, snapshot.SuccessResponses,
+ snapshot.RedirectionResponses, snapshot.ClientErrorResponses, snapshot.ServerErrorResponses, snapshot.ResponseBytes);
+}
+
+[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
+[JsonSerializable(typeof(StatisticsDelta))]
+internal sealed partial class StatisticsDeltaJsonContext : JsonSerializerContext;
diff --git a/src/MockAPI/Management/StatisticsSnapshotCache.cs b/src/MockAPI/Management/StatisticsSnapshotCache.cs
new file mode 100644
index 0000000..183b540
--- /dev/null
+++ b/src/MockAPI/Management/StatisticsSnapshotCache.cs
@@ -0,0 +1,70 @@
+using System.Text.Json;
+using MockAPI.Runtime;
+
+namespace MockAPI.Management;
+
+/// Shares one immutable statistics view and its compact SSE serialization across management readers.
+internal sealed class StatisticsSnapshotCache(RequestStatisticsCollector statistics)
+{
+ private static readonly ManagementJsonContext CompactJsonContext = new(
+ new JsonSerializerOptions(ManagementJsonContext.Default.Options) { WriteIndented = false });
+ private readonly object _gate = new();
+ private (long Version, long Minute) _key;
+ private RequestStatisticsSnapshot? _snapshot;
+ private string? _compactJson;
+ private long _resetVersion;
+
+ internal (RequestStatisticsSnapshot Snapshot, long ResetVersion) GetView()
+ {
+ lock (_gate)
+ {
+ return (GetSnapshotCore(), _resetVersion);
+ }
+ }
+
+ internal string GetCompactJson(RequestStatisticsSnapshot snapshot)
+ {
+ lock (_gate)
+ {
+ if (ReferenceEquals(snapshot, _snapshot))
+ {
+ return _compactJson ??= JsonSerializer.Serialize(snapshot, CompactJsonContext.RequestStatisticsSnapshot);
+ }
+ return JsonSerializer.Serialize(snapshot, CompactJsonContext.RequestStatisticsSnapshot);
+ }
+ }
+
+ internal RequestStatisticsSnapshot GetSnapshot()
+ {
+ lock (_gate)
+ {
+ return GetSnapshotCore();
+ }
+ }
+
+ internal string GetCompactJson()
+ {
+ lock (_gate)
+ {
+ var snapshot = GetSnapshotCore();
+ return _compactJson ??= JsonSerializer.Serialize(snapshot, CompactJsonContext.RequestStatisticsSnapshot);
+ }
+ }
+
+ private RequestStatisticsSnapshot GetSnapshotCore()
+ {
+ var now = statistics.UtcNow;
+ var key = (statistics.Version, now.ToUnixTimeSeconds() / 60);
+ if (_snapshot is null || _key != key)
+ {
+ // Capture the version BEFORE reading counters: a recording/reset that finishes
+ // during capture must invalidate the next read, not label a partial view as current.
+ // Only readers take this gate; serialization never holds a recorder's lock.
+ _resetVersion = statistics.ResetVersion;
+ _snapshot = statistics.GetSnapshot(now);
+ _key = key;
+ _compactJson = null;
+ }
+ return _snapshot;
+ }
+}
diff --git a/src/MockAPI/Runtime/EndpointRegistry.cs b/src/MockAPI/Runtime/EndpointRegistry.cs
index 310ea12..76098ee 100644
--- a/src/MockAPI/Runtime/EndpointRegistry.cs
+++ b/src/MockAPI/Runtime/EndpointRegistry.cs
@@ -1,6 +1,7 @@
using System.Collections.Frozen;
using System.Collections.Immutable;
using System.Text;
+using System.Text.Unicode;
using System.Threading.RateLimiting;
using MockAPI.Configuration;
@@ -26,7 +27,7 @@ public ConfigurationValidationResult TryReplace(MockApiConfigurationDocument doc
return validation;
}
- var replacement = EndpointRegistrySnapshot.Create(document);
+ var replacement = EndpointRegistrySnapshot.Create(document, Current);
Interlocked.Exchange(ref _current, replacement);
return validation;
}
@@ -37,16 +38,20 @@ public ConfigurationValidationResult TryReplace(MockApiConfigurationDocument doc
public sealed class EndpointRegistrySnapshot
{
private readonly FrozenDictionary> _endpointsByMethod;
+ private readonly FrozenDictionary _endpointsById;
private EndpointRegistrySnapshot(
- FrozenDictionary> endpointsByMethod)
+ FrozenDictionary> endpointsByMethod,
+ FrozenDictionary endpointsById)
{
_endpointsByMethod = endpointsByMethod;
+ _endpointsById = endpointsById;
}
/// Gets an immutable registry containing no enabled endpoints.
public static EndpointRegistrySnapshot Empty { get; } = new(
- FrozenDictionary>.Empty);
+ FrozenDictionary>.Empty,
+ FrozenDictionary.Empty);
/// Looks up an enabled endpoint by exact HTTP method and path.
/// The request HTTP method, compared case-insensitively.
@@ -70,10 +75,13 @@ public bool TryGet(string method, string path, out RuntimeEndpoint endpoint)
return false;
}
- internal static EndpointRegistrySnapshot Create(MockApiConfigurationDocument document)
+ internal static EndpointRegistrySnapshot Create(
+ MockApiConfigurationDocument document,
+ EndpointRegistrySnapshot previous)
{
var endpointsByMethod = new Dictionary>(
StringComparer.OrdinalIgnoreCase);
+ var endpointsById = new Dictionary();
foreach (var definition in document.Endpoints)
{
@@ -82,7 +90,9 @@ internal static EndpointRegistrySnapshot Create(MockApiConfigurationDocument doc
continue;
}
- var endpoint = RuntimeEndpoint.Create(definition);
+ previous._endpointsById.TryGetValue(definition.Id, out var previousEndpoint);
+ var endpoint = RuntimeEndpoint.Create(definition, previousEndpoint);
+ endpointsById.Add(definition.Id, endpoint);
foreach (var method in definition.Methods)
{
if (!endpointsByMethod.TryGetValue(method, out var endpointsByPath))
@@ -99,14 +109,14 @@ internal static EndpointRegistrySnapshot Create(MockApiConfigurationDocument doc
pair => pair.Key,
pair => pair.Value.ToFrozenDictionary(StringComparer.Ordinal),
StringComparer.OrdinalIgnoreCase);
- return new EndpointRegistrySnapshot(frozenEndpoints);
+ return new EndpointRegistrySnapshot(frozenEndpoints, endpointsById.ToFrozenDictionary());
}
}
/// Represents the immutable, wire-ready behavior for one enabled endpoint.
public sealed class RuntimeEndpoint
{
- private readonly byte[] _body;
+ private readonly ReadOnlyMemory _body;
private readonly SlidingWindowRateLimiter? _rateLimiter;
private readonly RuntimeSuccessResponse? _successResponse;
@@ -118,7 +128,7 @@ private RuntimeEndpoint(
string? reasonPhrase,
ImmutableArray headers,
string? contentType,
- byte[] body,
+ ReadOnlyMemory body,
SlidingWindowRateLimiter? rateLimiter,
RuntimeSuccessResponse? successResponse)
{
@@ -172,13 +182,13 @@ internal RuntimeResponse SelectResponse()
: new RuntimeResponse(StatusCode!.Value, ReasonPhrase, Headers, ContentType, Body);
}
- internal static RuntimeEndpoint Create(MockEndpointDefinition definition)
+ internal static RuntimeEndpoint Create(MockEndpointDefinition definition, RuntimeEndpoint? previous = null)
{
var response = definition.Response;
- var headers = response.Headers
- .Select(pair => new RuntimeResponseHeader(pair.Key, [.. pair.Value]))
- .ToImmutableArray();
+ var headers = RuntimeResponseCompilation.CreateHeaders(response.Headers, previous?.Headers ?? default);
+ var body = RuntimeResponseCompilation.CreateBody(response.Body, previous?.Body);
var rateLimit = response.RateLimit;
+ // Share only immutable wire data. Each replacement still starts with fresh rate-limit permits.
var limiter = rateLimit is null
? null
: new SlidingWindowRateLimiter(new SlidingWindowRateLimiterOptions
@@ -191,7 +201,7 @@ internal static RuntimeEndpoint Create(MockEndpointDefinition definition)
});
RuntimeSuccessResponse? successResponse = rateLimit is null
? null
- : RuntimeSuccessResponse.Create(rateLimit.SuccessResponse);
+ : RuntimeSuccessResponse.Create(rateLimit.SuccessResponse, previous?._successResponse);
return new RuntimeEndpoint(
definition.Id,
@@ -201,7 +211,7 @@ internal static RuntimeEndpoint Create(MockEndpointDefinition definition)
response.ReasonPhrase,
headers,
response.ContentType,
- Encoding.UTF8.GetBytes(response.Body),
+ body,
limiter,
successResponse);
}
@@ -216,15 +226,83 @@ internal readonly record struct RuntimeResponse(
internal readonly record struct RuntimeSuccessResponse(RuntimeResponse Response)
{
- public static RuntimeSuccessResponse Create(MockSuccessResponseDefinition response) => new(
+ public static RuntimeSuccessResponse Create(
+ MockSuccessResponseDefinition response,
+ RuntimeSuccessResponse? previous = null) => new(
new RuntimeResponse(
response.StatusCode,
response.ReasonPhrase,
- response.Headers
- .Select(pair => new RuntimeResponseHeader(pair.Key, [.. pair.Value]))
- .ToImmutableArray(),
+ RuntimeResponseCompilation.CreateHeaders(response.Headers, previous?.Response.Headers ?? default),
response.ContentType,
- Encoding.UTF8.GetBytes(response.Body)));
+ RuntimeResponseCompilation.CreateBody(response.Body, previous?.Response.Body)));
+}
+
+internal static class RuntimeResponseCompilation
+{
+ internal static ImmutableArray CreateHeaders(
+ Dictionary headers,
+ ImmutableArray previous)
+ {
+ if (HeadersMatch(headers, previous))
+ {
+ return previous;
+ }
+
+ return headers.Select(pair => new RuntimeResponseHeader(pair.Key, [.. pair.Value])).ToImmutableArray();
+ }
+
+ private static bool HeadersMatch(
+ Dictionary headers,
+ ImmutableArray previous)
+ {
+ if (previous.IsDefault || headers.Count != previous.Length)
+ {
+ return false;
+ }
+
+ var index = 0;
+ foreach (var header in headers)
+ {
+ var existing = previous[index++];
+ if (!string.Equals(header.Key, existing.Name, StringComparison.Ordinal) ||
+ !header.Value.AsSpan().SequenceEqual(existing.Values.AsSpan()))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ internal static ReadOnlyMemory CreateBody(string body, ReadOnlyMemory? previous)
+ {
+ if (previous is { } bytes && BodyMatches(body, bytes.Span))
+ {
+ return bytes;
+ }
+
+ return Encoding.UTF8.GetBytes(body);
+ }
+
+ private static bool BodyMatches(ReadOnlySpan body, ReadOnlySpan previous)
+ {
+ // Compare the actual UTF-8 representation in bounded stack storage, including replacement fallback.
+ // Retaining the source UTF-16 string would save comparison work but increase every snapshot's resident memory.
+ Span scratch = stackalloc byte[512];
+ while (!body.IsEmpty)
+ {
+ Utf8.FromUtf16(body, scratch, out var charactersRead, out var bytesWritten, replaceInvalidSequences: true);
+ if (bytesWritten > previous.Length || !scratch[..bytesWritten].SequenceEqual(previous[..bytesWritten]))
+ {
+ return false;
+ }
+
+ body = body[charactersRead..];
+ previous = previous[bytesWritten..];
+ }
+
+ return previous.IsEmpty;
+ }
}
/// Represents one response header field and its ordered wire values.
diff --git a/src/MockAPI/Runtime/MockRequestBodyValidator.cs b/src/MockAPI/Runtime/MockRequestBodyValidator.cs
index 3c83fe5..c3b081e 100644
--- a/src/MockAPI/Runtime/MockRequestBodyValidator.cs
+++ b/src/MockAPI/Runtime/MockRequestBodyValidator.cs
@@ -1,3 +1,4 @@
+using System.Buffers;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;
@@ -8,6 +9,7 @@ namespace MockAPI.Runtime;
internal static class MockRequestBodyValidator
{
internal const int MaximumBodyBytes = 1024 * 1024;
+ private const int ReadBufferBytes = 64 * 1024;
internal const string SampleJsonBody =
"{\"id\":\"sample-item-001\",\"name\":\"Example item\",\"status\":\"active\",\"quantity\":2,\"tags\":[\"sample\",\"dashboard\"],\"metadata\":{\"source\":\"MockAPI dashboard\"}}";
internal const string InventorySampleJsonBody =
@@ -25,7 +27,10 @@ internal static class MockRequestBodyValidator
internal static bool HasSampleRequestBody(string method) =>
HttpMethods.IsPost(method) || HttpMethods.IsPut(method) || HttpMethods.IsPatch(method);
- internal static async Task ValidateAsync(HttpRequest request)
+ internal static Task ValidateAsync(HttpRequest request) =>
+ ValidateAsync(request, ArrayPool.Shared);
+
+ internal static async Task ValidateAsync(HttpRequest request, ArrayPool bufferPool)
{
if (!HasSampleRequestBody(request.Method))
{
@@ -48,19 +53,27 @@ internal static bool HasSampleRequestBody(string method) =>
var mediaType = contentType?.MediaType.Value;
var isJson = string.Equals(mediaType, "application/json", StringComparison.OrdinalIgnoreCase) ||
mediaType?.EndsWith("+json", StringComparison.OrdinalIgnoreCase) is true;
- using var jsonBuffer = new MemoryStream();
- var buffer = new byte[64 * 1024];
+ // Each request rents its own scratch array and reuses it across that request's reads.
+ // The shared pool is thread-safe; another request can rent this array only after it is returned.
+ // Reuse reduces allocations once warm, but does not cap total memory held by concurrent requests.
+ // Returned arrays may remain cached, so pooling does not necessarily reduce resident memory.
+ var buffer = bufferPool.Rent(ReadBufferBytes);
+ // Rent accumulation storage only when JSON bytes arrive. Empty and non-JSON bodies need no second buffer,
+ // and keeping JSON as UTF-8 avoids allocating a decoded UTF-16 string.
+ byte[]? jsonBuffer = null;
var totalBytes = 0;
try
{
while (true)
{
- var count = await request.Body.ReadAsync(buffer, request.HttpContext.RequestAborted);
+ var count = await request.Body.ReadAsync(
+ buffer.AsMemory(0, ReadBufferBytes), request.HttpContext.RequestAborted);
if (count == 0)
{
break;
}
+ var previousTotalBytes = totalBytes;
totalBytes += count;
if (totalBytes > MaximumBodyBytes)
{
@@ -69,52 +82,99 @@ internal static bool HasSampleRequestBody(string method) =>
if (isJson)
{
- jsonBuffer.Write(buffer, 0, count);
+ // Check the actual size before growing storage. Finish reading before parsing so size and
+ // transport errors keep precedence over charset or JSON-syntax failures, even for streamed bodies.
+ jsonBuffer = EnsureJsonBufferCapacity(bufferPool, jsonBuffer, previousTotalBytes, totalBytes);
+ buffer.AsSpan(0, count).CopyTo(jsonBuffer.AsSpan(previousTotalBytes));
}
}
+
+ if (totalBytes == 0)
+ {
+ return null;
+ }
+
+ var charset = contentType?.Charset.Value?.Trim('"');
+ if (isJson && !string.IsNullOrEmpty(charset) &&
+ !charset.Equals("utf-8", StringComparison.OrdinalIgnoreCase) &&
+ !charset.Equals("utf8", StringComparison.OrdinalIgnoreCase))
+ {
+ return new MockRequestProblem("https://mockapi.local/problems/unsupported-charset",
+ "Unsupported JSON charset", StatusCodes.Status415UnsupportedMediaType,
+ "Mock JSON request bodies must use UTF-8.");
+ }
+
+ if (jsonBuffer is not null && !IsValidJson(jsonBuffer.AsSpan(0, totalBytes)))
+ {
+ return InvalidJson();
+ }
+
+ return null;
}
catch (BadHttpRequestException exception) when (exception.StatusCode == StatusCodes.Status400BadRequest)
{
return InvalidBody("invalid-request-body", "Invalid request body",
"The request body could not be read as a complete HTTP payload.");
}
+ finally
+ {
+ // Clearing costs work proportional to rented capacity, but prevents request content surviving reuse.
+ // Returning arrays in finally preserves reuse even when reading is cancelled or validation fails.
+ bufferPool.Return(buffer, clearArray: true);
+ if (jsonBuffer is not null)
+ {
+ bufferPool.Return(jsonBuffer, clearArray: true);
+ }
+ }
+ }
+
+ private static byte[] EnsureJsonBufferCapacity(
+ ArrayPool bufferPool, byte[]? buffer, int storedBytes, int requiredBytes)
+ {
+ if (buffer is not null && buffer.Length >= requiredBytes)
+ {
+ return buffer;
+ }
- if (totalBytes == 0)
+ // Geometric growth avoids renting and copying on every small read from a fragmented upload.
+ // The caller has already enforced the body limit, and requested growth is capped at that limit.
+ var capacity = buffer is null
+ ? requiredBytes
+ : Math.Max(requiredBytes, Math.Min(buffer.Length * 2, MaximumBodyBytes));
+ var replacement = bufferPool.Rent(capacity);
+ if (buffer is not null)
{
- return null;
+ // Copy only populated bytes; return the replaced array immediately so later requests can reuse it.
+ buffer.AsSpan(0, storedBytes).CopyTo(replacement);
+ bufferPool.Return(buffer, clearArray: true);
}
- var charset = contentType?.Charset.Value?.Trim('"');
- if (isJson && !string.IsNullOrEmpty(charset) &&
- !charset.Equals("utf-8", StringComparison.OrdinalIgnoreCase) &&
- !charset.Equals("utf8", StringComparison.OrdinalIgnoreCase))
+ return replacement;
+ }
+
+ private static bool IsValidJson(ReadOnlySpan json)
+ {
+ // Token traversal does not decode every string, so check all UTF-8 bytes independently.
+ if (!Utf8.IsValid(json))
{
- return new MockRequestProblem("https://mockapi.local/problems/unsupported-charset",
- "Unsupported JSON charset", StatusCodes.Status415UnsupportedMediaType,
- "Mock JSON request bodies must use UTF-8.");
+ return false;
}
- if (isJson)
+ try
{
- var json = jsonBuffer.GetBuffer().AsMemory(0, totalBytes);
- // JsonDocument defers decoding some strings, so validate every UTF-8 byte explicitly.
- if (!Utf8.IsValid(json.Span))
+ var reader = new Utf8JsonReader(json);
+ // Traverse the existing UTF-8 bytes without allocating JsonDocument token metadata or decoded strings.
+ // Consume every token to preserve syntax checks and the default 64-level nesting limit.
+ while (reader.Read())
{
- return InvalidJson();
}
- try
- {
- // Parse syntax only. No application fields or values influence the configured response.
- using var document = JsonDocument.Parse(json);
- }
- catch (JsonException)
- {
- return InvalidJson();
- }
+ return reader.TokenType != JsonTokenType.None;
+ }
+ catch (JsonException)
+ {
+ return false;
}
-
- return null;
}
private static MockRequestProblem InvalidBody(string type, string title, string detail) =>
diff --git a/src/MockAPI/Runtime/RequestStatisticsCollector.cs b/src/MockAPI/Runtime/RequestStatisticsCollector.cs
index 309d600..ea44416 100644
--- a/src/MockAPI/Runtime/RequestStatisticsCollector.cs
+++ b/src/MockAPI/Runtime/RequestStatisticsCollector.cs
@@ -36,8 +36,11 @@ public sealed class RequestStatisticsCollector
private long _serverErrorResponses;
private long _responseBytes;
private long _version;
+ private long _resetVersion;
internal long Version => Interlocked.Read(ref _version);
+ internal long ResetVersion => Interlocked.Read(ref _resetVersion);
+ internal DateTimeOffset UtcNow => _timeProvider.GetUtcNow();
/// Initializes a request statistics collector.
/// The UTC time source, or to use .
@@ -154,9 +157,11 @@ public void RecordAbortedConnection(Guid endpointId, string method, string path,
/// Captures aggregate, endpoint, and trailing 60-minute statistics without blocking recorders globally.
/// An immutable, point-in-time view ordered by endpoint ID.
- public RequestStatisticsSnapshot GetSnapshot()
+ public RequestStatisticsSnapshot GetSnapshot() => GetSnapshot(UtcNow);
+
+ // The management cache uses the same instant for its minute key and rolling buckets.
+ internal RequestStatisticsSnapshot GetSnapshot(DateTimeOffset now)
{
- var now = _timeProvider.GetUtcNow();
var endpoints = _endpoints
.Select(pair => pair.Value.GetSnapshot(pair.Key, now))
.OrderBy(snapshot => snapshot.EndpointId)
@@ -203,6 +208,7 @@ public void Reset()
_recentUnmatchedRequestIds.Clear();
_recentUnmatchedRequestIdSet.Clear();
}
+ Interlocked.Increment(ref _resetVersion);
Interlocked.Increment(ref _version);
}
@@ -241,6 +247,7 @@ public bool Reset(Guid endpointId)
}
}
+ Interlocked.Increment(ref _resetVersion);
Interlocked.Increment(ref _version);
return true;
}
@@ -461,9 +468,8 @@ public EndpointStatisticsSnapshot GetSnapshot(Guid endpointId, DateTimeOffset no
private sealed class MinuteBucketSeries
{
private const int BucketCount = 60;
- private readonly MinuteBucket[] _buckets = Enumerable.Range(0, BucketCount)
- .Select(_ => new MinuteBucket())
- .ToArray();
+ // Inline the six packed atomic counters per bucket instead of allocating an object for every counter.
+ private readonly MinuteBucket[] _buckets = new MinuteBucket[BucketCount];
public void Record(DateTimeOffset timestamp, int? statusCode = null)
{
@@ -478,7 +484,8 @@ public ImmutableArray GetSnapshot(DateTimeOffset timestamp
for (var offset = BucketCount - 1; offset >= 0; offset--)
{
var minute = currentMinute - offset;
- var bucket = _buckets[GetBucketIndex(minute)];
+ // Read the stored struct by reference: copying it would bypass the counters' volatile reads.
+ ref var bucket = ref _buckets[GetBucketIndex(minute)];
builder.Add(new MinuteBucketSnapshot(
DateTimeOffset.FromUnixTimeSeconds(Math.Max(
(long)minute * 60,
@@ -496,9 +503,9 @@ public ImmutableArray GetSnapshot(DateTimeOffset timestamp
public void Reset()
{
- foreach (var bucket in _buckets)
+ for (var index = 0; index < _buckets.Length; index++)
{
- bucket.Reset();
+ _buckets[index].Reset();
}
}
@@ -508,14 +515,14 @@ private static int GetUnixMinute(DateTimeOffset timestamp) =>
private static int GetBucketIndex(int minute) => Math.Abs(minute % BucketCount);
}
- private sealed class MinuteBucket
+ private struct MinuteBucket
{
- private readonly MinuteCounter _requests = new();
- private readonly MinuteCounter _informationalResponses = new();
- private readonly MinuteCounter _successResponses = new();
- private readonly MinuteCounter _redirectionResponses = new();
- private readonly MinuteCounter _clientErrorResponses = new();
- private readonly MinuteCounter _serverErrorResponses = new();
+ private MinuteCounter _requests;
+ private MinuteCounter _informationalResponses;
+ private MinuteCounter _successResponses;
+ private MinuteCounter _redirectionResponses;
+ private MinuteCounter _clientErrorResponses;
+ private MinuteCounter _serverErrorResponses;
public void Record(int minute, int? statusCode)
{
@@ -563,7 +570,7 @@ public void Reset()
}
}
- private sealed class MinuteCounter
+ private struct MinuteCounter
{
private long _state;
diff --git a/src/MockAPI/wwwroot/app.js b/src/MockAPI/wwwroot/app.js
index 61d806e..b545e6d 100644
--- a/src/MockAPI/wwwroot/app.js
+++ b/src/MockAPI/wwwroot/app.js
@@ -638,6 +638,7 @@ if (!createEventSource) {
console.warn("Server-sent events are unavailable. Dashboard updates will use polling.");
}
dashboardSynchronizer = createDashboardSynchronizer({
+ useStatisticsDeltas: true,
request: api,
createEventSource,
onConfiguration(configuration) {
diff --git a/src/MockAPI/wwwroot/dashboard-core.js b/src/MockAPI/wwwroot/dashboard-core.js
index a62b71e..f3547bf 100644
--- a/src/MockAPI/wwwroot/dashboard-core.js
+++ b/src/MockAPI/wwwroot/dashboard-core.js
@@ -157,6 +157,84 @@
* @property {readonly RequestSummary[]} recentRequests At most 100 newest-first privacy-safe summaries.
*/
+/**
+ * @typedef {object} StatisticsDelta
+ * @property {number} baseSequence Required baseline sequence.
+ * @property {number} sequence New stream sequence.
+ * @property {string} windowStartUtc Oldest retained UTC minute.
+ * @property {Omit} totals Absolute aggregate counters.
+ * @property {readonly MinuteStatistics[]} recentMinutes Changed aggregate buckets.
+ * @property {readonly (Omit & {recentMinutes: readonly MinuteStatistics[]})[]} endpoints Changed endpoint summaries with changed buckets only.
+ * @property {readonly string[]} removedEndpointIds Removed counters.
+ * @property {readonly RequestSummary[]|null} recentRequests Replacement bounded log, or null when unchanged.
+ */
+
+/**
+ * Applies an interval state delta without modifying either input.
+ * Values replace counters rather than incrementing them, so delivery must never add the same counts twice.
+ * Omitted endpoints/buckets remain unchanged; window movement expires old minutes even without new activity.
+ * Unchanged endpoint records and minute buckets retain their identity for incremental rendering.
+ * @param {DashboardStatistics} previous Full baseline maintained by the stream owner.
+ * @param {StatisticsDelta} delta Sequenced absolute updates; the caller verifies stream sequence continuity.
+ * @returns {DashboardStatistics} Complete current view with exactly sixty buckets per history.
+ * @throws {Error} The retention window is not a valid UTC timestamp.
+ */
+export function applyStatisticsDelta(previous, delta) {
+ const start = Date.parse(delta.windowStartUtc);
+ if (!Number.isFinite(start)) throw new Error("Invalid statistics retention window.");
+ const moved = Date.parse(previous.recentMinutes[0]?.minuteUtc) !== start;
+ let endpoints = previous.endpoints;
+ if (moved || delta.endpoints.length || delta.removedEndpointIds.length) {
+ const entries = new Map(previous.endpoints.map((endpoint) => [endpoint.endpointId, endpoint]));
+ for (const id of delta.removedEndpointIds) entries.delete(id);
+ if (moved) {
+ for (const [id, endpoint] of entries) {
+ entries.set(id, { ...endpoint, recentMinutes: mergeStatisticsMinutes(endpoint.recentMinutes, [], start) });
+ }
+ }
+ for (const endpoint of delta.endpoints) {
+ const old = entries.get(endpoint.endpointId);
+ entries.set(endpoint.endpointId, {
+ ...endpoint,
+ recentMinutes: mergeStatisticsMinutes(old?.recentMinutes || [], endpoint.recentMinutes, start),
+ });
+ }
+ endpoints = [...entries.values()].sort((left, right) => left.endpointId.localeCompare(right.endpointId));
+ }
+ return {
+ ...previous,
+ ...delta.totals,
+ recentMinutes:
+ !moved && delta.recentMinutes.length === 0
+ ? previous.recentMinutes
+ : mergeStatisticsMinutes(previous.recentMinutes, delta.recentMinutes, start),
+ endpoints,
+ recentRequests: delta.recentRequests ?? previous.recentRequests,
+ };
+}
+
+function mergeStatisticsMinutes(previous, changes, start) {
+ // Equivalent UTC timestamps can use Z or +00:00. Numeric keys preserve minute identity across both spellings.
+ const buckets = new Map(previous.map((bucket) => [Date.parse(bucket.minuteUtc), bucket]));
+ for (const bucket of changes) buckets.set(Date.parse(bucket.minuteUtc), bucket);
+ // Rebuild only the bounded window: old buckets expire, and omitted new minutes start at zero.
+ // Existing bucket objects remain shared because callers treat snapshot data as immutable.
+ return Array.from({ length: 60 }, (_, index) => {
+ const timestamp = start + index * 60_000;
+ return (
+ buckets.get(timestamp) || {
+ minuteUtc: new Date(timestamp).toISOString(),
+ requests: 0,
+ informationalResponses: 0,
+ successResponses: 0,
+ redirectionResponses: 0,
+ clientErrorResponses: 0,
+ serverErrorResponses: 0,
+ }
+ );
+ });
+}
+
/** @typedef {{query: string, method: string, enabled: string, statusClass: string}} EndpointFilters */
/** @typedef {"name"|"methods"|"path"|"response"|"requests"|"enabled"} EndpointSortKey */
/** @typedef {{key: EndpointSortKey, direction: "ascending"|"descending"}} EndpointSort */
diff --git a/src/MockAPI/wwwroot/dashboard-statistics.js b/src/MockAPI/wwwroot/dashboard-statistics.js
index 82cdcf1..11265d3 100644
--- a/src/MockAPI/wwwroot/dashboard-statistics.js
+++ b/src/MockAPI/wwwroot/dashboard-statistics.js
@@ -71,13 +71,20 @@ export function createDashboardStatistics({ documentRoot, preferencesStore, onRe
const STATISTICS_VISIBLE_MINUTES = 30;
const preferences = preferencesStore.get();
const events = createDashboardEventScope();
- const chartEvents = createDashboardEventScope();
const logEvents = createDashboardEventScope();
const { makeElement } = createDashboardDom(document, events);
/** @type {readonly import("./dashboard-core.js").MockEndpoint[]|null} */
let statisticsPickerEndpoints = null;
/** @type {string|null} */
let requestLogCache = null;
+ /** @type {Map>} */
+ const chartColumns = new Map();
+ /** @type {HTMLDivElement|null} */
+ let chartTooltip = null;
+ /** @type {ReturnType|null} */
+ let hoveredColumn = null;
+ /** @type {{endpointMode: boolean, body: HTMLTableSectionElement, rows: Map}|null} */
+ let statisticsTable = null;
/** @type {{
* endpoints: readonly import("./dashboard-core.js").MockEndpoint[],
* statistics: import("./dashboard-core.js").DashboardStatistics|null,
@@ -335,48 +342,48 @@ export function createDashboardStatistics({ documentRoot, preferencesStore, onRe
function renderStatisticsTable(endpointMode) {
const container = elements["statistics-table-view"];
- const table = document.createElement("table");
- const head = document.createElement("thead");
- const body = document.createElement("tbody");
- const headerRow = document.createElement("tr");
-
- if (endpointMode) {
- for (const label of ["Endpoint", "Attempts", "Rate", "Last status", "Response bytes", "Why this response"]) {
+ if (!statisticsTable || statisticsTable.endpointMode !== endpointMode) {
+ const table = document.createElement("table");
+ const head = document.createElement("thead");
+ const body = document.createElement("tbody");
+ const headerRow = document.createElement("tr");
+ const labels = endpointMode
+ ? ["Endpoint", "Attempts", "Rate", "Last status", "Response bytes", "Why this response"]
+ : ["Measure", "Value", "Meaning"];
+ for (const label of labels) {
const header = makeElement("th", null, label);
header.scope = "col";
headerRow.append(header);
- if (["Attempts", "Rate", "Response bytes"].includes(label)) {
- header.classList.add("numeric");
- }
+ if (["Attempts", "Rate", "Response bytes"].includes(label)) header.classList.add("numeric");
}
+ head.append(headerRow);
+ table.append(head, body);
+ container.replaceChildren(table);
+ statisticsTable = { endpointMode, body, rows: new Map() };
+ }
+ /** @type {{key: string, values: string[]}[]} */
+ const rows = [];
+ if (endpointMode) {
for (const endpoint of state.endpoints) {
const statistics = endpointStatistics(endpoint.id);
const recent = statistics?.recentMinutes || [];
- const row = document.createElement("tr");
- const endpointCell = document.createElement("td");
- endpointCell.append(
- makeElement("strong", null, endpoint.name),
- makeElement("small", "statistics-path", endpoint.path)
- );
- row.append(
- endpointCell,
- makeElement("td", "numeric", formatNumber(statistics?.totalRequests || 0)),
- makeElement("td", "numeric", `${(sumRequests(recent) / 60).toFixed(1)} attempts/min`),
- makeElement("td", "numeric", statistics?.lastStatusCode ? String(statistics.lastStatusCode) : "—"),
- makeElement("td", "numeric", formatBytes(statistics?.responseBytes || 0)),
- makeElement("td", "statistics-explanation", explainEndpointStatistics(endpoint, statistics))
- );
- body.append(row);
+ rows.push({
+ key: endpoint.id,
+ values: [
+ endpoint.name,
+ endpoint.path,
+ formatNumber(statistics?.totalRequests || 0),
+ `${(sumRequests(recent) / 60).toFixed(1)} attempts/min`,
+ statistics?.lastStatusCode ? String(statistics.lastStatusCode) : "—",
+ formatBytes(statistics?.responseBytes || 0),
+ explainEndpointStatistics(endpoint, statistics),
+ ],
+ });
}
} else {
- for (const label of ["Measure", "Value", "Meaning"]) {
- const header = makeElement("th", null, label);
- header.scope = "col";
- headerRow.append(header);
- }
const statistics = state.statistics;
/** @type {[string, number|string, string][]} */
- const rows = [
+ const measures = [
["Total attempts", statistics.totalRequests, "Every transport attempt seen by the mock dispatcher"],
["Matched", statistics.matchedRequests, "Transport attempts attributed to a configured endpoint"],
["Unmatched", statistics.unmatchedRequests, "Transport attempts that did not match an enabled endpoint"],
@@ -392,22 +399,57 @@ export function createDashboardStatistics({ documentRoot, preferencesStore, onRe
["5xx responses", statistics.serverErrorResponses, "Server-error responses"],
["Response bytes", formatBytes(statistics.responseBytes), "Response body bytes written by matched endpoints"],
];
- for (const [label, value, meaning] of rows) {
- const row = document.createElement("tr");
- const heading = makeElement("th", null, label);
- heading.scope = "row";
- row.append(heading, makeElement("td", "numeric", String(value)), makeElement("td", null, meaning));
- body.append(row);
+ for (const [label, value, meaning] of measures) {
+ rows.push({ key: label, values: [label, String(value), meaning] });
}
}
- head.append(headerRow);
- table.append(head, body);
- container.replaceChildren(table);
+ const retained = new Set(rows.map((row) => row.key));
+ for (const [key, entry] of statisticsTable.rows) {
+ if (!retained.has(key)) {
+ entry.row.remove();
+ statisticsTable.rows.delete(key);
+ }
+ }
+ for (const [index, descriptor] of rows.entries()) {
+ let entry = statisticsTable.rows.get(descriptor.key);
+ if (!entry) {
+ const row = document.createElement("tr");
+ const targets = [];
+ if (endpointMode) {
+ const cell = document.createElement("td");
+ const name = document.createElement("strong");
+ const path = makeElement("small", "statistics-path");
+ cell.append(name, path);
+ row.append(cell);
+ targets.push(name, path);
+ for (let column = 0; column < 5; column++) {
+ const value = makeElement("td", column === 4 ? "statistics-explanation" : "numeric");
+ row.append(value);
+ targets.push(value);
+ }
+ } else {
+ const heading = document.createElement("th");
+ heading.scope = "row";
+ const value = makeElement("td", "numeric");
+ const meaning = document.createElement("td");
+ row.append(heading, value, meaning);
+ targets.push(heading, value, meaning);
+ }
+ entry = { row, targets, values: [] };
+ statisticsTable.rows.set(descriptor.key, entry);
+ }
+ descriptor.values.forEach((value, column) => {
+ if (entry.values[column] !== value) entry.targets[column].textContent = value;
+ });
+ entry.values = descriptor.values;
+ if (statisticsTable.body.children[index] !== entry.row) {
+ statisticsTable.body.insertBefore(entry.row, statisticsTable.body.children[index] || null);
+ }
+ }
}
function renderStatisticsGraph(endpointMode, endpoint, statistics) {
- chartEvents.clear();
const recent = endpointMode ? statistics?.recentMinutes || [] : state.statistics.recentMinutes || [];
const total = sumRequests(recent);
elements["statistics-chart-title"].textContent = endpointMode
@@ -424,6 +466,7 @@ export function createDashboardStatistics({ documentRoot, preferencesStore, onRe
: `${formatNumber(state.statistics.matchedRequests)} matched and ${formatNumber(state.statistics.unmatchedRequests)} unmatched attempts have been observed.`;
const chart = elements["statistics-chart"];
+ const focusedChartColumn = chart.contains(document.activeElement);
const chartScroll = elements["statistics-chart-scroll"];
const chartTimeline = elements["statistics-chart-timeline"];
const wasFollowingNewest =
@@ -442,48 +485,55 @@ export function createDashboardStatistics({ documentRoot, preferencesStore, onRe
const requestLogBuckets = new Set(
groupRequestsByMinute(state.statistics.recentRequests || []).map((group) => minuteBucketKey(group.minuteUtc))
);
- const tooltip = createStatisticsTooltip();
- const columns = recent.map((bucket) => {
+ if (!chartTooltip) {
+ chartTooltip = createStatisticsTooltip();
+ chart.append(chartTooltip);
+ }
+ const retained = new Set(recent.map((bucket) => minuteBucketKey(bucket.minuteUtc)));
+ for (const [key, entry] of chartColumns) {
+ if (!retained.has(key)) removeChartColumn(key, entry);
+ }
+ for (const [index, bucket] of recent.entries()) {
const bucketKey = minuteBucketKey(bucket.minuteUtc);
const hasRequestLogBucket = bucket.requests > 0 && requestLogBuckets.has(bucketKey);
- const column = makeElement(hasRequestLogBucket ? "button" : "i", "chart-column");
const statusCounts = getMinuteStatusCounts(bucket);
- column.style.height = `${(bucket.requests / maximum) * 100}%`;
- if (bucket.requests > 0) column.classList.add("active");
+ let entry = chartColumns.get(bucketKey);
+ const restoreFocus = entry?.column === document.activeElement;
+ if (entry && entry.interactive !== hasRequestLogBucket) {
+ removeChartColumn(bucketKey, entry);
+ entry = null;
+ }
+ if (!entry) {
+ entry = createChartColumn(bucket, hasRequestLogBucket);
+ chartColumns.set(bucketKey, entry);
+ }
+ const { column } = entry;
+ entry.bucket = bucket;
+ entry.statusCounts = statusCounts;
+ const height = `${(bucket.requests / maximum) * 100}%`;
+ if (column.style.height !== height) column.style.height = height;
+ column.classList.toggle("active", bucket.requests > 0);
if (hasRequestLogBucket) {
- column.setAttribute("type", "button");
- column.classList.add("interactive");
column.setAttribute(
"aria-label",
`Show ${formatNumber(bucket.requests)} ${bucket.requests === 1 ? "attempt" : "attempts"} from ${formatTime(bucket.minuteUtc)} in the request log`
);
- chartEvents.listen(column, "click", () => revealRequestLogBucket(bucketKey));
}
- for (const [statusClass, count] of [
- ["status-1xx", statusCounts.informational],
- ["status-2xx", statusCounts.success],
- ["status-3xx", statusCounts.redirection],
- ["status-4xx", statusCounts.clientError],
- ["status-5xx", statusCounts.serverError],
- ["status-other", statusCounts.other],
- ]) {
- const segment = makeElement("span", statusClass);
- segment.style.flexGrow = String(count);
+ Object.values(statusCounts).forEach((count, segmentIndex) => {
+ const segment = entry.segments[segmentIndex];
+ if (segment.style.flexGrow !== String(count)) segment.style.flexGrow = String(count);
segment.hidden = count === 0;
- column.append(segment);
- }
- chartEvents.listen(column, "pointerenter", (event) => {
- showStatisticsTooltip(tooltip, bucket, statusCounts, event);
- });
- chartEvents.listen(column, "pointermove", (event) => {
- positionStatisticsTooltip(tooltip, event);
});
- chartEvents.listen(column, "pointerleave", () => {
- tooltip.hidden = true;
- });
- return column;
- });
- chart.replaceChildren(...columns, tooltip);
+ if (chart.children[index] !== column) chart.insertBefore(column, chart.children[index] || chartTooltip);
+ if (restoreFocus && document.activeElement !== column) {
+ if (hasRequestLogBucket) column.focus({ preventScroll: true });
+ else chartScroll.focus({ preventScroll: true });
+ }
+ if (hoveredColumn === entry && entry.pointer) {
+ showStatisticsTooltip(chartTooltip, bucket, statusCounts, entry.pointer);
+ }
+ }
+ if (focusedChartColumn && !chart.contains(document.activeElement)) chartScroll.focus({ preventScroll: true });
chartScroll.dataset.initialized = "true";
if (wasFollowingNewest) chartScroll.scrollLeft = chartScroll.scrollWidth;
const navigationDescription = hasOlderActivity
@@ -495,6 +545,57 @@ export function createDashboardStatistics({ documentRoot, preferencesStore, onRe
);
}
+ function createChartColumn(bucket, interactive) {
+ const column = makeElement(interactive ? "button" : "i", "chart-column");
+ // Each retained column owns its listeners; removal releases them without disturbing neighboring columns.
+ const listeners = createDashboardEventScope();
+ const segments = ["status-1xx", "status-2xx", "status-3xx", "status-4xx", "status-5xx", "status-other"].map(
+ (statusClass) => makeElement("span", statusClass)
+ );
+ column.append(...segments);
+ const entry = {
+ column,
+ segments,
+ listeners,
+ interactive,
+ bucket,
+ statusCounts: getMinuteStatusCounts(bucket),
+ /** @type {PointerEvent|null} */
+ pointer: null,
+ };
+ // Read the entry's refreshed data instead of capturing the bucket from the column's first render.
+ if (interactive) {
+ column.setAttribute("type", "button");
+ column.classList.add("interactive");
+ listeners.listen(column, "click", () => revealRequestLogBucket(minuteBucketKey(entry.bucket.minuteUtc)));
+ }
+ listeners.listen(column, "pointerenter", (event) => {
+ hoveredColumn = entry;
+ entry.pointer = event;
+ showStatisticsTooltip(chartTooltip, entry.bucket, entry.statusCounts, event);
+ });
+ listeners.listen(column, "pointermove", (event) => {
+ entry.pointer = event;
+ positionStatisticsTooltip(chartTooltip, event);
+ });
+ listeners.listen(column, "pointerleave", () => {
+ hoveredColumn = null;
+ entry.pointer = null;
+ chartTooltip.hidden = true;
+ });
+ return entry;
+ }
+
+ function removeChartColumn(key, entry) {
+ entry.listeners.clear();
+ entry.column.remove();
+ chartColumns.delete(key);
+ if (hoveredColumn === entry) {
+ hoveredColumn = null;
+ chartTooltip.hidden = true;
+ }
+ }
+
function createStatisticsTooltip() {
const tooltip = makeElement("div", "chart-tooltip");
tooltip.setAttribute("aria-hidden", "true");
@@ -626,7 +727,11 @@ export function createDashboardStatistics({ documentRoot, preferencesStore, onRe
},
dispose() {
events.clear();
- chartEvents.clear();
+ for (const entry of chartColumns.values()) entry.listeners.clear();
+ chartColumns.clear();
+ hoveredColumn = null;
+ chartTooltip = null;
+ statisticsTable = null;
logEvents.clear();
requestLogCache = null;
statisticsPickerEndpoints = null;
diff --git a/src/MockAPI/wwwroot/dashboard-sync.js b/src/MockAPI/wwwroot/dashboard-sync.js
index c7f7f8f..5cd458a 100644
--- a/src/MockAPI/wwwroot/dashboard-sync.js
+++ b/src/MockAPI/wwwroot/dashboard-sync.js
@@ -1,5 +1,7 @@
"use strict";
+import { applyStatisticsDelta } from "./dashboard-core.js?v={{ASSET_VERSION}}";
+
/**
* @typedef {import("./dashboard-core.js").ConfigurationStatus} ConfigurationStatus
*/
@@ -38,6 +40,7 @@
* @param {(callback: () => void, delay: number) => ReturnType} [options.schedule] Timer scheduler.
* @param {(timer: ReturnType) => void} [options.cancel] Timer cancellation.
* @param {number} [options.pollInterval] Recovery interval in milliseconds.
+ * @param {boolean} [options.useStatisticsDeltas] Opt into sequenced interval updates; defaults to legacy full events.
* @param {(configuration: ConfigurationStatus) => void} options.onConfiguration Status callback.
* @param {(endpoints: readonly import("./dashboard-core.js").MockEndpoint[]) => void} options.onEndpoints Read-only endpoint snapshot callback.
* @param {(statistics: import("./dashboard-core.js").DashboardStatistics) => void} options.onStatistics Statistics snapshot callback.
@@ -53,6 +56,7 @@ export function createDashboardSynchronizer({
schedule = globalThis.setTimeout.bind(globalThis),
cancel = globalThis.clearTimeout.bind(globalThis),
pollInterval = 15000,
+ useStatisticsDeltas = false,
onConfiguration,
onEndpoints,
onStatistics,
@@ -83,6 +87,11 @@ export function createDashboardSynchronizer({
let refreshWork = null;
let refreshAgain = false;
let statisticsRequested = false;
+ // HTTP refreshes may be newer, but only sequenced stream frames can supply the next delta's exact base.
+ /** @type {import("./dashboard-core.js").DashboardStatistics|null} */
+ let streamStatistics = null;
+ /** @type {number|null} */
+ let streamSequence = null;
const active = (epoch) => visible && !disposed && generation === epoch;
@@ -96,6 +105,7 @@ export function createDashboardSynchronizer({
timer = schedule(async () => {
timer = null;
await synchronize();
+ if (!stream && createEventSource) await activate();
if (!streamHealthy) schedulePoll();
}, pollInterval);
}
@@ -210,15 +220,33 @@ export function createDashboardSynchronizer({
if (!createEventSource) {
return synchronize().then(schedulePoll);
}
- stream = createEventSource("/dashboard/events");
+ stream = createEventSource(useStatisticsDeltas ? "/dashboard/events?deltas=true" : "/dashboard/events");
+ const connection = stream;
+ // Recovery can replace the connection without changing the page epoch; ignore late callbacks from its predecessor.
+ const currentConnection = () => active(epoch) && stream === connection;
+ function rejectStatisticsFrame(error) {
+ if (useStatisticsDeltas) {
+ // Retire only this stream: an authoritative management refresh must remain valid.
+ // Normal recovery polling reconnects for a fresh baseline instead of immediately looping on bad frames.
+ connection.close();
+ stream = null;
+ streamHealthy = false;
+ streamStatistics = null;
+ streamSequence = null;
+ }
+ fail(error, epoch);
+ }
stream.onopen = () => {
- if (!active(epoch)) return;
- // Reconnect can reach a restarted process with the same numeric revision.
+ if (!currentConnection()) return;
+ // Reconnect can reach a restarted process with the same numeric revision and restarted statistics sequence.
+ // Discard the old delta base and wait for the server's complete baseline before accepting patches.
endpointsRevision = null;
configurationSequence++;
+ streamStatistics = null;
+ streamSequence = null;
};
stream.addEventListener("configuration", (event) => {
- if (!active(epoch)) return;
+ if (!currentConnection()) return;
try {
configurationSequence++;
const work = applyConfiguration(JSON.parse(event.data));
@@ -231,17 +259,48 @@ export function createDashboardSynchronizer({
}
});
stream.addEventListener("statistics", (event) => {
- if (!active(epoch)) return;
+ if (!currentConnection()) return;
try {
const statistics = JSON.parse(event.data);
+ if (useStatisticsDeltas) {
+ const sequence = Number(event.lastEventId);
+ if (!Number.isSafeInteger(sequence) || sequence < 1) {
+ throw new Error("Invalid dashboard statistics baseline sequence.");
+ }
+ streamStatistics = statistics;
+ streamSequence = sequence;
+ }
statisticsSequence++;
onStatistics(statistics);
} catch (error) {
- fail(error, epoch);
+ rejectStatisticsFrame(error);
}
});
+ if (useStatisticsDeltas) {
+ stream.addEventListener("statistics-delta", (event) => {
+ if (!currentConnection()) return;
+ try {
+ const delta = JSON.parse(event.data);
+ if (!Number.isSafeInteger(delta.sequence) || Number(event.lastEventId) !== delta.sequence) {
+ throw new Error("Invalid dashboard statistics delta sequence.");
+ }
+ // Ignore duplicate/older patches. Absolute values prevent double-counting, but an old patch could
+ // still roll the displayed state backward. A missing base requires recovery, never a best-effort merge.
+ if (streamSequence !== null && delta.sequence <= streamSequence) return;
+ if (!streamStatistics || delta.baseSequence !== streamSequence || delta.sequence !== streamSequence + 1) {
+ throw new Error("Dashboard statistics sequence missed; refreshing the baseline.");
+ }
+ streamStatistics = applyStatisticsDelta(streamStatistics, delta);
+ streamSequence = delta.sequence;
+ statisticsSequence++;
+ onStatistics(streamStatistics);
+ } catch (error) {
+ rejectStatisticsFrame(error);
+ }
+ });
+ }
stream.onerror = () => {
- if (!active(epoch)) return;
+ if (!currentConnection()) return;
streamHealthy = false;
fail(new Error("Dashboard event stream disconnected; retrying with polling fallback."), epoch);
};
@@ -261,6 +320,8 @@ export function createDashboardSynchronizer({
refreshWork = null;
refreshAgain = false;
statisticsRequested = false;
+ streamStatistics = null;
+ streamSequence = null;
}
async function start() {
diff --git a/tests/MockAPI.Tests/Configuration/ConfigurationBlobStoreTests.cs b/tests/MockAPI.Tests/Configuration/ConfigurationBlobStoreTests.cs
index ed4a9cb..8ed3833 100644
--- a/tests/MockAPI.Tests/Configuration/ConfigurationBlobStoreTests.cs
+++ b/tests/MockAPI.Tests/Configuration/ConfigurationBlobStoreTests.cs
@@ -65,20 +65,43 @@ public async Task LoadAsync_MissingBlobHonorsAllowEmptyConfiguration()
Assert.Equal(0, allowedState.Current.Revision);
}
+ [Fact]
+ public async Task SaveAsync_DoesNotAllocateADocumentSizedUploadBuffer()
+ {
+ var state = new ConfigurationState();
+ Assert.Equal(ConfigurationUpdateStatus.Applied,
+ state.TryReplace(CreateDocument("/large", new string('x', 512 * 1024)), 0).Status);
+ var store = CreateStore(
+ _ => Task.FromResult(null),
+ (_, _) => Task.CompletedTask,
+ allowEmptyConfiguration: true);
+ await store.SaveAsync(state, 1, CancellationToken.None);
+
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var save = store.SaveAsync(state, 1, CancellationToken.None);
+ Assert.True(save.IsCompletedSuccessfully);
+ await save;
+ var allocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before;
+
+ Assert.InRange(allocatedBytes, 0, 64 * 1024);
+ }
+
[Fact]
public async Task SaveAsync_UploadsSnapshotAndMarksRevisionPersisted()
{
- ReadOnlyMemory uploaded = default;
+ using var uploaded = new MemoryStream();
+ Stream? uploadStream = null;
var state = new ConfigurationState();
Assert.Equal(
ConfigurationUpdateStatus.Applied,
state.TryReplace(CreateDocument("/saved", "saved"), expectedRevision: 0).Status);
var store = CreateStore(
_ => Task.FromResult(null),
- (content, _) =>
+ async (content, token) =>
{
- uploaded = content.ToArray();
- return Task.CompletedTask;
+ uploadStream = content;
+ Assert.False(content.CanWrite);
+ await content.CopyToAsync(uploaded, token);
},
allowEmptyConfiguration: true);
@@ -88,6 +111,49 @@ public async Task SaveAsync_UploadsSnapshotAndMarksRevisionPersisted()
Assert.True(result.IsCurrentRevision);
Assert.False(state.Current.HasUnsavedChanges);
Assert.Equal(state.Current.ExportUtf8(), uploaded.ToArray());
+ Assert.NotNull(uploadStream);
+ Assert.False(uploadStream.CanRead);
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task SaveAsync_FailedOrCancelledUploadDisposesStreamAndLeavesRevisionDirty(bool cancel)
+ {
+ var state = CreateDirtyState();
+ using var cancellation = new CancellationTokenSource();
+ Stream? uploadStream = null;
+ var store = CreateStore(
+ _ => Task.FromResult(null),
+ (content, token) =>
+ {
+ uploadStream = content;
+ if (cancel)
+ {
+ cancellation.Cancel();
+ return Task.FromCanceled(token);
+ }
+
+ return Task.FromException(new IOException("upload failed"));
+ },
+ allowEmptyConfiguration: true);
+
+ if (cancel)
+ {
+ await Assert.ThrowsAnyAsync(
+ () => store.SaveAsync(state, 1, cancellation.Token));
+ }
+ else
+ {
+ var failure = await Assert.ThrowsAsync(
+ () => store.SaveAsync(state, 1, cancellation.Token));
+ Assert.Equal(ConfigurationPersistenceError.IoFailure, failure.Error);
+ }
+
+ Assert.NotNull(uploadStream);
+ Assert.False(uploadStream.CanRead);
+ Assert.True(state.Current.HasUnsavedChanges);
+ Assert.Equal(1, state.Current.Revision);
}
[Fact]
@@ -221,10 +287,16 @@ public async Task SaveAsync_RejectsRevisionMismatchAndReportsUploadFailures()
public async Task SaveAsync_PreservesDirtyStateWhenConfigurationChangesDuringUpload()
{
var state = CreateDirtyState();
+ var expected = state.Current.ExportUtf8();
+ using var uploaded = new MemoryStream();
var store = new ConfigurationBlobStore(
CreateOptions(),
_ => Task.FromResult(null),
- (_, _) => Task.CompletedTask,
+ async (content, token) =>
+ {
+ await Task.Yield();
+ await content.CopyToAsync(uploaded, token);
+ },
onSnapshotCaptured: _ =>
{
Assert.Equal(
@@ -238,6 +310,7 @@ public async Task SaveAsync_PreservesDirtyStateWhenConfigurationChangesDuringUpl
Assert.Equal(1, result.Revision);
Assert.False(result.IsCurrentRevision);
Assert.True(state.Current.HasUnsavedChanges);
+ Assert.Equal(expected, uploaded.ToArray());
}
[Fact]
@@ -266,7 +339,7 @@ public async Task SdkConstructor_DownloadsUploadsAndHandlesMissingBlob()
private static ConfigurationBlobStore CreateStore(
Func> download,
- Func, CancellationToken, Task> upload,
+ Func upload,
bool allowEmptyConfiguration) =>
new(
new MockApiOptions
@@ -338,13 +411,16 @@ public override Task> DownloadStreamingAsy
return Task.FromResult(Response.FromValue(result, new TestResponse()));
}
- public override Task> UploadAsync(
- BinaryData content,
+ public override async Task> UploadAsync(
+ Stream content,
bool overwrite = false,
CancellationToken cancellationToken = default)
{
- Uploaded = content.ToMemory();
- return Task.FromResult(Response.FromValue(
+ Assert.True(overwrite);
+ using var uploaded = new MemoryStream();
+ await content.CopyToAsync(uploaded, cancellationToken);
+ Uploaded = uploaded.ToArray();
+ return Response.FromValue(
BlobsModelFactory.BlobContentInfo(
new ETag("test"),
DateTimeOffset.UtcNow,
@@ -353,7 +429,7 @@ public override Task> UploadAsync(
encryptionKeySha256: null,
encryptionScope: null,
blobSequenceNumber: 0),
- new TestResponse()));
+ new TestResponse());
}
}
diff --git a/tests/MockAPI.Tests/Configuration/ConfigurationStateTests.cs b/tests/MockAPI.Tests/Configuration/ConfigurationStateTests.cs
index fe27760..a39d45f 100644
--- a/tests/MockAPI.Tests/Configuration/ConfigurationStateTests.cs
+++ b/tests/MockAPI.Tests/Configuration/ConfigurationStateTests.cs
@@ -5,6 +5,91 @@ namespace MockAPI.Tests.Configuration;
public sealed class ConfigurationStateTests
{
+ [Fact]
+ public void GetEndpoint_FindsIdAfterNestedResponseWithoutAdvancingDeserializationReader()
+ {
+ var id = Guid.NewGuid();
+ var bytes = System.Text.Encoding.UTF8.GetBytes($$"""
+ {
+ "schemaVersion": "1.0",
+ "endpoints": [{
+ "name": "Selected endpoint",
+ "enabled": true,
+ "path": "/selected",
+ "methods": ["GET"],
+ "response": { "statusCode": 201, "headers": { "X-Values": ["first", "second"] }, "body": "raw body" },
+ "id": "{{id}}"
+ }]
+ }
+ """);
+ var snapshot = ConfigurationStateSnapshot.CreateFromOwnedSerializedDocument(
+ bytes, null, new ConfigurationState().Current.Endpoints, 1, false);
+
+ var selected = snapshot.GetEndpoint(id);
+
+ Assert.Equal(id, selected.Id);
+ Assert.Equal("/selected", selected.Path);
+ Assert.Equal("GET", Assert.Single(selected.Methods));
+ Assert.Equal(201, selected.Response.StatusCode);
+ Assert.Equal(new[] { "first", "second" }, selected.Response.Headers["X-Values"]);
+ Assert.Equal("raw body", selected.Response.Body);
+ Assert.Throws(() => snapshot.GetEndpoint(Guid.NewGuid()));
+ }
+
+ [Fact]
+ public void GetEndpoint_ReturnsDetachedCanonicalDataFromCapturedRevision()
+ {
+ var state = new ConfigurationState();
+ var first = CreateEndpoint("GET", "/first", "first");
+ var selected = CreateEndpoint("POST", "/selected", " \r\n{\"raw\": true}\n") with
+ {
+ Response = new()
+ {
+ StatusCode = 201,
+ Headers = new() { ["X-Z"] = ["first", "second"], ["X-A"] = ["value"] },
+ ContentType = "application/json",
+ Body = " \r\n{\"raw\": true}\n"
+ }
+ };
+ Assert.Equal(ConfigurationUpdateStatus.Applied, state.TryReplace(CreateDocument(first, selected), 0).Status);
+ var captured = state.Current;
+ var expected = captured.GetDocument().Endpoints[1];
+ var actual = captured.GetEndpoint(selected.Id);
+ Assert.Equal(JsonSerializer.Serialize(expected, MockApiJsonContext.Default.MockEndpointDefinition),
+ JsonSerializer.Serialize(actual, MockApiJsonContext.Default.MockEndpointDefinition));
+ Assert.IsAssignableFrom>(actual.Methods)[0] = "DELETE";
+ actual.Response.Headers["X-Z"][0] = "mutated";
+ Assert.Equal("POST", captured.GetEndpoint(selected.Id).Methods[0]);
+ Assert.Equal("first", captured.GetEndpoint(selected.Id).Response.Headers["X-Z"][0]);
+
+ state.TryReplace(CreateDocument(first), 1);
+ Assert.Equal(selected.Id, captured.GetEndpoint(selected.Id).Id);
+ Assert.Equal(first.Id, state.Current.GetEndpoint(first.Id).Id);
+ Assert.Throws(() => state.Current.GetEndpoint(selected.Id));
+ Assert.Throws(() => new ConfigurationState().Current.GetEndpoint(first.Id));
+ }
+
+ [Fact]
+ public void GetEndpoint_DoesNotAllocateForUnrelatedLargeBodies()
+ {
+ var state = new ConfigurationState();
+ var selected = CreateEndpoint("GET", "/selected", "small");
+ var large = CreateEndpoint("GET", "/large", new string('x', 960 * 1024));
+ state.TryReplace(CreateDocument(large, selected), 0);
+ var captured = state.Current;
+ for (var index = 0; index < 5; index++)
+ {
+ captured.GetEndpoint(selected.Id);
+ }
+
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var result = captured.GetEndpoint(selected.Id);
+ var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
+
+ Assert.Equal(selected.Id, result.Id);
+ Assert.InRange(allocated, 0, 8_192);
+ }
+
[Fact]
public void ApiDescriptions_AreDetachedAndCanonicallyOrderedAcrossImportExport()
{
@@ -250,6 +335,84 @@ public void Export_IsDeterministicAndValidatesAgainstSchema()
Assert.True(text.IndexOf("A-First", StringComparison.Ordinal) < text.IndexOf("Z-Last", StringComparison.Ordinal));
}
+ [Fact]
+ public void ExportUtf8_ReturnsIndependentMutableCopies()
+ {
+ var state = new ConfigurationState();
+ state.TryReplace(CreateDocument(CreateEndpoint("GET", "/detached", "body")), 0);
+ var snapshot = state.Current;
+ var first = snapshot.ExportUtf8();
+ var second = snapshot.ExportUtf8();
+
+ Assert.NotSame(first, second);
+ first[0] = 0;
+
+ Assert.Equal(second, snapshot.ExportUtf8());
+ Assert.Equal("/detached", Assert.Single(snapshot.GetDocument().Endpoints).Path);
+ }
+
+ [Fact]
+ public async Task WriteToAsync_WritesCapturedCanonicalBytesAndLeavesDestinationOpen()
+ {
+ var state = new ConfigurationState();
+ state.TryReplace(CreateDocument(CreateEndpoint("GET", "/captured", "\u00e9\r\nbody")), 0);
+ var snapshot = state.Current;
+ var expected = snapshot.ExportUtf8();
+ Assert.True(state.TryMarkPersisted(snapshot.Revision));
+ state.TryReplace(CreateDocument(CreateEndpoint("GET", "/newer", "newer")), snapshot.Revision);
+ using var destination = new MemoryStream();
+
+ await snapshot.WriteToAsync(destination, CancellationToken.None);
+
+ Assert.Equal(expected, destination.ToArray());
+ Assert.True(destination.CanWrite);
+ Assert.Equal("/newer", Assert.Single(state.Current.GetDocument().Endpoints).Path);
+ }
+
+ [Fact]
+ public async Task WriteToAsync_RejectsNullDestinationAndPropagatesCancellation()
+ {
+ var snapshot = new ConfigurationState().Current;
+ Assert.Throws(() => snapshot.WriteToAsync(null!, CancellationToken.None));
+ using var cancellation = new CancellationTokenSource();
+ cancellation.Cancel();
+
+ await Assert.ThrowsAnyAsync(
+ () => snapshot.WriteToAsync(Stream.Null, cancellation.Token).AsTask());
+ }
+
+ [Fact]
+ public async Task OpenRead_ReturnsIndependentReadOnlyStreamsWithoutExposingSnapshotStorage()
+ {
+ var state = new ConfigurationState();
+ state.TryReplace(CreateDocument(CreateEndpoint("GET", "/captured", "body")), 0);
+ var snapshot = state.Current;
+ var expected = snapshot.ExportUtf8();
+ using var first = snapshot.OpenRead();
+ using var second = snapshot.OpenRead();
+
+ Assert.True(first.CanRead);
+ Assert.True(first.CanSeek);
+ Assert.False(first.CanWrite);
+ Assert.Equal(expected.Length, first.Length);
+ Assert.Equal(expected[0], first.ReadByte());
+ Assert.Equal(0, second.Position);
+ Assert.Throws(() => first.WriteByte(0));
+ Assert.Throws(() => first.SetLength(0));
+ var memoryStream = Assert.IsType(first);
+ Assert.False(memoryStream.TryGetBuffer(out _));
+ Assert.Throws(() => memoryStream.GetBuffer());
+
+ first.Dispose();
+ state.TryReplace(CreateDocument(CreateEndpoint("GET", "/newer", "newer")), snapshot.Revision);
+ using var destination = new MemoryStream();
+ await second.CopyToAsync(destination);
+
+ Assert.Equal(expected, destination.ToArray());
+ Assert.Equal(expected, snapshot.ExportUtf8());
+ Assert.Equal("/newer", Assert.Single(state.Current.GetDocument().Endpoints).Path);
+ }
+
[Fact]
public void DeserializeDocument_RejectsNullAndReadsValidDocument()
{
diff --git a/tests/MockAPI.Tests/Management/ApiKeySecurityTests.cs b/tests/MockAPI.Tests/Management/ApiKeySecurityTests.cs
index fd605c3..c11d132 100644
--- a/tests/MockAPI.Tests/Management/ApiKeySecurityTests.cs
+++ b/tests/MockAPI.Tests/Management/ApiKeySecurityTests.cs
@@ -25,6 +25,85 @@ public sealed class ApiKeySecurityTests : IDisposable
private readonly string _directory = Path.Combine(Path.GetTempPath(), "mockapi-security-tests", Guid.NewGuid().ToString("N"));
private string ConfigurationPath => Path.Combine(_directory, "mockapi.json");
+ [Theory]
+ [InlineData(32)]
+ [InlineData(43)]
+ [InlineData(256)]
+ public async Task WarmAuthorization_DoesNotAllocateForEncodingHashingOrStoredHashDecoding(int length)
+ {
+ var key = new string('a', length);
+ using var security = new ApiKeySecurity(new MockApiOptions { ConfigurationPath = ConfigurationPath, ApiKey = key });
+ await security.LoadAsync(CancellationToken.None);
+ var context = new DefaultHttpContext();
+ context.Request.Headers[ApiKeySecurity.HeaderName] = key;
+ for (var index = 0; index < 100; index++)
+ {
+ Assert.True(security.Authorizes(context));
+ }
+
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var authorized = true;
+ for (var index = 0; index < 1_000; index++)
+ {
+ authorized &= security.Authorizes(context);
+ }
+ var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
+
+ Assert.True(authorized);
+ Assert.InRange(allocated, 0, 1_024);
+ }
+
+ [Fact]
+ public async Task ParallelAuthorization_UsesIndependentScratchStorage()
+ {
+ var key = new string('a', 256);
+ using var security = new ApiKeySecurity(new MockApiOptions { ConfigurationPath = ConfigurationPath, ApiKey = key });
+ await security.LoadAsync(CancellationToken.None);
+ var valid = new DefaultHttpContext();
+ valid.Request.Headers[ApiKeySecurity.HeaderName] = key;
+ var invalid = new DefaultHttpContext();
+ invalid.Request.Headers[ApiKeySecurity.HeaderName] = new string('b', 256);
+ Assert.True(security.Authorizes(valid));
+ Assert.False(security.Authorizes(invalid));
+
+ Parallel.For(0, 5_000, index =>
+ Assert.Equal(index % 2 == 0, security.Authorizes(index % 2 == 0 ? valid : invalid)));
+ }
+
+ [Fact]
+ public async Task PersistedLowercaseHash_IsDecodedWithoutChangingStoredContract()
+ {
+ var key = new string('a', 32);
+ Directory.CreateDirectory(_directory);
+ var document = new ApiSecurityDocument(true,
+ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key))).ToLowerInvariant(), 1);
+ var content = JsonSerializer.Serialize(document, ApiSecurityJsonContext.Default.ApiSecurityDocument);
+ await File.WriteAllTextAsync(ConfigurationPath + ".security.json", content);
+ using var security = new ApiKeySecurity(new MockApiOptions { ConfigurationPath = ConfigurationPath });
+
+ await security.LoadAsync(CancellationToken.None);
+
+ Assert.True(Authorizes(security, key));
+ Assert.Equal(content, await File.ReadAllTextAsync(ConfigurationPath + ".security.json"));
+ }
+
+ [Fact]
+ public async Task FailedRotation_PreservesPreviouslyPublishedDigestAndStatus()
+ {
+ var key = new string('a', 32);
+ using var security = new ApiKeySecurity(new MockApiOptions { ConfigurationPath = ConfigurationPath, ApiKey = key });
+ await security.LoadAsync(CancellationToken.None);
+ var previous = security.Status;
+ File.Delete(ConfigurationPath + ".security.json");
+ Directory.CreateDirectory(ConfigurationPath + ".security.json");
+
+ var failure = await Record.ExceptionAsync(() => security.UpdateAsync(previous.ETag, true, true, CancellationToken.None));
+
+ Assert.True(failure is IOException or UnauthorizedAccessException);
+ Assert.Equal(previous, security.Status);
+ Assert.True(Authorizes(security, key));
+ }
+
[Theory]
[InlineData(32)]
[InlineData(36)]
diff --git a/tests/MockAPI.Tests/Management/ConfigurationAutosaveTests.cs b/tests/MockAPI.Tests/Management/ConfigurationAutosaveTests.cs
index d39a80a..507d1e8 100644
--- a/tests/MockAPI.Tests/Management/ConfigurationAutosaveTests.cs
+++ b/tests/MockAPI.Tests/Management/ConfigurationAutosaveTests.cs
@@ -233,7 +233,7 @@ public async Task RequestDisconnect_DoesNotCancelPersistenceAfterActivation()
Assert.False(token.CanBeCanceled);
captured.TrySetResult();
await release.Task;
- _blobBytes = content.ToArray();
+ _blobBytes = await ReadUploadAsync(content, token);
});
await using var factory = CreateFactory(store);
using var client = factory.CreateClient();
@@ -278,7 +278,7 @@ public async Task AutoSave_ConcurrentRevisionsPersistTheWinnerWithoutOverwriting
captured.SetResult();
await release.Task.WaitAsync(token);
}
- uploads.Add(content.ToArray());
+ uploads.Add(await ReadUploadAsync(content, token));
});
var state = new ConfigurationState();
var service = new ConfigurationManagementService(state, store);
@@ -329,12 +329,11 @@ private IConfigurationStore CreateStore(bool useBlob)
_ => Task.FromResult(_blobBytes is null
? null
: new(new MemoryStream(_blobBytes), _blobBytes.Length)),
- (content, _) =>
+ async (content, token) =>
{
_saveCount++;
if (_saveFails) throw new RequestFailedException(503, "private-storage-error");
- _blobBytes = content.ToArray();
- return Task.CompletedTask;
+ _blobBytes = await ReadUploadAsync(content, token);
});
}
@@ -347,6 +346,13 @@ private IConfigurationStore CreateStore(bool useBlob)
});
}
+ private static async Task ReadUploadAsync(Stream content, CancellationToken cancellationToken)
+ {
+ using var buffer = new MemoryStream();
+ await content.CopyToAsync(buffer, cancellationToken);
+ return buffer.ToArray();
+ }
+
private WebApplicationFactory CreateFactory(IConfigurationStore store) =>
new WebApplicationFactory().WithWebHostBuilder(builder =>
{
diff --git a/tests/MockAPI.Tests/Management/ConfigurationReadDiagnostics.cs b/tests/MockAPI.Tests/Management/ConfigurationReadDiagnostics.cs
index 1d837c4..88ea589 100644
--- a/tests/MockAPI.Tests/Management/ConfigurationReadDiagnostics.cs
+++ b/tests/MockAPI.Tests/Management/ConfigurationReadDiagnostics.cs
@@ -36,6 +36,12 @@ public void MeasureStatusProjectionStatusHandlerAndNativeExport()
Measure("status-handler -> Stream.Null", () => CompleteSynchronously(ConfigurationReadTests.WriteStatus(statusContext, statusService)));
Measure("native-export omitted IDs -> Stream.Null", () => CompleteSynchronously(ConfigurationReadTests.WriteExport(exportContext, exportService, null, null, true)));
Measure("native-export empty IDs -> Stream.Null", () => CompleteSynchronously(ConfigurationReadTests.WriteExport(exportContext, exportService, [], null, true)));
+
+ var blobStore = new ConfigurationBlobStore(
+ new MockApiOptions { ConfigurationPath = "unused-diagnostic-path" },
+ _ => Task.FromResult(null),
+ (_, _) => Task.CompletedTask);
+ Measure("blob-save -> completed upload", () => CompleteSynchronously(blobStore.SaveAsync(state, snapshot.Revision, CancellationToken.None)));
}
private void Measure(string name, Action operation)
diff --git a/tests/MockAPI.Tests/Management/ConfigurationReadTests.cs b/tests/MockAPI.Tests/Management/ConfigurationReadTests.cs
index f0ccbc1..714e6d9 100644
--- a/tests/MockAPI.Tests/Management/ConfigurationReadTests.cs
+++ b/tests/MockAPI.Tests/Management/ConfigurationReadTests.cs
@@ -116,6 +116,27 @@ public async Task GeneratedExports_PreserveFilteredAndUnfilteredArtifacts(string
}
}
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task NativeExport_DoesNotAllocateADocumentSizedCopy(bool emptySelection)
+ {
+ var state = CreateState("text", bodyLength: 166000, endpointCount: 25);
+ var service = new ConfigurationManagementService(state, new UnusedStore());
+ var context = new DefaultHttpContext();
+ context.Response.Body = Stream.Null;
+ Guid[]? endpointIds = emptySelection ? [] : null;
+ await WriteExport(context, service, endpointIds, null, true);
+
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var export = WriteExport(context, service, endpointIds, null, true);
+ Assert.True(export.IsCompletedSuccessfully);
+ await export;
+ var allocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before;
+
+ Assert.InRange(allocatedBytes, 0, 64 * 1024);
+ }
+
[Theory]
[InlineData("omitted")]
[InlineData("empty")]
diff --git a/tests/MockAPI.Tests/Management/DashboardAuthenticationTests.cs b/tests/MockAPI.Tests/Management/DashboardAuthenticationTests.cs
index 60a215e..f1040d8 100644
--- a/tests/MockAPI.Tests/Management/DashboardAuthenticationTests.cs
+++ b/tests/MockAPI.Tests/Management/DashboardAuthenticationTests.cs
@@ -14,12 +14,13 @@ public sealed class DashboardAuthenticationTests
private const string Username = "operator";
private const string Password = "test-password";
- [Fact]
- public async Task DashboardEvents_AuthenticateBeforeOpeningStream()
+ [Theory]
+ [InlineData("/__mockapi/api/dashboard/events")]
+ [InlineData("/__mockapi/api/statistics/events")]
+ public async Task EventStreams_AuthenticateBeforeOpeningStream(string path)
{
await using var factory = CreateFactory();
using var client = factory.CreateClient();
- const string path = "/__mockapi/api/dashboard/events";
using var anonymous = await client.GetAsync(path);
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
@@ -54,6 +55,7 @@ public async Task DashboardEvents_AuthenticateBeforeOpeningStream()
[InlineData("/dashboard-test-request.js")]
[InlineData("/dashboard-tutorial.js")]
[InlineData("/__mockapi/api/configuration")]
+ [InlineData("/__mockapi/api/statistics")]
[InlineData("/__mockapi/api/configuration/export/openapi?download=false")]
[InlineData("/__mockapi/openapi/v1.json")]
[InlineData("/__mockapi/swagger/index.html")]
diff --git a/tests/MockAPI.Tests/Management/DashboardOptimizationTests.cs b/tests/MockAPI.Tests/Management/DashboardOptimizationTests.cs
index 2d15d0b..f28a9b1 100644
--- a/tests/MockAPI.Tests/Management/DashboardOptimizationTests.cs
+++ b/tests/MockAPI.Tests/Management/DashboardOptimizationTests.cs
@@ -211,7 +211,8 @@ public async Task IdleDashboardStream_SendsOnlyKeepaliveUntilStatisticsChange()
// Advance the reported time on each read while retaining the real two-second timer.
// The first idle tick stays below the heartbeat threshold; the next crosses it.
var clock = new SteppingClock();
- var events = new DashboardEventStream(new ConfigurationState(), new RequestStatisticsCollector(), clock);
+ // Keep the collector's minute fixed independently of the accelerated heartbeat clock.
+ var events = new DashboardEventStream(new ConfigurationState(), new RequestStatisticsCollector(new Clock()), clock);
var pipe = new Pipe();
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var context = new DefaultHttpContext { RequestAborted = cancellation.Token };
diff --git a/tests/MockAPI.Tests/Management/ManagementApiTests.cs b/tests/MockAPI.Tests/Management/ManagementApiTests.cs
index 2c5ba3d..582b3e4 100644
--- a/tests/MockAPI.Tests/Management/ManagementApiTests.cs
+++ b/tests/MockAPI.Tests/Management/ManagementApiTests.cs
@@ -156,7 +156,7 @@ public async Task StatisticsStream_CancellationIsHandled()
var streamTask = MockAPI.Management.ManagementApiEndpoints.StreamStatisticsAsync(
context,
- new MockAPI.Runtime.RequestStatisticsCollector());
+ new MockAPI.Management.StatisticsSnapshotCache(new MockAPI.Runtime.RequestStatisticsCollector()));
await WaitForAsync(() => context.Response.Body.Length > 0, TimeSpan.FromSeconds(2));
cancellation.Cancel();
await streamTask;
diff --git a/tests/MockAPI.Tests/Management/RemainingManagementApiTests.cs b/tests/MockAPI.Tests/Management/RemainingManagementApiTests.cs
index f215265..b56eb71 100644
--- a/tests/MockAPI.Tests/Management/RemainingManagementApiTests.cs
+++ b/tests/MockAPI.Tests/Management/RemainingManagementApiTests.cs
@@ -1207,6 +1207,11 @@ public async Task OpenApi_DescribesManagementRoutesAndExcludesRuntimeRoutes()
}
var dashboardEvents = paths.GetProperty($"{BasePath}/dashboard/events").GetProperty("get");
Assert.Equal("StreamDashboardEvents", dashboardEvents.GetProperty("operationId").GetString());
+ var deltasParameter = Assert.Single(dashboardEvents.GetProperty("parameters").EnumerateArray(),
+ parameter => parameter.GetProperty("name").GetString() == "deltas");
+ Assert.Equal("query", deltasParameter.GetProperty("in").GetString());
+ Assert.False(deltasParameter.TryGetProperty("required", out var deltasRequired) && deltasRequired.GetBoolean());
+ Assert.Contains("statistics-delta", dashboardEvents.GetProperty("description").GetString(), StringComparison.Ordinal);
Assert.True(dashboardEvents.GetProperty("responses").GetProperty("200").GetProperty("content")
.TryGetProperty("text/event-stream", out _));
Assert.All(operations, operation =>
diff --git a/tests/MockAPI.Tests/Management/StatisticsDeliveryDiagnostics.cs b/tests/MockAPI.Tests/Management/StatisticsDeliveryDiagnostics.cs
new file mode 100644
index 0000000..8faffec
--- /dev/null
+++ b/tests/MockAPI.Tests/Management/StatisticsDeliveryDiagnostics.cs
@@ -0,0 +1,115 @@
+using System.Diagnostics;
+using System.Text.Json;
+using Microsoft.AspNetCore.Http;
+using MockAPI.Configuration;
+using MockAPI.Management;
+using MockAPI.Runtime;
+using Xunit.Abstractions;
+
+namespace MockAPI.Tests.Management;
+
+public sealed class StatisticsDeliveryDiagnostics(ITestOutputHelper output)
+{
+ // Opt in with MOCKAPI_STATISTICS_DIAGNOSTICS=1, Release, DOTNET_TieredCompilation=0,
+ // and --logger "console;verbosity=detailed". Fixture creation is not measured.
+ [Fact]
+ [Trait("Category", "Diagnostic")]
+ public void MeasureSnapshotAndDeliveryAllocations()
+ {
+ if (Environment.GetEnvironmentVariable("MOCKAPI_STATISTICS_DIAGNOSTICS") != "1")
+ {
+ return;
+ }
+
+ var collector = StatisticsDeliveryTests.CreateCollector(RequestStatisticsCollector.MaximumTrackedEndpoints);
+ var cache = new StatisticsSnapshotCache(collector);
+ var events = new DashboardEventStream(new ConfigurationState(), cache, new StatisticsDeliveryTests.Clock());
+ var getContext = new DefaultHttpContext();
+ getContext.Response.Body = Stream.Null;
+ var compact = JsonSerializer.Serialize(collector.GetSnapshot(), StatisticsDeliveryTests.CompactJson.RequestStatisticsSnapshot);
+ output.WriteLine($"Runtime={Environment.Version}; endpoints={RequestStatisticsCollector.MaximumTrackedEndpoints}; compactJsonChars={compact.Length}");
+ Measure("uncached snapshot + compact serialization (reference)", () =>
+ GC.KeepAlive(JsonSerializer.Serialize(collector.GetSnapshot(), StatisticsDeliveryTests.CompactJson.RequestStatisticsSnapshot)));
+ Measure("idle dashboard compact JSON", () => GC.KeepAlive(events.GetStatisticsJson()));
+ Measure("idle GET -> Stream.Null", () => Complete(ManagementApiEndpoints.WriteStatisticsAsync(getContext, cache)));
+ Measure("idle standalone SSE, one event -> counting sink", () => WriteStream(dashboard: false));
+ Measure("idle dashboard SSE, initial events -> counting sink", () => WriteStream(dashboard: true));
+ Measure("changed dashboard compact JSON", () =>
+ {
+ collector.RecordUnmatched();
+ GC.KeepAlive(events.GetStatisticsJson());
+ });
+
+ void WriteStream(bool dashboard)
+ {
+ using var cancellation = new CancellationTokenSource();
+ using var sink = new CancelOnFlushSink(cancellation);
+ var context = new DefaultHttpContext { RequestAborted = cancellation.Token };
+ context.Response.Body = sink;
+ Complete(dashboard ? events.WriteAsync(context) : ManagementApiEndpoints.StreamStatisticsAsync(context, cache));
+ }
+ }
+
+ private void Measure(string name, Action operation)
+ {
+ const int iterations = 10;
+ const int samples = 5;
+ for (var index = 0; index < 10; index++)
+ {
+ operation();
+ }
+ var allocations = new long[samples];
+ var elapsed = new double[samples];
+ for (var sample = 0; sample < samples; sample++)
+ {
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ GC.Collect();
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var start = Stopwatch.GetTimestamp();
+ for (var index = 0; index < iterations; index++)
+ {
+ operation();
+ }
+ elapsed[sample] = Stopwatch.GetElapsedTime(start).TotalMilliseconds / iterations;
+ allocations[sample] = (GC.GetAllocatedBytesForCurrentThread() - before) / iterations;
+ }
+ output.WriteLine($"{name}: bytes/op=[{string.Join(", ", allocations)}]; ms/op=[{string.Join(", ", elapsed.Select(value => value.ToString("F6", System.Globalization.CultureInfo.InvariantCulture)))}]; iterations={iterations}; samples={samples}");
+ }
+
+ private static void Complete(Task operation)
+ {
+ Assert.True(operation.IsCompleted, "Thread-local allocation measurement requires synchronous sink completion.");
+ operation.GetAwaiter().GetResult();
+ }
+
+ private sealed class CancelOnFlushSink(CancellationTokenSource cancellation) : Stream
+ {
+ private long _bytes;
+ private long _lastFlushedBytes;
+ public override bool CanRead => false;
+ public override bool CanSeek => false;
+ public override bool CanWrite => true;
+ public override long Length => throw new NotSupportedException();
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+ public override void Flush() { }
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
+ if (_bytes > 0 && _bytes == _lastFlushedBytes)
+ {
+ cancellation.Cancel();
+ }
+ _lastFlushedBytes = _bytes;
+ return Task.CompletedTask;
+ }
+ public override void Write(byte[] buffer, int offset, int count) => _bytes += count;
+ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default)
+ {
+ _bytes += buffer.Length;
+ return ValueTask.CompletedTask;
+ }
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+ public override void SetLength(long value) => throw new NotSupportedException();
+ }
+}
diff --git a/tests/MockAPI.Tests/Management/StatisticsDeliveryTests.cs b/tests/MockAPI.Tests/Management/StatisticsDeliveryTests.cs
new file mode 100644
index 0000000..c67faf9
--- /dev/null
+++ b/tests/MockAPI.Tests/Management/StatisticsDeliveryTests.cs
@@ -0,0 +1,496 @@
+using System.Text;
+using System.Text.Json;
+using System.IO.Pipelines;
+using Microsoft.AspNetCore.Http;
+using MockAPI.Configuration;
+using MockAPI.Management;
+using MockAPI.Runtime;
+
+namespace MockAPI.Tests.Management;
+
+public sealed class StatisticsDeliveryTests
+{
+ internal static readonly ManagementJsonContext CompactJson = new(
+ new JsonSerializerOptions(ManagementJsonContext.Default.Options) { WriteIndented = false });
+
+ [Fact]
+ public async Task StatisticsGet_PreservesExactIndentedJsonAndHeaders()
+ {
+ var collector = CreateCollector();
+ var expected = JsonSerializer.Serialize(collector.GetSnapshot(), ManagementJsonContext.Default.RequestStatisticsSnapshot);
+ var context = new DefaultHttpContext();
+ using var body = new MemoryStream();
+ context.Response.Body = body;
+
+ await ManagementApiEndpoints.WriteStatisticsAsync(context, new StatisticsSnapshotCache(collector));
+
+ Assert.Equal(expected, Encoding.UTF8.GetString(body.ToArray()));
+ Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
+ Assert.Equal("application/json; charset=utf-8", context.Response.ContentType);
+ Assert.Equal("no-store", context.Response.Headers.CacheControl);
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task EventStreams_PreserveExactCompactFramesAndHeaders(bool dashboard)
+ {
+ var collector = CreateCollector();
+ var state = new ConfigurationState();
+ var expected = "event: statistics\ndata: " +
+ JsonSerializer.Serialize(collector.GetSnapshot(), CompactJson.RequestStatisticsSnapshot) + "\n\n";
+ if (dashboard)
+ {
+ expected = "event: configuration\ndata: " +
+ JsonSerializer.Serialize(ConfigurationStatusResponse.FromSnapshot(state.Current), CompactJson.ConfigurationStatusResponse) +
+ "\n\n" + expected;
+ }
+ using var cancellation = new CancellationTokenSource();
+ using var body = new CancelOnFlushStream(cancellation);
+ var context = new DefaultHttpContext { RequestAborted = cancellation.Token };
+ context.Response.Body = body;
+
+ await (dashboard
+ ? new DashboardEventStream(state, collector, new Clock()).WriteAsync(context)
+ : ManagementApiEndpoints.StreamStatisticsAsync(context, new StatisticsSnapshotCache(collector)));
+
+ Assert.Equal(expected, Encoding.UTF8.GetString(body.ToArray()));
+ Assert.Equal("text/event-stream", context.Response.ContentType);
+ Assert.Equal(dashboard ? "no-store" : "no-cache", context.Response.Headers.CacheControl);
+ Assert.Equal(dashboard ? "" : "keep-alive", context.Response.Headers.Connection.ToString());
+ Assert.Equal(dashboard ? "no" : "", context.Response.Headers["X-Accel-Buffering"].ToString());
+ Assert.True(cancellation.IsCancellationRequested);
+ }
+
+ [Fact]
+ public void Cache_UsesCollectorMinuteAndInvalidatesForRecordingRetriesAndResets()
+ {
+ var clock = new Clock { Now = new(2026, 1, 1, 0, 0, 59, TimeSpan.Zero) };
+ var collector = new RequestStatisticsCollector(clock);
+ var cache = new StatisticsSnapshotCache(collector);
+ var endpointId = Guid.NewGuid();
+ collector.RecordMatched(endpointId, "GET", "/items", 200, 5, "retry");
+ var initial = cache.GetSnapshot();
+ var initialJson = cache.GetCompactJson();
+ Assert.Same(initial, cache.GetSnapshot());
+ Assert.Same(initialJson, cache.GetCompactJson());
+
+ clock.Now += TimeSpan.FromMilliseconds(500);
+ Assert.Same(initial, cache.GetSnapshot());
+ clock.Now += TimeSpan.FromMilliseconds(500);
+ var rolled = cache.GetSnapshot();
+ Assert.NotSame(initial, rolled);
+ Assert.Equal(60, rolled.RecentMinutes.Length);
+ Assert.Equal(0, rolled.RecentMinutes[^1].Requests);
+ Assert.Equal(1, rolled.RecentMinutes[^2].Requests);
+ Assert.Equal(1, Assert.Single(rolled.Endpoints).RecentMinutes[^2].Requests);
+ Assert.NotSame(initialJson, cache.GetCompactJson());
+
+ collector.RecordMatched(endpointId, "GET", "/items", 200, 5, "retry");
+ var retry = cache.GetSnapshot();
+ Assert.NotSame(rolled, retry);
+ Assert.Equal(1, retry.TotalRequests);
+ Assert.Equal(2, Assert.Single(retry.RecentRequests).TransportAttempts);
+ Assert.Equal(1, Assert.Single(initial.RecentRequests).TransportAttempts);
+
+ Assert.True(collector.Reset(endpointId));
+ var endpointReset = cache.GetSnapshot();
+ Assert.NotSame(retry, endpointReset);
+ Assert.Empty(endpointReset.Endpoints);
+ Assert.Empty(endpointReset.RecentRequests);
+ Assert.Equal(1, endpointReset.TotalRequests);
+ Assert.False(collector.Reset(endpointId));
+ Assert.Same(endpointReset, cache.GetSnapshot());
+ collector.Reset();
+ var reset = cache.GetSnapshot();
+ Assert.NotSame(endpointReset, reset);
+ Assert.Equal(0, reset.TotalRequests);
+ Assert.All(reset.RecentMinutes, minute => Assert.Equal(0, minute.Requests));
+ Assert.Equal(JsonSerializer.Serialize(reset, CompactJson.RequestStatisticsSnapshot), cache.GetCompactJson());
+ Assert.Single(initial.Endpoints);
+ Assert.Equal(1, initial.TotalRequests);
+ }
+
+ [Fact]
+ public void Cache_IdleRolloverExpiresBothAggregateAndEndpointHistoryAfterSixtyMinutes()
+ {
+ var clock = new Clock();
+ var collector = new RequestStatisticsCollector(clock);
+ collector.RecordMatched(Guid.NewGuid(), 503, 3);
+ var cache = new StatisticsSnapshotCache(collector);
+ var initial = cache.GetSnapshot();
+ clock.Now += TimeSpan.FromMinutes(59);
+ var retained = cache.GetSnapshot();
+ Assert.Equal(1, retained.RecentMinutes[0].Requests);
+ Assert.Equal(1, Assert.Single(retained.Endpoints).RecentMinutes[0].ServerErrorResponses);
+ clock.Now += TimeSpan.FromMinutes(1);
+ var expired = cache.GetSnapshot();
+ Assert.Equal(60, expired.RecentMinutes.Length);
+ Assert.Equal(0, expired.RecentMinutes.Sum(minute => minute.Requests));
+ Assert.Equal(0, Assert.Single(expired.Endpoints).RecentMinutes.Sum(minute => minute.Requests));
+ Assert.Equal(1, expired.TotalRequests);
+ Assert.Equal(1, initial.RecentMinutes[^1].Requests);
+ }
+
+ [Fact]
+ public async Task Cache_IsSharedByGetAndBothEventStreamsWithoutMutableSnapshots()
+ {
+ var collector = CreateCollector();
+ var cache = new StatisticsSnapshotCache(collector);
+ var snapshot = cache.GetSnapshot();
+ var json = cache.GetCompactJson();
+ var events = new DashboardEventStream(new ConfigurationState(), cache);
+ var context = new DefaultHttpContext();
+ context.Response.Body = Stream.Null;
+ await ManagementApiEndpoints.WriteStatisticsAsync(context, cache);
+ Assert.Same(snapshot, cache.GetSnapshot());
+ Assert.Same(json, events.GetStatisticsJson());
+ foreach (var dashboard in new[] { false, true })
+ {
+ using var cancellation = new CancellationTokenSource();
+ using var body = new CancelOnFlushStream(cancellation);
+ var streamContext = new DefaultHttpContext { RequestAborted = cancellation.Token };
+ streamContext.Response.Body = body;
+ await (dashboard ? events.WriteAsync(streamContext) : ManagementApiEndpoints.StreamStatisticsAsync(streamContext, cache));
+ Assert.Contains($"event: statistics\ndata: {json}\n\n", Encoding.UTF8.GetString(body.ToArray()), StringComparison.Ordinal);
+ Assert.Same(snapshot, cache.GetSnapshot());
+ Assert.Same(json, events.GetStatisticsJson());
+ }
+ collector.Reset();
+ Assert.NotSame(snapshot, cache.GetSnapshot());
+ Assert.NotSame(json, events.GetStatisticsJson());
+ Assert.Equal(4, snapshot.TotalRequests);
+ }
+
+ [Fact]
+ public void Cache_ConcurrentIdleReadersShareOneSnapshotAndOneSerialization()
+ {
+ var cache = new StatisticsSnapshotCache(CreateCollector());
+ var snapshots = new RequestStatisticsSnapshot[16];
+ var payloads = new string[16];
+ Parallel.For(0, snapshots.Length, index =>
+ {
+ snapshots[index] = cache.GetSnapshot();
+ payloads[index] = cache.GetCompactJson();
+ });
+ Assert.All(snapshots, snapshot => Assert.Same(snapshots[0], snapshot));
+ Assert.All(payloads, payload => Assert.Same(payloads[0], payload));
+ }
+
+ [Fact]
+ public void Cache_UsesOneClockReadForTheKeyAndRollingBuckets()
+ {
+ var clock = new AdvancingClock();
+ var cache = new StatisticsSnapshotCache(new RequestStatisticsCollector(clock));
+ using var first = JsonDocument.Parse(cache.GetCompactJson());
+ Assert.Equal(1, clock.Reads);
+ Assert.Equal(clock.Start, first.RootElement.GetProperty("recentMinutes")[59].GetProperty("minuteUtc").GetDateTimeOffset());
+ using var second = JsonDocument.Parse(cache.GetCompactJson());
+ Assert.Equal(2, clock.Reads);
+ Assert.Equal(clock.Start.AddMinutes(1), second.RootElement.GetProperty("recentMinutes")[59].GetProperty("minuteUtc").GetDateTimeOffset());
+ }
+
+ [Fact]
+ public async Task StandaloneStream_RetransmitsUnchangedStatisticsEveryRefresh()
+ {
+ var collector = CreateCollector();
+ var cache = new StatisticsSnapshotCache(collector);
+ var expected = cache.GetCompactJson();
+ var pipe = new Pipe();
+ using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10));
+ await using var writer = pipe.Writer.AsStream();
+ await using var readerStream = pipe.Reader.AsStream();
+ using var reader = new StreamReader(readerStream);
+ var context = new DefaultHttpContext { RequestAborted = cancellation.Token };
+ context.Response.Body = writer;
+ var streaming = ManagementApiEndpoints.StreamStatisticsAsync(context, cache);
+ try
+ {
+ for (var refresh = 0; refresh < 2; refresh++)
+ {
+ Assert.Equal("event: statistics", await reader.ReadLineAsync(cancellation.Token));
+ Assert.Equal($"data: {expected}", await reader.ReadLineAsync(cancellation.Token));
+ Assert.Equal("", await reader.ReadLineAsync(cancellation.Token));
+ Assert.Same(expected, cache.GetCompactJson());
+ }
+ }
+ finally
+ {
+ cancellation.Cancel();
+ await streaming;
+ }
+ }
+
+ [Fact]
+ public async Task Cache_RecordingCompletionInvalidatesAPartialConcurrentView()
+ {
+ using var reachedEndpoint = new ManualResetEventSlim();
+ using var release = new ManualResetEventSlim();
+ var endpointId = Guid.NewGuid();
+ var collector = new RequestStatisticsCollector(new Clock(), () =>
+ {
+ reachedEndpoint.Set();
+ Assert.True(release.Wait(TimeSpan.FromSeconds(10)));
+ });
+ var cache = new StatisticsSnapshotCache(collector);
+ var recording = Task.Run(() => collector.RecordMatched(endpointId, 200, 5));
+ try
+ {
+ Assert.True(reachedEndpoint.Wait(TimeSpan.FromSeconds(10)));
+ var partial = cache.GetSnapshot();
+ Assert.Equal(1, partial.TotalRequests);
+ Assert.Empty(partial.Endpoints);
+ _ = cache.GetCompactJson();
+ }
+ finally
+ {
+ release.Set();
+ await recording;
+ }
+ var completed = cache.GetSnapshot();
+ Assert.Equal(1, Assert.Single(completed.Endpoints).TotalRequests);
+ Assert.Equal(JsonSerializer.Serialize(completed, CompactJson.RequestStatisticsSnapshot), cache.GetCompactJson());
+ }
+
+ [Fact]
+ public async Task Cache_ConcurrentRecordersAndReadersConvergeWithoutLosingCounters()
+ {
+ var collector = new RequestStatisticsCollector(new Clock());
+ var cache = new StatisticsSnapshotCache(collector);
+ var endpointId = Guid.NewGuid();
+ using var start = new ManualResetEventSlim();
+ var recorders = Enumerable.Range(0, 4).Select(_ => Task.Run(() =>
+ {
+ start.Wait();
+ for (var index = 0; index < 1_000; index++)
+ {
+ collector.RecordMatched(endpointId, 201, 3);
+ }
+ })).ToArray();
+ var readers = Enumerable.Range(0, 4).Select(_ => Task.Run(() =>
+ {
+ start.Wait();
+ for (var index = 0; index < 100; index++)
+ {
+ var snapshot = cache.GetSnapshot();
+ Assert.Equal(60, snapshot.RecentMinutes.Length);
+ Assert.InRange(snapshot.TotalRequests, 0, 4_000);
+ Assert.InRange(snapshot.RecentRequests.Length, 0, RequestStatisticsCollector.MaximumRecentRequests);
+ using var json = JsonDocument.Parse(cache.GetCompactJson());
+ Assert.InRange(json.RootElement.GetProperty("totalRequests").GetInt64(), 0, 4_000);
+ }
+ })).ToArray();
+ start.Set();
+ await Task.WhenAll(recorders.Concat(readers)).WaitAsync(TimeSpan.FromSeconds(20));
+ var final = cache.GetSnapshot();
+ Assert.Equal(4_000, final.TotalRequests);
+ Assert.Equal(4_000, final.MatchedRequests);
+ Assert.Equal(12_000, final.ResponseBytes);
+ Assert.Equal(4_000, final.RecentMinutes[^1].SuccessResponses);
+ Assert.Equal(4_000, Assert.Single(final.Endpoints).TotalRequests);
+ Assert.Equal(JsonSerializer.Serialize(final, CompactJson.RequestStatisticsSnapshot), cache.GetCompactJson());
+ }
+
+ [Fact]
+ public async Task Cache_ConcurrentResetsAndRecordingCannotLeaveAStaleQuiescentView()
+ {
+ var collector = CreateCollector();
+ var cache = new StatisticsSnapshotCache(collector);
+ var beforeReset = cache.GetSnapshot();
+ var endpointId = beforeReset.Endpoints[0].EndpointId;
+ using var start = new ManualResetEventSlim();
+ var recording = Task.Run(() =>
+ {
+ start.Wait();
+ for (var index = 0; index < 1_000; index++)
+ {
+ collector.RecordMatched(endpointId, 200, 1);
+ }
+ });
+ var resetting = Task.Run(() =>
+ {
+ start.Wait();
+ for (var index = 0; index < 100; index++)
+ {
+ collector.Reset(endpointId);
+ collector.Reset();
+ }
+ });
+ var reading = Task.Run(() =>
+ {
+ start.Wait();
+ for (var index = 0; index < 100; index++)
+ {
+ Assert.Equal(60, cache.GetSnapshot().RecentMinutes.Length);
+ using var json = JsonDocument.Parse(cache.GetCompactJson());
+ Assert.InRange(json.RootElement.GetProperty("endpoints").GetArrayLength(), 0, 1);
+ }
+ });
+ start.Set();
+ await Task.WhenAll(recording, resetting, reading).WaitAsync(TimeSpan.FromSeconds(20));
+ collector.Reset();
+ var reset = cache.GetSnapshot();
+ Assert.Equal(0, reset.TotalRequests);
+ Assert.Empty(reset.Endpoints);
+ Assert.Empty(reset.RecentRequests);
+ Assert.All(reset.RecentMinutes, minute => Assert.Equal(0, minute.Requests));
+ Assert.Equal(JsonSerializer.Serialize(reset, CompactJson.RequestStatisticsSnapshot), cache.GetCompactJson());
+ Assert.Equal(4, beforeReset.TotalRequests);
+ collector.RecordMatched(endpointId, 200, 7);
+ var final = cache.GetSnapshot();
+ Assert.Equal(1, final.TotalRequests);
+ Assert.Equal(7, final.ResponseBytes);
+ Assert.Equal(1, Assert.Single(final.Endpoints).TotalRequests);
+ }
+
+ [Fact]
+ public async Task IdleGet_DoesNotAllocateAnotherFullSnapshot()
+ {
+ var cache = new StatisticsSnapshotCache(CreateCollector(RequestStatisticsCollector.MaximumTrackedEndpoints));
+ var context = new DefaultHttpContext();
+ context.Response.Body = Stream.Null;
+ for (var warmup = 0; warmup < 5; warmup++)
+ {
+ await ManagementApiEndpoints.WriteStatisticsAsync(context, cache);
+ }
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var writing = ManagementApiEndpoints.WriteStatisticsAsync(context, cache);
+ Assert.True(writing.IsCompletedSuccessfully);
+ await writing;
+ var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
+ // Indented async serialization still allocates traversal state. The old path
+ // also rebuilt ~1 MiB of minute/endpoint snapshots, exceeding this bound.
+ Assert.InRange(allocated, 0, 1536 * 1024);
+ }
+
+ [Fact]
+ public async Task EventFraming_DoesNotAllocateAnotherPayloadSizedString()
+ {
+ var json = "{\"value\":\"" + new string('x', 256 * 1024) + "\"}";
+ var context = new DefaultHttpContext();
+ context.Response.Body = Stream.Null;
+ for (var warmup = 0; warmup < 5; warmup++)
+ {
+ await ManagementEventWriter.WriteAsync(context, "statistics", json);
+ }
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var writing = ManagementEventWriter.WriteAsync(context, "statistics", json);
+ Assert.True(writing.IsCompletedSuccessfully);
+ await writing;
+ var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
+ Assert.InRange(allocated, 0, 64 * 1024);
+ }
+
+ [Theory]
+ [InlineData(false, 1)]
+ [InlineData(false, 2)]
+ [InlineData(false, 3)]
+ [InlineData(true, 1)]
+ [InlineData(true, 2)]
+ [InlineData(true, 3)]
+ [InlineData(true, 4)]
+ [InlineData(true, 5)]
+ [InlineData(true, 6)]
+ public async Task EventStreams_CancellationDuringAnyFrameWriteEndsNormally(bool dashboard, int cancelOnWrite)
+ {
+ using var cancellation = new CancellationTokenSource();
+ using var body = new CancelDuringWriteStream(cancellation, cancelOnWrite);
+ var context = new DefaultHttpContext { RequestAborted = cancellation.Token };
+ context.Response.Body = body;
+ var cache = new StatisticsSnapshotCache(CreateCollector());
+ await (dashboard
+ ? new DashboardEventStream(new ConfigurationState(), cache).WriteAsync(context)
+ : ManagementApiEndpoints.StreamStatisticsAsync(context, cache));
+ Assert.True(cancellation.IsCancellationRequested);
+ }
+
+ [Fact]
+ public async Task StatisticsGet_CancelledResponsePropagatesCancellation()
+ {
+ using var cancellation = new CancellationTokenSource();
+ cancellation.Cancel();
+ var context = new DefaultHttpContext { RequestAborted = cancellation.Token };
+ context.Response.Body = Stream.Null;
+ await Assert.ThrowsAnyAsync(() =>
+ ManagementApiEndpoints.WriteStatisticsAsync(context, new StatisticsSnapshotCache(CreateCollector())));
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task EventStreams_DoNotSwallowUncancelledTransportFailures(bool dashboard)
+ {
+ var context = new DefaultHttpContext();
+ using var body = new BrokenStream();
+ context.Response.Body = body;
+ var cache = new StatisticsSnapshotCache(CreateCollector());
+ await Assert.ThrowsAsync(() => dashboard
+ ? new DashboardEventStream(new ConfigurationState(), cache).WriteAsync(context)
+ : ManagementApiEndpoints.StreamStatisticsAsync(context, cache));
+ }
+
+ private sealed class BrokenStream : MemoryStream
+ {
+ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) =>
+ ValueTask.FromException(new IOException("Test disconnect"));
+ }
+
+ private sealed class CancelDuringWriteStream(CancellationTokenSource cancellation, int cancelOnWrite) : MemoryStream
+ {
+ private int _writes;
+ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default)
+ {
+ if (++_writes == cancelOnWrite)
+ {
+ cancellation.Cancel();
+ return ValueTask.FromCanceled(cancellation.Token);
+ }
+ return base.WriteAsync(buffer, cancellationToken);
+ }
+ }
+
+ internal static RequestStatisticsCollector CreateCollector(int endpointCount = 1)
+ {
+ var collector = new RequestStatisticsCollector(new Clock());
+ for (var index = 0; index < endpointCount; index++)
+ {
+ // Stable fixture ordering and JSON size across diagnostic runs.
+ var endpointId = new Guid(index + 1, 0, 0, new byte[8]);
+ collector.RecordMatched(endpointId, "GET", "/items/\u00e9\n\"test\"", 201, 12);
+ collector.RecordFailedWrite(endpointId, null);
+ collector.RecordAbortedConnection(endpointId);
+ }
+ collector.RecordUnmatched();
+ return collector;
+ }
+
+ internal sealed class Clock : TimeProvider
+ {
+ public DateTimeOffset Now { get; set; } = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
+ public override DateTimeOffset GetUtcNow() => Now;
+ }
+
+ private sealed class AdvancingClock : TimeProvider
+ {
+ public DateTimeOffset Start { get; } = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
+ public int Reads { get; private set; }
+ public override DateTimeOffset GetUtcNow() => Start.AddMinutes(Reads++);
+ }
+
+ internal sealed class CancelOnFlushStream(CancellationTokenSource cancellation) : MemoryStream
+ {
+ private long _lastFlushedLength;
+
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
+ // Response.WriteAsync flushes its PipeWriter too. Cancel at the explicit
+ // end-of-event body flush, after all framed bytes have reached the sink.
+ if (Length > 0 && Length == _lastFlushedLength)
+ {
+ cancellation.Cancel();
+ }
+ _lastFlushedLength = Length;
+ return Task.CompletedTask;
+ }
+ }
+}
diff --git a/tests/MockAPI.Tests/Management/StatisticsDeltaTests.cs b/tests/MockAPI.Tests/Management/StatisticsDeltaTests.cs
new file mode 100644
index 0000000..2aaa997
--- /dev/null
+++ b/tests/MockAPI.Tests/Management/StatisticsDeltaTests.cs
@@ -0,0 +1,363 @@
+using System.IO.Pipelines;
+using System.Text;
+using System.Text.Json;
+using Microsoft.AspNetCore.Http;
+using MockAPI.Configuration;
+using MockAPI.Management;
+using MockAPI.Runtime;
+using Xunit.Abstractions;
+
+namespace MockAPI.Tests.Management;
+
+public sealed class StatisticsDeltaTests(ITestOutputHelper output)
+{
+ [Fact]
+ public void Frames_CoalesceCapturesAndShareImmutablePayloadsAcrossReaders()
+ {
+ var clock = new StatisticsDeliveryTests.Clock();
+ var collector = new RequestStatisticsCollector(clock);
+ var snapshots = new StatisticsSnapshotCache(collector);
+ var cache = new StatisticsDeltaCache(snapshots, clock);
+ var first = cache.GetFrame();
+ Assert.Equal(1, first.Sequence);
+ Assert.Null(first.Delta);
+ Assert.Throws(() => first.GetDeltaJson());
+ Assert.Same(snapshots.GetCompactJson(), first.GetSnapshotJson());
+ collector.RecordMatched(Guid.NewGuid(), 201, 4);
+ Assert.Same(first, cache.GetFrame());
+ clock.Now += TimeSpan.FromSeconds(2);
+ var frames = new StatisticsDeltaFrame[16];
+ var payloads = new string[16];
+ Parallel.For(0, frames.Length, index =>
+ {
+ frames[index] = cache.GetFrame();
+ payloads[index] = frames[index].GetDeltaJson();
+ });
+ Assert.All(frames, frame => Assert.Same(frames[0], frame));
+ Assert.All(payloads, payload => Assert.Same(payloads[0], payload));
+ Assert.Equal(2, frames[0].Sequence);
+ Assert.Equal(1, frames[0].Delta!.BaseSequence);
+ clock.Now += TimeSpan.FromSeconds(2);
+ Assert.Same(frames[0], cache.GetFrame());
+ Assert.Equal(0, first.Snapshot.TotalRequests);
+
+ // A later GET must not cause an older, still-streaming frame to serialize newer state.
+ collector.RecordUnmatched();
+ var latest = snapshots.GetSnapshot();
+ Assert.NotSame(latest, frames[0].Snapshot);
+ using var captured = JsonDocument.Parse(frames[0].GetSnapshotJson());
+ Assert.Equal(1, captured.RootElement.GetProperty("totalRequests").GetInt64());
+ Assert.Same(latest, snapshots.GetSnapshot());
+ Assert.Same(frames[0].GetSnapshotJson(), frames[0].GetSnapshotJson());
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void SuccessfulResets_RequireBaselinesButMissingEndpointResetsDoNot(bool global)
+ {
+ var clock = new StatisticsDeliveryTests.Clock();
+ var collector = new RequestStatisticsCollector(clock);
+ var id = Guid.NewGuid();
+ collector.RecordMatched(id, 200, 4);
+ var cache = new StatisticsDeltaCache(new StatisticsSnapshotCache(collector), clock);
+ var before = cache.GetFrame();
+ Assert.False(collector.Reset(Guid.NewGuid()));
+ clock.Now += TimeSpan.FromSeconds(2);
+ Assert.Same(before, cache.GetFrame());
+ if (global) collector.Reset();
+ else Assert.True(collector.Reset(id));
+ clock.Now += TimeSpan.FromSeconds(2);
+ var reset = cache.GetFrame();
+ Assert.Equal(before.Sequence + 1, reset.Sequence);
+ Assert.Null(reset.Delta);
+ Assert.Empty(reset.Snapshot.Endpoints);
+ Assert.Empty(reset.Snapshot.RecentRequests);
+ }
+
+ [Fact]
+ public void Deltas_ContainAbsoluteChangedCountersAndReplaceRetrySummaries()
+ {
+ var clock = new StatisticsDeliveryTests.Clock();
+ var collector = new RequestStatisticsCollector(clock);
+ var id = Guid.NewGuid();
+ collector.RecordMatched(id, "GET", "/items", 200, 5, "retry");
+ var first = collector.GetSnapshot();
+ collector.RecordMatched(id, "GET", "/items", 200, 5, "retry");
+ var retried = collector.GetSnapshot();
+ var retry = Assert.IsType(StatisticsDelta.Create(first, retried, 1, 2));
+ Assert.Equal(1, retry.Totals.TotalRequests);
+ Assert.Empty(retry.RecentMinutes);
+ Assert.Empty(retry.Endpoints);
+ Assert.Equal(2, Assert.Single(retry.RecentRequests!.Value).TransportAttempts);
+ collector.RecordMatched(id, 503, 7);
+ var current = collector.GetSnapshot();
+ var changed = Assert.IsType(StatisticsDelta.Create(retried, current, 2, 3));
+ var endpoint = Assert.Single(changed.Endpoints);
+ Assert.Equal(2, endpoint.TotalRequests);
+ Assert.Equal(12, endpoint.ResponseBytes);
+ Assert.Equal(503, endpoint.LastStatusCode);
+ Assert.Equal(2, Assert.Single(endpoint.RecentMinutes).Requests);
+ Assert.Equal(1, Assert.Single(changed.RecentMinutes).ServerErrorResponses);
+ Assert.Equal(1, first.TotalRequests);
+ Assert.Equal(1, Assert.Single(first.RecentRequests).TransportAttempts);
+ var idle = Assert.IsType(StatisticsDelta.Create(current, current, 3, 4));
+ Assert.Null(idle.RecentRequests);
+ Assert.Empty(idle.Endpoints);
+ Assert.Empty(idle.RecentMinutes);
+ var removed = Assert.IsType(StatisticsDelta.Create(current, first with
+ {
+ Endpoints = [],
+ RecentRequests = []
+ }, 3, 4));
+ Assert.Equal(id, Assert.Single(removed.RemovedEndpointIds));
+ Assert.Empty(removed.RecentRequests!.Value);
+ }
+
+ [Fact]
+ public void NewEndpoints_SendOnlyNonzeroMinutesAndRetainAllScalarChanges()
+ {
+ var collector = new RequestStatisticsCollector(new StatisticsDeliveryTests.Clock());
+ var empty = collector.GetSnapshot();
+ var id = Guid.NewGuid();
+ collector.RecordMatched(id, 201, 3);
+ var populated = collector.GetSnapshot();
+ var added = Assert.IsType(StatisticsDelta.Create(empty, populated, 1, 2));
+ Assert.Single(Assert.Single(added.Endpoints).RecentMinutes);
+ var original = Assert.Single(populated.Endpoints);
+ foreach (var endpoint in new[]
+ {
+ original with { TotalRequests = 9 },
+ original with { LastRequestUtc = original.LastRequestUtc!.Value.AddSeconds(1) },
+ original with { LastStatusCode = 404 },
+ original with { ResponseBytes = 9 }
+ })
+ {
+ var delta = Assert.IsType(StatisticsDelta.Create(populated, populated with
+ {
+ Endpoints = [endpoint]
+ }, 2, 3));
+ Assert.Empty(Assert.Single(delta.Endpoints).RecentMinutes);
+ }
+ var zero = original with { RecentMinutes = empty.RecentMinutes };
+ var zeroAdded = Assert.IsType(StatisticsDelta.Create(empty, empty with
+ {
+ Endpoints = [zero]
+ }, 1, 2));
+ Assert.Empty(Assert.Single(zeroAdded.Endpoints).RecentMinutes);
+ }
+
+ [Theory]
+ [InlineData(100)]
+ [InlineData(200)]
+ [InlineData(300)]
+ [InlineData(400)]
+ [InlineData(500)]
+ public void NewEndpointDeltas_PreserveStatusCountsCapturedBeforeRequestCount(int statusCode)
+ {
+ var collector = new RequestStatisticsCollector(new StatisticsDeliveryTests.Clock());
+ var empty = collector.GetSnapshot();
+ collector.RecordMatched(Guid.NewGuid(), statusCode, 0);
+ var populated = collector.GetSnapshot();
+ var endpoint = Assert.Single(populated.Endpoints);
+ // Snapshot counters are non-transactional: the status increment can be visible before the request increment.
+ var partialMinutes = endpoint.RecentMinutes.SetItem(
+ endpoint.RecentMinutes.Length - 1, endpoint.RecentMinutes[^1] with { Requests = 0 });
+ var partial = populated with { Endpoints = [endpoint with { RecentMinutes = partialMinutes }] };
+
+ var delta = Assert.IsType(StatisticsDelta.Create(empty, partial, 1, 2));
+
+ Assert.Equal(partialMinutes[^1], Assert.Single(Assert.Single(delta.Endpoints).RecentMinutes));
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(60)]
+ [InlineData(-1)]
+ public void Windows_CompareByUtcIdentityIncludingRolloverAndBackwardClockChanges(int minutes)
+ {
+ var clock = new StatisticsDeliveryTests.Clock();
+ var collector = new RequestStatisticsCollector(clock);
+ collector.RecordMatched(Guid.NewGuid(), 200, 3);
+ var cache = new StatisticsDeltaCache(new StatisticsSnapshotCache(collector), clock);
+ var first = cache.GetFrame();
+ clock.Now += TimeSpan.FromMinutes(minutes);
+ var current = cache.GetFrame();
+ Assert.NotSame(first, current);
+ var delta = Assert.IsType(current.Delta);
+ Assert.Equal(current.Snapshot.RecentMinutes[0].MinuteUtc, delta.WindowStartUtc);
+ Assert.Equal(Math.Min(Math.Abs(minutes), 60), delta.RecentMinutes.Length);
+ Assert.Equal(1, first.Snapshot.RecentMinutes[^1].Requests);
+ }
+
+ [Fact]
+ public void ClampedDuplicateMinuteIdentities_UseBaselinesInBothDirections()
+ {
+ var clock = new StatisticsDeliveryTests.Clock { Now = DateTimeOffset.MinValue };
+ var collector = new RequestStatisticsCollector(clock);
+ var clamped = collector.GetSnapshot();
+ clock.Now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
+ var normal = collector.GetSnapshot();
+ Assert.Null(StatisticsDelta.Create(clamped, normal, 1, 2));
+ Assert.Null(StatisticsDelta.Create(normal, clamped, 1, 2));
+ }
+
+ [Fact]
+ public void SparseInterval_At256EndpointsUsesLessThanTwoPercentOfTheFullPayload()
+ {
+ var clock = new StatisticsDeliveryTests.Clock();
+ var collector = StatisticsDeliveryTests.CreateCollector(RequestStatisticsCollector.MaximumTrackedEndpoints);
+ var cache = new StatisticsDeltaCache(new StatisticsSnapshotCache(collector), clock);
+ var first = cache.GetFrame();
+ collector.RecordMatched(first.Snapshot.Endpoints[0].EndpointId, 201, 1);
+ clock.Now += TimeSpan.FromSeconds(2);
+ var changed = cache.GetFrame();
+ var fullBytes = Encoding.UTF8.GetByteCount(changed.GetSnapshotJson());
+ var deltaBytes = Encoding.UTF8.GetByteCount(changed.GetDeltaJson());
+ output.WriteLine($"256 endpoints: full={fullBytes:N0} bytes; delta={deltaBytes:N0} bytes; reduction={1d - (double)deltaBytes / fullBytes:P2}");
+ Assert.InRange(deltaBytes, 1, fullBytes / 50);
+ Assert.Single(changed.Delta!.Endpoints);
+ using var json = JsonDocument.Parse(changed.GetDeltaJson());
+ Assert.Equal(JsonValueKind.Array, json.RootElement.GetProperty("recentRequests").ValueKind);
+ Assert.Equal(2, json.RootElement.GetProperty("sequence").GetInt64());
+ Assert.Equal(1, json.RootElement.GetProperty("baseSequence").GetInt64());
+ Assert.Equal("response", json.RootElement.GetProperty("recentRequests")[0].GetProperty("outcome").GetString());
+ }
+
+ [Fact]
+ public async Task SlowStream_MissingAnIntermediateFrameReceivesAFreshBaseline()
+ {
+ var clock = new StatisticsDeliveryTests.Clock();
+ var collector = new RequestStatisticsCollector(clock);
+ var events = new DashboardEventStream(new ConfigurationState(), collector, clock);
+ using var fastCancellation = new CancellationTokenSource(TimeSpan.FromSeconds(15));
+ using var slowCancellation = new CancellationTokenSource(TimeSpan.FromSeconds(15));
+ var pipe = new Pipe();
+ await using var writer = pipe.Writer.AsStream();
+ await using var input = pipe.Reader.AsStream();
+ using var reader = new StreamReader(input);
+ var fastContext = new DefaultHttpContext { RequestAborted = fastCancellation.Token };
+ fastContext.Response.Body = writer;
+ var fast = events.WriteAsync(fastContext, true);
+ using var slowBody = new PausedBaselineStream(slowCancellation);
+ var slowContext = new DefaultHttpContext { RequestAborted = slowCancellation.Token };
+ slowContext.Response.Body = slowBody;
+ Task? slow = null;
+ try
+ {
+ await ReadUntilId(1);
+ slow = events.WriteAsync(slowContext, true);
+ await slowBody.Paused.Task.WaitAsync(slowCancellation.Token);
+ for (var sequence = 2; sequence <= 3; sequence++)
+ {
+ collector.RecordUnmatched();
+ clock.Now += TimeSpan.FromSeconds(2);
+ await ReadUntilId(sequence);
+ }
+ slowBody.Resume.TrySetResult();
+ await slow.WaitAsync(TimeSpan.FromSeconds(5));
+ var received = Encoding.UTF8.GetString(slowBody.ToArray());
+ Assert.Contains("id: 1\nevent: statistics\n", received, StringComparison.Ordinal);
+ Assert.Contains("id: 3\nevent: statistics\n", received, StringComparison.Ordinal);
+ Assert.DoesNotContain("event: statistics-delta", received, StringComparison.Ordinal);
+ }
+ finally
+ {
+ slowBody.Resume.TrySetResult();
+ fastCancellation.Cancel();
+ slowCancellation.Cancel();
+ await fast;
+ if (slow is not null) await slow;
+ }
+
+ async Task ReadUntilId(int sequence)
+ {
+ while (await reader.ReadLineAsync(fastCancellation.Token) is { } line)
+ {
+ if (line == $"id: {sequence}") return;
+ }
+ Assert.Fail("The stream ended before its expected statistics frame.");
+ }
+ }
+
+ private sealed class PausedBaselineStream(CancellationTokenSource cancellation) : MemoryStream
+ {
+ public TaskCompletionSource Paused { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public TaskCompletionSource Resume { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ private long _lastFlushedLength;
+
+ public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default)
+ {
+ if (buffer.Span.SequenceEqual("id: 1\n"u8))
+ {
+ Paused.TrySetResult();
+ await Resume.Task.WaitAsync(cancellationToken);
+ }
+ await base.WriteAsync(buffer, cancellationToken);
+ }
+
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
+ if (Length == _lastFlushedLength &&
+ Encoding.UTF8.GetString(GetBuffer(), 0, (int)Length).Contains("id: 3\n", StringComparison.Ordinal))
+ {
+ cancellation.Cancel();
+ }
+ _lastFlushedLength = Length;
+ return Task.CompletedTask;
+ }
+ }
+
+ [Fact]
+ public async Task OptInStream_SendsASequencedBaselineThenAnAbsoluteDelta()
+ {
+ var clock = new StatisticsDeliveryTests.Clock();
+ var collector = new RequestStatisticsCollector(clock);
+ var pipe = new Pipe();
+ using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(15));
+ await using var writer = pipe.Writer.AsStream();
+ await using var input = pipe.Reader.AsStream();
+ using var reader = new StreamReader(input);
+ var context = new DefaultHttpContext { RequestAborted = cancellation.Token };
+ context.Response.Body = writer;
+ var streaming = new DashboardEventStream(new ConfigurationState(), collector, clock).WriteAsync(context, true);
+ try
+ {
+ Assert.Equal("configuration", (await ReadEvent()).Name);
+ var baseline = await ReadEvent();
+ Assert.Equal("statistics", baseline.Name);
+ Assert.Equal("id: 1", baseline.Id);
+ collector.RecordMatched(Guid.NewGuid(), 200, 5);
+ clock.Now += TimeSpan.FromSeconds(2);
+ var delta = await ReadEvent();
+ Assert.Equal("statistics-delta", delta.Name);
+ Assert.Equal("id: 2", delta.Id);
+ using var json = JsonDocument.Parse(delta.Data);
+ Assert.Equal(1, json.RootElement.GetProperty("totals").GetProperty("totalRequests").GetInt64());
+ collector.Reset();
+ clock.Now += TimeSpan.FromSeconds(2);
+ var reset = await ReadEvent();
+ Assert.Equal("statistics", reset.Name);
+ Assert.Equal("id: 3", reset.Id);
+ }
+ finally
+ {
+ cancellation.Cancel();
+ await streaming;
+ }
+
+ async Task<(string Name, string? Id, string Data)> ReadEvent()
+ {
+ var name = await reader.ReadLineAsync(cancellation.Token);
+ string? id = null;
+ if (name!.StartsWith("id:", StringComparison.Ordinal))
+ {
+ id = name;
+ name = await reader.ReadLineAsync(cancellation.Token);
+ }
+ var data = await reader.ReadLineAsync(cancellation.Token);
+ Assert.Equal("", await reader.ReadLineAsync(cancellation.Token));
+ return (name!["event: ".Length..], id, data!["data: ".Length..]);
+ }
+ }
+}
diff --git a/tests/MockAPI.Tests/Runtime/BackendRefactoringDiagnostics.cs b/tests/MockAPI.Tests/Runtime/BackendRefactoringDiagnostics.cs
new file mode 100644
index 0000000..a8e298b
--- /dev/null
+++ b/tests/MockAPI.Tests/Runtime/BackendRefactoringDiagnostics.cs
@@ -0,0 +1,114 @@
+using System.Diagnostics;
+using System.Globalization;
+using Microsoft.AspNetCore.Http;
+using MockAPI.Configuration;
+using MockAPI.Management;
+using MockAPI.Runtime;
+using Xunit.Abstractions;
+
+namespace MockAPI.Tests.Runtime;
+
+public sealed class BackendRefactoringDiagnostics(ITestOutputHelper output)
+{
+ [Fact]
+ [Trait("Category", "Diagnostic")]
+ public async Task MeasureBackendAllocationBundle()
+ {
+ if (Environment.GetEnvironmentVariable("MOCKAPI_BACKEND_DIAGNOSTICS") != "1")
+ {
+ return;
+ }
+
+ output.WriteLine($"Runtime={Environment.Version}; architecture={System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}");
+ var body = new string('x', 960 * 1024);
+ var document = CompiledResponseReuseTests.CreateDocument(Enumerable.Range(0, 4)
+ .Select(index => new MockEndpointDefinition
+ {
+ Id = Guid.NewGuid(),
+ Name = $"Endpoint {index}",
+ Path = $"/endpoint-{index}",
+ Methods = ["GET"],
+ Enabled = true,
+ Response = new() { StatusCode = 200, Headers = [], ContentType = "text/plain", Body = body }
+ }).ToArray());
+ var registry = new EndpointRegistry();
+ var state = new ConfigurationState();
+ Measure("unchanged near-limit registry replacement", () => Assert.True(registry.TryReplace(document).IsValid));
+ Measure("unchanged near-limit full configuration replacement", () =>
+ Assert.Equal(ConfigurationUpdateStatus.Applied, state.TryReplace(document, state.Current.Revision).Status));
+ var selected = document.Endpoints[0] with
+ {
+ Id = Guid.NewGuid(),
+ Path = "/selected",
+ Response = new() { StatusCode = 200, Headers = [], ContentType = "text/plain", Body = "small" }
+ };
+ var selectionDocument = CompiledResponseReuseTests.CreateDocument([.. document.Endpoints, selected]);
+ Assert.Equal(ConfigurationUpdateStatus.Applied, state.TryReplace(selectionDocument, state.Current.Revision).Status);
+ var snapshot = state.Current;
+ var selectedId = selected.Id;
+ Measure("single endpoint via full document", () =>
+ GC.KeepAlive(snapshot.GetDocument().Endpoints.Single(endpoint => endpoint.Id == selectedId)));
+ Measure("single endpoint via targeted canonical read", () => GC.KeepAlive(snapshot.GetEndpoint(selectedId)));
+
+ var ids = Enumerable.Range(0, RequestStatisticsCollector.MaximumTrackedEndpoints)
+ .Select(_ => Guid.NewGuid()).ToArray();
+ Measure("populate 256 endpoint counters", () =>
+ {
+ var collector = new RequestStatisticsCollector();
+ foreach (var id in ids)
+ {
+ collector.RecordMatched(id, 200, 0);
+ }
+ GC.KeepAlive(collector);
+ });
+
+ var directory = Path.Combine(Path.GetTempPath(), "mockapi-backend-diagnostics", Guid.NewGuid().ToString("N"));
+ try
+ {
+ var key = new string('a', 43);
+ using var security = new ApiKeySecurity(new MockApiOptions
+ {
+ ConfigurationPath = Path.Combine(directory, "mockapi.json"),
+ ApiKey = key
+ });
+ await security.LoadAsync(CancellationToken.None);
+ var context = new DefaultHttpContext();
+ context.Request.Headers[ApiKeySecurity.HeaderName] = key;
+ Measure("valid API-key verification", () => Assert.True(security.Authorizes(context)), iterations: 1_000);
+ context.Request.Headers[ApiKeySecurity.HeaderName] = new string('b', 43);
+ Measure("invalid API-key verification", () => Assert.False(security.Authorizes(context)), iterations: 1_000);
+ }
+ finally
+ {
+ if (Directory.Exists(directory))
+ {
+ Directory.Delete(directory, recursive: true);
+ }
+ }
+ }
+
+ private void Measure(string name, Action operation, int iterations = 10)
+ {
+ for (var index = 0; index < 10; index++)
+ {
+ operation();
+ }
+ var allocations = new long[5];
+ var elapsed = new double[5];
+ for (var sample = 0; sample < allocations.Length; sample++)
+ {
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ GC.Collect();
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var start = Stopwatch.GetTimestamp();
+ for (var iteration = 0; iteration < iterations; iteration++)
+ {
+ operation();
+ }
+ allocations[sample] = (GC.GetAllocatedBytesForCurrentThread() - before) / iterations;
+ elapsed[sample] = Stopwatch.GetElapsedTime(start).TotalMilliseconds / iterations;
+ }
+ output.WriteLine($"{name}: bytes/op=[{string.Join(", ", allocations)}]; ms/op=[{string.Join(", ", elapsed.Select(value => value.ToString("F6", CultureInfo.InvariantCulture)))}]; iterations={iterations}");
+ }
+}
diff --git a/tests/MockAPI.Tests/Runtime/CompiledResponseReuseTests.cs b/tests/MockAPI.Tests/Runtime/CompiledResponseReuseTests.cs
new file mode 100644
index 0000000..8376f77
--- /dev/null
+++ b/tests/MockAPI.Tests/Runtime/CompiledResponseReuseTests.cs
@@ -0,0 +1,248 @@
+using System.Text;
+using MockAPI.Configuration;
+using MockAPI.Runtime;
+
+namespace MockAPI.Tests.Runtime;
+
+public sealed class CompiledResponseReuseTests
+{
+ [Fact]
+ public void Replacement_ReusesResponseStorageByStableIdAcrossRouteAndMetadataChanges()
+ {
+ var definition = CreateEndpoint("original");
+ var registry = new EndpointRegistry();
+ Assert.True(registry.TryReplace(CreateDocument(definition)).IsValid);
+ var originalSnapshot = registry.Current;
+ Assert.True(originalSnapshot.TryGet("GET", "/original", out var original));
+
+ var edited = definition with { Name = "renamed", Path = "/renamed", Methods = ["POST"] };
+ Assert.True(registry.TryReplace(CreateDocument(edited)).IsValid);
+ Assert.True(registry.Current.TryGet("POST", "/renamed", out var replacement));
+
+ Assert.NotSame(original, replacement);
+ Assert.True(original.Body.Equals(replacement.Body));
+ Assert.True(original.Headers.Equals(replacement.Headers));
+ Assert.False(registry.Current.TryGet("GET", "/original", out _));
+ Assert.True(originalSnapshot.TryGet("GET", "/original", out _));
+
+ edited.Response.Headers["X-First"][0] = "mutated";
+ Assert.Equal("first", original.Headers[0].Values[0]);
+ Assert.Equal("first", replacement.Headers[0].Values[0]);
+ }
+
+ [Theory]
+ [MemberData(nameof(BodyCases))]
+ public void Replacement_ReusesOnlyIdenticalEncodedBodyBytes(string originalBody, string replacementBody, bool reuse)
+ {
+ var definition = CreateEndpoint(originalBody);
+ var registry = new EndpointRegistry();
+ Assert.True(registry.TryReplace(CreateDocument(definition)).IsValid);
+ Assert.True(registry.Current.TryGet("GET", "/original", out var original));
+ var edited = definition with { Response = definition.Response with { Body = replacementBody } };
+
+ Assert.True(registry.TryReplace(CreateDocument(edited)).IsValid);
+ Assert.True(registry.Current.TryGet("GET", "/original", out var replacement));
+
+ Assert.Equal(reuse, original.Body.Equals(replacement.Body));
+ Assert.Equal(Encoding.UTF8.GetBytes(originalBody), original.Body.ToArray());
+ Assert.Equal(Encoding.UTF8.GetBytes(replacementBody), replacement.Body.ToArray());
+ }
+
+ public static TheoryData BodyCases => new()
+ {
+ { "", "", true },
+ { "same", "same", true },
+ { "before", "after", false },
+ { "longer", "long", false },
+ { "short", "shorter", false },
+ { "nonempty", "", false },
+ { "", "nonempty", false },
+ { new string('x', 511) + "\uD83D\uDE03", new string('x', 511) + "\uD83D\uDE03", true },
+ { new string('x', 1023) + "\u00E9\u6C34", new string('x', 1023) + "\u00E9\u6C34", true },
+ { new string('x', 1024) + "end", new string('x', 1024) + "edited", false }
+ };
+
+ [Fact]
+ public void BodyComparison_PreservesEncodingReplacementFallbackForLoneSurrogates()
+ {
+ foreach (var surrogate in new[] { "\uD800", "\uDC00" })
+ {
+ var definition = CreateEndpoint(new string('x', 511) + surrogate);
+ var original = RuntimeEndpoint.Create(definition);
+ var edited = definition with { Response = definition.Response with { Body = new string('x', 511) + "\uFFFD" } };
+
+ var replacement = RuntimeEndpoint.Create(edited, original);
+
+ Assert.True(original.Body.Equals(replacement.Body));
+ Assert.Equal(Encoding.UTF8.GetBytes(edited.Response.Body), replacement.Body.ToArray());
+ }
+ }
+
+ [Fact]
+ public void ReusedWireData_DoesNotRetainPreviousStatusContentTypeReasonOrDelay()
+ {
+ var definition = CreateEndpoint("body");
+ var original = RuntimeEndpoint.Create(definition);
+ var edited = definition with
+ {
+ Response = definition.Response with
+ {
+ StatusCode = 202,
+ ReasonPhrase = "Accepted",
+ ContentType = "application/custom",
+ DelaySeconds = 1
+ }
+ };
+
+ var replacement = RuntimeEndpoint.Create(edited, original);
+
+ Assert.True(original.Body.Equals(replacement.Body));
+ Assert.True(original.Headers.Equals(replacement.Headers));
+ Assert.Equal(202, replacement.StatusCode);
+ Assert.Equal("Accepted", replacement.ReasonPhrase);
+ Assert.Equal("application/custom", replacement.ContentType);
+ Assert.Equal(TimeSpan.FromSeconds(1), replacement.Delay);
+ Assert.Equal(200, original.StatusCode);
+ Assert.Null(original.ReasonPhrase);
+ Assert.Equal(TimeSpan.Zero, original.Delay);
+ }
+
+ [Theory]
+ [InlineData(0, true)]
+ [InlineData(1, false)]
+ [InlineData(2, false)]
+ [InlineData(3, false)]
+ [InlineData(4, false)]
+ [InlineData(5, false)]
+ [InlineData(6, false)]
+ public void Replacement_PreservesExactHeaderNamesOrderingAndValues(int change, bool reuse)
+ {
+ var definition = CreateEndpoint("body");
+ var registry = new EndpointRegistry();
+ Assert.True(registry.TryReplace(CreateDocument(definition)).IsValid);
+ Assert.True(registry.Current.TryGet("GET", "/original", out var original));
+ Dictionary headers = change switch
+ {
+ 0 => new() { ["X-First"] = ["first", "second"], ["X-Last"] = ["last"] },
+ 1 => new() { ["x-first"] = ["first", "second"], ["X-Last"] = ["last"] },
+ 2 => new() { ["X-Last"] = ["last"], ["X-First"] = ["first", "second"] },
+ 3 => new() { ["X-First"] = ["second", "first"], ["X-Last"] = ["last"] },
+ 4 => new() { ["X-First"] = ["first", "second"] },
+ 5 => new() { ["X-First"] = ["first", "second"], ["X-Last"] = ["last"], ["X-New"] = ["new"] },
+ _ => new() { ["X-First"] = ["first"], ["X-Last"] = ["last"] }
+ };
+ var edited = definition with { Response = definition.Response with { Headers = headers } };
+
+ Assert.True(registry.TryReplace(CreateDocument(edited)).IsValid);
+ Assert.True(registry.Current.TryGet("GET", "/original", out var replacement));
+
+ Assert.Equal(reuse, original.Headers.Equals(replacement.Headers));
+ Assert.True(original.Body.Equals(replacement.Body));
+ Assert.Equal(headers.Keys, replacement.Headers.Select(header => header.Name));
+ Assert.Equal(headers.Values, replacement.Headers.Select(header => header.Values.ToArray()));
+ }
+
+ [Fact]
+ public void ConfigurationReplacement_ReusesBothResponsesButResetsRateLimitPermits()
+ {
+ var definition = CreateEndpoint("limited") with
+ {
+ Response = new MockResponseDefinition
+ {
+ StatusCode = 429,
+ Headers = new() { ["Retry-After"] = ["3600"] },
+ ContentType = "text/plain",
+ Body = "limited",
+ RateLimit = new MockRateLimitDefinition
+ {
+ RequestLimit = 1,
+ WindowSeconds = 3600,
+ SuccessResponse = new MockSuccessResponseDefinition
+ {
+ StatusCode = 201,
+ Headers = new() { ["X-Success"] = ["first", "second"] },
+ ContentType = "text/plain",
+ Body = "success"
+ }
+ }
+ }
+ };
+ var state = new ConfigurationState();
+ Assert.Equal(ConfigurationUpdateStatus.Applied, state.TryReplace(CreateDocument(definition), 0).Status);
+ var oldSnapshot = state.Current;
+ Assert.True(oldSnapshot.Endpoints.TryGet("GET", "/original", out var original));
+ var oldSuccess = original.SelectResponse();
+ Assert.Equal(201, oldSuccess.StatusCode);
+ Assert.Equal(429, original.SelectResponse().StatusCode);
+
+ Assert.Equal(ConfigurationUpdateStatus.Applied, state.TryReplace(CreateDocument(definition), 1).Status);
+ Assert.True(state.Current.Endpoints.TryGet("GET", "/original", out var replacement));
+ var newSuccess = replacement.SelectResponse();
+
+ Assert.NotSame(original, replacement);
+ Assert.True(original.Body.Equals(replacement.Body));
+ Assert.True(original.Headers.Equals(replacement.Headers));
+ Assert.True(oldSuccess.Body.Equals(newSuccess.Body));
+ Assert.True(oldSuccess.Headers.Equals(newSuccess.Headers));
+ Assert.Equal(201, newSuccess.StatusCode);
+ Assert.Equal(429, replacement.SelectResponse().StatusCode);
+ Assert.Equal(429, original.SelectResponse().StatusCode);
+ Assert.Equal(1, oldSnapshot.Revision);
+ }
+
+ [Fact]
+ public void Replacement_DoesNotReuseStorageForAnUnrelatedEndpointId()
+ {
+ var definition = CreateEndpoint("body");
+ var registry = new EndpointRegistry();
+ Assert.True(registry.TryReplace(CreateDocument(definition)).IsValid);
+ Assert.True(registry.Current.TryGet("GET", "/original", out var original));
+
+ Assert.True(registry.TryReplace(CreateDocument(definition with { Id = Guid.NewGuid() })).IsValid);
+ Assert.True(registry.Current.TryGet("GET", "/original", out var replacement));
+
+ Assert.False(original.Body.Equals(replacement.Body));
+ Assert.False(original.Headers.Equals(replacement.Headers));
+ }
+
+ [Fact]
+ public void WarmResponseCompilation_DoesNotAllocateAnotherLargeBodyArray()
+ {
+ var definition = CreateEndpoint(new string('x', 512 * 1024));
+ var previous = RuntimeEndpoint.Create(definition);
+ for (var index = 0; index < 5; index++)
+ {
+ RuntimeEndpoint.Create(definition, previous);
+ }
+
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var replacement = RuntimeEndpoint.Create(definition, previous);
+ var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
+
+ Assert.True(previous.Body.Equals(replacement.Body));
+ // Isolate compilation: full validation still serializes the document and may refill serializer pools.
+ Assert.InRange(allocated, 0, 1_024);
+ }
+
+ internal static MockApiConfigurationDocument CreateDocument(params MockEndpointDefinition[] endpoints) => new()
+ {
+ SchemaVersion = "1.0",
+ Endpoints = endpoints
+ };
+
+ private static MockEndpointDefinition CreateEndpoint(string body) => new()
+ {
+ Id = Guid.NewGuid(),
+ Name = "original",
+ Enabled = true,
+ Methods = ["GET"],
+ Path = "/original",
+ Response = new MockResponseDefinition
+ {
+ StatusCode = 200,
+ Headers = new() { ["X-First"] = ["first", "second"], ["X-Last"] = ["last"] },
+ ContentType = "text/plain",
+ Body = body
+ }
+ };
+}
diff --git a/tests/MockAPI.Tests/Runtime/MockRequestBodyValidationDiagnostics.cs b/tests/MockAPI.Tests/Runtime/MockRequestBodyValidationDiagnostics.cs
new file mode 100644
index 0000000..6486afb
--- /dev/null
+++ b/tests/MockAPI.Tests/Runtime/MockRequestBodyValidationDiagnostics.cs
@@ -0,0 +1,69 @@
+using System.Diagnostics;
+using MockAPI.Runtime;
+using Xunit.Abstractions;
+
+namespace MockAPI.Tests.Runtime;
+
+public sealed class MockRequestBodyValidationDiagnostics(ITestOutputHelper output)
+{
+ // Opt in with MOCKAPI_BODY_VALIDATION_DIAGNOSTICS=1 in Release with DOTNET_TieredCompilation=0.
+ [Fact]
+ [Trait("Category", "Diagnostic")]
+ public void MeasureValidationAllocationsAndElapsedTime()
+ {
+ if (Environment.GetEnvironmentVariable("MOCKAPI_BODY_VALIDATION_DIAGNOSTICS") != "1")
+ {
+ return;
+ }
+
+ output.WriteLine($"Runtime={Environment.Version}; architecture={System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}; synchronous memory streams, no network");
+ foreach (var scenario in new[] { "empty", "text", "json", "large-text", "large-json" })
+ {
+ foreach (var knownLength in new[] { true, false })
+ {
+ using var body = new MemoryStream(MockRequestBodyValidatorTests.CreateBody(scenario));
+ var request = MockRequestBodyValidatorTests.CreateRequest(body,
+ scenario.Contains("json", StringComparison.Ordinal) ? "application/json" : "text/plain",
+ knownLength ? body.Length : null);
+ Measure($"{scenario}; knownLength={knownLength}", () =>
+ {
+ body.Position = 0;
+ var validation = MockRequestBodyValidator.ValidateAsync(request);
+ Assert.True(validation.IsCompleted, "Thread-local allocation measurements require synchronous completion.");
+ Assert.Null(validation.GetAwaiter().GetResult());
+ });
+ }
+ }
+ }
+
+ private void Measure(string name, Action operation)
+ {
+ const int iterations = 30;
+ const int samples = 3;
+ for (var iteration = 0; iteration < 10; iteration++)
+ {
+ operation();
+ }
+
+ var allocations = new long[samples];
+ var elapsed = new double[samples];
+ for (var sample = 0; sample < samples; sample++)
+ {
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ GC.Collect();
+ // Collections can trim ArrayPool caches; measure steady-state reuse, not pool refill.
+ operation();
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var start = Stopwatch.GetTimestamp();
+ for (var iteration = 0; iteration < iterations; iteration++)
+ {
+ operation();
+ }
+ elapsed[sample] = Stopwatch.GetElapsedTime(start).TotalMilliseconds / iterations;
+ allocations[sample] = (GC.GetAllocatedBytesForCurrentThread() - before) / iterations;
+ }
+
+ output.WriteLine($"{name}: bytes/op=[{string.Join(", ", allocations)}]; ms/op=[{string.Join(", ", elapsed.Select(value => value.ToString("F6", System.Globalization.CultureInfo.InvariantCulture)))}]; iterations={iterations}; samples={samples}");
+ }
+}
diff --git a/tests/MockAPI.Tests/Runtime/MockRequestBodyValidatorTests.cs b/tests/MockAPI.Tests/Runtime/MockRequestBodyValidatorTests.cs
new file mode 100644
index 0000000..f2cbd01
--- /dev/null
+++ b/tests/MockAPI.Tests/Runtime/MockRequestBodyValidatorTests.cs
@@ -0,0 +1,304 @@
+using System.Buffers;
+using System.Text;
+using Microsoft.AspNetCore.Http;
+using MockAPI.Runtime;
+
+namespace MockAPI.Tests.Runtime;
+
+public sealed class MockRequestBodyValidatorTests
+{
+ [Theory]
+ [InlineData("empty", true)]
+ [InlineData("text", true)]
+ [InlineData("json", true)]
+ [InlineData("large-text", false)]
+ [InlineData("large-json", true)]
+ [InlineData("large-json", false)]
+ public async Task RepeatedValidation_DoesNotAllocateRequestSizedBuffers(string scenario, bool knownLength)
+ {
+ using var body = new MemoryStream(CreateBody(scenario));
+ var request = CreateRequest(body, scenario.Contains("json", StringComparison.Ordinal) ? "application/json" : "text/plain",
+ knownLength ? body.Length : null);
+ for (var iteration = 0; iteration < 3; iteration++)
+ {
+ body.Position = 0;
+ Assert.Null(await MockRequestBodyValidator.ValidateAsync(request));
+ }
+
+ body.Position = 0;
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var validation = MockRequestBodyValidator.ValidateAsync(request);
+ Assert.True(validation.IsCompletedSuccessfully);
+ var problem = await validation;
+ var allocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before;
+
+ Assert.Null(problem);
+ Assert.InRange(allocatedBytes, 0, 4096);
+ }
+
+ [Theory]
+ [InlineData("{}", true)]
+ [InlineData("[]", true)]
+ [InlineData(" null\r\n", true)]
+ [InlineData("true", true)]
+ [InlineData("false", true)]
+ [InlineData("-1.25e+2", true)]
+ [InlineData("\"\"", true)]
+ [InlineData("\"\\uD800\"", true)]
+ [InlineData("{\"field\":1,\"field\":2}", true)]
+ [InlineData(" ", false)]
+ [InlineData("{} {}", false)]
+ [InlineData("{} garbage", false)]
+ [InlineData("[1,]", false)]
+ [InlineData("{\"x\":}", false)]
+ [InlineData("/*comment*/{}", false)]
+ [InlineData("NaN", false)]
+ [InlineData("01", false)]
+ [InlineData("\"\\uXXXX\"", false)]
+ public async Task JsonSyntaxValidation_PreservesAcceptedValuesAndRejectedSyntax(string json, bool valid)
+ {
+ using var body = new MemoryStream(Encoding.UTF8.GetBytes(json));
+ var request = CreateRequest(body, "application/json", body.Length);
+
+ var problem = await MockRequestBodyValidator.ValidateAsync(request);
+
+ if (valid)
+ {
+ Assert.Null(problem);
+ }
+ else
+ {
+ Assert.Equal(400, problem?.Status);
+ Assert.EndsWith("/invalid-json", problem?.Type, StringComparison.Ordinal);
+ }
+ }
+
+ [Theory]
+ [InlineData(64, true)]
+ [InlineData(65, false)]
+ public async Task JsonNestingLimit_RemainsInclusive(int depth, bool valid)
+ {
+ var json = new string('[', depth) + "0" + new string(']', depth);
+ using var body = new MemoryStream(Encoding.UTF8.GetBytes(json));
+
+ var problem = await MockRequestBodyValidator.ValidateAsync(CreateRequest(body, "application/json", null));
+
+ Assert.Equal(valid ? null : 400, problem?.Status);
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(7)]
+ [InlineData(65535)]
+ public async Task FragmentedJson_PreservesUtf8TokensAndBufferGrowth(int chunkSize)
+ {
+ var json = "[\"" + new string('x', 65535) + "\u00e9\U0001f600\",true,null,-1.25e+2]";
+ using var body = new FragmentedReadStream(Encoding.UTF8.GetBytes(json), chunkSize);
+ var pool = new TrackingArrayPool();
+
+ var problem = await MockRequestBodyValidator.ValidateAsync(
+ CreateRequest(body, "application/problem+json", null), pool);
+
+ Assert.Null(problem);
+ AssertBuffersReturnedAndCleared(pool);
+ }
+
+ [Theory]
+ [InlineData("valid")]
+ [InlineData("invalid-json")]
+ [InlineData("unsupported-charset")]
+ [InlineData("oversized")]
+ [InlineData("protocol-error")]
+ [InlineData("protocol-too-large")]
+ [InlineData("io-error")]
+ [InlineData("cancelled")]
+ public async Task EveryExit_ReturnsAndClearsAllRentedBuffers(string outcome)
+ {
+ var payload = outcome == "oversized"
+ ? new byte[MockRequestBodyValidator.MaximumBodyBytes + 1]
+ : Encoding.UTF8.GetBytes("\"" + new string('s', 70000) + (outcome == "invalid-json" ? "" : "\""));
+ Exception? failure = outcome switch
+ {
+ "protocol-error" => new BadHttpRequestException("Private protocol details"),
+ "protocol-too-large" => new BadHttpRequestException("Private protocol details", 413),
+ "io-error" => new IOException("Read failed"),
+ "cancelled" => new OperationCanceledException(),
+ _ => null
+ };
+ using var body = new FragmentedReadStream(payload, 8192, failure, asynchronous: true);
+ var contentType = outcome == "unsupported-charset" ? "application/json; charset=utf-16" : "application/json";
+ var request = CreateRequest(body, contentType, null);
+ var pool = new TrackingArrayPool();
+
+ if (outcome is "io-error" or "cancelled" or "protocol-too-large")
+ {
+ var thrown = await Assert.ThrowsAnyAsync(() => MockRequestBodyValidator.ValidateAsync(request, pool));
+ Assert.Same(failure, thrown);
+ }
+ else
+ {
+ var problem = await MockRequestBodyValidator.ValidateAsync(request, pool);
+ int? expectedStatus = outcome switch
+ {
+ "valid" => null,
+ "unsupported-charset" => 415,
+ "oversized" => 413,
+ _ => 400
+ };
+ Assert.Equal(expectedStatus, problem?.Status);
+ Assert.DoesNotContain("Private protocol details", problem?.Detail ?? "");
+ }
+
+ AssertBuffersReturnedAndCleared(pool);
+ }
+
+ [Theory]
+ [InlineData("invalid media type", 0, 400)]
+ [InlineData("invalid media type", 1048577, 413)]
+ [InlineData("application/json; charset=utf-16", 0, null)]
+ [InlineData("application/json; charset=utf-16", 1, 415)]
+ [InlineData("application/json; charset=utf-16", 1048577, 413)]
+ public async Task ErrorPrecedence_PreservesSizeMediaTypeAndEmptyBodyRules(
+ string contentType, int length, int? expectedStatus)
+ {
+ using var body = new MemoryStream(new byte[length]);
+
+ var problem = await MockRequestBodyValidator.ValidateAsync(CreateRequest(body, contentType, length));
+
+ Assert.Equal(expectedStatus, problem?.Status);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData(0L)]
+ [InlineData(1L)]
+ public async Task DeclaredLength_DoesNotReplaceReadingOrActualSizeEnforcement(long? declaredLength)
+ {
+ using var body = new MemoryStream(new byte[MockRequestBodyValidator.MaximumBodyBytes + 1]);
+
+ var problem = await MockRequestBodyValidator.ValidateAsync(
+ CreateRequest(body, "application/json; charset=utf-16", declaredLength));
+
+ Assert.Equal(413, problem?.Status);
+ }
+
+ [Theory]
+ [InlineData("POST", null)]
+ [InlineData("PUT", "text/plain")]
+ [InlineData("PATCH", "application/octet-stream")]
+ public async Task NonJsonBodies_OnlyRentOneScratchBuffer(string method, string? contentType)
+ {
+ using var body = new MemoryStream("not valid JSON"u8.ToArray());
+ var request = CreateRequest(body, contentType, body.Length);
+ request.Method = method;
+ var pool = new TrackingArrayPool();
+
+ Assert.Null(await MockRequestBodyValidator.ValidateAsync(request, pool));
+
+ Assert.Single(pool.Rented);
+ AssertBuffersReturnedAndCleared(pool);
+ }
+
+ [Theory]
+ [InlineData("GET", "application/json", 0, null)]
+ [InlineData("POST", "invalid media type", 0, 400)]
+ [InlineData("POST", "application/json", 1048577, 413)]
+ public async Task RequestsRejectedOrSkippedBeforeReading_DoNotRentBuffers(
+ string method, string contentType, long declaredLength, int? expectedStatus)
+ {
+ using var body = new MemoryStream();
+ var request = CreateRequest(body, contentType, declaredLength);
+ request.Method = method;
+ var pool = new TrackingArrayPool();
+
+ var problem = await MockRequestBodyValidator.ValidateAsync(request, pool);
+
+ Assert.Equal(expectedStatus, problem?.Status);
+ Assert.Empty(pool.Rented);
+ }
+
+ [Fact]
+ public async Task FragmentedInvalidUtf8_RemainsAnInvalidJsonProblem()
+ {
+ using var body = new FragmentedReadStream([0x22, 0xc3, 0x28, 0x22], 1);
+
+ var problem = await MockRequestBodyValidator.ValidateAsync(CreateRequest(body, "application/json", null));
+
+ Assert.Equal(400, problem?.Status);
+ Assert.EndsWith("/invalid-json", problem?.Type, StringComparison.Ordinal);
+ }
+
+ internal static HttpRequest CreateRequest(Stream body, string? contentType, long? contentLength)
+ {
+ var context = new DefaultHttpContext();
+ context.Request.Method = "POST";
+ context.Request.Body = body;
+ context.Request.ContentType = contentType;
+ context.Request.ContentLength = contentLength;
+ return context.Request;
+ }
+
+ internal static byte[] CreateBody(string scenario) => scenario switch
+ {
+ "empty" => [],
+ "text" => "example"u8.ToArray(),
+ "json" => "{\"ok\":true}"u8.ToArray(),
+ "large-text" => new byte[MockRequestBodyValidator.MaximumBodyBytes],
+ "large-json" => Encoding.UTF8.GetBytes("\"" + new string('x', MockRequestBodyValidator.MaximumBodyBytes - 2) + "\""),
+ _ => throw new ArgumentOutOfRangeException(nameof(scenario), scenario, "Unknown request-body fixture.")
+ };
+
+ private static void AssertBuffersReturnedAndCleared(TrackingArrayPool pool)
+ {
+ Assert.NotEmpty(pool.Rented);
+ Assert.Equal(pool.Rented.Count, pool.Returned.Count);
+ Assert.All(pool.Rented, buffer =>
+ {
+ Assert.Contains(pool.Returned, returned => ReferenceEquals(buffer, returned));
+ Assert.InRange(buffer.Length, 1, MockRequestBodyValidator.MaximumBodyBytes);
+ Assert.True(buffer.AsSpan().IndexOfAnyExcept((byte)0) < 0);
+ });
+ }
+
+ private sealed class TrackingArrayPool : ArrayPool
+ {
+ internal List Rented { get; } = [];
+ internal List Returned { get; } = [];
+
+ public override byte[] Rent(int minimumLength)
+ {
+ var buffer = new byte[minimumLength];
+ Array.Fill(buffer, (byte)0xa5);
+ Rented.Add(buffer);
+ return buffer;
+ }
+
+ public override void Return(byte[] array, bool clearArray = false)
+ {
+ Assert.True(clearArray);
+ Assert.DoesNotContain(Returned, returned => ReferenceEquals(array, returned));
+ Array.Clear(array);
+ Returned.Add(array);
+ }
+ }
+
+ private sealed class FragmentedReadStream(
+ byte[] payload, int chunkSize, Exception? failure = null, bool asynchronous = false) : MemoryStream(payload)
+ {
+ public override bool CanSeek => false;
+
+ public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
+ {
+ if (asynchronous)
+ {
+ await Task.Yield();
+ }
+ if (Position == Length && failure is not null)
+ {
+ throw failure;
+ }
+
+ return await base.ReadAsync(buffer[..Math.Min(buffer.Length, chunkSize)], cancellationToken);
+ }
+ }
+}
diff --git a/tests/MockAPI.Tests/Runtime/RequestStatisticsCollectorTests.cs b/tests/MockAPI.Tests/Runtime/RequestStatisticsCollectorTests.cs
index 140e5ce..df6c109 100644
--- a/tests/MockAPI.Tests/Runtime/RequestStatisticsCollectorTests.cs
+++ b/tests/MockAPI.Tests/Runtime/RequestStatisticsCollectorTests.cs
@@ -4,6 +4,69 @@ namespace MockAPI.Tests.Runtime;
public sealed class RequestStatisticsCollectorTests
{
+ [Fact]
+ public void EndpointCounterPopulation_HasBoundedAllocationWithoutObjectPerMinuteCounter()
+ {
+ var ids = Enumerable.Range(0, RequestStatisticsCollector.MaximumTrackedEndpoints)
+ .Select(_ => Guid.NewGuid()).ToArray();
+ var warmup = new RequestStatisticsCollector();
+ warmup.RecordMatched(ids[0], 200, 0);
+
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ var collector = new RequestStatisticsCollector();
+ foreach (var id in ids)
+ {
+ collector.RecordMatched(id, 200, 0);
+ }
+ var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
+
+ Assert.InRange(allocated, 0, 1_500_000);
+ Assert.Equal(ids.Length, collector.GetSnapshot().Endpoints.Length);
+ }
+
+ [Fact]
+ public void EveryStatusCounter_SurvivesConcurrentRecordingRolloverAndReset()
+ {
+ var clock = new ManualTimeProvider(DateTimeOffset.Parse("2026-01-01T00:00:00Z"));
+ var collector = new RequestStatisticsCollector(clock);
+ var endpointId = Guid.NewGuid();
+ RecordAllClasses();
+ var original = collector.GetSnapshot();
+ AssertBuckets(original, expected: 1_000);
+
+ clock.Advance(TimeSpan.FromMinutes(60));
+ AssertBuckets(collector.GetSnapshot(), expected: 0);
+ RecordAllClasses();
+ AssertBuckets(collector.GetSnapshot(), expected: 1_000);
+ AssertBuckets(original, expected: 1_000);
+
+ collector.Reset();
+ var reset = collector.GetSnapshot();
+ Assert.Empty(reset.Endpoints);
+ Assert.All(reset.RecentMinutes, bucket => Assert.Equal(default, bucket with { MinuteUtc = default }));
+ RecordAllClasses();
+ AssertBuckets(collector.GetSnapshot(), expected: 1_000);
+
+ void RecordAllClasses() => Parallel.For(0, 5_000,
+ index => collector.RecordMatched(endpointId, ((index % 5) + 1) * 100, 0));
+
+ static void AssertBuckets(RequestStatisticsSnapshot snapshot, long expected)
+ {
+ AssertSeries(snapshot.RecentMinutes);
+ AssertSeries(Assert.Single(snapshot.Endpoints).RecentMinutes);
+
+ void AssertSeries(IEnumerable buckets)
+ {
+ Assert.Equal(expected * 5, buckets.Sum(bucket => bucket.Requests));
+ Assert.Equal(expected, buckets.Sum(bucket => bucket.InformationalResponses));
+ Assert.Equal(expected, buckets.Sum(bucket => bucket.SuccessResponses));
+ Assert.Equal(expected, buckets.Sum(bucket => bucket.RedirectionResponses));
+ Assert.Equal(expected, buckets.Sum(bucket => bucket.ClientErrorResponses));
+ Assert.Equal(expected, buckets.Sum(bucket => bucket.ServerErrorResponses));
+ }
+ }
+ }
+
[Fact]
public void Snapshot_DistinguishesOutcomesAndTracksEndpointByStableId()
{
diff --git a/tests/MockAPI.Tests/Runtime/StatisticsRecordingDiagnostics.cs b/tests/MockAPI.Tests/Runtime/StatisticsRecordingDiagnostics.cs
new file mode 100644
index 0000000..ec8c5c8
--- /dev/null
+++ b/tests/MockAPI.Tests/Runtime/StatisticsRecordingDiagnostics.cs
@@ -0,0 +1,61 @@
+using System.Diagnostics;
+using MockAPI.Runtime;
+using Xunit.Abstractions;
+
+namespace MockAPI.Tests.Runtime;
+
+public sealed class StatisticsRecordingDiagnostics(ITestOutputHelper output)
+{
+ [Fact]
+ [Trait("Category", "Diagnostic")]
+ public void MeasureConcurrentRecording()
+ {
+ if (Environment.GetEnvironmentVariable("MOCKAPI_RECORDING_DIAGNOSTICS") != "1")
+ {
+ return;
+ }
+
+ output.WriteLine($"Runtime={Environment.Version}; processors={Environment.ProcessorCount}; architecture={System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}");
+ foreach (var matched in new[] { false, true })
+ {
+ foreach (var workers in new[] { 1, 2, 4, 8 })
+ {
+ var samples = Enumerable.Range(0, 5).Select(_ => Measure(matched, workers)).ToArray();
+ output.WriteLine($"{(matched ? "matched with bounded request log" : "unmatched without request ID")}; workers={workers}; requests/s=[{string.Join(", ", samples.Select(sample => sample.Rate))}]; monitorContentions=[{string.Join(", ", samples.Select(sample => sample.Contentions))}]");
+ }
+ }
+ }
+
+ private static (long Rate, long Contentions) Measure(bool matched, int workers)
+ {
+ const int totalRequests = 120_000;
+ var collector = new RequestStatisticsCollector();
+ var ids = Enumerable.Range(0, workers).Select(_ => Guid.NewGuid()).ToArray();
+ foreach (var id in ids)
+ {
+ collector.RecordMatched(id, "GET", "/diagnostic", 200, 0);
+ }
+ using var ready = new CountdownEvent(workers);
+ using var start = new ManualResetEventSlim();
+ var threads = Enumerable.Range(0, workers).Select(worker => new Thread(() =>
+ {
+ ready.Signal();
+ start.Wait();
+ for (var request = 0; request < totalRequests / workers; request++)
+ {
+ if (matched) collector.RecordMatched(ids[worker], "GET", "/diagnostic", 200, 0);
+ else collector.RecordUnmatched();
+ }
+ })).ToArray();
+ foreach (var thread in threads) thread.Start();
+ ready.Wait();
+ var contentions = Monitor.LockContentionCount;
+ var timestamp = Stopwatch.GetTimestamp();
+ start.Set();
+ foreach (var thread in threads) thread.Join();
+ var elapsed = Stopwatch.GetElapsedTime(timestamp);
+ contentions = Monitor.LockContentionCount - contentions;
+ Assert.Equal(totalRequests + workers, collector.GetSnapshot().TotalRequests);
+ return ((long)(totalRequests / elapsed.TotalSeconds), contentions);
+ }
+}
diff --git a/tests/browser/dashboard-controllers.spec.js b/tests/browser/dashboard-controllers.spec.js
index 80d359b..ec1f033 100644
--- a/tests/browser/dashboard-controllers.spec.js
+++ b/tests/browser/dashboard-controllers.spec.js
@@ -662,7 +662,7 @@ test("endpoint table owns selection snapshots and releases controls and obsolete
await expect(frame.locator(".endpoint-row")).toHaveCount(1);
});
-test("statistics controller owns scope and bucket navigation and releases replaced chart listeners", async ({
+test("statistics controller retains current chart listeners and releases replaced chart listeners", async ({
page,
request,
}) => {
@@ -716,12 +716,21 @@ test("statistics controller owns scope and bucket navigation and releases replac
window.oldColumn = document.querySelector(".chart-column.interactive");
window.originalBucket = document.querySelector(".request-log-bucket-toggle");
window.panel.updateStatistics(window.statistics);
+ window.retainedBucket = document.querySelector(".request-log-bucket-toggle") === window.originalBucket;
+ window.oldColumn.click();
+ });
+ expect(await frame.evaluate(() => window.retainedBucket)).toBe(true);
+ await expect(frame.locator(".request-log-bucket-toggle")).toHaveAttribute("aria-expanded", "true");
+ await frame.locator(".request-log-bucket-toggle").click();
+ await frame.evaluate(() => {
+ window.panel.updateStatistics({
+ ...window.statistics,
+ recentMinutes: [{ ...window.statistics.recentMinutes[0], requests: 0, successResponses: 0 }],
+ });
window.oldColumn.click();
});
- expect(
- await frame.evaluate(() => document.querySelector(".request-log-bucket-toggle") === window.originalBucket)
- ).toBe(true);
await expect(frame.locator(".request-log-bucket-toggle")).toHaveAttribute("aria-expanded", "false");
+ await frame.evaluate(() => window.panel.updateStatistics(window.statistics));
await frame.locator(".chart-column.interactive").click();
await expect(frame.locator(".request-log-bucket-toggle")).toHaveAttribute("aria-expanded", "true");
await expect(frame.locator(".request-log-bucket-toggle")).toBeFocused();
@@ -732,3 +741,120 @@ test("statistics controller owns scope and bucket navigation and releases replac
await frame.locator("#reset-statistics-scope").click();
expect(await frame.evaluate(() => window.resets)).toEqual([endpoint.id, null]);
});
+
+test("statistics updates retain keyed rows and sixty minute columns, focus, tooltip, and scroll", async ({
+ page,
+ request,
+}) => {
+ const frame = await createFixture(page, request);
+ const statistics = await (await request.get("/__mockapi/api/statistics")).json();
+ await frame.evaluate(
+ async ({ definition, statistics }) => {
+ const { createDashboardStatistics } = await import("/dashboard-statistics.js");
+ const { createDashboardPreferencesStore } = await import("/dashboard-preferences.js");
+ const start = Date.UTC(2026, 0, 1);
+ window.buckets = Array.from({ length: 60 }, (_, index) => ({
+ minuteUtc: new Date(start + index * 60000).toISOString(),
+ requests: index === 0 || index >= 58 ? 1 : 0,
+ successResponses: index === 0 || index >= 58 ? 1 : 0,
+ }));
+ window.statistics = {
+ ...statistics,
+ totalRequests: 3,
+ recentMinutes: window.buckets,
+ endpoints: [{ endpointId: definition.id, totalRequests: 3, recentMinutes: window.buckets }],
+ recentRequests: window.buckets.slice(58).map((bucket) => ({
+ timestampUtc: bucket.minuteUtc,
+ endpointId: definition.id,
+ method: "GET",
+ path: definition.path,
+ outcome: "response",
+ statusCode: 200,
+ responseBytes: 1,
+ })),
+ };
+ window.definition = definition;
+ window.panel = createDashboardStatistics({
+ documentRoot: document,
+ preferencesStore: createDashboardPreferencesStore({ getItem: () => null, setItem() {} }),
+ onReset() {},
+ });
+ window.panel.updateEndpoints([definition, { ...definition, id: "second", name: "Second" }]);
+ window.panel.updateStatistics(window.statistics);
+ },
+ { definition: endpoint, statistics }
+ );
+ await frame.locator("#statistics-endpoint").click();
+ await frame.locator("#statistics-table").click();
+ expect(
+ await frame.evaluate(() => {
+ const table = document.querySelector("#statistics-table-view table");
+ const row = table.tBodies[0].rows[0];
+ const name = row.querySelector("strong");
+ window.panel.updateStatistics({
+ ...window.statistics,
+ endpoints: [{ ...window.statistics.endpoints[0], totalRequests: 7 }],
+ });
+ const kept = table === document.querySelector("#statistics-table-view table") && row === table.tBodies[0].rows[0];
+ window.panel.updateEndpoints([{ ...window.definition, name: "Renamed" }]);
+ return (
+ kept &&
+ name === row.querySelector("strong") &&
+ name.textContent === "Renamed" &&
+ row.cells[1].textContent === "7" &&
+ table.tBodies[0].rows.length === 1
+ );
+ })
+ ).toBe(true);
+ await frame.locator("#statistics-overall").click();
+ expect(
+ await frame.evaluate(() => {
+ const row = document.querySelector("#statistics-table-view tbody tr");
+ window.panel.updateStatistics(window.statistics);
+ return row === document.querySelector("#statistics-table-view tbody tr");
+ })
+ ).toBe(true);
+ await frame.locator("#statistics-graph").click();
+ await frame.locator(".chart-column.interactive").first().hover();
+ expect(
+ await frame.evaluate(() => {
+ const chart = document.querySelector("#statistics-chart");
+ const columns = [...chart.querySelectorAll(".chart-column")];
+ const focus = columns[58];
+ const segment = focus.querySelector(".status-2xx");
+ const tooltip = chart.querySelector(".chart-tooltip");
+ const scroll = document.querySelector("#statistics-chart-scroll");
+ focus.focus({ preventScroll: true });
+ scroll.scrollLeft = 10;
+ const left = scroll.scrollLeft;
+ const changed = window.buckets.map((bucket, index) =>
+ index === 58 ? { ...bucket, requests: 2, successResponses: 2 } : bucket
+ );
+ window.panel.updateStatistics({ ...window.statistics, totalRequests: 4, recentMinutes: changed });
+ return (
+ [...chart.querySelectorAll(".chart-column")].every((column, index) => column === columns[index]) &&
+ segment === focus.querySelector(".status-2xx") &&
+ segment.style.flexGrow === "2" &&
+ document.activeElement === focus &&
+ scroll.scrollLeft === left &&
+ chart.querySelector(".chart-tooltip") === tooltip &&
+ tooltip.textContent.includes("2 attempts")
+ );
+ })
+ ).toBe(true);
+ expect(
+ await frame.evaluate(() => {
+ const chart = document.querySelector("#statistics-chart");
+ const kept = chart.querySelectorAll(".chart-column")[58];
+ const rolled = [
+ ...window.buckets.slice(1),
+ { ...window.buckets[59], minuteUtc: "2026-01-01T01:00:00Z", requests: 0, successResponses: 0 },
+ ];
+ window.panel.updateStatistics({ ...window.statistics, recentMinutes: rolled });
+ return (
+ chart.querySelectorAll(".chart-column").length === 60 && chart.querySelectorAll(".chart-column")[57] === kept
+ );
+ })
+ ).toBe(true);
+ await frame.evaluate(() => window.panel.dispose());
+});
diff --git a/tests/browser/dashboard-statistics.spec.js b/tests/browser/dashboard-statistics.spec.js
index 6ce2ef6..69c476b 100644
--- a/tests/browser/dashboard-statistics.spec.js
+++ b/tests/browser/dashboard-statistics.spec.js
@@ -263,12 +263,15 @@ test("bulk bucket controls preserve column widths through collapse, expansion, a
window.requestLogEvents.dispatchEvent(new MessageEvent("configuration", { data: JSON.stringify(configuration) }));
}, configuration);
+ let statisticsSequence = 0;
async function publishRequests(recentRequests) {
await page.evaluate(
- (statistics) => {
- window.requestLogEvents.dispatchEvent(new MessageEvent("statistics", { data: JSON.stringify(statistics) }));
+ ({ statistics, sequence }) => {
+ window.requestLogEvents.dispatchEvent(
+ new MessageEvent("statistics", { data: JSON.stringify(statistics), lastEventId: String(sequence) })
+ );
},
- { ...statistics, recentRequests }
+ { statistics: { ...statistics, recentRequests }, sequence: ++statisticsSequence }
);
await expect(page.locator("#request-log-count")).toHaveText(String(recentRequests.length));
}
diff --git a/tests/frontend/dashboard-statistics-delta.test.js b/tests/frontend/dashboard-statistics-delta.test.js
new file mode 100644
index 0000000..19134bd
--- /dev/null
+++ b/tests/frontend/dashboard-statistics-delta.test.js
@@ -0,0 +1,123 @@
+import { describe, expect, it } from "vitest";
+import { applyStatisticsDelta } from "../../src/MockAPI/wwwroot/dashboard-core.js";
+
+const start = Date.parse("2026-01-01T00:00:00Z");
+const bucket = (index, requests = 0) => ({
+ minuteUtc: new Date(start + index * 60_000).toISOString(),
+ requests,
+ informationalResponses: 0,
+ successResponses: requests,
+ redirectionResponses: 0,
+ clientErrorResponses: 0,
+ serverErrorResponses: 0,
+});
+const history = () => Array.from({ length: 60 }, (_, index) => bucket(index));
+const endpoint = (id) => ({
+ endpointId: id,
+ totalRequests: 0,
+ lastStatusCode: null,
+ lastRequestUtc: null,
+ responseBytes: 0,
+ recentMinutes: history(),
+});
+const baseline = () => ({
+ totalRequests: 0,
+ matchedRequests: 0,
+ unmatchedRequests: 0,
+ failedWrites: 0,
+ abortedConnections: 0,
+ informationalResponses: 0,
+ successResponses: 0,
+ redirectionResponses: 0,
+ clientErrorResponses: 0,
+ serverErrorResponses: 0,
+ responseBytes: 0,
+ recentMinutes: history(),
+ endpoints: [endpoint("a"), endpoint("b")],
+ recentRequests: [],
+});
+const delta = (changes = {}) => ({
+ baseSequence: 1,
+ sequence: 2,
+ windowStartUtc: new Date(start).toISOString(),
+ totals: { totalRequests: 1 },
+ recentMinutes: [],
+ endpoints: [],
+ removedEndpointIds: [],
+ recentRequests: null,
+ ...changes,
+});
+
+describe("statistics interval state deltas", () => {
+ it("applies absolute values once and preserves untouched records without mutating the baseline", () => {
+ const previous = baseline();
+ const patch = delta({
+ recentMinutes: [bucket(59, 1)],
+ endpoints: [{ ...endpoint("b"), totalRequests: 1, recentMinutes: [bucket(59, 1)] }],
+ recentRequests: [{ outcome: "response", transportAttempts: 1 }],
+ });
+ const result = applyStatisticsDelta(previous, patch);
+ expect(result.totalRequests).toBe(1);
+ expect(result.recentMinutes[59].requests).toBe(1);
+ expect(result.recentMinutes[0]).toBe(previous.recentMinutes[0]);
+ expect(result.endpoints[0]).toBe(previous.endpoints[0]);
+ expect(result.endpoints[1].recentMinutes[0]).toBe(previous.endpoints[1].recentMinutes[0]);
+ expect(result.endpoints[1].recentMinutes[59].requests).toBe(1);
+ expect(applyStatisticsDelta(result, patch)).toEqual(result);
+ expect(previous.totalRequests).toBe(0);
+ expect(previous.endpoints[1].recentMinutes[59].requests).toBe(0);
+ expect(result.recentRequests).toBe(patch.recentRequests);
+ });
+
+ it("keeps all history and endpoint identities when only aggregate counters change", () => {
+ const previous = baseline();
+ const result = applyStatisticsDelta(previous, delta());
+ expect(result.endpoints).toBe(previous.endpoints);
+ expect(result.recentMinutes).toBe(previous.recentMinutes);
+ expect(result.recentRequests).toBe(previous.recentRequests);
+ });
+
+ it("adds and removes endpoints, fills zero buckets, orders IDs, and replaces a cleared log", () => {
+ const previous = baseline();
+ previous.recentRequests = [{ transportAttempts: 1 }];
+ const result = applyStatisticsDelta(
+ previous,
+ delta({
+ endpoints: [{ ...endpoint("0"), totalRequests: 4, recentMinutes: [bucket(59, 4)] }],
+ removedEndpointIds: ["a"],
+ recentRequests: [],
+ })
+ );
+ expect(result.endpoints.map((entry) => entry.endpointId)).toEqual(["0", "b"]);
+ expect(result.endpoints[0].recentMinutes).toHaveLength(60);
+ expect(result.endpoints[0].recentMinutes[0]).toEqual(bucket(0));
+ expect(result.endpoints[0].recentMinutes[59]).toEqual(bucket(59, 4));
+ expect(result.recentRequests).toEqual([]);
+ });
+
+ it("advances all histories, expires old minutes, and accepts equivalent UTC spellings", () => {
+ const previous = baseline();
+ previous.endpoints[0].recentMinutes[0] = bucket(0, 9);
+ const result = applyStatisticsDelta(
+ previous,
+ delta({
+ windowStartUtc: "2026-01-01T00:01:00+00:00",
+ recentMinutes: [bucket(60, 2)],
+ endpoints: [{ ...endpoint("b"), recentMinutes: [bucket(60, 2)] }],
+ })
+ );
+ expect(result.recentMinutes[0]).toBe(previous.recentMinutes[1]);
+ expect(result.recentMinutes[59]).toEqual(bucket(60, 2));
+ expect(result.endpoints[0].recentMinutes.reduce((sum, entry) => sum + entry.requests, 0)).toBe(0);
+ expect(result.endpoints[1].recentMinutes[59].requests).toBe(2);
+ expect(previous.endpoints[0].recentMinutes[0].requests).toBe(9);
+ });
+
+ it("builds an initial window from an empty history and rejects invalid timestamps", () => {
+ const previous = { ...baseline(), recentMinutes: [] };
+ expect(applyStatisticsDelta(previous, delta()).recentMinutes).toHaveLength(60);
+ expect(() => applyStatisticsDelta(baseline(), delta({ windowStartUtc: "invalid" }))).toThrow(
+ "Invalid statistics retention window"
+ );
+ });
+});
diff --git a/tests/frontend/dashboard-sync.test.js b/tests/frontend/dashboard-sync.test.js
index c0c44ef..14cb0df 100644
--- a/tests/frontend/dashboard-sync.test.js
+++ b/tests/frontend/dashboard-sync.test.js
@@ -40,8 +40,8 @@ function harness({ eventSource = true, ...options } = {}) {
path,
close: vi.fn(),
addEventListener: (name, listener) => listeners.set(name, listener),
- emit: (name, data) => listeners.get(name)({ data: JSON.stringify(data) }),
- raw: (name, data) => listeners.get(name)({ data }),
+ emit: (name, data, lastEventId = "") => listeners.get(name)({ data: JSON.stringify(data), lastEventId }),
+ raw: (name, data, lastEventId = "") => listeners.get(name)({ data, lastEventId }),
};
streams.push(stream);
return stream;
@@ -77,6 +77,123 @@ describe("event-driven dashboard synchronization", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
+ const statisticsBaseline = () => ({
+ totalRequests: 0,
+ recentMinutes: Array.from({ length: 60 }, (_, index) => ({
+ minuteUtc: new Date(Date.UTC(2026, 0, 1, 0, index)).toISOString(),
+ requests: 0,
+ })),
+ endpoints: [],
+ recentRequests: [],
+ });
+ const statisticsDelta = (changes = {}) => ({
+ baseSequence: 1,
+ sequence: 2,
+ windowStartUtc: "2026-01-01T00:00:00Z",
+ totals: { totalRequests: 3 },
+ recentMinutes: [],
+ endpoints: [],
+ removedEndpointIds: [],
+ recentRequests: null,
+ ...changes,
+ });
+ async function connectDeltas() {
+ const h = harness({ useStatisticsDeltas: true });
+ await h.synchronizer.start();
+ const stream = h.streams[0];
+ stream.onopen();
+ stream.emit("configuration", status());
+ stream.emit("statistics", statisticsBaseline(), "1");
+ await flush();
+ return h;
+ }
+
+ it("opts into deltas, ignores duplicates, and retains a stream baseline independent from GET refreshes", async () => {
+ const h = await connectDeltas();
+ const stream = h.streams[0];
+ expect(stream.path).toBe("/dashboard/events?deltas=true");
+ await h.synchronizer.synchronize();
+ stream.emit("statistics-delta", statisticsDelta(), "2");
+ expect(h.callbacks.statistics).toHaveBeenLastCalledWith(
+ expect.objectContaining({ totalRequests: 3, recentMinutes: expect.any(Array) })
+ );
+ const calls = h.callbacks.statistics.mock.calls.length;
+ stream.emit("statistics-delta", statisticsDelta(), "2");
+ stream.emit("statistics-delta", statisticsDelta({ sequence: 1 }), "1");
+ expect(h.callbacks.statistics).toHaveBeenCalledTimes(calls);
+ stream.onopen();
+ stream.emit("statistics", statisticsBaseline(), "1");
+ stream.emit("statistics-delta", statisticsDelta(), "2");
+ expect(h.callbacks.statistics).toHaveBeenCalledTimes(calls + 2);
+ h.synchronizer.dispose();
+ stream.emit("statistics-delta", statisticsDelta({ baseSequence: 2, sequence: 3 }), "3");
+ expect(h.callbacks.statistics).toHaveBeenCalledTimes(calls + 2);
+ });
+
+ it("recovers sequence gaps without aborting a command refresh or accepting retired-stream events", async () => {
+ const h = await connectDeltas();
+ const old = h.streams[0];
+ const pending = deferred();
+ h.request.mockReturnValueOnce(pending.promise);
+ const refreshing = h.synchronizer.synchronize();
+ old.emit("statistics-delta", statisticsDelta({ baseSequence: 2, sequence: 3 }), "3");
+ expect(old.close).toHaveBeenCalledOnce();
+ expect(h.callbacks.error).toHaveBeenCalledWith(
+ expect.objectContaining({ message: expect.stringContaining("missed") })
+ );
+ expect(h.streams).toHaveLength(1);
+ old.onopen();
+ old.emit("configuration", status(99));
+ old.emit("statistics", statisticsBaseline(), "99");
+ old.onerror();
+ pending.resolve(status());
+ expect(await refreshing).toEqual({ kind: "completed" });
+ await vi.advanceTimersByTimeAsync(15000);
+ expect(h.streams).toHaveLength(2);
+ h.streams[1].onopen();
+ h.streams[1].emit("configuration", status());
+ h.streams[1].emit("statistics", statisticsBaseline(), "1");
+ await flush();
+ expect(vi.getTimerCount()).toBe(0);
+ h.synchronizer.dispose();
+ });
+
+ it.each(["", "0", "1.5", "9007199254740992"])("rejects invalid baseline sequence %s", async (id) => {
+ const h = harness({ useStatisticsDeltas: true });
+ await h.synchronizer.start();
+ h.streams[0].emit("statistics", statisticsBaseline(), id);
+ expect(h.callbacks.error).toHaveBeenCalledOnce();
+ expect(h.streams[0].close).toHaveBeenCalledOnce();
+ expect(h.callbacks.statistics).not.toHaveBeenCalled();
+ h.synchronizer.dispose();
+ });
+
+ it.each([
+ [statisticsDelta({ sequence: 2.5 }), "2.5"],
+ [statisticsDelta(), "9"],
+ [statisticsDelta({ baseSequence: 0 }), "2"],
+ [statisticsDelta({ windowStartUtc: "invalid" }), "2"],
+ ])("reports malformed or discontinuous delta frames", async (delta, id) => {
+ const h = await connectDeltas();
+ h.streams[0].emit("statistics-delta", delta, id);
+ expect(h.callbacks.error).toHaveBeenCalledOnce();
+ expect(h.streams[0].close).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(1);
+ h.synchronizer.dispose();
+ });
+
+ it("rejects deltas before a baseline and malformed JSON after a baseline", async () => {
+ const h = harness({ useStatisticsDeltas: true });
+ await h.synchronizer.start();
+ h.streams[0].emit("statistics-delta", statisticsDelta(), "2");
+ expect(h.callbacks.error).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(15000);
+ h.streams[1].emit("statistics", statisticsBaseline(), "1");
+ h.streams[1].raw("statistics-delta", "{", "2");
+ expect(h.callbacks.error).toHaveBeenCalledTimes(2);
+ h.synchronizer.dispose();
+ });
+
it("returns explicit success and failure outcomes while retaining background recovery", async () => {
const h = harness();
await h.connect();
diff --git a/tests/site/accessibility.spec.js b/tests/site/accessibility.spec.js
index 9bb5c92..0932ee9 100644
--- a/tests/site/accessibility.spec.js
+++ b/tests/site/accessibility.spec.js
@@ -5,6 +5,12 @@ test.beforeEach(async ({ page }) => {
await page.route("https://www.googletagmanager.com/**", (route) =>
route.fulfill({ contentType: "application/javascript", body: "" })
);
+ await page.route("https://img.shields.io/**", (route) =>
+ route.fulfill({
+ contentType: "image/svg+xml",
+ body: 'Docker Hub ',
+ })
+ );
});
test("uniform header, styled links and arrow controls meet contrast and keyboard requirements in both themes", async ({
diff --git a/tests/site/landing.spec.js b/tests/site/landing.spec.js
index 7244d60..3f20c94 100644
--- a/tests/site/landing.spec.js
+++ b/tests/site/landing.spec.js
@@ -13,6 +13,12 @@ test.beforeEach(async ({ page }) => {
route.fulfill({ contentType: "application/javascript", body: "" })
);
await page.route(/https:\/\/(?:[^/]+\.)?(?:google-analytics|analytics\.google)\.com\//, (route) => route.abort());
+ await page.route("https://img.shields.io/**", (route) =>
+ route.fulfill({
+ contentType: "image/svg+xml",
+ body: 'Docker Hub ',
+ })
+ );
});
async function serveProductionSite(page, baseURL) {
@@ -155,6 +161,101 @@ test("quick starts, assets and accessibility work under the Pages repository pre
expect(failures).toEqual([]);
});
+test("Docker Hub badge links to the published image and is keyboard accessible", async ({ page }) => {
+ await page.goto("./");
+ const badge = page.getByRole("link", { name: "MockAPI on Docker Hub", exact: true });
+ await expect(badge).toHaveAttribute("href", "https://hub.docker.com/r/simonkurtzmsft/mockapi");
+ const image = badge.getByRole("img", { name: "MockAPI on Docker Hub", exact: true });
+ await expect(image).toHaveAttribute(
+ "src",
+ "https://img.shields.io/docker/v/simonkurtzmsft/mockapi?label=Docker%20Hub&logo=docker&sort=semver"
+ );
+ await expect(image).toHaveAttribute("referrerpolicy", "no-referrer");
+ expect(await image.evaluate((element) => element.complete && element.naturalWidth > 0)).toBe(true);
+ const size = await badge.boundingBox();
+ expect(size.width).toBeGreaterThanOrEqual(24);
+ expect(size.height).toBeGreaterThanOrEqual(24);
+ await page.getByRole("link", { name: "Read the documentation", exact: true }).focus();
+ await page.keyboard.press("Tab");
+ await expect(badge).toBeFocused();
+ await expect(badge).toHaveCSS("outline-style", "solid");
+});
+
+test("Docker Hub link retains an accessible name if the badge service is unavailable", async ({ page }) => {
+ await page.route("https://img.shields.io/**", (route) => route.abort());
+ await page.goto("./");
+ const badge = page.getByRole("link", { name: "MockAPI on Docker Hub", exact: true });
+ await expect(badge).toBeVisible();
+ await expect(badge).toHaveAttribute("href", "https://hub.docker.com/r/simonkurtzmsft/mockapi");
+ expect(await badge.locator("img").evaluate((image) => image.complete && image.naturalWidth === 0)).toBe(true);
+});
+
+test("example cards align headings, descriptions, and links across desktop widths and enlarged text", async ({
+ page,
+}) => {
+ await page.goto("./");
+ const cards = page.locator("#examples .card");
+ await expect(cards).toHaveCount(3);
+ for (const [width, fontSize] of [
+ [1280, "100%"],
+ [1024, "100%"],
+ [951, "100%"],
+ [1280, "200%"],
+ ]) {
+ await page.setViewportSize({ width, height: 900 });
+ await page.evaluate((size) => {
+ document.documentElement.style.fontSize = size;
+ }, fontSize);
+ const positions = await cards.evaluateAll((elements) =>
+ elements.map((card) => ({
+ top: card.getBoundingClientRect().top,
+ bottom: card.getBoundingClientRect().bottom,
+ width: card.getBoundingClientRect().width,
+ heading: card.querySelector("h3").getBoundingClientRect().top,
+ description: card.querySelector("p").getBoundingClientRect().top,
+ links: card.querySelector("a").getBoundingClientRect().top,
+ }))
+ );
+ for (const position of positions.slice(1)) {
+ for (const key of ["top", "bottom", "width", "heading", "description", "links"]) {
+ expect(Math.abs(position[key] - positions[0][key]), `${key} at ${width}px with ${fontSize} text`).toBeLessThan(
+ 1
+ );
+ }
+ }
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
+ }
+});
+
+test("example cards stack at natural heights on narrow viewports", async ({ page }) => {
+ await page.goto("./");
+ const cards = page.locator("#examples .card");
+ await expect(cards).toHaveCount(3);
+ for (const width of [950, 390, 320]) {
+ await page.setViewportSize({ width, height: 900 });
+ const positions = await cards.evaluateAll((elements) =>
+ elements.map((card) => ({
+ top: card.getBoundingClientRect().top,
+ bottom: card.getBoundingClientRect().bottom,
+ height: card.getBoundingClientRect().height,
+ left: card.getBoundingClientRect().left,
+ right: card.getBoundingClientRect().right,
+ linksBottom: card.querySelector("a:last-child").getBoundingClientRect().bottom,
+ }))
+ );
+ for (let index = 1; index < positions.length; index += 1) {
+ expect(positions[index].top).toBeGreaterThan(positions[index - 1].bottom);
+ expect(positions[index].left).toBe(positions[0].left);
+ expect(positions[index].right).toBe(positions[0].right);
+ expect(positions[index].height).toBeLessThan(positions[0].height);
+ }
+ for (const position of positions) {
+ expect(position.linksBottom).toBeLessThan(position.bottom);
+ }
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
+ }
+});
+
test("navigation buttons share the call-to-action hover effect without underlines", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "no-preference" });
await page.goto("./");
@@ -208,18 +309,29 @@ test("getting-started content stays usable on desktop and narrow screens", async
test("features describe the small, hardened container and supported capabilities", async ({ page }) => {
await page.goto("./");
const features = page.getByRole("region", { name: "A small, hardened container for your mock APIs" });
- await expect(features.locator(".card")).toHaveCount(4);
+ await expect(features.locator(".card")).toHaveCount(5);
await expect(features.getByRole("heading", { level: 3 })).toHaveText([
"Minimal Native AOT image",
"Hardened by default",
"Import, save, and export",
"Live request view",
+ "APIM Samples integration",
]);
await expect(features).toContainText("no .NET SDK, managed runtime, JIT, compiler, or debug symbols");
await expect(features).toContainText("non-root user");
await expect(features).toContainText("read-only root filesystem");
await expect(features).toContainText("API key by default");
await expect(features).toContainText("Postman, Insomnia, cURL, JMeter, OpenAPI, k6, or HTTP files");
+ const apimCard = features.getByRole("article").last();
+ await expect(apimCard).toContainText("Easily connect APIM Samples to your custom mock APIs.");
+ await expect(apimCard).toContainText("use MockAPI as the backend");
+ const apimGuide = apimCard.getByRole("link", { name: "Connect custom APIs to APIM" });
+ await expect(apimGuide).toBeVisible();
+ await expect(apimGuide).toHaveAttribute(
+ "href",
+ "https://github.com/simonkurtz-MSFT/MockAPI/blob/main/docs/MANAGEMENT_API.md#live-mock-openapi-and-apim-import"
+ );
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
});
test("footer links to Simon Kurtz's website in a protected new tab", async ({ page }) => {