@tearleads/client-sdk 0.1.258 → 0.1.259
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/internal/api-client/apiRequestMetrics.d.ts +3 -0
- package/internal/api-client/apiRequestMetrics.js +24 -0
- package/internal/api-client/apiRequestMetrics.js.map +1 -1
- package/internal/api-client/apiRequestRuntime.js +4 -3
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/client/documents.js +4 -4
- package/internal/api-client/client/documents.js.map +1 -1
- package/internal/api-client/client/organizations.js +2 -1
- package/internal/api-client/client/organizations.js.map +1 -1
- package/internal/api-client/measureApiRequest.js +9 -4
- package/internal/api-client/measureApiRequest.js.map +1 -1
- package/internal/api-client/principalHistoryRequest.js +2 -0
- package/internal/api-client/principalHistoryRequest.js.map +1 -1
- package/internal/api-client/resourceRequestActivity.d.ts +12 -0
- package/internal/api-client/resourceRequestActivity.js +28 -0
- package/internal/api-client/resourceRequestActivity.js.map +1 -0
- package/internal/api-client/types.d.ts +2 -0
- package/internal/api-client/types.js.map +1 -1
- package/internal/api-client/writerProjectionRequests.js +8 -2
- package/internal/api-client/writerProjectionRequests.js.map +1 -1
- package/package.json +1 -1
|
@@ -45,6 +45,7 @@ export declare class ApiRequestMetrics {
|
|
|
45
45
|
private readonly now;
|
|
46
46
|
private readonly scopes;
|
|
47
47
|
private readonly durations;
|
|
48
|
+
private readonly activeResources;
|
|
48
49
|
private readonly listeners;
|
|
49
50
|
private readonly generations;
|
|
50
51
|
/** `now` must be monotonic; tests inject a fake clock. */
|
|
@@ -52,6 +53,8 @@ export declare class ApiRequestMetrics {
|
|
|
52
53
|
getSnapshot: (identity: string | null) => ApiRequestMetricsSnapshot;
|
|
53
54
|
subscribe: (listener: () => void) => (() => void);
|
|
54
55
|
reset(identity: string | null): void;
|
|
56
|
+
isResourceInFlight(identity: string | null, operation: Pick<HttpOperation, "id">, resourceId: string | null): boolean;
|
|
57
|
+
beginResource(identity: string | null, operation: Pick<HttpOperation, "id">, resourceId: string): () => void;
|
|
55
58
|
begin(identity: string | null, operation: HttpOperation): (outcome: Outcome, serverTiming?: ApiServerTiming | null) => void;
|
|
56
59
|
private recordDurations;
|
|
57
60
|
private update;
|
|
@@ -27,6 +27,9 @@ export class ApiRequestMetrics {
|
|
|
27
27
|
now;
|
|
28
28
|
scopes = new Map();
|
|
29
29
|
durations = new Map();
|
|
30
|
+
// Resource IDs live only for the duration of an HTTP attempt and never
|
|
31
|
+
// enter the endpoint snapshots used by System Monitor and support reports.
|
|
32
|
+
activeResources = new Map();
|
|
30
33
|
listeners = new Set();
|
|
31
34
|
generations = new Map();
|
|
32
35
|
/** `now` must be monotonic; tests inject a fake clock. */
|
|
@@ -51,6 +54,27 @@ export class ApiRequestMetrics {
|
|
|
51
54
|
this.durations.delete(identity);
|
|
52
55
|
this.notify();
|
|
53
56
|
}
|
|
57
|
+
isResourceInFlight(identity, operation, resourceId) {
|
|
58
|
+
return (resourceId !== null &&
|
|
59
|
+
this.activeResources.has(JSON.stringify([identity, operation.id, resourceId])));
|
|
60
|
+
}
|
|
61
|
+
beginResource(identity, operation, resourceId) {
|
|
62
|
+
const key = JSON.stringify([identity, operation.id, resourceId]);
|
|
63
|
+
this.activeResources.set(key, (this.activeResources.get(key) ?? 0) + 1);
|
|
64
|
+
this.notify();
|
|
65
|
+
let finished = false;
|
|
66
|
+
return () => {
|
|
67
|
+
if (finished)
|
|
68
|
+
return;
|
|
69
|
+
finished = true;
|
|
70
|
+
const remaining = (this.activeResources.get(key) ?? 1) - 1;
|
|
71
|
+
if (remaining === 0)
|
|
72
|
+
this.activeResources.delete(key);
|
|
73
|
+
else
|
|
74
|
+
this.activeResources.set(key, remaining);
|
|
75
|
+
this.notify();
|
|
76
|
+
};
|
|
77
|
+
}
|
|
54
78
|
begin(identity, operation) {
|
|
55
79
|
const generation = this.generations.get(identity) ?? 0;
|
|
56
80
|
const startedAt = this.now();
|
|
@@ -1 +1 @@
|
|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CAAC;YAAC,MAAM,CAAC;gBACP,0CAA0C;YAC5C,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport type { ApiReachabilityProbe } from \"./apiReachabilityProbe\";\nimport {\n type ApiRequestDurationSummary,\n DurationSampleWindow,\n} from \"./durationSampleWindow\";\nimport type { ApiServerTiming } from \"./serverTiming\";\n\nexport interface ApiRequestCounts {\n readonly total: number;\n readonly inFlight: number;\n readonly succeeded: number;\n readonly failed: number;\n readonly cancelled: number;\n}\n\nexport interface ApiRequestEndpointCounts extends ApiRequestCounts {\n readonly method: string;\n readonly path: string;\n /** Dispatch until response headers, a connection failure, or cancellation. */\n readonly duration: ApiRequestDurationSummary | null;\n /** The API's Server-Timing `total`; null until a response reports it. */\n readonly serverDuration: ApiRequestDurationSummary | null;\n /** The API's Server-Timing `db`; null until a response reports it. */\n readonly databaseDuration: ApiRequestDurationSummary | null;\n}\n\nexport interface ApiRequestMetricsSnapshot extends ApiRequestCounts {\n readonly startedAt: string;\n readonly endpoints: readonly ApiRequestEndpointCounts[];\n}\n\nexport interface ApiRequestInstrumentation {\n readonly metrics: ApiRequestMetrics;\n readonly getIdentity: () => string | null;\n /** Host-enabled follow-up probe that classifies failed fetches. */\n readonly networkFailureProbe?: ApiReachabilityProbe | null | undefined;\n /**\n * The host's authoritative connectivity reading (a native source where the\n * WebView's `navigator.onLine` is wrong); null defers to `navigator.onLine`.\n */\n readonly isOnline?: (() => boolean | null) | undefined;\n}\n\ntype Outcome = \"succeeded\" | \"failed\" | \"cancelled\";\n\ninterface EndpointDurations {\n readonly duration: DurationSampleWindow;\n readonly serverDuration: DurationSampleWindow;\n readonly databaseDuration: DurationSampleWindow;\n}\n\nconst emptyCounts: ApiRequestCounts = {\n total: 0,\n inFlight: 0,\n succeeded: 0,\n failed: 0,\n cancelled: 0,\n};\n\ntype EndpointDurationSummaries = Pick<\n ApiRequestEndpointCounts,\n \"duration\" | \"serverDuration\" | \"databaseDuration\"\n>;\n\nconst emptyDurations: EndpointDurationSummaries = {\n duration: null,\n serverDuration: null,\n databaseDuration: null,\n};\n\nfunction emptySnapshot(): ApiRequestMetricsSnapshot {\n return { ...emptyCounts, startedAt: new Date().toISOString(), endpoints: [] };\n}\n\nfunction endpointKey(row: { readonly method: string; readonly path: string }) {\n return `${row.method} ${row.path}`;\n}\n\n/**\n * In-memory HTTP attempt counts and durations, partitioned by identity at\n * dispatch time. Only operation templates are retained: no URLs, queries,\n * bodies or tokens. Hosts may reuse this store across client lifetimes until a\n * page reload.\n */\nexport class ApiRequestMetrics {\n private readonly scopes = new Map<string | null, ApiRequestMetricsSnapshot>();\n private readonly durations = new Map<\n string | null,\n Map<string, EndpointDurations>\n >();\n private readonly listeners = new Set<() => void>();\n private readonly generations = new Map<string | null, number>();\n\n /** `now` must be monotonic; tests inject a fake clock. */\n constructor(private readonly now: () => number = () => performance.now()) {}\n\n getSnapshot = (identity: string | null): ApiRequestMetricsSnapshot => {\n let snapshot = this.scopes.get(identity);\n if (!snapshot) {\n snapshot = emptySnapshot();\n this.scopes.set(identity, snapshot);\n }\n return snapshot;\n };\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n reset(identity: string | null): void {\n this.generations.set(identity, (this.generations.get(identity) ?? 0) + 1);\n this.scopes.set(identity, emptySnapshot());\n this.durations.delete(identity);\n this.notify();\n }\n\n begin(\n identity: string | null,\n operation: HttpOperation,\n ): (outcome: Outcome, serverTiming?: ApiServerTiming | null) => void {\n const generation = this.generations.get(identity) ?? 0;\n const startedAt = this.now();\n const previous = this.getSnapshot(identity);\n const existing = previous.endpoints.find(\n (row) => row.method === operation.method && row.path === operation.path,\n );\n let row: ApiRequestEndpointCounts = {\n ...emptyDurations,\n ...(existing ?? emptyCounts),\n method: operation.method,\n path: operation.path,\n total: (existing?.total ?? 0) + 1,\n inFlight: (existing?.inFlight ?? 0) + 1,\n };\n this.update(identity, previous, existing, row, {\n total: previous.total + 1,\n inFlight: previous.inFlight + 1,\n });\n // Reset replaces the scope's endpoints. Capture a generation independently\n // of snapshots, which are replaced for every concurrent request update.\n let completed = false;\n return (outcome, serverTiming) => {\n if (completed) return;\n completed = true;\n if ((this.generations.get(identity) ?? 0) !== generation) return;\n const current = this.getSnapshot(identity);\n const endpoint = current.endpoints.find(\n (candidate) =>\n candidate.method === row.method && candidate.path === row.path,\n );\n if (!endpoint) return;\n row = {\n ...endpoint,\n ...this.recordDurations(\n identity,\n endpoint,\n this.now() - startedAt,\n serverTiming,\n ),\n inFlight: endpoint.inFlight - 1,\n [outcome]: endpoint[outcome] + 1,\n };\n this.update(identity, current, endpoint, row, {\n inFlight: current.inFlight - 1,\n [outcome]: current[outcome] + 1,\n });\n };\n }\n\n private recordDurations(\n identity: string | null,\n endpoint: ApiRequestEndpointCounts,\n elapsedMs: number,\n serverTiming: ApiServerTiming | null | undefined,\n ): EndpointDurationSummaries {\n let byEndpoint = this.durations.get(identity);\n if (!byEndpoint) {\n byEndpoint = new Map();\n this.durations.set(identity, byEndpoint);\n }\n const key = endpointKey(endpoint);\n let windows = byEndpoint.get(key);\n if (!windows) {\n windows = {\n duration: new DurationSampleWindow(),\n serverDuration: new DurationSampleWindow(),\n databaseDuration: new DurationSampleWindow(),\n };\n byEndpoint.set(key, windows);\n }\n windows.duration.record(elapsedMs);\n const serverMs = serverTiming?.totalMs;\n if (typeof serverMs === \"number\") windows.serverDuration.record(serverMs);\n const databaseMs = serverTiming?.databaseMs;\n if (typeof databaseMs === \"number\") {\n windows.databaseDuration.record(databaseMs);\n }\n return {\n duration: windows.duration.summarize(),\n serverDuration: windows.serverDuration.summarize(),\n databaseDuration: windows.databaseDuration.summarize(),\n };\n }\n\n private update(\n identity: string | null,\n previous: ApiRequestMetricsSnapshot,\n existing: ApiRequestEndpointCounts | undefined,\n row: ApiRequestEndpointCounts,\n counts: Partial<ApiRequestCounts>,\n ): void {\n const endpoints = existing\n ? previous.endpoints.map((candidate) =>\n candidate === existing ? row : candidate,\n )\n : [...previous.endpoints, row];\n endpoints.sort(\n (left, right) =>\n right.total - left.total ||\n endpointKey(left).localeCompare(endpointKey(right), \"en\"),\n );\n this.scopes.set(identity, { ...previous, ...counts, endpoints });\n this.notify();\n }\n\n private notify(): void {\n for (const listener of this.listeners) {\n // Instrumentation must never change a request's outcome.\n try {\n listener();\n } catch {\n /* A broken observer cannot block HTTP. */\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"apiRequestMetrics.js","sourceRoot":"","sources":["apiRequestMetrics.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,oBAAoB,GACrB,MAAM,wBAAwB,CAAC;AA+ChC,MAAM,WAAW,GAAqB;IACpC,KAAK,EAAE,CAAC;IACR,QAAQ,EAAE,CAAC;IACX,SAAS,EAAE,CAAC;IACZ,MAAM,EAAE,CAAC;IACT,SAAS,EAAE,CAAC;CACb,CAAC;AAOF,MAAM,cAAc,GAA8B;IAChD,QAAQ,EAAE,IAAI;IACd,cAAc,EAAE,IAAI;IACpB,gBAAgB,EAAE,IAAI;CACvB,CAAC;AAEF,SAAS,aAAa;IACpB,OAAO,EAAE,GAAG,WAAW,EAAE,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;AAChF,CAAC;AAED,SAAS,WAAW,CAAC,GAAuD;IAC1E,OAAO,GAAG,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC;AACrC,CAAC;AAED;;;;;GAKG;AACH,MAAM,OAAO,iBAAiB;IAaC;IAZZ,MAAM,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC7D,SAAS,GAAG,IAAI,GAAG,EAGjC,CAAC;IACJ,uEAAuE;IACvE,2EAA2E;IAC1D,eAAe,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC5C,SAAS,GAAG,IAAI,GAAG,EAAc,CAAC;IAClC,WAAW,GAAG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AS,EAAE,CAAC,CAAC;QACjE,IAAI,CAAC,MAAM,EAAE,CAAC;IAChB,CAAC;IAEO,MAAM;QACZ,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACtC,yDAAyD;YACzD,IAAI,CAAC;gBACH,QAAQ,EAAE,CAAC;YACb,CAAC;YAAC,MAAM,CAAC;gBACP,0CAA0C;YAC5C,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport type { ApiReachabilityProbe } from \"./apiReachabilityProbe\";\nimport {\n type ApiRequestDurationSummary,\n DurationSampleWindow,\n} from \"./durationSampleWindow\";\nimport type { ApiServerTiming } from \"./serverTiming\";\n\nexport interface ApiRequestCounts {\n readonly total: number;\n readonly inFlight: number;\n readonly succeeded: number;\n readonly failed: number;\n readonly cancelled: number;\n}\n\nexport interface ApiRequestEndpointCounts extends ApiRequestCounts {\n readonly method: string;\n readonly path: string;\n /** Dispatch until response headers, a connection failure, or cancellation. */\n readonly duration: ApiRequestDurationSummary | null;\n /** The API's Server-Timing `total`; null until a response reports it. */\n readonly serverDuration: ApiRequestDurationSummary | null;\n /** The API's Server-Timing `db`; null until a response reports it. */\n readonly databaseDuration: ApiRequestDurationSummary | null;\n}\n\nexport interface ApiRequestMetricsSnapshot extends ApiRequestCounts {\n readonly startedAt: string;\n readonly endpoints: readonly ApiRequestEndpointCounts[];\n}\n\nexport interface ApiRequestInstrumentation {\n readonly metrics: ApiRequestMetrics;\n readonly getIdentity: () => string | null;\n /** Host-enabled follow-up probe that classifies failed fetches. */\n readonly networkFailureProbe?: ApiReachabilityProbe | null | undefined;\n /**\n * The host's authoritative connectivity reading (a native source where the\n * WebView's `navigator.onLine` is wrong); null defers to `navigator.onLine`.\n */\n readonly isOnline?: (() => boolean | null) | undefined;\n}\n\ntype Outcome = \"succeeded\" | \"failed\" | \"cancelled\";\n\ninterface EndpointDurations {\n readonly duration: DurationSampleWindow;\n readonly serverDuration: DurationSampleWindow;\n readonly databaseDuration: DurationSampleWindow;\n}\n\nconst emptyCounts: ApiRequestCounts = {\n total: 0,\n inFlight: 0,\n succeeded: 0,\n failed: 0,\n cancelled: 0,\n};\n\ntype EndpointDurationSummaries = Pick<\n ApiRequestEndpointCounts,\n \"duration\" | \"serverDuration\" | \"databaseDuration\"\n>;\n\nconst emptyDurations: EndpointDurationSummaries = {\n duration: null,\n serverDuration: null,\n databaseDuration: null,\n};\n\nfunction emptySnapshot(): ApiRequestMetricsSnapshot {\n return { ...emptyCounts, startedAt: new Date().toISOString(), endpoints: [] };\n}\n\nfunction endpointKey(row: { readonly method: string; readonly path: string }) {\n return `${row.method} ${row.path}`;\n}\n\n/**\n * In-memory HTTP attempt counts and durations, partitioned by identity at\n * dispatch time. Only operation templates are retained: no URLs, queries,\n * bodies or tokens. Hosts may reuse this store across client lifetimes until a\n * page reload.\n */\nexport class ApiRequestMetrics {\n private readonly scopes = new Map<string | null, ApiRequestMetricsSnapshot>();\n private readonly durations = new Map<\n string | null,\n Map<string, EndpointDurations>\n >();\n // Resource IDs live only for the duration of an HTTP attempt and never\n // enter the endpoint snapshots used by System Monitor and support reports.\n private readonly activeResources = new Map<string, number>();\n private readonly listeners = new Set<() => void>();\n private readonly generations = new Map<string | null, number>();\n\n /** `now` must be monotonic; tests inject a fake clock. */\n constructor(private readonly now: () => number = () => performance.now()) {}\n\n getSnapshot = (identity: string | null): ApiRequestMetricsSnapshot => {\n let snapshot = this.scopes.get(identity);\n if (!snapshot) {\n snapshot = emptySnapshot();\n this.scopes.set(identity, snapshot);\n }\n return snapshot;\n };\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n\n reset(identity: string | null): void {\n this.generations.set(identity, (this.generations.get(identity) ?? 0) + 1);\n this.scopes.set(identity, emptySnapshot());\n this.durations.delete(identity);\n this.notify();\n }\n\n isResourceInFlight(\n identity: string | null,\n operation: Pick<HttpOperation, \"id\">,\n resourceId: string | null,\n ): boolean {\n return (\n resourceId !== null &&\n this.activeResources.has(\n JSON.stringify([identity, operation.id, resourceId]),\n )\n );\n }\n\n beginResource(\n identity: string | null,\n operation: Pick<HttpOperation, \"id\">,\n resourceId: string,\n ): () => void {\n const key = JSON.stringify([identity, operation.id, resourceId]);\n this.activeResources.set(key, (this.activeResources.get(key) ?? 0) + 1);\n this.notify();\n let finished = false;\n return () => {\n if (finished) return;\n finished = true;\n const remaining = (this.activeResources.get(key) ?? 1) - 1;\n if (remaining === 0) this.activeResources.delete(key);\n else this.activeResources.set(key, remaining);\n this.notify();\n };\n }\n\n begin(\n identity: string | null,\n operation: HttpOperation,\n ): (outcome: Outcome, serverTiming?: ApiServerTiming | null) => void {\n const generation = this.generations.get(identity) ?? 0;\n const startedAt = this.now();\n const previous = this.getSnapshot(identity);\n const existing = previous.endpoints.find(\n (row) => row.method === operation.method && row.path === operation.path,\n );\n let row: ApiRequestEndpointCounts = {\n ...emptyDurations,\n ...(existing ?? emptyCounts),\n method: operation.method,\n path: operation.path,\n total: (existing?.total ?? 0) + 1,\n inFlight: (existing?.inFlight ?? 0) + 1,\n };\n this.update(identity, previous, existing, row, {\n total: previous.total + 1,\n inFlight: previous.inFlight + 1,\n });\n // Reset replaces the scope's endpoints. Capture a generation independently\n // of snapshots, which are replaced for every concurrent request update.\n let completed = false;\n return (outcome, serverTiming) => {\n if (completed) return;\n completed = true;\n if ((this.generations.get(identity) ?? 0) !== generation) return;\n const current = this.getSnapshot(identity);\n const endpoint = current.endpoints.find(\n (candidate) =>\n candidate.method === row.method && candidate.path === row.path,\n );\n if (!endpoint) return;\n row = {\n ...endpoint,\n ...this.recordDurations(\n identity,\n endpoint,\n this.now() - startedAt,\n serverTiming,\n ),\n inFlight: endpoint.inFlight - 1,\n [outcome]: endpoint[outcome] + 1,\n };\n this.update(identity, current, endpoint, row, {\n inFlight: current.inFlight - 1,\n [outcome]: current[outcome] + 1,\n });\n };\n }\n\n private recordDurations(\n identity: string | null,\n endpoint: ApiRequestEndpointCounts,\n elapsedMs: number,\n serverTiming: ApiServerTiming | null | undefined,\n ): EndpointDurationSummaries {\n let byEndpoint = this.durations.get(identity);\n if (!byEndpoint) {\n byEndpoint = new Map();\n this.durations.set(identity, byEndpoint);\n }\n const key = endpointKey(endpoint);\n let windows = byEndpoint.get(key);\n if (!windows) {\n windows = {\n duration: new DurationSampleWindow(),\n serverDuration: new DurationSampleWindow(),\n databaseDuration: new DurationSampleWindow(),\n };\n byEndpoint.set(key, windows);\n }\n windows.duration.record(elapsedMs);\n const serverMs = serverTiming?.totalMs;\n if (typeof serverMs === \"number\") windows.serverDuration.record(serverMs);\n const databaseMs = serverTiming?.databaseMs;\n if (typeof databaseMs === \"number\") {\n windows.databaseDuration.record(databaseMs);\n }\n return {\n duration: windows.duration.summarize(),\n serverDuration: windows.serverDuration.summarize(),\n databaseDuration: windows.databaseDuration.summarize(),\n };\n }\n\n private update(\n identity: string | null,\n previous: ApiRequestMetricsSnapshot,\n existing: ApiRequestEndpointCounts | undefined,\n row: ApiRequestEndpointCounts,\n counts: Partial<ApiRequestCounts>,\n ): void {\n const endpoints = existing\n ? previous.endpoints.map((candidate) =>\n candidate === existing ? row : candidate,\n )\n : [...previous.endpoints, row];\n endpoints.sort(\n (left, right) =>\n right.total - left.total ||\n endpointKey(left).localeCompare(endpointKey(right), \"en\"),\n );\n this.scopes.set(identity, { ...previous, ...counts, endpoints });\n this.notify();\n }\n\n private notify(): void {\n for (const listener of this.listeners) {\n // Instrumentation must never change a request's outcome.\n try {\n listener();\n } catch {\n /* A broken observer cannot block HTTP. */\n }\n }\n }\n}\n"]}
|
|
@@ -2,6 +2,7 @@ import { apiVersionHeaderName, parseApiVersion, } from "../validators/operation/
|
|
|
2
2
|
import { measureApiRequest } from "./measureApiRequest.js";
|
|
3
3
|
import { networkFailureMessage, settleNetworkFailure, } from "./networkFailure.js";
|
|
4
4
|
import { bindPrototypeMethods, describeErrorResponse, isSuccessfulResponse, normalizeApiBaseUrl, requestFailureKey, } from "./requestInternals.js";
|
|
5
|
+
import { resourceRequestActivity } from "./resourceRequestActivity.js";
|
|
5
6
|
import { shouldRetryAfterSessionExpired } from "./sessionRefresh.js";
|
|
6
7
|
import { SessionRenewalTracker, sessionAuthChallengeBytes, } from "./sessionRenewal.js";
|
|
7
8
|
import { sessionRequestInit } from "./sessionRequestInit.js";
|
|
@@ -165,6 +166,7 @@ export class ApiRequestRuntime {
|
|
|
165
166
|
return result;
|
|
166
167
|
}
|
|
167
168
|
const errorDescription = await describeErrorResponse(response, failureOperation, options.expectedPaymentRequiredOrganizationId);
|
|
169
|
+
options[resourceRequestActivity]?.finish();
|
|
168
170
|
const retired = () => this.retiredResponse(session, method, path, response, errorDescription.code);
|
|
169
171
|
if (requestRetired(session, options))
|
|
170
172
|
return retired();
|
|
@@ -227,12 +229,11 @@ export class ApiRequestRuntime {
|
|
|
227
229
|
const session = this.sessionRenewals.signal;
|
|
228
230
|
if (options.stillCurrent?.() === false)
|
|
229
231
|
return retiredRequest(method, path);
|
|
230
|
-
const reportErrors = options.reportErrors ?? true;
|
|
231
232
|
const { headers, init } = sessionRequestInit(method, body, options, authToken);
|
|
232
233
|
let response;
|
|
233
234
|
const startedAt = Date.now();
|
|
234
235
|
try {
|
|
235
|
-
response = await measureApiRequest(this.instrumentation, operation, () => fetch(`${this.baseUrl}${path}`, init), options.signal);
|
|
236
|
+
response = await measureApiRequest(this.instrumentation, operation, () => fetch(`${this.baseUrl}${path}`, init), options.signal, options[resourceRequestActivity]);
|
|
236
237
|
}
|
|
237
238
|
catch (error) {
|
|
238
239
|
if (requestRetired(session, options))
|
|
@@ -260,7 +261,7 @@ export class ApiRequestRuntime {
|
|
|
260
261
|
method,
|
|
261
262
|
networkError,
|
|
262
263
|
path,
|
|
263
|
-
reportErrors: cancelled
|
|
264
|
+
reportErrors: !cancelled && (options.reportErrors ?? true),
|
|
264
265
|
stalePrincipalHeads: undefined,
|
|
265
266
|
status: null,
|
|
266
267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AmB;YAC/D,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,MAAM;YAC7B,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,UAAU;SACtC,CAAC,CAAC;IACL,CAAC;IAEO,4BAA4B,CAClC,KAA4C;QAE5C,IAAI,KAAK,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,KAAK;YAC3C,OAAO,cAAc,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QAClD,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC7B,IAAI,CAAC,cAAc,EAAE,EAAE,CAAC;QAC1B,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;YACzB,GAAG,KAAK;YACR,YAAY,EAAE,KAAK,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI;YACjD,mBAAmB,EAAE,SAAS;SAC/B,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n apiVersionHeaderName,\n parseApiVersion,\n} from \"@tearleads/validators/operation\";\nimport type { ApiRequestInstrumentation } from \"./apiRequestMetrics\";\nimport { measureApiRequest } from \"./measureApiRequest\";\nimport {\n type ApiNetworkError,\n networkFailureMessage,\n settleNetworkFailure,\n} from \"./networkFailure\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport {\n type SessionBoundary,\n SessionRenewalTracker,\n sessionAuthChallengeBytes,\n} from \"./sessionRenewal\";\nimport { sessionRequestInit } from \"./sessionRequestInit\";\nimport {\n readSessionJson,\n requestRetired,\n retiredRequest,\n} from \"./sessionResponse\";\nimport type {\n HttpMethod,\n OperationRequestFn,\n OperationRequestResultFn,\n OperationResponseRequestFn,\n RequestBody,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n ResponseRequestValidationFailureInput,\n} from \"./types\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\nexport class ApiRequestRuntime {\n private authToken: string | null = null;\n private readonly sessionRenewals = new SessionRenewalTracker(\n () => this.authToken,\n );\n private readonly baseUrl: string;\n private onError: ((message: string) => void) | null = null;\n private onNetworkError: (() => void) | null = null;\n private onNetworkSuccess: (() => void) | null = null;\n private onNetworkFailure: ((error: ApiNetworkError) => void) | null = null;\n private onApiVersion: ((version: number) => void) | null = null;\n private onSessionExpired: ExpiredHandler | null = null;\n private onPaymentRequired: PaymentRequiredHandler | null = null;\n private readonly requestFailuresByKey = new Map<string, RequestFailure>();\n readonly request: OperationRequestFn;\n readonly requestResult: OperationRequestResultFn;\n readonly responseRequest: OperationResponseRequestFn;\n\n constructor(\n baseUrl?: string | null,\n private readonly instrumentation?: ApiRequestInstrumentation,\n ) {\n this.baseUrl = normalizeApiBaseUrl(baseUrl);\n bindPrototypeMethods(this, ApiRequestRuntime.prototype);\n this.request = this.makeRequest;\n this.requestResult = this.makeRequestResult;\n this.responseRequest = Object.assign(this.makeResponseRequest, {\n reportFailure: this.reportResponseRequestFailure,\n sessionSignal: () => this.sessionRenewals.signal,\n });\n }\n\n /**\n * The bytes a login challenge is signed as, bound to the API this client\n * addresses. A relative base URL resolves against the page, as its requests\n * do; with neither, there is no API origin to sign for.\n */\n authChallengeBytes(challengeHex: string, fingerprint: string): Uint8Array {\n return sessionAuthChallengeBytes(this.baseUrl, challengeHex, fingerprint);\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.onError = handler;\n }\n\n /** Reports a failure carried inside a successful batched response. */\n reportError(message: string): void {\n this.onError?.(message);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.onNetworkError = handler;\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.onNetworkSuccess = handler;\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.onNetworkFailure = handler;\n }\n\n /** Receives the build named by each response that carries one. */\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.onApiVersion = handler;\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.onSessionExpired = handler;\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.onPaymentRequired = handler;\n }\n\n setAuthToken(token: string | null, boundary?: SessionBoundary): boolean {\n const changed = Boolean(boundary) || this.authToken !== token;\n if (boundary) this.requestFailuresByKey.clear();\n if (changed) this.sessionRenewals.tokenChanged(boundary);\n this.authToken = token;\n return changed;\n }\n\n captureCredential() {\n return this.sessionRenewals.captureCredential();\n }\n\n withSessionSignal(options: RequestResultOptions): RequestResultOptions {\n return this.sessionRenewals.withSessionSignal(options);\n }\n\n getAuthToken(): string | null {\n return this.authToken;\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;\n }\n\n private async makeRequest<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<T | null> {\n const result = await this.makeRequestResult(\n path,\n validator,\n method,\n body,\n options,\n failureOperation,\n );\n return result.ok ? result.data : null;\n }\n\n private requestFailure(input: {\n code?: string | undefined;\n kind: RequestFailureKind;\n message: string;\n method: HttpMethod;\n networkError?: ApiNetworkError | undefined;\n path: string;\n reportErrors: boolean;\n requiredContainerIds?: RequestFailure[\"requiredContainerIds\"];\n stalePrincipalHeads: RequestFailure[\"stalePrincipalHeads\"];\n status: number | null;\n statusText: string;\n }): RequestFailure {\n const failure: RequestFailure = {\n ...(input.code === undefined ? {} : { code: input.code }),\n kind: input.kind,\n message: input.message,\n method: input.method,\n ...(input.networkError ? { networkError: input.networkError } : {}),\n ok: false,\n path: input.path,\n report: () => {\n if (input.kind !== \"cancelled\") this.onError?.(input.message);\n },\n status: input.status,\n statusText: input.statusText,\n ...(input.stalePrincipalHeads\n ? { stalePrincipalHeads: input.stalePrincipalHeads }\n : {}),\n ...(input.requiredContainerIds\n ? { requiredContainerIds: input.requiredContainerIds }\n : {}),\n };\n this.requestFailuresByKey.set(\n requestFailureKey({ method: input.method, path: input.path }),\n failure,\n );\n\n if (input.reportErrors) {\n failure.report();\n }\n\n return failure;\n }\n\n private async makeRequestResult<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\n const session = this.sessionRenewals.signal;\n const responseResult = await this.makeResponseRequest(\n path,\n method,\n body,\n options ?? {},\n [],\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n\n const response = responseResult.data;\n const reportErrors = options?.reportErrors ?? true;\n const decoded = await readSessionJson(\n this.responseRequest,\n response,\n method,\n path,\n options ?? {},\n session,\n );\n if (requestRetired(session, options)) return retiredRequest(method, path);\n if (!decoded.ok) return decoded;\n const data = decoded.data;\n if (!validator(data)) {\n return this.requestFailure({\n kind: \"shape\",\n message: `Invalid response shape for ${path}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n return { data, ok: true };\n }\n\n private async makeResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: Parameters<OperationResponseRequestFn>[5],\n authToken = this.authToken,\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n const callerOptions = options;\n const waitOptions = this.sessionRenewals.withRenewalWaitSignal(options);\n options = this.sessionRenewals.withSessionSignal(options);\n const result = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n failureOperation,\n attempt,\n );\n if (!result.ok) return result;\n if (requestRetired(session, options))\n return this.retiredResponse(session, method, path, result.data);\n const response = result.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return result;\n }\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\n const retired = () =>\n this.retiredResponse(\n session,\n method,\n path,\n response,\n errorDescription.code,\n );\n if (requestRetired(session, options)) return retired();\n const failure = {\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\n };\n if (attempt === 2) return this.httpFailure(failure);\n\n // An independent replacement or caller cancellation ends this wait. A\n // refusal from the renewal itself must finish reporting its typed error.\n const shouldRetry = await shouldRetryAfterSessionExpired({\n authToken,\n body,\n code: errorDescription.code,\n getCurrentAuthToken: () => this.authToken,\n isKnownSessionRenewal: (from, to) =>\n this.sessionRenewals.isKnown(from, to),\n pendingSessionRenewal: (from) => this.sessionRenewals.pending(from),\n options: waitOptions,\n refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n });\n if (requestRetired(session, options)) return retired();\n const retryToken = this.sessionRenewals.currentToken(authToken);\n if (!shouldRetry || !retryToken) return this.httpFailure(failure);\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n ...failure,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n });\n return this.makeResponseRequest(\n path,\n method,\n body,\n callerOptions,\n additionalSuccessStatuses,\n failureOperation,\n retryToken,\n 2,\n );\n }\n\n private retiredResponse(\n session: AbortSignal,\n method: HttpMethod,\n path: string,\n response: Response,\n code?: string | null,\n ): RequestFailure {\n const retired = retiredRequest(method, path);\n // Principal writes refused before dispatch have a definitive outcome.\n if (response.status !== 401 || !this.sessionRenewals.refused(session))\n return retired;\n return {\n ...retired,\n kind: \"http\",\n status: 401,\n statusText: response.statusText,\n code: code ?? undefined,\n message: `${method} ${path}: 401 ${response.statusText}`,\n };\n }\n\n private async fetchResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n authToken: string | null,\n operation: Parameters<OperationResponseRequestFn>[5],\n /** 2 is the retry after a session renewal. */\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n if (options.stillCurrent?.() === false) return retiredRequest(method, path);\n const reportErrors = options.reportErrors ?? true;\n const { headers, init } = sessionRequestInit(\n method,\n body,\n options,\n authToken,\n );\n\n let response: Response;\n const startedAt = Date.now();\n try {\n response = await measureApiRequest(\n this.instrumentation,\n operation,\n () => fetch(`${this.baseUrl}${path}`, init),\n options.signal,\n );\n } catch (error) {\n if (requestRetired(session, options)) return retiredRequest(method, path);\n const { cancelled, networkError } = await settleNetworkFailure({\n attempt,\n baseUrl: this.baseUrl,\n elapsedMs: Date.now() - startedAt,\n error,\n headers,\n isOnline: this.instrumentation?.isOnline,\n method,\n onNetworkError: () => this.onNetworkError?.(),\n pathTemplate: operation.path,\n probe: this.instrumentation?.networkFailureProbe,\n signal: options.signal,\n onNetworkFailure: (failure) => this.onNetworkFailure?.(failure),\n });\n if (requestRetired(session, options)) return retiredRequest(method, path);\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${networkFailureMessage(error, networkError)}`,\n method,\n networkError,\n path,\n reportErrors: cancelled ? false : reportErrors,\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n\n if (requestRetired(session, options))\n return this.retiredResponse(session, method, path, response);\n this.onNetworkSuccess?.();\n const apiVersion = parseApiVersion(\n response.headers.get(apiVersionHeaderName),\n );\n if (apiVersion !== null) this.onApiVersion?.(apiVersion);\n return { data: response, ok: true };\n }\n\n private httpFailure(input: {\n readonly errorDescription: ErrorResponseDescription;\n readonly failureOperation: Parameters<OperationResponseRequestFn>[5];\n readonly method: HttpMethod;\n readonly options: RequestResultOptions;\n readonly path: string;\n readonly response: Response;\n }): RequestFailure {\n const cancelled = input.options.signal?.aborted === true;\n const reportErrors = input.options.reportErrors ?? true;\n if (\n !cancelled &&\n input.response.status === 402 &&\n input.failureOperation.failureResponses?.[402] &&\n input.errorDescription.paymentRequiredOrganizationId !== undefined &&\n input.errorDescription.paymentRequiredOrganizationId ===\n input.options.expectedPaymentRequiredOrganizationId\n ) {\n this.onPaymentRequired?.(\n input.errorDescription.paymentRequiredOrganizationId,\n );\n }\n return this.requestFailure({\n ...(cancelled\n ? { code: \"request_aborted\" }\n : input.errorDescription.code === null\n ? {}\n : { code: input.errorDescription.code }),\n kind: cancelled ? \"cancelled\" : \"http\",\n message: `${input.method} ${input.path}: ${input.response.status} ${input.response.statusText}${input.errorDescription.detail}`,\n method: input.method,\n path: input.path,\n reportErrors: !cancelled && reportErrors,\n requiredContainerIds: input.errorDescription.requiredContainerIds,\n stalePrincipalHeads: input.errorDescription.stalePrincipalHeads,\n status: input.response.status,\n statusText: input.response.statusText,\n });\n }\n\n private reportResponseRequestFailure(\n input: ResponseRequestValidationFailureInput,\n ): RequestFailure {\n if (input.options?.stillCurrent?.() === false)\n return retiredRequest(input.method, input.path);\n if (input.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n ...input,\n reportErrors: input.options?.reportErrors ?? true,\n stalePrincipalHeads: undefined,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"apiRequestRuntime.js","sourceRoot":"","sources":["apiRequestRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAEL,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EAErB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MA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;QAClD,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC7B,IAAI,CAAC,cAAc,EAAE,EAAE,CAAC;QAC1B,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;YACzB,GAAG,KAAK;YACR,YAAY,EAAE,KAAK,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI;YACjD,mBAAmB,EAAE,SAAS;SAC/B,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n apiVersionHeaderName,\n parseApiVersion,\n} from \"@tearleads/validators/operation\";\nimport type { ApiRequestInstrumentation } from \"./apiRequestMetrics\";\nimport { measureApiRequest } from \"./measureApiRequest\";\nimport {\n type ApiNetworkError,\n networkFailureMessage,\n settleNetworkFailure,\n} from \"./networkFailure\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { resourceRequestActivity } from \"./resourceRequestActivity\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport {\n type SessionBoundary,\n SessionRenewalTracker,\n sessionAuthChallengeBytes,\n} from \"./sessionRenewal\";\nimport { sessionRequestInit } from \"./sessionRequestInit\";\nimport {\n readSessionJson,\n requestRetired,\n retiredRequest,\n} from \"./sessionResponse\";\nimport type {\n HttpMethod,\n OperationRequestFn,\n OperationRequestResultFn,\n OperationResponseRequestFn,\n RequestBody,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n ResponseRequestValidationFailureInput,\n} from \"./types\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\nexport class ApiRequestRuntime {\n private authToken: string | null = null;\n private readonly sessionRenewals = new SessionRenewalTracker(\n () => this.authToken,\n );\n private readonly baseUrl: string;\n private onError: ((message: string) => void) | null = null;\n private onNetworkError: (() => void) | null = null;\n private onNetworkSuccess: (() => void) | null = null;\n private onNetworkFailure: ((error: ApiNetworkError) => void) | null = null;\n private onApiVersion: ((version: number) => void) | null = null;\n private onSessionExpired: ExpiredHandler | null = null;\n private onPaymentRequired: PaymentRequiredHandler | null = null;\n private readonly requestFailuresByKey = new Map<string, RequestFailure>();\n readonly request: OperationRequestFn;\n readonly requestResult: OperationRequestResultFn;\n readonly responseRequest: OperationResponseRequestFn;\n\n constructor(\n baseUrl?: string | null,\n private readonly instrumentation?: ApiRequestInstrumentation,\n ) {\n this.baseUrl = normalizeApiBaseUrl(baseUrl);\n bindPrototypeMethods(this, ApiRequestRuntime.prototype);\n this.request = this.makeRequest;\n this.requestResult = this.makeRequestResult;\n this.responseRequest = Object.assign(this.makeResponseRequest, {\n reportFailure: this.reportResponseRequestFailure,\n sessionSignal: () => this.sessionRenewals.signal,\n });\n }\n\n /**\n * The bytes a login challenge is signed as, bound to the API this client\n * addresses. A relative base URL resolves against the page, as its requests\n * do; with neither, there is no API origin to sign for.\n */\n authChallengeBytes(challengeHex: string, fingerprint: string): Uint8Array {\n return sessionAuthChallengeBytes(this.baseUrl, challengeHex, fingerprint);\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.onError = handler;\n }\n\n /** Reports a failure carried inside a successful batched response. */\n reportError(message: string): void {\n this.onError?.(message);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.onNetworkError = handler;\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.onNetworkSuccess = handler;\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.onNetworkFailure = handler;\n }\n\n /** Receives the build named by each response that carries one. */\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.onApiVersion = handler;\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.onSessionExpired = handler;\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.onPaymentRequired = handler;\n }\n\n setAuthToken(token: string | null, boundary?: SessionBoundary): boolean {\n const changed = Boolean(boundary) || this.authToken !== token;\n if (boundary) this.requestFailuresByKey.clear();\n if (changed) this.sessionRenewals.tokenChanged(boundary);\n this.authToken = token;\n return changed;\n }\n\n captureCredential() {\n return this.sessionRenewals.captureCredential();\n }\n\n withSessionSignal(options: RequestResultOptions): RequestResultOptions {\n return this.sessionRenewals.withSessionSignal(options);\n }\n\n getAuthToken(): string | null {\n return this.authToken;\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;\n }\n\n private async makeRequest<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<T | null> {\n const result = await this.makeRequestResult(\n path,\n validator,\n method,\n body,\n options,\n failureOperation,\n );\n return result.ok ? result.data : null;\n }\n\n private requestFailure(input: {\n code?: string | undefined;\n kind: RequestFailureKind;\n message: string;\n method: HttpMethod;\n networkError?: ApiNetworkError | undefined;\n path: string;\n reportErrors: boolean;\n requiredContainerIds?: RequestFailure[\"requiredContainerIds\"];\n stalePrincipalHeads: RequestFailure[\"stalePrincipalHeads\"];\n status: number | null;\n statusText: string;\n }): RequestFailure {\n const failure: RequestFailure = {\n ...(input.code === undefined ? {} : { code: input.code }),\n kind: input.kind,\n message: input.message,\n method: input.method,\n ...(input.networkError ? { networkError: input.networkError } : {}),\n ok: false,\n path: input.path,\n report: () => {\n if (input.kind !== \"cancelled\") this.onError?.(input.message);\n },\n status: input.status,\n statusText: input.statusText,\n ...(input.stalePrincipalHeads\n ? { stalePrincipalHeads: input.stalePrincipalHeads }\n : {}),\n ...(input.requiredContainerIds\n ? { requiredContainerIds: input.requiredContainerIds }\n : {}),\n };\n this.requestFailuresByKey.set(\n requestFailureKey({ method: input.method, path: input.path }),\n failure,\n );\n\n if (input.reportErrors) {\n failure.report();\n }\n\n return failure;\n }\n\n private async makeRequestResult<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\n const session = this.sessionRenewals.signal;\n const responseResult = await this.makeResponseRequest(\n path,\n method,\n body,\n options ?? {},\n [],\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n\n const response = responseResult.data;\n const reportErrors = options?.reportErrors ?? true;\n const decoded = await readSessionJson(\n this.responseRequest,\n response,\n method,\n path,\n options ?? {},\n session,\n );\n if (requestRetired(session, options)) return retiredRequest(method, path);\n if (!decoded.ok) return decoded;\n const data = decoded.data;\n if (!validator(data)) {\n return this.requestFailure({\n kind: \"shape\",\n message: `Invalid response shape for ${path}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n return { data, ok: true };\n }\n\n private async makeResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: Parameters<OperationResponseRequestFn>[5],\n authToken = this.authToken,\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n const callerOptions = options;\n const waitOptions = this.sessionRenewals.withRenewalWaitSignal(options);\n options = this.sessionRenewals.withSessionSignal(options);\n const result = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n failureOperation,\n attempt,\n );\n if (!result.ok) return result;\n if (requestRetired(session, options))\n return this.retiredResponse(session, method, path, result.data);\n const response = result.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return result;\n }\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\n options[resourceRequestActivity]?.finish();\n const retired = () =>\n this.retiredResponse(\n session,\n method,\n path,\n response,\n errorDescription.code,\n );\n if (requestRetired(session, options)) return retired();\n const failure = {\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\n };\n if (attempt === 2) return this.httpFailure(failure);\n\n // An independent replacement or caller cancellation ends this wait. A\n // refusal from the renewal itself must finish reporting its typed error.\n const shouldRetry = await shouldRetryAfterSessionExpired({\n authToken,\n body,\n code: errorDescription.code,\n getCurrentAuthToken: () => this.authToken,\n isKnownSessionRenewal: (from, to) =>\n this.sessionRenewals.isKnown(from, to),\n pendingSessionRenewal: (from) => this.sessionRenewals.pending(from),\n options: waitOptions,\n refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n });\n if (requestRetired(session, options)) return retired();\n const retryToken = this.sessionRenewals.currentToken(authToken);\n if (!shouldRetry || !retryToken) return this.httpFailure(failure);\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n ...failure,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n });\n return this.makeResponseRequest(\n path,\n method,\n body,\n callerOptions,\n additionalSuccessStatuses,\n failureOperation,\n retryToken,\n 2,\n );\n }\n\n private retiredResponse(\n session: AbortSignal,\n method: HttpMethod,\n path: string,\n response: Response,\n code?: string | null,\n ): RequestFailure {\n const retired = retiredRequest(method, path);\n // Principal writes refused before dispatch have a definitive outcome.\n if (response.status !== 401 || !this.sessionRenewals.refused(session))\n return retired;\n return {\n ...retired,\n kind: \"http\",\n status: 401,\n statusText: response.statusText,\n code: code ?? undefined,\n message: `${method} ${path}: 401 ${response.statusText}`,\n };\n }\n\n private async fetchResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n authToken: string | null,\n operation: Parameters<OperationResponseRequestFn>[5],\n /** 2 is the retry after a session renewal. */\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n if (options.stillCurrent?.() === false) return retiredRequest(method, path);\n const { headers, init } = sessionRequestInit(\n method,\n body,\n options,\n authToken,\n );\n let response: Response;\n const startedAt = Date.now();\n try {\n response = await measureApiRequest(\n this.instrumentation,\n operation,\n () => fetch(`${this.baseUrl}${path}`, init),\n options.signal,\n options[resourceRequestActivity],\n );\n } catch (error) {\n if (requestRetired(session, options)) return retiredRequest(method, path);\n const { cancelled, networkError } = await settleNetworkFailure({\n attempt,\n baseUrl: this.baseUrl,\n elapsedMs: Date.now() - startedAt,\n error,\n headers,\n isOnline: this.instrumentation?.isOnline,\n method,\n onNetworkError: () => this.onNetworkError?.(),\n pathTemplate: operation.path,\n probe: this.instrumentation?.networkFailureProbe,\n signal: options.signal,\n onNetworkFailure: (failure) => this.onNetworkFailure?.(failure),\n });\n if (requestRetired(session, options)) return retiredRequest(method, path);\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${networkFailureMessage(error, networkError)}`,\n method,\n networkError,\n path,\n reportErrors: !cancelled && (options.reportErrors ?? true),\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n if (requestRetired(session, options))\n return this.retiredResponse(session, method, path, response);\n this.onNetworkSuccess?.();\n const apiVersion = parseApiVersion(\n response.headers.get(apiVersionHeaderName),\n );\n if (apiVersion !== null) this.onApiVersion?.(apiVersion);\n return { data: response, ok: true };\n }\n\n private httpFailure(input: {\n readonly errorDescription: ErrorResponseDescription;\n readonly failureOperation: Parameters<OperationResponseRequestFn>[5];\n readonly method: HttpMethod;\n readonly options: RequestResultOptions;\n readonly path: string;\n readonly response: Response;\n }): RequestFailure {\n const cancelled = input.options.signal?.aborted === true;\n const reportErrors = input.options.reportErrors ?? true;\n if (\n !cancelled &&\n input.response.status === 402 &&\n input.failureOperation.failureResponses?.[402] &&\n input.errorDescription.paymentRequiredOrganizationId !== undefined &&\n input.errorDescription.paymentRequiredOrganizationId ===\n input.options.expectedPaymentRequiredOrganizationId\n ) {\n this.onPaymentRequired?.(\n input.errorDescription.paymentRequiredOrganizationId,\n );\n }\n return this.requestFailure({\n ...(cancelled\n ? { code: \"request_aborted\" }\n : input.errorDescription.code === null\n ? {}\n : { code: input.errorDescription.code }),\n kind: cancelled ? \"cancelled\" : \"http\",\n message: `${input.method} ${input.path}: ${input.response.status} ${input.response.statusText}${input.errorDescription.detail}`,\n method: input.method,\n path: input.path,\n reportErrors: !cancelled && reportErrors,\n requiredContainerIds: input.errorDescription.requiredContainerIds,\n stalePrincipalHeads: input.errorDescription.stalePrincipalHeads,\n status: input.response.status,\n statusText: input.response.statusText,\n });\n }\n\n private reportResponseRequestFailure(\n input: ResponseRequestValidationFailureInput,\n ): RequestFailure {\n if (input.options?.stillCurrent?.() === false)\n return retiredRequest(input.method, input.path);\n if (input.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n ...input,\n reportErrors: input.options?.reportErrors ?? true,\n stalePrincipalHeads: undefined,\n });\n }\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createDocumentOperation, documentSyncOperation, linkDocumentOperation, unlinkDocumentOperation, } from "../../validators/operation/index.js";
|
|
2
2
|
import { getDocumentPurgeProof as readPurgeProof, purgeDocument as submitDocumentPurge, } from "../documentPurge.js";
|
|
3
3
|
import { bindPrototypeMethods, evictWriterProjectionIfSyncChanged, } from "../requestInternals.js";
|
|
4
|
+
import { withResourceRequestActivity } from "../resourceRequestActivity.js";
|
|
4
5
|
import { documentCreate, documentLink, documentUnlink, } from "../routes/documents/mutations.js";
|
|
5
6
|
/**
|
|
6
7
|
* Document creates, link-set changes, purges, syncs, and edit attribution.
|
|
@@ -79,11 +80,10 @@ export class DocumentArea {
|
|
|
79
80
|
syncDocument(documentId, input, options = {}) {
|
|
80
81
|
this.context.invalidateDocumentAttribution(documentId);
|
|
81
82
|
const cachedBefore = this.projections.get(documentId);
|
|
82
|
-
return this.context.transport
|
|
83
|
-
.request(documentSyncOperation, {
|
|
83
|
+
return withResourceRequestActivity(documentId, options, (requestOptions) => this.context.transport.request(documentSyncOperation, {
|
|
84
84
|
body: input,
|
|
85
85
|
params: { documentId },
|
|
86
|
-
},
|
|
86
|
+
}, requestOptions))
|
|
87
87
|
.then(async (response) => {
|
|
88
88
|
if (response) {
|
|
89
89
|
await this.settleSyncedDocument(documentId, input, response);
|
|
@@ -105,7 +105,7 @@ export class DocumentArea {
|
|
|
105
105
|
this.context.invalidateDocumentAttribution(documentId);
|
|
106
106
|
const cachedBefore = this.projections.get(documentId);
|
|
107
107
|
try {
|
|
108
|
-
const result = await this.context.transport.requestResult(documentSyncOperation, { body: input, params: { documentId } },
|
|
108
|
+
const result = await withResourceRequestActivity(documentId, options, (requestOptions) => this.context.transport.requestResult(documentSyncOperation, { body: input, params: { documentId } }, requestOptions));
|
|
109
109
|
if (result.ok) {
|
|
110
110
|
await this.settleSyncedDocument(documentId, input, result.data);
|
|
111
111
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documents.js","sourceRoot":"","sources":["documents.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,qBAAqB,EACrB,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,iCAAiC,CAAC;AAYzC,OAAO,EACL,qBAAqB,IAAI,cAAc,EACvC,aAAa,IAAI,mBAAmB,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,oBAAoB,EACpB,kCAAkC,GACnC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,cAAc,EACd,YAAY,EACZ,cAAc,GACf,MAAM,+BAA+B,CAAC;AASvC;;;GAGG;AACH,MAAM,OAAO,YAAY;IAMJ;IACA;IANF,eAAe,CAAiE;IAChF,WAAW,CAAmE;IAC9E,iBAAiB,CAA0E;IAE5G,YACmB,OAAyB,EACzB,IAA0D;QAD1D,YAAO,GAAP,OAAO,CAAkB;QACzB,SAAI,GAAJ,IAAI,CAAsD;QAE3E,oBAAoB,CAAC,IAAI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AM,CAAC;gBACN,IAAI,CAAC,yBAAyB,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;YAC3D,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,OAAO,CAAC,6BAA6B,CAAC,UAAU,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;CACF","sourcesContent":["import {\n createDocumentOperation,\n documentSyncOperation,\n linkDocumentOperation,\n unlinkDocumentOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n DocumentCreateRequest,\n DocumentLinkSetMutationRequest,\n DocumentPurgeRequest,\n DocumentSyncRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n DocumentCreateResponse,\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n getDocumentPurgeProof as readPurgeProof,\n purgeDocument as submitDocumentPurge,\n} from \"../documentPurge\";\nimport {\n bindPrototypeMethods,\n evictWriterProjectionIfSyncChanged,\n} from \"../requestInternals\";\nimport {\n type DocumentPurgeProofOptions,\n documentCreate,\n documentLink,\n documentUnlink,\n} from \"../routes/documents/mutations\";\nimport type {\n ListDocumentEditAttributionRangesOptions,\n RequestResult,\n RequestResultOptions,\n} from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\nimport type { ApiClientSelf } from \"./apiClientSelf\";\n\n/**\n * Document creates, link-set changes, purges, syncs, and edit attribution.\n * Every write invalidates the document's attribution before and after it.\n */\nexport class DocumentArea {\n private readonly attachmentLists: ApiClientContext[\"documentAttachmentListRequestsByDocumentId\"];\n private readonly projections: ApiClientContext[\"documentWriterProjectionRequestsByDocumentId\"];\n private readonly projectionResults: ApiClientContext[\"documentWriterProjectionResultsInFlightByDocumentId\"];\n\n constructor(\n private readonly context: ApiClientContext,\n private readonly self: Pick<ApiClientSelf, \"evictDocumentWriterProjection\">,\n ) {\n bindPrototypeMethods(this, DocumentArea.prototype);\n this.attachmentLists = context.documentAttachmentListRequestsByDocumentId;\n this.projections = context.documentWriterProjectionRequestsByDocumentId;\n this.projectionResults =\n context.documentWriterProjectionResultsInFlightByDocumentId;\n }\n\n // A link-set write or purge changes the document's placement: its\n // attribution, projection, and attachment envelopes all go stale.\n private placementWrite<T>(\n documentId: string,\n write: () => Promise<T>,\n ): Promise<T> {\n this.context.invalidateDocumentAttribution(documentId);\n return write().finally(() => {\n this.context.invalidateDocumentAttribution(documentId);\n this.self.evictDocumentWriterProjection(documentId);\n });\n }\n\n // A committed sync drops a changed attachment list and evicts the cached\n // projection only if the sync moved its write material.\n private settleSyncedDocument(\n documentId: string,\n request: DocumentSyncRequest,\n response: DocumentSyncResponse,\n ): Promise<void> {\n if (response.updates.length > 0) {\n this.attachmentLists.delete(documentId);\n }\n return evictWriterProjectionIfSyncChanged(\n this.projections,\n documentId,\n request,\n () => this.projectionResults.delete(documentId),\n );\n }\n\n // A failed sync leaves its outcome unknown: drop the projection it started\n // against, unless something replaced that entry meanwhile.\n private dropProjectionIfUnchanged(\n documentId: string,\n cachedBefore: Promise<DocumentWriterProjectionResponse | null> | undefined,\n ): void {\n if (this.projections.get(documentId) === cachedBefore) {\n this.projections.delete(documentId);\n this.projectionResults.delete(documentId);\n }\n }\n\n createDocument(\n input: DocumentCreateRequest,\n options: RequestResultOptions = {},\n ) {\n return this.context.send(\n documentCreate,\n documentCreate.path,\n createDocumentOperation,\n input,\n options,\n );\n }\n\n createDocumentResult(\n input: DocumentCreateRequest,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<DocumentCreateResponse>> {\n return this.context.sendResult(\n documentCreate,\n documentCreate.path,\n createDocumentOperation,\n input,\n options,\n );\n }\n\n getDocumentEditAttribution(documentId: string, requestKey = \"\") {\n return this.context.documentAttributionRequests.get(documentId, requestKey);\n }\n\n listDocumentEditAttributionRanges(\n documentId: string,\n options: ListDocumentEditAttributionRangesOptions = {},\n ) {\n return this.context.documentAttributionRequests.listRanges(\n documentId,\n options,\n );\n }\n\n linkDocument(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n this.context.send(\n documentLink,\n documentLink.path(documentId),\n linkDocumentOperation,\n input,\n options,\n ),\n );\n }\n\n linkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n this.context.sendResult(\n documentLink,\n documentLink.path(documentId),\n linkDocumentOperation,\n input,\n options,\n ),\n );\n }\n\n unlinkDocument(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n this.context.send(\n documentUnlink,\n documentUnlink.path(documentId),\n unlinkDocumentOperation,\n input,\n options,\n ),\n );\n }\n\n unlinkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n this.context.sendResult(\n documentUnlink,\n documentUnlink.path(documentId),\n unlinkDocumentOperation,\n input,\n options,\n ),\n );\n }\n\n purgeDocument(\n documentId: string,\n input: DocumentPurgeRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n submitDocumentPurge(this.context.runtime, documentId, input, options),\n );\n }\n\n getDocumentPurgeProof(\n documentId: string,\n options?: DocumentPurgeProofOptions,\n requestOptions: RequestResultOptions = {},\n ) {\n return readPurgeProof(\n this.context.runtime,\n documentId,\n options,\n requestOptions,\n );\n }\n\n syncDocument(\n documentId: string,\n input: DocumentSyncRequest,\n options: RequestResultOptions = {},\n ) {\n this.context.invalidateDocumentAttribution(documentId);\n const cachedBefore = this.projections.get(documentId);\n return this.context.transport\n .request(\n documentSyncOperation,\n {\n body: input,\n params: { documentId },\n },\n options,\n )\n .then(async (response) => {\n if (response) {\n await this.settleSyncedDocument(documentId, input, response);\n } else {\n this.dropProjectionIfUnchanged(documentId, cachedBefore);\n }\n return response;\n })\n .catch((error: unknown) => {\n this.dropProjectionIfUnchanged(documentId, cachedBefore);\n throw error;\n })\n .finally(() => {\n this.context.invalidateDocumentAttribution(documentId);\n });\n }\n\n async syncDocumentResult(\n documentId: string,\n input: DocumentSyncRequest,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<DocumentSyncResponse>> {\n this.context.invalidateDocumentAttribution(documentId);\n const cachedBefore = this.projections.get(documentId);\n try {\n const result = await this.context.transport.requestResult(\n documentSyncOperation,\n { body: input, params: { documentId } },\n options,\n );\n if (result.ok) {\n await this.settleSyncedDocument(documentId, input, result.data);\n } else {\n this.dropProjectionIfUnchanged(documentId, cachedBefore);\n }\n return result;\n } finally {\n this.context.invalidateDocumentAttribution(documentId);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documents.js","sourceRoot":"","sources":["documents.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,qBAAqB,EACrB,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,iCAAiC,CAAC;AAYzC,OAAO,EACL,qBAAqB,IAAI,cAAc,EACvC,aAAa,IAAI,mBAAmB,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,oBAAoB,EACpB,kCAAkC,GACnC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAEL,cAAc,EACd,YAAY,EACZ,cAAc,GACf,MAAM,+BAA+B,CAAC;AASvC;;;GAGG;AACH,MAAM,OAAO,YAAY;IAMJ;IACA;IANF,eAAe,CAAiE;IAChF,WAAW,CAAmE;IAC9E,iBAAiB,CAA0E;IAE5G,YACmB,OAAyB,EACzB,IAA0D;QAD1D,YAAO,GAAP,OAAO,CAAkB;QACzB,SAAI,GAAJ,IAAI,CAAsD;QAE3E,oBAAoB,CAAC,IAAI,EAAE,YAAY,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,0CAA0C,CAAC;QAC1E,IAAI,CAAC,WAA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AI,CAAC,CAAC;YAClE,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,yBAAyB,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;YAC3D,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,OAAO,CAAC,6BAA6B,CAAC,UAAU,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;CACF","sourcesContent":["import {\n createDocumentOperation,\n documentSyncOperation,\n linkDocumentOperation,\n unlinkDocumentOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n DocumentCreateRequest,\n DocumentLinkSetMutationRequest,\n DocumentPurgeRequest,\n DocumentSyncRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n DocumentCreateResponse,\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n getDocumentPurgeProof as readPurgeProof,\n purgeDocument as submitDocumentPurge,\n} from \"../documentPurge\";\nimport {\n bindPrototypeMethods,\n evictWriterProjectionIfSyncChanged,\n} from \"../requestInternals\";\nimport { withResourceRequestActivity } from \"../resourceRequestActivity\";\nimport {\n type DocumentPurgeProofOptions,\n documentCreate,\n documentLink,\n documentUnlink,\n} from \"../routes/documents/mutations\";\nimport type {\n ListDocumentEditAttributionRangesOptions,\n RequestResult,\n RequestResultOptions,\n} from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\nimport type { ApiClientSelf } from \"./apiClientSelf\";\n\n/**\n * Document creates, link-set changes, purges, syncs, and edit attribution.\n * Every write invalidates the document's attribution before and after it.\n */\nexport class DocumentArea {\n private readonly attachmentLists: ApiClientContext[\"documentAttachmentListRequestsByDocumentId\"];\n private readonly projections: ApiClientContext[\"documentWriterProjectionRequestsByDocumentId\"];\n private readonly projectionResults: ApiClientContext[\"documentWriterProjectionResultsInFlightByDocumentId\"];\n\n constructor(\n private readonly context: ApiClientContext,\n private readonly self: Pick<ApiClientSelf, \"evictDocumentWriterProjection\">,\n ) {\n bindPrototypeMethods(this, DocumentArea.prototype);\n this.attachmentLists = context.documentAttachmentListRequestsByDocumentId;\n this.projections = context.documentWriterProjectionRequestsByDocumentId;\n this.projectionResults =\n context.documentWriterProjectionResultsInFlightByDocumentId;\n }\n\n // A link-set write or purge changes the document's placement: its\n // attribution, projection, and attachment envelopes all go stale.\n private placementWrite<T>(\n documentId: string,\n write: () => Promise<T>,\n ): Promise<T> {\n this.context.invalidateDocumentAttribution(documentId);\n return write().finally(() => {\n this.context.invalidateDocumentAttribution(documentId);\n this.self.evictDocumentWriterProjection(documentId);\n });\n }\n\n // A committed sync drops a changed attachment list and evicts the cached\n // projection only if the sync moved its write material.\n private settleSyncedDocument(\n documentId: string,\n request: DocumentSyncRequest,\n response: DocumentSyncResponse,\n ): Promise<void> {\n if (response.updates.length > 0) {\n this.attachmentLists.delete(documentId);\n }\n return evictWriterProjectionIfSyncChanged(\n this.projections,\n documentId,\n request,\n () => this.projectionResults.delete(documentId),\n );\n }\n\n // A failed sync leaves its outcome unknown: drop the projection it started\n // against, unless something replaced that entry meanwhile.\n private dropProjectionIfUnchanged(\n documentId: string,\n cachedBefore: Promise<DocumentWriterProjectionResponse | null> | undefined,\n ): void {\n if (this.projections.get(documentId) === cachedBefore) {\n this.projections.delete(documentId);\n this.projectionResults.delete(documentId);\n }\n }\n\n createDocument(\n input: DocumentCreateRequest,\n options: RequestResultOptions = {},\n ) {\n return this.context.send(\n documentCreate,\n documentCreate.path,\n createDocumentOperation,\n input,\n options,\n );\n }\n\n createDocumentResult(\n input: DocumentCreateRequest,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<DocumentCreateResponse>> {\n return this.context.sendResult(\n documentCreate,\n documentCreate.path,\n createDocumentOperation,\n input,\n options,\n );\n }\n\n getDocumentEditAttribution(documentId: string, requestKey = \"\") {\n return this.context.documentAttributionRequests.get(documentId, requestKey);\n }\n\n listDocumentEditAttributionRanges(\n documentId: string,\n options: ListDocumentEditAttributionRangesOptions = {},\n ) {\n return this.context.documentAttributionRequests.listRanges(\n documentId,\n options,\n );\n }\n\n linkDocument(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n this.context.send(\n documentLink,\n documentLink.path(documentId),\n linkDocumentOperation,\n input,\n options,\n ),\n );\n }\n\n linkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n this.context.sendResult(\n documentLink,\n documentLink.path(documentId),\n linkDocumentOperation,\n input,\n options,\n ),\n );\n }\n\n unlinkDocument(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n this.context.send(\n documentUnlink,\n documentUnlink.path(documentId),\n unlinkDocumentOperation,\n input,\n options,\n ),\n );\n }\n\n unlinkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n this.context.sendResult(\n documentUnlink,\n documentUnlink.path(documentId),\n unlinkDocumentOperation,\n input,\n options,\n ),\n );\n }\n\n purgeDocument(\n documentId: string,\n input: DocumentPurgeRequest,\n options: RequestResultOptions = {},\n ) {\n return this.placementWrite(documentId, () =>\n submitDocumentPurge(this.context.runtime, documentId, input, options),\n );\n }\n\n getDocumentPurgeProof(\n documentId: string,\n options?: DocumentPurgeProofOptions,\n requestOptions: RequestResultOptions = {},\n ) {\n return readPurgeProof(\n this.context.runtime,\n documentId,\n options,\n requestOptions,\n );\n }\n\n syncDocument(\n documentId: string,\n input: DocumentSyncRequest,\n options: RequestResultOptions = {},\n ) {\n this.context.invalidateDocumentAttribution(documentId);\n const cachedBefore = this.projections.get(documentId);\n return withResourceRequestActivity(documentId, options, (requestOptions) =>\n this.context.transport.request(\n documentSyncOperation,\n {\n body: input,\n params: { documentId },\n },\n requestOptions,\n ),\n )\n .then(async (response) => {\n if (response) {\n await this.settleSyncedDocument(documentId, input, response);\n } else {\n this.dropProjectionIfUnchanged(documentId, cachedBefore);\n }\n return response;\n })\n .catch((error: unknown) => {\n this.dropProjectionIfUnchanged(documentId, cachedBefore);\n throw error;\n })\n .finally(() => {\n this.context.invalidateDocumentAttribution(documentId);\n });\n }\n\n async syncDocumentResult(\n documentId: string,\n input: DocumentSyncRequest,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<DocumentSyncResponse>> {\n this.context.invalidateDocumentAttribution(documentId);\n const cachedBefore = this.projections.get(documentId);\n try {\n const result = await withResourceRequestActivity(\n documentId,\n options,\n (requestOptions) =>\n this.context.transport.requestResult(\n documentSyncOperation,\n { body: input, params: { documentId } },\n requestOptions,\n ),\n );\n if (result.ok) {\n await this.settleSyncedDocument(documentId, input, result.data);\n } else {\n this.dropProjectionIfUnchanged(documentId, cachedBefore);\n }\n return result;\n } finally {\n this.context.invalidateDocumentAttribution(documentId);\n }\n }\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createOrganizationOperation, getOrganizationDataUsageOperation, getOrganizationReadModelOperation, listOrganizationGroupMembersOperation, listOrganizationMembershipsOperation, listOrganizationPendingBlobDeletionsOperation, requestOrganizationLeaveOperation, updateOrganizationMembershipOperation, updateOrganizationProfileOperation, updateOrganizationRosterEntryOperation, withdrawOrganizationLeaveRequestOperation, } from "../../validators/operation/index.js";
|
|
2
2
|
import { bindPrototypeMethods } from "../requestInternals.js";
|
|
3
|
+
import { withResourceRequestActivity } from "../resourceRequestActivity.js";
|
|
3
4
|
import { getOrganizationDataUsage as organizationDataUsage } from "../routes/organizations/dataUsage.js";
|
|
4
5
|
import { listOrganizationGroupMembers as groupMembers } from "../routes/organizations/groupMembers.js";
|
|
5
6
|
import { withdrawOrganizationLeaveRequest as leaveRequestDelete, requestOrganizationLeave as leaveRequestPut, listOrganizationMemberships as membershipsList, updateOrganizationMembership as membershipUpdate, } from "../routes/organizations/memberships.js";
|
|
@@ -53,7 +54,7 @@ export class OrganizationArea {
|
|
|
53
54
|
: this.context.sendResult(leaveRequestDelete, leaveRequestDelete.path(organizationId), withdrawOrganizationLeaveRequestOperation, undefined, { reportErrors: false });
|
|
54
55
|
}
|
|
55
56
|
updateOrganizationProfile(organizationId, input) {
|
|
56
|
-
return this.context.send(profileUpdate, profileUpdate.path(organizationId), updateOrganizationProfileOperation, input,
|
|
57
|
+
return withResourceRequestActivity(organizationId, { expectedPaymentRequiredOrganizationId: organizationId }, (options) => this.context.send(profileUpdate, profileUpdate.path(organizationId), updateOrganizationProfileOperation, input, options));
|
|
57
58
|
}
|
|
58
59
|
listOrganizationGroupMembers(organizationId, groupId) {
|
|
59
60
|
return this.context.send(groupMembers, groupMembers.path(organizationId, groupId), listOrganizationGroupMembersOperation);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizations.js","sourceRoot":"","sources":["organizations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,EACjC,iCAAiC,EACjC,qCAAqC,EACrC,oCAAoC,EACpC,6CAA6C,EAE7C,iCAAiC,EACjC,qCAAqC,EACrC,kCAAkC,EAClC,sCAAsC,EACtC,yCAAyC,GAC1C,MAAM,iCAAiC,CAAC;AAczC,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,wBAAwB,IAAI,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AACtG,OAAO,EAAE,4BAA4B,IAAI,YAAY,EAAE,MAAM,sCAAsC,CAAC;AACpG,OAAO,EACL,gCAAgC,IAAI,kBAAkB,EACtD,wBAAwB,IAAI,eAAe,EAC3C,2BAA2B,IAAI,eAAe,EAC9C,4BAA4B,IAAI,gBAAgB,GACjD,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,yBAAyB,IAAI,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAC7F,OAAO,EAAE,6BAA6B,IAAI,YAAY,EAAE,MAAM,gCAAgC,C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,CAC3B,cAAsB,EACtB,MAAc,EACd,KAA2C;QAE3C,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CACtB,YAAY,EACZ,YAAY,CAAC,IAAI,CAAC,cAAc,EAAE,MAAM,CAAC,EACzC,sCAAsC,EACtC,KAAK,EACL,EAAE,qCAAqC,EAAE,cAAc,EAAE,CAC1D,CAAC;IACJ,CAAC;IAED,yEAAyE;IACzE,2BAA2B;QACzB,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CACtB,eAAe,EACf,eAAe,CAAC,IAAI,EACpB,oCAAoC,CACrC,CAAC;IACJ,CAAC;IAED,4BAA4B,CAC1B,cAAsB,EACtB,KAA0C;QAE1C,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,gBAAgB,EAChB,gBAAgB,CAAC,IAAI,CAAC,cAAc,CAAC,EACrC,qCAAqC,EACrC,KAAK,EACL,EAAE,YAAY,EAAE,KAAK,EAAE,CACxB,CAAC;IACJ,CAAC;IAED,wEAAwE;IACxE,2BAA2B,CACzB,cAAsB,EACtB,OAAwC;QAExC,OAAO,OAAO;YACZ,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CACrB,eAAe,EACf,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,EACpC,iCAAiC,EACjC,OAAO,EACP,EAAE,YAAY,EAAE,KAAK,EAAE,CACxB;YACH,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CACrB,kBAAkB,EAClB,kBAAkB,CAAC,IAAI,CAAC,cAAc,CAAC,EACvC,yCAAyC,EACzC,SAAS,EACT,EAAE,YAAY,EAAE,KAAK,EAAE,CACxB,CAAC;IACR,CAAC;IAED,yBAAyB,CACvB,cAAsB,EACtB,KAAuC;QAEvC,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,
|
|
1
|
+
{"version":3,"file":"organizations.js","sourceRoot":"","sources":["organizations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,iCA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,EACL,EAAE,YAAY,EAAE,KAAK,EAAE,CACxB,CAAC;IACJ,CAAC;IAED,wEAAwE;IACxE,2BAA2B,CACzB,cAAsB,EACtB,OAAwC;QAExC,OAAO,OAAO;YACZ,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CACrB,eAAe,EACf,eAAe,CAAC,IAAI,CAAC,cAAc,CAAC,EACpC,iCAAiC,EACjC,OAAO,EACP,EAAE,YAAY,EAAE,KAAK,EAAE,CACxB;YACH,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CACrB,kBAAkB,EAClB,kBAAkB,CAAC,IAAI,CAAC,cAAc,CAAC,EACvC,yCAAyC,EACzC,SAAS,EACT,EAAE,YAAY,EAAE,KAAK,EAAE,CACxB,CAAC;IACR,CAAC;IAED,yBAAyB,CACvB,cAAsB,EACtB,KAAuC;QAEvC,OAAO,2BAA2B,CAChC,cAAc,EACd,EAAE,qCAAqC,EAAE,cAAc,EAAE,EACzD,CAAC,OAAO,EAAE,EAAE,CACV,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,aAAa,EACb,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,EAClC,kCAAkC,EAClC,KAAK,EACL,OAAO,CACR,CACJ,CAAC;IACJ,CAAC;IAED,4BAA4B,CAAC,cAAsB,EAAE,OAAe;QAClE,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CACtB,YAAY,EACZ,YAAY,CAAC,IAAI,CAAC,cAAc,EAAE,OAAO,CAAC,EAC1C,qCAAqC,CACtC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n createOrganizationOperation,\n getOrganizationDataUsageOperation,\n getOrganizationReadModelOperation,\n listOrganizationGroupMembersOperation,\n listOrganizationMembershipsOperation,\n listOrganizationPendingBlobDeletionsOperation,\n type PendingBlobDeletionsQuery,\n requestOrganizationLeaveOperation,\n updateOrganizationMembershipOperation,\n updateOrganizationProfileOperation,\n updateOrganizationRosterEntryOperation,\n withdrawOrganizationLeaveRequestOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n CreateOrganizationRequest,\n UpdateOrganizationMembershipRequest,\n UpdateOrganizationProfileRequest,\n UpdateOrganizationRosterEntryRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationDataUsageResponse,\n OrganizationMembershipResponse,\n OrganizationReadModelResponse,\n PendingBlobDeletionsResponse,\n} from \"@tearleads/validators/response\";\nimport type { OrganizationLeaveRequest } from \"@tearleads/validators/util\";\nimport { bindPrototypeMethods } from \"../requestInternals\";\nimport { withResourceRequestActivity } from \"../resourceRequestActivity\";\nimport { getOrganizationDataUsage as organizationDataUsage } from \"../routes/organizations/dataUsage\";\nimport { listOrganizationGroupMembers as groupMembers } from \"../routes/organizations/groupMembers\";\nimport {\n withdrawOrganizationLeaveRequest as leaveRequestDelete,\n requestOrganizationLeave as leaveRequestPut,\n listOrganizationMemberships as membershipsList,\n updateOrganizationMembership as membershipUpdate,\n} from \"../routes/organizations/memberships\";\nimport { updateOrganizationProfile as profileUpdate } from \"../routes/organizations/profile\";\nimport { updateOrganizationRosterEntry as rosterUpdate } from \"../routes/organizations/roster\";\nimport type { RequestResult, RequestResultOptions } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\n/** Organization creation, read model, roster, profile, and memberships. */\nexport class OrganizationArea {\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, OrganizationArea.prototype);\n }\n\n listOrganizationPendingBlobDeletionsResult(\n organizationId: string,\n query: PendingBlobDeletionsQuery = {},\n options: RequestResultOptions = {},\n ): Promise<RequestResult<PendingBlobDeletionsResponse>> {\n return this.context.transport.requestResult(\n listOrganizationPendingBlobDeletionsOperation,\n { params: { organizationId }, query },\n options,\n );\n }\n\n createOrganization(request: CreateOrganizationRequest) {\n return this.context.transport.request(createOrganizationOperation, {\n body: request,\n params: {},\n });\n }\n\n createOrganizationResult(request: CreateOrganizationRequest) {\n return this.context.transport.requestResult(createOrganizationOperation, {\n body: request,\n params: {},\n });\n }\n\n getOrganizationReadModelResult(\n organizationId: string,\n cursor?: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<OrganizationReadModelResponse>> {\n return this.context.transport.requestResult(\n getOrganizationReadModelOperation,\n {\n params: { organizationId },\n query: { cursor },\n },\n options,\n );\n }\n\n getOrganizationDataUsageResult(\n organizationId: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<OrganizationDataUsageResponse>> {\n return this.context.sendResult(\n organizationDataUsage,\n organizationDataUsage.path(organizationId),\n getOrganizationDataUsageOperation,\n undefined,\n options,\n );\n }\n\n updateOrganizationRosterEntry(\n organizationId: string,\n userId: string,\n input: UpdateOrganizationRosterEntryRequest,\n ) {\n return this.context.send(\n rosterUpdate,\n rosterUpdate.path(organizationId, userId),\n updateOrganizationRosterEntryOperation,\n input,\n { expectedPaymentRequiredOrganizationId: organizationId },\n );\n }\n\n /** The session user's own organization memberships; no role required. */\n listOrganizationMemberships() {\n return this.context.send(\n membershipsList,\n membershipsList.path,\n listOrganizationMembershipsOperation,\n );\n }\n\n updateOrganizationMembership(\n organizationId: string,\n input: UpdateOrganizationMembershipRequest,\n ): Promise<RequestResult<OrganizationMembershipResponse>> {\n return this.context.sendResult(\n membershipUpdate,\n membershipUpdate.path(organizationId),\n updateOrganizationMembershipOperation,\n input,\n { reportErrors: false },\n );\n }\n\n /** Files the user's signed request to leave, or withdraws it (null). */\n setOrganizationLeaveRequest(\n organizationId: string,\n request: OrganizationLeaveRequest | null,\n ): Promise<RequestResult<OrganizationMembershipResponse>> {\n return request\n ? this.context.sendResult(\n leaveRequestPut,\n leaveRequestPut.path(organizationId),\n requestOrganizationLeaveOperation,\n request,\n { reportErrors: false },\n )\n : this.context.sendResult(\n leaveRequestDelete,\n leaveRequestDelete.path(organizationId),\n withdrawOrganizationLeaveRequestOperation,\n undefined,\n { reportErrors: false },\n );\n }\n\n updateOrganizationProfile(\n organizationId: string,\n input: UpdateOrganizationProfileRequest,\n ) {\n return withResourceRequestActivity(\n organizationId,\n { expectedPaymentRequiredOrganizationId: organizationId },\n (options) =>\n this.context.send(\n profileUpdate,\n profileUpdate.path(organizationId),\n updateOrganizationProfileOperation,\n input,\n options,\n ),\n );\n }\n\n listOrganizationGroupMembers(organizationId: string, groupId: string) {\n return this.context.send(\n groupMembers,\n groupMembers.path(organizationId, groupId),\n listOrganizationGroupMembersOperation,\n );\n }\n}\n"]}
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { parseServerTiming, serverTimingHeaderName } from "./serverTiming.js";
|
|
2
|
-
function beginMeasurement(instrumentation, operation) {
|
|
2
|
+
function beginMeasurement(instrumentation, operation, activity) {
|
|
3
3
|
let finish;
|
|
4
4
|
try {
|
|
5
|
-
|
|
5
|
+
if (instrumentation) {
|
|
6
|
+
const identity = instrumentation.getIdentity();
|
|
7
|
+
finish = instrumentation.metrics.begin(identity, operation);
|
|
8
|
+
activity?.start(instrumentation.metrics, identity, operation);
|
|
9
|
+
}
|
|
6
10
|
}
|
|
7
11
|
catch {
|
|
8
12
|
// Optional host instrumentation must not prevent HTTP dispatch.
|
|
@@ -21,14 +25,15 @@ function beginMeasurement(instrumentation, operation) {
|
|
|
21
25
|
* Counts and times each fetch, including automatic retries, without consuming
|
|
22
26
|
* bodies: an attempt ends when its response headers arrive or it fails.
|
|
23
27
|
*/
|
|
24
|
-
export async function measureApiRequest(instrumentation, operation, fetchResponse, signal) {
|
|
25
|
-
const finish = beginMeasurement(instrumentation, operation);
|
|
28
|
+
export async function measureApiRequest(instrumentation, operation, fetchResponse, signal, activity) {
|
|
29
|
+
const finish = beginMeasurement(instrumentation, operation, activity);
|
|
26
30
|
try {
|
|
27
31
|
const response = await fetchResponse();
|
|
28
32
|
finish(response.status >= 200 && response.status < 400 ? "succeeded" : "failed", response);
|
|
29
33
|
return response;
|
|
30
34
|
}
|
|
31
35
|
catch (error) {
|
|
36
|
+
activity?.finish();
|
|
32
37
|
finish(signal?.aborted ? "cancelled" : "failed");
|
|
33
38
|
throw error;
|
|
34
39
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"measureApiRequest.js","sourceRoot":"","sources":["measureApiRequest.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"measureApiRequest.js","sourceRoot":"","sources":["measureApiRequest.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAO3E,SAAS,gBAAgB,CACvB,eAAsD,EACtD,SAAwB,EACxB,QAAkC;IAElC,IAAI,MAAqC,CAAC;IAC1C,IAAI,CAAC;QACH,IAAI,eAAe,EAAE,CAAC;YACpB,MAAM,QAAQ,GAAG,eAAe,CAAC,WAAW,EAAE,CAAC;YAC/C,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;YAC5D,QAAQ,EAAE,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;QAChE,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,gEAAgE;IAClE,CAAC;IACD,OAAO,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE;QAC3B,IAAI,CAAC;YACH,MAAM,EAAE,CACN,OAAO,EACP,QAAQ;gBACN,iBAAiB,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,CAClE,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,8DAA8D;QAChE,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,eAAsD,EACtD,SAAwB,EACxB,aAAsC,EACtC,MAA+B,EAC/B,QAAkC;IAElC,MAAM,MAAM,GAAG,gBAAgB,CAAC,eAAe,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;IACtE,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,aAAa,EAAE,CAAC;QACvC,MAAM,CACJ,QAAQ,CAAC,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,EACxE,QAAQ,CACT,CAAC;QACF,OAAO,QAAQ,CAAC;IAClB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;QACjD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport type { ApiRequestInstrumentation } from \"./apiRequestMetrics\";\nimport type { ResourceRequestActivity } from \"./resourceRequestActivity\";\nimport { parseServerTiming, serverTimingHeaderName } from \"./serverTiming\";\n\ntype FinishMeasurement = ReturnType<\n ApiRequestInstrumentation[\"metrics\"][\"begin\"]\n>;\ntype Outcome = Parameters<FinishMeasurement>[0];\n\nfunction beginMeasurement(\n instrumentation: ApiRequestInstrumentation | undefined,\n operation: HttpOperation,\n activity?: ResourceRequestActivity,\n): (outcome: Outcome, response?: Response) => void {\n let finish: FinishMeasurement | undefined;\n try {\n if (instrumentation) {\n const identity = instrumentation.getIdentity();\n finish = instrumentation.metrics.begin(identity, operation);\n activity?.start(instrumentation.metrics, identity, operation);\n }\n } catch {\n // Optional host instrumentation must not prevent HTTP dispatch.\n }\n return (outcome, response) => {\n try {\n finish?.(\n outcome,\n response &&\n parseServerTiming(response.headers.get(serverTimingHeaderName)),\n );\n } catch {\n // Nor may a recording failure replace the transport's result.\n }\n };\n}\n\n/**\n * Counts and times each fetch, including automatic retries, without consuming\n * bodies: an attempt ends when its response headers arrive or it fails.\n */\nexport async function measureApiRequest(\n instrumentation: ApiRequestInstrumentation | undefined,\n operation: HttpOperation,\n fetchResponse: () => Promise<Response>,\n signal: AbortSignal | undefined,\n activity?: ResourceRequestActivity,\n): Promise<Response> {\n const finish = beginMeasurement(instrumentation, operation, activity);\n try {\n const response = await fetchResponse();\n finish(\n response.status >= 200 && response.status < 400 ? \"succeeded\" : \"failed\",\n response,\n );\n return response;\n } catch (error) {\n activity?.finish();\n finish(signal?.aborted ? \"cancelled\" : \"failed\");\n throw error;\n }\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { decodeJsonOperationResponse } from "./operationResponse.js";
|
|
2
2
|
import { PrincipalHistoryRequestContext } from "./principalHistoryRequestContext.js";
|
|
3
3
|
import { requestDeadline } from "./requestDeadline.js";
|
|
4
|
+
import { resourceRequestActivity } from "./resourceRequestActivity.js";
|
|
4
5
|
const PRINCIPAL_HISTORY_READ_TIMEOUT_MS = 15_000;
|
|
5
6
|
function requestContext(runtime, input) {
|
|
6
7
|
return (input.context ??
|
|
@@ -126,6 +127,7 @@ async function readResponse(runtime, context, input) {
|
|
|
126
127
|
return result ?? interruptedFailure(context, deadline, body);
|
|
127
128
|
}
|
|
128
129
|
finally {
|
|
130
|
+
options[resourceRequestActivity]?.finish();
|
|
129
131
|
deadline.dispose();
|
|
130
132
|
}
|
|
131
133
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryRequest.js","sourceRoot":"","sources":["principalHistoryRequest.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AAClF,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAQpD,MAAM,iCAAiC,GAAG,MAAM,CAAC;AAEjD,SAAS,cAAc,CACrB,OAA0B,EAC1B,KAKC;IAED,OAAO,CACL,KAAK,CAAC,OAAO;QACb,IAAI,8BAA8B,CAChC,OAAO,EACP,KAAK,CAAC,MAAM,EACZ,KAAK,CAAC,IAAI,EACV,KAAK,CAA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,EAAE,2CAA2C;SACrD,CAAC;IACJ,QAAQ,CAAC,SAAS,GAAG,KAAK,KAAK,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,QAAQ,CAAC,QAAQ,GAAG,KAAK,CAAC;IAC1B,IAAI,QAAQ,CAAC,SAAS,IAAI,CAAC;QACzB,OAAO;YACL,IAAI,EAAE,uCAAuC;YAC7C,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,4DAA4D;SACtE,CAAC;IACJ,4EAA4E;IAC5E,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAClC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CACnD,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { JsonOperation } from \"@tearleads/validators/operation\";\nimport type { ApiRequestRuntime } from \"./apiRequestRuntime\";\nimport { decodeJsonOperationResponse } from \"./operationResponse\";\nimport { PrincipalHistoryRequestContext } from \"./principalHistoryRequestContext\";\nimport { requestDeadline } from \"./requestDeadline\";\nimport type {\n HttpMethod,\n RequestFailure,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nconst PRINCIPAL_HISTORY_READ_TIMEOUT_MS = 15_000;\n\nfunction requestContext(\n runtime: ApiRequestRuntime,\n input: {\n readonly path: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions;\n readonly context?: PrincipalHistoryRequestContext;\n },\n): PrincipalHistoryRequestContext {\n return (\n input.context ??\n new PrincipalHistoryRequestContext(\n runtime,\n input.method,\n input.path,\n input.options,\n )\n );\n}\n\n/** Retry only an explicit, validated response proving the operation rolled back. */\nexport async function principalHistoryRequest<T>(\n runtime: ApiRequestRuntime,\n input: {\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n /** Maps a schema-valid 200 body to the value the validator checks. */\n readonly decode?: (value: unknown) => unknown;\n readonly method: HttpMethod;\n readonly body?: string;\n readonly options?: RequestResultOptions;\n readonly operation: JsonOperation;\n readonly context?: PrincipalHistoryRequestContext;\n readonly requestTimeoutMs?: number;\n },\n): Promise<RequestResult<T>> {\n const { path, method } = input;\n const context = requestContext(runtime, input);\n const options = context.options;\n const progress: PreparationProgress = { previous: undefined, unchanged: 0 };\n while (true) {\n if (context.cancelled()) return context.failure();\n const decoded = await readResponse(runtime, context, input);\n if (!decoded.ok && context.restartReadAfterRenewal()) continue;\n if (!decoded.ok) return preserveCommitUncertainty(method, context, decoded);\n if (decoded.data.status === 202) {\n context.afterPreparation();\n const failure = await continuePreparation(decoded.data.data, progress);\n if (failure)\n return runtime.responseRequest.reportFailure({\n ...failure,\n method,\n options,\n path,\n status: 202,\n statusText: decoded.data.statusText,\n });\n continue;\n }\n const valid = validatedSuccess(decoded.data, input);\n return valid\n ? { ok: true, data: valid.data }\n : invalidResponseFailure(runtime, context, input, decoded.data);\n }\n}\n\nfunction invalidResponseFailure(\n runtime: ApiRequestRuntime,\n context: PrincipalHistoryRequestContext,\n input: { readonly path: string; readonly method: HttpMethod },\n response: { readonly status: number; readonly statusText: string },\n): RequestFailure {\n const { path, method } = input;\n const options = context.options;\n const failure = runtime.responseRequest.reportFailure({\n kind: \"shape\",\n message: `Invalid principal policy response for ${path}`,\n method,\n options: method === \"GET\" ? options : { ...options, reportErrors: false },\n path,\n status: response.status,\n statusText: response.statusText,\n });\n return preserveCommitUncertainty(method, context, failure);\n}\n\nfunction decodeSuccess(\n response: { readonly data: unknown; readonly status: number },\n decode: ((value: unknown) => unknown) | undefined,\n): unknown {\n return response.status === 200 && decode\n ? decode(response.data)\n : response.data;\n}\n\nfunction validatedSuccess<T>(\n response: { readonly data: unknown; readonly status: number },\n input: {\n readonly validator: (value: unknown) => value is T;\n readonly decode?: (value: unknown) => unknown;\n },\n): { readonly data: T } | null {\n const data = decodeSuccess(response, input.decode);\n return response.status === 200 && input.validator(data) ? { data } : null;\n}\n\nfunction preserveCommitUncertainty(\n method: HttpMethod,\n context: PrincipalHistoryRequestContext,\n failure: RequestFailure,\n): RequestFailure {\n if (method === \"GET\") return failure;\n // A network/decode failure or intermediary 5xx says nothing about commit.\n // Inner write errors are silent until this final classification is known.\n const ambiguous =\n failure.kind !== \"http\" ||\n ((failure.status ?? 0) >= 500 &&\n // The declared 503 schema requires the exact code and committed:false.\n // Unvalidated codes never reach RequestFailure.code.\n !(\n failure.status === 503 &&\n failure.code === \"principal_history_preparation_unavailable\"\n )) ||\n failure.status === 408 ||\n failure.status === 499;\n const result =\n ambiguous && failure.kind !== \"outcome-unknown\"\n ? context.failure()\n : failure;\n if (\n context.options.reportErrors !== false &&\n (result.kind === \"http\" || !context.cancelled())\n )\n result.report();\n return result;\n}\n\n/** A cancelled request is not a timeout, even if its deadline also passed. */\nfunction interruptedFailure(\n context: PrincipalHistoryRequestContext,\n deadline: { readonly expired: () => boolean },\n response: Response | undefined,\n): RequestFailure {\n return context.failure(response, deadline.expired() && !context.cancelled());\n}\n\nasync function readResponse(\n runtime: ApiRequestRuntime,\n context: PrincipalHistoryRequestContext,\n input: {\n readonly path: string;\n readonly method: HttpMethod;\n readonly body?: string;\n readonly operation: JsonOperation;\n readonly requestTimeoutMs?: number;\n },\n) {\n // A fresh timer per response, so preparation continuations reset it.\n const deadline = requestDeadline(\n context.options,\n // Writes await acknowledgement unless the caller supplies a deadline.\n // Aborting a committed write cannot be repaired by the continuation loop.\n input.requestTimeoutMs ??\n (input.method === \"GET\" ? PRINCIPAL_HISTORY_READ_TIMEOUT_MS : null),\n );\n const options =\n input.method === \"GET\"\n ? deadline.options\n : { ...deadline.options, reportErrors: false };\n try {\n const session = runtime.responseRequest.sessionSignal?.();\n const response = await context.withCredential(options.signal, () => {\n context.beforeRequest();\n return runtime.responseRequest(\n input.path,\n input.method,\n input.body,\n options,\n [],\n input.operation,\n );\n });\n if (!response) return interruptedFailure(context, deadline, undefined);\n if (!response.ok) {\n // Authentication rejection precedes the workflow and remains definitive.\n if (response.kind === \"http\" && response.status === 401) return response;\n return (\n (await context.withCredential(options.signal, () => response)) ??\n interruptedFailure(context, deadline, undefined)\n );\n }\n const body = response.data;\n const decoded = await context.withCredential(options.signal, () =>\n decodeJsonOperationResponse(\n runtime.responseRequest,\n input.operation,\n body,\n input.path,\n options,\n session,\n ),\n );\n if (!decoded) return interruptedFailure(context, deadline, body);\n const result = await context.withCredential(options.signal, () =>\n decoded.ok\n ? {\n ok: true as const,\n data: { ...decoded.data, statusText: body.statusText },\n }\n : decoded,\n );\n return result ?? interruptedFailure(context, deadline, body);\n } finally {\n deadline.dispose();\n }\n}\n\ninterface PreparationProgress {\n previous: string | undefined;\n unchanged: number;\n}\n\nasync function continuePreparation(\n data: unknown,\n progress: PreparationProgress,\n): Promise<{\n readonly kind: \"shape\" | \"http\";\n readonly message: string;\n readonly code?: string;\n} | null> {\n const token =\n typeof data === \"object\" &&\n data !== null &&\n \"progressToken\" in data &&\n typeof data.progressToken === \"string\"\n ? data.progressToken\n : undefined;\n if (token === undefined)\n return {\n kind: \"shape\",\n message: \"Principal preparation progress is missing\",\n };\n progress.unchanged = token === progress.previous ? progress.unchanged + 1 : 0;\n progress.previous = token;\n if (progress.unchanged >= 2)\n return {\n code: \"principal_history_preparation_stalled\",\n kind: \"http\",\n message: \"Principal history preparation did not advance; retry later\",\n };\n // The next round checks cancellation and identity again before any request.\n await new Promise<void>((resolve) =>\n setTimeout(resolve, progress.unchanged ? 250 : 25),\n );\n return null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalHistoryRequest.js","sourceRoot":"","sources":["principalHistoryRequest.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AAClF,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE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,CAChC,IAAa,EACb,QAA6B;IAM7B,MAAM,KAAK,GACT,OAAO,IAAI,KAAK,QAAQ;QACxB,IAAI,KAAK,IAAI;QACb,eAAe,IAAI,IAAI;QACvB,OAAO,IAAI,CAAC,aAAa,KAAK,QAAQ;QACpC,CAAC,CAAC,IAAI,CAAC,aAAa;QACpB,CAAC,CAAC,SAAS,CAAC;IAChB,IAAI,KAAK,KAAK,SAAS;QACrB,OAAO;YACL,IAAI,EAAE,OAAO;YACb,OAAO,EAAE,2CAA2C;SACrD,CAAC;IACJ,QAAQ,CAAC,SAAS,GAAG,KAAK,KAAK,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,QAAQ,CAAC,QAAQ,GAAG,KAAK,CAAC;IAC1B,IAAI,QAAQ,CAAC,SAAS,IAAI,CAAC;QACzB,OAAO;YACL,IAAI,EAAE,uCAAuC;YAC7C,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,4DAA4D;SACtE,CAAC;IACJ,4EAA4E;IAC5E,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAClC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CACnD,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { JsonOperation } from \"@tearleads/validators/operation\";\nimport type { ApiRequestRuntime } from \"./apiRequestRuntime\";\nimport { decodeJsonOperationResponse } from \"./operationResponse\";\nimport { PrincipalHistoryRequestContext } from \"./principalHistoryRequestContext\";\nimport { requestDeadline } from \"./requestDeadline\";\nimport { resourceRequestActivity } from \"./resourceRequestActivity\";\nimport type {\n HttpMethod,\n RequestFailure,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nconst PRINCIPAL_HISTORY_READ_TIMEOUT_MS = 15_000;\n\nfunction requestContext(\n runtime: ApiRequestRuntime,\n input: {\n readonly path: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions;\n readonly context?: PrincipalHistoryRequestContext;\n },\n): PrincipalHistoryRequestContext {\n return (\n input.context ??\n new PrincipalHistoryRequestContext(\n runtime,\n input.method,\n input.path,\n input.options,\n )\n );\n}\n\n/** Retry only an explicit, validated response proving the operation rolled back. */\nexport async function principalHistoryRequest<T>(\n runtime: ApiRequestRuntime,\n input: {\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n /** Maps a schema-valid 200 body to the value the validator checks. */\n readonly decode?: (value: unknown) => unknown;\n readonly method: HttpMethod;\n readonly body?: string;\n readonly options?: RequestResultOptions;\n readonly operation: JsonOperation;\n readonly context?: PrincipalHistoryRequestContext;\n readonly requestTimeoutMs?: number;\n },\n): Promise<RequestResult<T>> {\n const { path, method } = input;\n const context = requestContext(runtime, input);\n const options = context.options;\n const progress: PreparationProgress = { previous: undefined, unchanged: 0 };\n while (true) {\n if (context.cancelled()) return context.failure();\n const decoded = await readResponse(runtime, context, input);\n if (!decoded.ok && context.restartReadAfterRenewal()) continue;\n if (!decoded.ok) return preserveCommitUncertainty(method, context, decoded);\n if (decoded.data.status === 202) {\n context.afterPreparation();\n const failure = await continuePreparation(decoded.data.data, progress);\n if (failure)\n return runtime.responseRequest.reportFailure({\n ...failure,\n method,\n options,\n path,\n status: 202,\n statusText: decoded.data.statusText,\n });\n continue;\n }\n const valid = validatedSuccess(decoded.data, input);\n return valid\n ? { ok: true, data: valid.data }\n : invalidResponseFailure(runtime, context, input, decoded.data);\n }\n}\n\nfunction invalidResponseFailure(\n runtime: ApiRequestRuntime,\n context: PrincipalHistoryRequestContext,\n input: { readonly path: string; readonly method: HttpMethod },\n response: { readonly status: number; readonly statusText: string },\n): RequestFailure {\n const { path, method } = input;\n const options = context.options;\n const failure = runtime.responseRequest.reportFailure({\n kind: \"shape\",\n message: `Invalid principal policy response for ${path}`,\n method,\n options: method === \"GET\" ? options : { ...options, reportErrors: false },\n path,\n status: response.status,\n statusText: response.statusText,\n });\n return preserveCommitUncertainty(method, context, failure);\n}\n\nfunction decodeSuccess(\n response: { readonly data: unknown; readonly status: number },\n decode: ((value: unknown) => unknown) | undefined,\n): unknown {\n return response.status === 200 && decode\n ? decode(response.data)\n : response.data;\n}\n\nfunction validatedSuccess<T>(\n response: { readonly data: unknown; readonly status: number },\n input: {\n readonly validator: (value: unknown) => value is T;\n readonly decode?: (value: unknown) => unknown;\n },\n): { readonly data: T } | null {\n const data = decodeSuccess(response, input.decode);\n return response.status === 200 && input.validator(data) ? { data } : null;\n}\n\nfunction preserveCommitUncertainty(\n method: HttpMethod,\n context: PrincipalHistoryRequestContext,\n failure: RequestFailure,\n): RequestFailure {\n if (method === \"GET\") return failure;\n // A network/decode failure or intermediary 5xx says nothing about commit.\n // Inner write errors are silent until this final classification is known.\n const ambiguous =\n failure.kind !== \"http\" ||\n ((failure.status ?? 0) >= 500 &&\n // The declared 503 schema requires the exact code and committed:false.\n // Unvalidated codes never reach RequestFailure.code.\n !(\n failure.status === 503 &&\n failure.code === \"principal_history_preparation_unavailable\"\n )) ||\n failure.status === 408 ||\n failure.status === 499;\n const result =\n ambiguous && failure.kind !== \"outcome-unknown\"\n ? context.failure()\n : failure;\n if (\n context.options.reportErrors !== false &&\n (result.kind === \"http\" || !context.cancelled())\n )\n result.report();\n return result;\n}\n\n/** A cancelled request is not a timeout, even if its deadline also passed. */\nfunction interruptedFailure(\n context: PrincipalHistoryRequestContext,\n deadline: { readonly expired: () => boolean },\n response: Response | undefined,\n): RequestFailure {\n return context.failure(response, deadline.expired() && !context.cancelled());\n}\n\nasync function readResponse(\n runtime: ApiRequestRuntime,\n context: PrincipalHistoryRequestContext,\n input: {\n readonly path: string;\n readonly method: HttpMethod;\n readonly body?: string;\n readonly operation: JsonOperation;\n readonly requestTimeoutMs?: number;\n },\n) {\n // A fresh timer per response, so preparation continuations reset it.\n const deadline = requestDeadline(\n context.options,\n // Writes await acknowledgement unless the caller supplies a deadline.\n // Aborting a committed write cannot be repaired by the continuation loop.\n input.requestTimeoutMs ??\n (input.method === \"GET\" ? PRINCIPAL_HISTORY_READ_TIMEOUT_MS : null),\n );\n const options =\n input.method === \"GET\"\n ? deadline.options\n : { ...deadline.options, reportErrors: false };\n try {\n const session = runtime.responseRequest.sessionSignal?.();\n const response = await context.withCredential(options.signal, () => {\n context.beforeRequest();\n return runtime.responseRequest(\n input.path,\n input.method,\n input.body,\n options,\n [],\n input.operation,\n );\n });\n if (!response) return interruptedFailure(context, deadline, undefined);\n if (!response.ok) {\n // Authentication rejection precedes the workflow and remains definitive.\n if (response.kind === \"http\" && response.status === 401) return response;\n return (\n (await context.withCredential(options.signal, () => response)) ??\n interruptedFailure(context, deadline, undefined)\n );\n }\n const body = response.data;\n const decoded = await context.withCredential(options.signal, () =>\n decodeJsonOperationResponse(\n runtime.responseRequest,\n input.operation,\n body,\n input.path,\n options,\n session,\n ),\n );\n if (!decoded) return interruptedFailure(context, deadline, body);\n const result = await context.withCredential(options.signal, () =>\n decoded.ok\n ? {\n ok: true as const,\n data: { ...decoded.data, statusText: body.statusText },\n }\n : decoded,\n );\n return result ?? interruptedFailure(context, deadline, body);\n } finally {\n options[resourceRequestActivity]?.finish();\n deadline.dispose();\n }\n}\n\ninterface PreparationProgress {\n previous: string | undefined;\n unchanged: number;\n}\n\nasync function continuePreparation(\n data: unknown,\n progress: PreparationProgress,\n): Promise<{\n readonly kind: \"shape\" | \"http\";\n readonly message: string;\n readonly code?: string;\n} | null> {\n const token =\n typeof data === \"object\" &&\n data !== null &&\n \"progressToken\" in data &&\n typeof data.progressToken === \"string\"\n ? data.progressToken\n : undefined;\n if (token === undefined)\n return {\n kind: \"shape\",\n message: \"Principal preparation progress is missing\",\n };\n progress.unchanged = token === progress.previous ? progress.unchanged + 1 : 0;\n progress.previous = token;\n if (progress.unchanged >= 2)\n return {\n code: \"principal_history_preparation_stalled\",\n kind: \"http\",\n message: \"Principal history preparation did not advance; retry later\",\n };\n // The next round checks cancellation and identity again before any request.\n await new Promise<void>((resolve) =>\n setTimeout(resolve, progress.unchanged ? 250 : 25),\n );\n return null;\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { HttpOperation } from "../validators/operation/index.js";
|
|
2
|
+
import type { ApiRequestMetrics } from "./apiRequestMetrics.js";
|
|
3
|
+
export declare const resourceRequestActivity: unique symbol;
|
|
4
|
+
export interface ResourceRequestActivity {
|
|
5
|
+
start(metrics: ApiRequestMetrics, identity: string | null, operation: HttpOperation): void;
|
|
6
|
+
finish(): void;
|
|
7
|
+
}
|
|
8
|
+
/** Start only at fetch dispatch. Release after the response has been read,
|
|
9
|
+
* including on decode failure, cancellation, or an early return. */
|
|
10
|
+
export declare function withResourceRequestActivity<TOptions extends object, T>(resourceId: string, options: TOptions, request: (options: TOptions & {
|
|
11
|
+
[resourceRequestActivity]: ResourceRequestActivity;
|
|
12
|
+
}) => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export const resourceRequestActivity = Symbol("resourceRequestActivity");
|
|
2
|
+
/** Start only at fetch dispatch. Release after the response has been read,
|
|
3
|
+
* including on decode failure, cancellation, or an early return. */
|
|
4
|
+
export async function withResourceRequestActivity(resourceId, options, request) {
|
|
5
|
+
let release;
|
|
6
|
+
const activity = {
|
|
7
|
+
start(metrics, identity, operation) {
|
|
8
|
+
release ??= metrics.beginResource(identity, operation, resourceId);
|
|
9
|
+
},
|
|
10
|
+
finish() {
|
|
11
|
+
const finish = release;
|
|
12
|
+
release = undefined;
|
|
13
|
+
try {
|
|
14
|
+
finish?.();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// A host's instrumentation cannot change a request's outcome.
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
try {
|
|
22
|
+
return await request({ ...options, [resourceRequestActivity]: activity });
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
activity.finish();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=resourceRequestActivity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resourceRequestActivity.js","sourceRoot":"","sources":["resourceRequestActivity.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC,yBAAyB,CAAC,CAAC;AAUzE;oEACoE;AACpE,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,UAAkB,EAClB,OAAiB,EACjB,OAEe;IAEf,IAAI,OAAiC,CAAC;IACtC,MAAM,QAAQ,GAA4B;QACxC,KAAK,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS;YAChC,OAAO,KAAK,OAAO,CAAC,aAAa,CAAC,QAAQ,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC;QACrE,CAAC;QACD,MAAM;YACJ,MAAM,MAAM,GAAG,OAAO,CAAC;YACvB,OAAO,GAAG,SAAS,CAAC;YACpB,IAAI,CAAC;gBACH,MAAM,EAAE,EAAE,CAAC;YACb,CAAC;YAAC,MAAM,CAAC;gBACP,8DAA8D;YAChE,CAAC;QACH,CAAC;KACF,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,CAAC,uBAAuB,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC5E,CAAC;YAAS,CAAC;QACT,QAAQ,CAAC,MAAM,EAAE,CAAC;IACpB,CAAC;AACH,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport type { ApiRequestMetrics } from \"./apiRequestMetrics\";\n\nexport const resourceRequestActivity = Symbol(\"resourceRequestActivity\");\nexport interface ResourceRequestActivity {\n start(\n metrics: ApiRequestMetrics,\n identity: string | null,\n operation: HttpOperation,\n ): void;\n finish(): void;\n}\n\n/** Start only at fetch dispatch. Release after the response has been read,\n * including on decode failure, cancellation, or an early return. */\nexport async function withResourceRequestActivity<TOptions extends object, T>(\n resourceId: string,\n options: TOptions,\n request: (\n options: TOptions & { [resourceRequestActivity]: ResourceRequestActivity },\n ) => Promise<T>,\n): Promise<T> {\n let release: (() => void) | undefined;\n const activity: ResourceRequestActivity = {\n start(metrics, identity, operation) {\n release ??= metrics.beginResource(identity, operation, resourceId);\n },\n finish() {\n const finish = release;\n release = undefined;\n try {\n finish?.();\n } catch {\n // A host's instrumentation cannot change a request's outcome.\n }\n },\n };\n try {\n return await request({ ...options, [resourceRequestActivity]: activity });\n } finally {\n activity.finish();\n }\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { DocumentAttributionRangesQuery, HttpOperation, HttpOperationMethod } from "../validators/operation/index.js";
|
|
2
2
|
import type { ReferencedPrincipalStateResponse } from "../validators/response/index.js";
|
|
3
3
|
import type { ApiNetworkError } from "./networkFailure.js";
|
|
4
|
+
import type { ResourceRequestActivity, resourceRequestActivity } from "./resourceRequestActivity.js";
|
|
4
5
|
import type { WriterProjectionListing } from "./verifiedManifestCitations.js";
|
|
5
6
|
export type HttpMethod = HttpOperationMethod;
|
|
6
7
|
export type RequestBody = BodyInit;
|
|
@@ -8,6 +9,7 @@ export type ListDocumentEditAttributionRangesOptions = Omit<DocumentAttributionR
|
|
|
8
9
|
cursor?: DocumentAttributionRangesQuery["cursor"] | null;
|
|
9
10
|
};
|
|
10
11
|
export interface RequestResultOptions {
|
|
12
|
+
readonly [resourceRequestActivity]?: ResourceRequestActivity;
|
|
11
13
|
/** Checked at dispatch, on renewal and before handling the response. */
|
|
12
14
|
readonly stillCurrent?: (() => boolean) | undefined;
|
|
13
15
|
readonly signal?: AbortSignal | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentAttributionRangesQuery,\n HttpOperation,\n HttpOperationMethod,\n} from \"@tearleads/validators/operation\";\nimport type { ReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { ApiNetworkError } from \"./networkFailure\";\nimport type { WriterProjectionListing } from \"./verifiedManifestCitations\";\n\nexport type HttpMethod = HttpOperationMethod;\nexport type RequestBody = BodyInit;\n\nexport type ListDocumentEditAttributionRangesOptions = Omit<\n DocumentAttributionRangesQuery,\n \"cursor\"\n> & {\n cursor?: DocumentAttributionRangesQuery[\"cursor\"] | null;\n};\n\nexport interface RequestResultOptions {\n /** Checked at dispatch, on renewal and before handling the response. */\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly signal?: AbortSignal | undefined;\n /** Expected target for a declared 402; mismatched response identities fail closed. */\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly reportErrors?: boolean | undefined;\n /** Called after this request or a concurrent request renews the same session. */\n readonly onSessionRenewed?: (() => void) | undefined;\n readonly retryOnSessionExpired?: boolean | \"renew-only\" | undefined;\n /**\n * Writer-projection reads only: where a listing placed the container, so\n * an unplaced container can cite its listed parent's held bytes. It\n * changes which hashes the read cites, never what the read accepts.\n */\n readonly projectionListing?: WriterProjectionListing | undefined;\n /**\n * Group creates, group policy commits and shares only: the organization\n * read-model cursor the caller holds. The response then carries the\n * read-model delta from it when the commit advanced from that cursor.\n */\n readonly readModelCursor?: string | undefined;\n}\n\nexport type OperationRequestFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<T | null>;\n\nexport type OperationRequestResultFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<RequestResult<T>>;\n\nexport type RequestFailureKind =\n | \"storage\"\n | \"http\"\n | \"network\"\n | \"json\"\n | \"shape\"\n | \"cancelled\"\n | \"outcome-unknown\";\n\nexport interface RequestFailure {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n /** Set when the fetch itself threw: what the client could observe, without secrets. */\n readonly networkError?: ApiNetworkError | undefined;\n readonly ok: false;\n readonly path: string;\n readonly report: () => void;\n readonly status: number | null;\n readonly statusText: string;\n readonly stalePrincipalHeads?: ReferencedPrincipalStateResponse[] | undefined;\n /**\n * With `container_descendant_rekeys_required`, the full owed set, parent-first;\n * with `container_descendant_rekeys_inaccessible`, its unwritable subset.\n * A hint, never authority; verify each container before signing for it.\n */\n readonly requiredContainerIds?: readonly string[] | undefined;\n}\n\nexport interface RequestSuccess<T> {\n readonly data: T;\n readonly ok: true;\n}\n\nexport type RequestResult<T> = RequestFailure | RequestSuccess<T>;\n\nexport interface ResponseRequestValidationFailureInput {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions | undefined;\n readonly path: string;\n readonly status: number | null;\n readonly statusText: string;\n}\n\nexport interface OperationResponseRequestFn {\n (\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: HttpOperation,\n ): Promise<RequestResult<Response>>;\n readonly sessionSignal?: () => AbortSignal;\n readonly reportFailure: (\n input: ResponseRequestValidationFailureInput,\n ) => RequestFailure;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentAttributionRangesQuery,\n HttpOperation,\n HttpOperationMethod,\n} from \"@tearleads/validators/operation\";\nimport type { ReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { ApiNetworkError } from \"./networkFailure\";\nimport type {\n ResourceRequestActivity,\n resourceRequestActivity,\n} from \"./resourceRequestActivity\";\nimport type { WriterProjectionListing } from \"./verifiedManifestCitations\";\n\nexport type HttpMethod = HttpOperationMethod;\nexport type RequestBody = BodyInit;\n\nexport type ListDocumentEditAttributionRangesOptions = Omit<\n DocumentAttributionRangesQuery,\n \"cursor\"\n> & {\n cursor?: DocumentAttributionRangesQuery[\"cursor\"] | null;\n};\n\nexport interface RequestResultOptions {\n readonly [resourceRequestActivity]?: ResourceRequestActivity;\n /** Checked at dispatch, on renewal and before handling the response. */\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly signal?: AbortSignal | undefined;\n /** Expected target for a declared 402; mismatched response identities fail closed. */\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly reportErrors?: boolean | undefined;\n /** Called after this request or a concurrent request renews the same session. */\n readonly onSessionRenewed?: (() => void) | undefined;\n readonly retryOnSessionExpired?: boolean | \"renew-only\" | undefined;\n /**\n * Writer-projection reads only: where a listing placed the container, so\n * an unplaced container can cite its listed parent's held bytes. It\n * changes which hashes the read cites, never what the read accepts.\n */\n readonly projectionListing?: WriterProjectionListing | undefined;\n /**\n * Group creates, group policy commits and shares only: the organization\n * read-model cursor the caller holds. The response then carries the\n * read-model delta from it when the commit advanced from that cursor.\n */\n readonly readModelCursor?: string | undefined;\n}\n\nexport type OperationRequestFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<T | null>;\n\nexport type OperationRequestResultFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<RequestResult<T>>;\n\nexport type RequestFailureKind =\n | \"storage\"\n | \"http\"\n | \"network\"\n | \"json\"\n | \"shape\"\n | \"cancelled\"\n | \"outcome-unknown\";\n\nexport interface RequestFailure {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n /** Set when the fetch itself threw: what the client could observe, without secrets. */\n readonly networkError?: ApiNetworkError | undefined;\n readonly ok: false;\n readonly path: string;\n readonly report: () => void;\n readonly status: number | null;\n readonly statusText: string;\n readonly stalePrincipalHeads?: ReferencedPrincipalStateResponse[] | undefined;\n /**\n * With `container_descendant_rekeys_required`, the full owed set, parent-first;\n * with `container_descendant_rekeys_inaccessible`, its unwritable subset.\n * A hint, never authority; verify each container before signing for it.\n */\n readonly requiredContainerIds?: readonly string[] | undefined;\n}\n\nexport interface RequestSuccess<T> {\n readonly data: T;\n readonly ok: true;\n}\n\nexport type RequestResult<T> = RequestFailure | RequestSuccess<T>;\n\nexport interface ResponseRequestValidationFailureInput {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions | undefined;\n readonly path: string;\n readonly status: number | null;\n readonly statusText: string;\n}\n\nexport interface OperationResponseRequestFn {\n (\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: HttpOperation,\n ): Promise<RequestResult<Response>>;\n readonly sessionSignal?: () => AbortSignal;\n readonly reportFailure: (\n input: ResponseRequestValidationFailureInput,\n ) => RequestFailure;\n}\n"]}
|
|
@@ -3,6 +3,7 @@ import { decodeContainerWriterProjection, decodeDocumentWriterProjection, } from
|
|
|
3
3
|
import { formatKnownManifestHints } from "../validators/util/index.js";
|
|
4
4
|
import { principalHistoryRequest } from "./principalHistoryRequest.js";
|
|
5
5
|
import { PrincipalHistoryRequestContext } from "./principalHistoryRequestContext.js";
|
|
6
|
+
import { withResourceRequestActivity } from "./resourceRequestActivity.js";
|
|
6
7
|
import { heldManifestCitations, } from "./verifiedManifestCitations.js";
|
|
7
8
|
const NO_CITATIONS = {
|
|
8
9
|
bundles: new Map(),
|
|
@@ -87,8 +88,13 @@ async function citedProjectionRead(runtime, citations, input, options) {
|
|
|
87
88
|
export function writerProjectionRequests(runtime, citations) {
|
|
88
89
|
const requestResult = (path, validator, method, body, options, operation) => {
|
|
89
90
|
const kind = method === "GET" ? writerProjectionKind(operation.id) : null;
|
|
90
|
-
if (kind)
|
|
91
|
-
|
|
91
|
+
if (kind) {
|
|
92
|
+
const read = (requestOptions) => citedProjectionRead(runtime, citations(), { kind, path, validator }, requestOptions);
|
|
93
|
+
const id = kind === "document" ? projectionId(path) : null;
|
|
94
|
+
return id === null
|
|
95
|
+
? read(options ?? {})
|
|
96
|
+
: withResourceRequestActivity(id, options ?? {}, read);
|
|
97
|
+
}
|
|
92
98
|
return runtime.requestResult(path, validator, method, body, options, operation);
|
|
93
99
|
};
|
|
94
100
|
const request = async (...args) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writerProjectionRequests.js","sourceRoot":"","sources":["writerProjectionRequests.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qCAAqC,EACrC,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,EAC/B,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAEtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AAOlF,OAAO,EAEL,qBAAqB,GAGtB,MAAM,6BAA6B,CAAC;AAErC,MAAM,YAAY,GAA4B;IAC5C,OAAO,EAAE,IAAI,GAAG,EAAE;IAClB,SAAS,EAAE,IAAI,GAAG,EAAE;IACpB,WAAW,EAAE,IAAI,GAAG,EAAE;CACvB,CAAC;AAEF,MAAM,eAAe,GACnB,6DAA6D,CAAC;AAEhE,SAAS,YAAY,CAAC,IAAY;IAChC,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAChD,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IACvC,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC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C,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;AAC/E,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,OAA0B,EAC1B,SAAiD;IAKjD,MAAM,aAAa,GAA6B,CAC9C,IAAI,EACJ,SAAS,EACT,MAAM,EACN,IAAI,EACJ,OAAO,EACP,SAAS,EACT,EAAE;QACF,MAAM,IAAI,GAAG,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,oBAAoB,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1E,IAAI,IAAI;YACN,OAAO,mBAAmB,CACxB,OAAO,EACP,SAAS,EAAE,EACX,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,EACzB,OAAO,IAAI,EAAE,CACd,CAAC;QACJ,OAAO,OAAO,CAAC,aAAa,CAC1B,IAAI,EACJ,SAAS,EACT,MAAM,EACN,IAAI,EACJ,OAAO,EACP,SAAS,CACV,CAAC;IACJ,CAAC,CAAC;IACF,MAAM,OAAO,GAAuB,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE;QACpD,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,GAAG,IAAI,CAAC,CAAC;QAC5C,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IACxC,CAAC,CAAC;IACF,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import {\n getContainerWriterProjectionOperation,\n getDocumentWriterProjectionOperation,\n} from \"@tearleads/validators/operation\";\nimport {\n decodeContainerWriterProjection,\n decodeDocumentWriterProjection,\n} from \"@tearleads/validators/response\";\nimport { formatKnownManifestHints } from \"@tearleads/validators/util\";\nimport type { ApiRequestRuntime } from \"./apiRequestRuntime\";\nimport { principalHistoryRequest } from \"./principalHistoryRequest\";\nimport { PrincipalHistoryRequestContext } from \"./principalHistoryRequestContext\";\nimport type {\n OperationRequestFn,\n OperationRequestResultFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\nimport {\n type HeldProjectionCitations,\n heldManifestCitations,\n type VerifiedManifestCitations,\n type WriterProjectionTarget,\n} from \"./verifiedManifestCitations\";\n\nconst NO_CITATIONS: HeldProjectionCitations = {\n bundles: new Map(),\n kekLevels: new Map(),\n directories: new Map(),\n};\n\nconst PROJECTION_PATH =\n /^\\/(?:containers|documents)\\/([^/?#]+)\\/writer-projection$/u;\n\nfunction projectionId(path: string): string | null {\n const encoded = PROJECTION_PATH.exec(path)?.[1];\n if (encoded === undefined) return null;\n try {\n return decodeURIComponent(encoded);\n } catch {\n return null;\n }\n}\n\nfunction writerProjectionKind(\n operationId: string,\n): WriterProjectionTarget[\"kind\"] | null {\n if (operationId === \"containers.writerProjection.get\") return \"container\";\n if (operationId === \"documents.writerProjection.get\") return \"document\";\n return null;\n}\n\nfunction readProjection<T>(\n runtime: ApiRequestRuntime,\n input: {\n readonly kind: WriterProjectionTarget[\"kind\"];\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n },\n held: HeldProjectionCitations,\n context: PrincipalHistoryRequestContext,\n): Promise<RequestResult<T>> {\n const container = input.kind === \"container\";\n return principalHistoryRequest(runtime, {\n path: input.path,\n validator: input.validator,\n decode: (value) =>\n container\n ? decodeContainerWriterProjection(\n value,\n held.bundles,\n held.kekLevels,\n held.directories,\n )\n : decodeDocumentWriterProjection(\n value,\n held.bundles,\n held.kekLevels,\n held.directories,\n ),\n method: \"GET\",\n context,\n operation: container\n ? getContainerWriterProjectionOperation\n : getDocumentWriterProjectionOperation,\n });\n}\n\n/**\n * Preparation and body deadlines sit inside the projection read. The wire\n * cites each manifest bundle by hash and may cite a held KEK level by digest;\n * decoding resolves every citation, from the response or from the exact bytes\n * this request declared held, before any validator, cache, or verifier sees\n * the projection. A response this device\n * cannot rebuild fails closed into one complete, hint-free refetch.\n */\nasync function citedProjectionRead<T>(\n runtime: ApiRequestRuntime,\n citations: VerifiedManifestCitations | null,\n input: {\n readonly kind: WriterProjectionTarget[\"kind\"];\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n },\n options: RequestResultOptions,\n): Promise<RequestResult<T>> {\n // Bind the identity before citations load: an account switch while they\n // load, or before the refetch, must not carry one identity's hints or\n // answer into another's session. Each request rechecks this context.\n const context = new PrincipalHistoryRequestContext(\n runtime,\n \"GET\",\n input.path,\n options,\n );\n const id = projectionId(input.path);\n // Caller-specific headers make a request its own; it cites nothing. The\n // caller's abort also ends a citation wait.\n const held =\n id === null || options.headers !== undefined\n ? NO_CITATIONS\n : await heldManifestCitations(\n citations,\n { kind: input.kind, id, listing: options.projectionListing },\n options.signal,\n );\n if (held.bundles.size + held.kekLevels.size + held.directories.size === 0)\n return readProjection(runtime, input, held, context);\n const hinted = await readProjection(\n runtime,\n input,\n held,\n context.derive({\n ...options,\n headers: {\n \"x-known-manifests\": formatKnownManifestHints({\n manifests: [...held.bundles.keys()],\n kekLevels: [...held.kekLevels.keys()],\n directories: [...held.directories.keys()],\n }),\n },\n reportErrors: false,\n }),\n );\n if (hinted.ok) return hinted;\n if (hinted.kind !== \"shape\") {\n if (options.reportErrors !== false) hinted.report();\n return hinted;\n }\n return readProjection(runtime, input, NO_CITATIONS, context.derive(options));\n}\n\nexport function writerProjectionRequests(\n runtime: ApiRequestRuntime,\n citations: () => VerifiedManifestCitations | null,\n): {\n request: OperationRequestFn;\n requestResult: OperationRequestResultFn;\n} {\n const requestResult: OperationRequestResultFn = (\n path,\n validator,\n method,\n body,\n options,\n operation,\n ) => {\n const kind = method === \"GET\" ? writerProjectionKind(operation.id) : null;\n if (kind)\n return citedProjectionRead(\n runtime,\n citations(),\n { kind, path, validator },\n options ?? {},\n );\n return runtime.requestResult(\n path,\n validator,\n method,\n body,\n options,\n operation,\n );\n };\n const request: OperationRequestFn = async (...args) => {\n const result = await requestResult(...args);\n return result.ok ? result.data : null;\n };\n return { request, requestResult };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"writerProjectionRequests.js","sourceRoot":"","sources":["writerProjectionRequests.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qCAAqC,EACrC,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,EAC/B,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAEtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AAClF,OAAO,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAOxE,OAAO,EAEL,qBAAqB,GAGtB,MAAM,6BAA6B,CAAC;AAErC,MAAM,YAAY,GAA4B;IAC5C,OAAO,EAAE,IAAI,GAAG,EAAE;IAClB,SAAS,EAAE,IAAI,GAAG,EAAE;IACpB,WAAW,EAAE,IAAI,GAAG,EAAE;CACvB,CAAC;AAEF,MAAM,eAAe,GACnB,6DAA6D,CAAC;AAEhE,SAAS,YAAY,CAAC,IAAY;IAChC,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAChD,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IACvC,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAC3B,WAAmB;IAEnB,IAAI,WAAW,KAAK,iCAAiC;QAAE,OAAO,WAAW,CAAC;IAC1E,IAAI,WAAW,KAAK,gCAAgC;QAAE,OAAO,UAAU,CAAC;IACxE,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,cAAc,CACrB,OAA0B,EAC1B,KAIC,E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AoB,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1E,IAAI,IAAI,EAAE,CAAC;YACT,MAAM,IAAI,GAAG,CAAC,cAAoC,EAAE,EAAE,CACpD,mBAAmB,CACjB,OAAO,EACP,SAAS,EAAE,EACX,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,EACzB,cAAc,CACf,CAAC;YACJ,MAAM,EAAE,GAAG,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;YAC3D,OAAO,EAAE,KAAK,IAAI;gBAChB,CAAC,CAAC,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;gBACrB,CAAC,CAAC,2BAA2B,CAAC,EAAE,EAAE,OAAO,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC;QAC3D,CAAC;QACD,OAAO,OAAO,CAAC,aAAa,CAC1B,IAAI,EACJ,SAAS,EACT,MAAM,EACN,IAAI,EACJ,OAAO,EACP,SAAS,CACV,CAAC;IACJ,CAAC,CAAC;IACF,MAAM,OAAO,GAAuB,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE;QACpD,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,GAAG,IAAI,CAAC,CAAC;QAC5C,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IACxC,CAAC,CAAC;IACF,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import {\n getContainerWriterProjectionOperation,\n getDocumentWriterProjectionOperation,\n} from \"@tearleads/validators/operation\";\nimport {\n decodeContainerWriterProjection,\n decodeDocumentWriterProjection,\n} from \"@tearleads/validators/response\";\nimport { formatKnownManifestHints } from \"@tearleads/validators/util\";\nimport type { ApiRequestRuntime } from \"./apiRequestRuntime\";\nimport { principalHistoryRequest } from \"./principalHistoryRequest\";\nimport { PrincipalHistoryRequestContext } from \"./principalHistoryRequestContext\";\nimport { withResourceRequestActivity } from \"./resourceRequestActivity\";\nimport type {\n OperationRequestFn,\n OperationRequestResultFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\nimport {\n type HeldProjectionCitations,\n heldManifestCitations,\n type VerifiedManifestCitations,\n type WriterProjectionTarget,\n} from \"./verifiedManifestCitations\";\n\nconst NO_CITATIONS: HeldProjectionCitations = {\n bundles: new Map(),\n kekLevels: new Map(),\n directories: new Map(),\n};\n\nconst PROJECTION_PATH =\n /^\\/(?:containers|documents)\\/([^/?#]+)\\/writer-projection$/u;\n\nfunction projectionId(path: string): string | null {\n const encoded = PROJECTION_PATH.exec(path)?.[1];\n if (encoded === undefined) return null;\n try {\n return decodeURIComponent(encoded);\n } catch {\n return null;\n }\n}\n\nfunction writerProjectionKind(\n operationId: string,\n): WriterProjectionTarget[\"kind\"] | null {\n if (operationId === \"containers.writerProjection.get\") return \"container\";\n if (operationId === \"documents.writerProjection.get\") return \"document\";\n return null;\n}\n\nfunction readProjection<T>(\n runtime: ApiRequestRuntime,\n input: {\n readonly kind: WriterProjectionTarget[\"kind\"];\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n },\n held: HeldProjectionCitations,\n context: PrincipalHistoryRequestContext,\n): Promise<RequestResult<T>> {\n const container = input.kind === \"container\";\n return principalHistoryRequest(runtime, {\n path: input.path,\n validator: input.validator,\n decode: (value) =>\n container\n ? decodeContainerWriterProjection(\n value,\n held.bundles,\n held.kekLevels,\n held.directories,\n )\n : decodeDocumentWriterProjection(\n value,\n held.bundles,\n held.kekLevels,\n held.directories,\n ),\n method: \"GET\",\n context,\n operation: container\n ? getContainerWriterProjectionOperation\n : getDocumentWriterProjectionOperation,\n });\n}\n\n/**\n * Preparation and body deadlines sit inside the projection read. The wire\n * cites each manifest bundle by hash and may cite a held KEK level by digest;\n * decoding resolves every citation, from the response or from the exact bytes\n * this request declared held, before any validator, cache, or verifier sees\n * the projection. A response this device\n * cannot rebuild fails closed into one complete, hint-free refetch.\n */\nasync function citedProjectionRead<T>(\n runtime: ApiRequestRuntime,\n citations: VerifiedManifestCitations | null,\n input: {\n readonly kind: WriterProjectionTarget[\"kind\"];\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n },\n options: RequestResultOptions,\n): Promise<RequestResult<T>> {\n // Bind the identity before citations load: an account switch while they\n // load, or before the refetch, must not carry one identity's hints or\n // answer into another's session. Each request rechecks this context.\n const context = new PrincipalHistoryRequestContext(\n runtime,\n \"GET\",\n input.path,\n options,\n );\n const id = projectionId(input.path);\n // Caller-specific headers make a request its own; it cites nothing. The\n // caller's abort also ends a citation wait.\n const held =\n id === null || options.headers !== undefined\n ? NO_CITATIONS\n : await heldManifestCitations(\n citations,\n { kind: input.kind, id, listing: options.projectionListing },\n options.signal,\n );\n if (held.bundles.size + held.kekLevels.size + held.directories.size === 0)\n return readProjection(runtime, input, held, context);\n const hinted = await readProjection(\n runtime,\n input,\n held,\n context.derive({\n ...options,\n headers: {\n \"x-known-manifests\": formatKnownManifestHints({\n manifests: [...held.bundles.keys()],\n kekLevels: [...held.kekLevels.keys()],\n directories: [...held.directories.keys()],\n }),\n },\n reportErrors: false,\n }),\n );\n if (hinted.ok) return hinted;\n if (hinted.kind !== \"shape\") {\n if (options.reportErrors !== false) hinted.report();\n return hinted;\n }\n return readProjection(runtime, input, NO_CITATIONS, context.derive(options));\n}\n\nexport function writerProjectionRequests(\n runtime: ApiRequestRuntime,\n citations: () => VerifiedManifestCitations | null,\n): {\n request: OperationRequestFn;\n requestResult: OperationRequestResultFn;\n} {\n const requestResult: OperationRequestResultFn = (\n path,\n validator,\n method,\n body,\n options,\n operation,\n ) => {\n const kind = method === \"GET\" ? writerProjectionKind(operation.id) : null;\n if (kind) {\n const read = (requestOptions: RequestResultOptions) =>\n citedProjectionRead(\n runtime,\n citations(),\n { kind, path, validator },\n requestOptions,\n );\n const id = kind === \"document\" ? projectionId(path) : null;\n return id === null\n ? read(options ?? {})\n : withResourceRequestActivity(id, options ?? {}, read);\n }\n return runtime.requestResult(\n path,\n validator,\n method,\n body,\n options,\n operation,\n );\n };\n const request: OperationRequestFn = async (...args) => {\n const result = await requestResult(...args);\n return result.ok ? result.data : null;\n };\n return { request, requestResult };\n}\n"]}
|
package/package.json
CHANGED