@10x-media/analytics 1.0.0-beta.15 → 1.0.0-beta.17
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/CHANGELOG.md +56 -0
- package/README.md +1 -1
- package/dist/adapters/ga4/ga4.js +33 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +4 -1
- package/dist/adapters/ga4/measurementId.js.map +1 -1
- package/dist/adapters/ga4/propertyId.js +17 -0
- package/dist/adapters/ga4/propertyId.js.map +1 -0
- package/dist/adapters/http/fetchJson.js +24 -1
- package/dist/adapters/http/fetchJson.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +16 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/plausible/siteId.js +31 -0
- package/dist/adapters/plausible/siteId.js.map +1 -0
- package/dist/adapters/posthog/cloud.js +20 -0
- package/dist/adapters/posthog/cloud.js.map +1 -0
- package/dist/adapters/posthog/credentials.js +20 -0
- package/dist/adapters/posthog/credentials.js.map +1 -0
- package/dist/adapters/posthog/posthog.d.ts +3 -3
- package/dist/adapters/posthog/posthog.js +24 -10
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.js +34 -7
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/contract.d.ts +16 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +1 -1
- package/dist/core/options.js +1 -1
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +62 -14
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceErrors.js +12 -1
- package/dist/core/sourceErrors.js.map +1 -1
- package/dist/core/sourceOptions.js +1 -1
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +8 -1
- package/dist/core/sourcePolicy.js.map +1 -1
- package/dist/core/throttle.js +3 -1
- package/dist/core/throttle.js.map +1 -1
- package/dist/exports/adapters/contract.d.ts +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -2
- package/dist/exports/adapters/native.d.ts +2 -2
- package/dist/exports/adapters/plausible.d.ts +2 -2
- package/dist/exports/adapters/posthog.d.ts +2 -2
- package/dist/exports/adapters/umami.d.ts +2 -2
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/next.d.ts +2 -2
- package/dist/exports/testing.d.ts +2 -2
- package/dist/exports/types.d.ts +3 -3
- package/dist/fields/config/fetchSources.js +1 -1
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/goals/collection.js +3 -2
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +50 -4
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/nativeAdapter.js +1 -1
- package/dist/plugin/createRuntime.js +57 -13
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/pluginCollections.js +4 -1
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/providerStatusEndpoint.js +80 -0
- package/dist/plugin/providerStatusEndpoint.js.map +1 -0
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +4 -3
- package/dist/plugin/readContextForRequest.js +2 -2
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/refreshEndpoint.js +1 -1
- package/dist/plugin/routes.d.ts +5 -0
- package/dist/plugin/routes.js +1 -0
- package/dist/plugin/routes.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/providers/ProviderConnection.d.ts +12 -0
- package/dist/providers/ProviderConnection.js +105 -0
- package/dist/providers/ProviderConnection.js.map +1 -0
- package/dist/providers/ProviderConnectionTest.d.ts +12 -0
- package/dist/providers/ProviderConnectionTest.js +55 -0
- package/dist/providers/ProviderConnectionTest.js.map +1 -0
- package/dist/providers/ProvidersListNotice.d.ts +1 -1
- package/dist/providers/ProvidersListNotice.js +3 -2
- package/dist/providers/ProvidersListNotice.js.map +1 -1
- package/dist/providers/collection.d.ts +1 -1
- package/dist/providers/collection.js +106 -41
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/connectionCheck.d.ts +1 -0
- package/dist/providers/connectionCheck.js +80 -0
- package/dist/providers/connectionCheck.js.map +1 -0
- package/dist/providers/connectionState.js +53 -0
- package/dist/providers/connectionState.js.map +1 -0
- package/dist/providers/factory.d.ts +1 -3
- package/dist/providers/factory.js +18 -21
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/hosts.js +31 -9
- package/dist/providers/hosts.js.map +1 -1
- package/dist/providers/ids.d.ts +6 -0
- package/dist/providers/ids.js +32 -0
- package/dist/providers/ids.js.map +1 -0
- package/dist/providers/providerStatusClient.js +60 -0
- package/dist/providers/providerStatusClient.js.map +1 -0
- package/dist/providers/registry.js +56 -20
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/retarget.js +39 -8
- package/dist/providers/retarget.js.map +1 -1
- package/dist/providers/secrets.d.ts +1 -1
- package/dist/providers/secrets.js.map +1 -1
- package/dist/providers/status.d.ts +1 -0
- package/dist/providers/status.js +181 -0
- package/dist/providers/status.js.map +1 -0
- package/dist/surfacing/classifyError.js +37 -5
- package/dist/surfacing/classifyError.js.map +1 -1
- package/dist/surfacing/engine.js +2 -2
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/lanes.js +29 -22
- package/dist/surfacing/lanes.js.map +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/testing/settle.d.ts +2 -1
- package/dist/testing/settle.js +6 -2
- package/dist/testing/settle.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/translations/ar.js +43 -8
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +43 -8
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +43 -8
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +43 -8
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +43 -8
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +43 -8
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +35 -0
- package/dist/translations/keys.js +35 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +43 -8
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +43 -8
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +43 -8
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +43 -8
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +43 -8
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +63 -0
- package/dist/ui/components/SourcesNoticeBanner.js +4 -3
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -1
- package/dist/view/ViewSections.js +9 -2
- package/dist/view/ViewSections.js.map +1 -1
- package/dist/view/sections/EmptyStates.js +5 -4
- package/dist/view/sections/EmptyStates.js.map +1 -1
- package/dist/view/sections/OverviewCards.js +6 -2
- package/dist/view/sections/OverviewCards.js.map +1 -1
- package/dist/view/sections/SourceConnectionNote.js +56 -0
- package/dist/view/sections/SourceConnectionNote.js.map +1 -0
- package/dist/view/viewProps.d.ts +2 -0
- package/dist/view/viewProps.js +2 -1
- package/dist/view/viewProps.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"classifyError.js","names":[],"sources":["../../src/surfacing/classifyError.ts"],"sourcesContent":["import {\n\tinvalidQuery,\n\tisHostRefused,\n\tisSourceMisconfigured,\n\trefusedFilter,\n} from '../core/sourceErrors'\nimport { isRecord } from '../core/values'\nimport { BREAKER_MAX_MS } from './breaker'\n\n/**\n * What a failed read means: `invalid_param` refused as asked (no retry, never served stale),\n * `source_misconfigured` set up wrong, `unavailable` down or slow, `rate_limited` scope full.\n */\nexport type ReadFailureKind =\n\t| 'invalid_param'\n\t| 'source_misconfigured'\n\t| 'unavailable'\n\t| 'rate_limited'\n\nexport interface ReadFailure {\n\tkind: ReadFailureKind\n\t/** The source's host is refused: unlisted, private, or not https. */\n\thostRefused?: true\n\t/** The read ran out of time, so trying it again at once cannot help. */\n\ttimeout?: true\n\t/** Refused as too big before it ran: the source answered, so the breaker sees an answer. */\n\trefused?: true\n\t/** The source's quota is spent, so trying it again at once cannot help either. */\n\tquota?: true\n\t/**\n\t * How long until the same read can succeed, when the source or the plugin knows: never longer\n\t * than the breaker's longest wait, whatever a vendor's `Retry-After` asked.\n\t */\n\tretryAfterMs?: number\n\t/** The parameter at fault, set on an `invalid_param` the plugin itself raised. */\n\tparam?: string\n\t/** A message safe to show, set on an `invalid_param` the plugin itself raised. */\n\tmessage?: string\n}\n\n/** Reason message the engine's own read-timeout abort uses. */\nexport const PROVIDER_READ_TIMEOUT_MESSAGE = 'analytics: provider read timed out'\n\nconst READ_FAILED: unique symbol = Symbol.for('@10x-media/analytics/readFailed')\n\nconst LANE_REFUSED: unique symbol = Symbol.for('@10x-media/analytics/laneRefused')\n\n/**\n * A read that failed, already classified. The engine throws it with the source's own error as its\n * `cause`, so the cause-chain readers (`refusedFilter`, `isHostRefused`) keep working through it.\n */\nexport class ReadFailedError extends Error {\n\treadonly [READ_FAILED] = true\n\treadonly failure: ReadFailure\n\n\tconstructor(failure: ReadFailure, cause?: unknown) {\n\t\t// The cause's own message rides along for the logs; no endpoint ever answers with it.\n\t\tsuper(\n\t\t\t`analytics: read failed (${failure.kind})${cause instanceof Error ? `: ${cause.message}` : ''}`,\n\t\t\tcause === undefined ? undefined : { cause }\n\t\t)\n\t\tthis.name = 'ReadFailedError'\n\t\tthis.failure = failure\n\t}\n}\n\n/**\n * A lane that would not start a request (breaker open, or `Retry-After` past the read's deadline);\n * never sent, so never a failure. `opened` lets a source rested for its setup keep saying so.\n */\nexport class LaneRefusedError extends Error {\n\treadonly [LANE_REFUSED] = true\n\treadonly retryAfterMs: number\n\treadonly reason: 'open' | 'paused'\n\treadonly opened?: ReadFailure\n\n\tconstructor(reason: 'open' | 'paused', retryAfterMs: number, opened?: ReadFailure) {\n\t\tsuper(\n\t\t\treason === 'open'\n\t\t\t\t? 'analytics: the source failed too often and is rested for now'\n\t\t\t\t: 'analytics: the source asked to be left alone for now'\n\t\t)\n\t\tthis.name = 'LaneRefusedError'\n\t\tthis.reason = reason\n\t\tthis.retryAfterMs = retryAfterMs\n\t\tif (opened) {\n\t\t\tthis.opened = opened\n\t\t}\n\t}\n}\n\n/** A cold read refused: its scope already has `cache.concurrency.perScope` reads waiting. */\nexport class ScopeBusyError extends Error {\n\treadonly retryAfterMs: number\n\n\tconstructor(retryAfterMs: number) {\n\t\tsuper('analytics: this scope has too many reads waiting on their sources')\n\t\tthis.name = 'ScopeBusyError'\n\t\tthis.retryAfterMs = retryAfterMs\n\t}\n}\n\nexport const isLaneRefused = (err: unknown): err is LaneRefusedError =>\n\tisRecord(err) && Reflect.get(err, LANE_REFUSED) === true\n\nconst isReadFailed = (err: unknown): err is ReadFailedError =>\n\tisRecord(err) && Reflect.get(err, READ_FAILED) === true\n\n/**\n * Statuses that refuse the request as it was sent (bad, too large, its URI or headers too long):\n * the read is the caller's to change, and the source's setup is not at fault.\n */\nconst HTTP_INVALID: ReadonlySet<number> = new Set([400, 413, 414, 422, 431])\n\n/** What an HTTP status from a vendor means for the read. */\nexport const httpStatusKind = (status: number): ReadFailureKind => {\n\tif (HTTP_INVALID.has(status)) return 'invalid_param'\n\tif (status === 408 || status === 429) return 'unavailable'\n\tif (status >= 400 && status < 500) return 'source_misconfigured'\n\treturn 'unavailable'\n}\n\n/** gRPC status codes (GA4's Data API) that say the request itself is wrong. */\nconst GRPC_INVALID: ReadonlySet<number> = new Set([3])\n\n/** NOT_FOUND, PERMISSION_DENIED, UNAUTHENTICATED: the property or the credentials are wrong. */\nconst GRPC_MISCONFIGURED: ReadonlySet<number> = new Set([5, 7, 16])\n\n/** CANCELLED and DEADLINE_EXCEEDED: the call ran out of the time the read gave it. */\nconst GRPC_TIMEOUT: ReadonlySet<number> = new Set([1, 4])\n\n/** RESOURCE_EXHAUSTED: the quota is spent, which a retry a second later only spends again. */\nconst GRPC_QUOTA = 8\n\n/** What a gRPC status code means for the read; anything not named above is an outage. */\nexport const grpcCodeKind = (code: number): ReadFailureKind => {\n\tif (GRPC_INVALID.has(code)) return 'invalid_param'\n\tif (GRPC_MISCONFIGURED.has(code)) return 'source_misconfigured'\n\treturn 'unavailable'\n}\n\nconst TIMEOUT_NAMES: ReadonlySet<string> = new Set([\n\t'AbortError',\n\t'TimeoutError',\n\t'ReadTimeoutError',\n])\n\nconst numberAt = (value: object, key: string): number | undefined => {\n\tconst found: unknown = Reflect.get(value, key)\n\treturn typeof found === 'number' && Number.isFinite(found) ? found : undefined\n}\n\nconst textAt = (value: object, key: string): string | undefined => {\n\tconst found: unknown = Reflect.get(value, key)\n\treturn typeof found === 'string' ? found : undefined\n}\n\n/** What the plugin answers for a pattern the database's regex dialect refused. */\nconst PATTERN_REFUSED: ReadFailure = {\n\tkind: 'invalid_param',\n\tparam: 'filters',\n\tmessage: \"analytics: the database cannot read this filter's pattern\",\n}\n\n/** A query the database refused as written: the same read fails the same way every time. */\nconst QUERY_REFUSED: ReadFailure = { kind: 'invalid_param' }\n\nconst DATABASE_TIMEOUT: ReadFailure = { kind: 'unavailable', timeout: true }\n\nconst DATABASE_SETUP: ReadFailure = { kind: 'source_misconfigured' }\n\nconst mentionsPattern = (message: string | undefined): boolean =>\n\tmessage !== undefined && /regular expression|\\bregex/i.test(message)\n\n/** Mongo's codes for a `$regex` or `$regexMatch` it cannot compile, and related input errors. */\nconst MONGO_PATTERN_CODES: ReadonlySet<number> = new Set([51091, 51092, 51108, 51111])\nconst MONGO_INPUT_CODES: ReadonlySet<number> = new Set([2, 9, 14, 15, 16, 10334])\nconst MONGO_TIMEOUT_CODES: ReadonlySet<number> = new Set([50, 262])\nconst MONGO_SETUP_CODES: ReadonlySet<number> = new Set([13, 18])\n\nconst mongoFailure = (code: number, message: string | undefined): ReadFailure => {\n\tif (MONGO_PATTERN_CODES.has(code)) return PATTERN_REFUSED\n\tif (MONGO_TIMEOUT_CODES.has(code)) return DATABASE_TIMEOUT\n\tif (MONGO_SETUP_CODES.has(code)) return DATABASE_SETUP\n\tif (MONGO_INPUT_CODES.has(code)) return mentionsPattern(message) ? PATTERN_REFUSED : QUERY_REFUSED\n\treturn { kind: 'unavailable' }\n}\n\n/** Postgres SQLSTATEs a missing table, column, schema or grant raises: the install's to fix. */\nconst POSTGRES_SETUP: ReadonlySet<string> = new Set(['42501', '42P01', '42703', '3F000'])\n\n/**\n * Class 22 (data exception) and 42 (syntax or rule) refuse the statement as written, 54 says it is\n * too complex; 57014 is the statement timeout. Any other class (connections, locks) is transient.\n */\nconst postgresFailure = (sqlState: string): ReadFailure | null => {\n\tif (sqlState === '2201B') return PATTERN_REFUSED\n\tif (sqlState === '57014') return DATABASE_TIMEOUT\n\tif (POSTGRES_SETUP.has(sqlState)) return DATABASE_SETUP\n\tconst sqlClass = sqlState.slice(0, 2)\n\tif (sqlClass === '22' || sqlClass === '42' || sqlClass === '54') return QUERY_REFUSED\n\treturn null\n}\n\nconst SQLITE_TRANSIENT: ReadonlySet<string> = new Set([\n\t'SQLITE_BUSY',\n\t'SQLITE_LOCKED',\n\t'SQLITE_IOERR',\n\t'SQLITE_FULL',\n\t'SQLITE_CANTOPEN',\n\t'SQLITE_NOMEM',\n\t'SQLITE_PROTOCOL',\n\t'SQLITE_CORRUPT',\n\t'SQLITE_NOTADB',\n])\n\nconst sqliteFailure = (code: string, message: string | undefined): ReadFailure => {\n\tconst primary = code.match(/^SQLITE_[A-Z]+/)?.[0] ?? code\n\tif (primary === 'SQLITE_INTERRUPT') return DATABASE_TIMEOUT\n\tif (SQLITE_TRANSIENT.has(primary)) return { kind: 'unavailable' }\n\tif (primary === 'SQLITE_AUTH' || primary === 'SQLITE_PERM') return DATABASE_SETUP\n\tif (\n\t\tprimary === 'SQLITE_ERROR' &&\n\t\tmessage !== undefined &&\n\t\t/no such (table|column)/i.test(message)\n\t) {\n\t\treturn DATABASE_SETUP\n\t}\n\tif (mentionsPattern(message)) return PATTERN_REFUSED\n\tif (\n\t\tprimary === 'SQLITE_ERROR' ||\n\t\tprimary === 'SQLITE_TOOBIG' ||\n\t\tprimary === 'SQLITE_RANGE' ||\n\t\tprimary === 'SQLITE_MISMATCH'\n\t) {\n\t\treturn QUERY_REFUSED\n\t}\n\treturn { kind: 'unavailable' }\n}\n\n/**\n * A database driver's error (Mongo, node-postgres, libsql), read by its own code so a query the\n * database refuses is never taken for an outage, and Mongo's small numeric codes never for gRPC's.\n */\nconst databaseFailure = (link: object): ReadFailure | null => {\n\tconst message = textAt(link, 'message')\n\tconst code: unknown = Reflect.get(link, 'code')\n\tconst name = textAt(link, 'name')\n\tif (\n\t\ttypeof code === 'number' &&\n\t\t(textAt(link, 'codeName') !== undefined || name?.startsWith('Mongo') === true)\n\t) {\n\t\treturn mongoFailure(code, message)\n\t}\n\tif (typeof code !== 'string') {\n\t\treturn null\n\t}\n\tif (/^[0-9A-Z]{5}$/.test(code) && textAt(link, 'severity') !== undefined) {\n\t\treturn postgresFailure(code)\n\t}\n\tif (code.startsWith('SQLITE_')) {\n\t\treturn sqliteFailure(code, message)\n\t}\n\treturn null\n}\n\nconst retryAfterOf = (value: object): { retryAfterMs: number } | Record<string, never> => {\n\tconst retryAfterMs = numberAt(value, 'retryAfterMs')\n\treturn retryAfterMs !== undefined && retryAfterMs >= 0\n\t\t? { retryAfterMs: Math.min(retryAfterMs, BREAKER_MAX_MS) }\n\t\t: {}\n}\n\n/** Links of an error's cause chain {@link classifyError} reads at most. */\nconst MAX_CAUSE_DEPTH = 5\n\n/** The signal one link of an error's cause chain carries, or null when it carries none. */\nconst classifyLink = (link: object): ReadFailure | null => {\n\tif (isReadFailed(link)) {\n\t\treturn link.failure\n\t}\n\tif (isLaneRefused(link)) {\n\t\t// A breaker opened by a refused key or host answers as that refusal, not as an outage: the\n\t\t// settings still need changing, and waiting out the rest will not do it.\n\t\treturn link.opened?.kind === 'source_misconfigured'\n\t\t\t? {\n\t\t\t\t\tkind: 'source_misconfigured',\n\t\t\t\t\t...(link.opened.hostRefused ? { hostRefused: true } : {}),\n\t\t\t\t\tretryAfterMs: link.retryAfterMs,\n\t\t\t\t}\n\t\t\t: { kind: 'unavailable', retryAfterMs: link.retryAfterMs }\n\t}\n\tif (link instanceof ScopeBusyError) {\n\t\treturn { kind: 'rate_limited', retryAfterMs: link.retryAfterMs }\n\t}\n\tconst name: unknown = Reflect.get(link, 'name')\n\tconst message: unknown = Reflect.get(link, 'message')\n\tif (name === 'DecryptFailedError') {\n\t\treturn { kind: 'source_misconfigured' }\n\t}\n\tif (\n\t\t(typeof name === 'string' && TIMEOUT_NAMES.has(name)) ||\n\t\tmessage === PROVIDER_READ_TIMEOUT_MESSAGE\n\t) {\n\t\treturn {\n\t\t\tkind: 'unavailable',\n\t\t\ttimeout: true,\n\t\t\t...(Reflect.get(link, 'refused') === true ? { refused: true as const } : {}),\n\t\t}\n\t}\n\tconst status = numberAt(link, 'status')\n\tif (status !== undefined && status >= 100 && status < 600) {\n\t\treturn { kind: httpStatusKind(status), ...retryAfterOf(link) }\n\t}\n\tconst database = databaseFailure(link)\n\tif (database) {\n\t\treturn database\n\t}\n\t// GA4's client rejects with a GoogleError whose numeric `code` is the gRPC status; Node's own\n\t// network errors carry string codes, and a DOMException's legacy numeric code means nothing here.\n\tconst code = link instanceof DOMException ? undefined : numberAt(link, 'code')\n\tif (code !== undefined && Number.isInteger(code) && code >= 1 && code <= 16) {\n\t\treturn {\n\t\t\tkind: grpcCodeKind(code),\n\t\t\t...(GRPC_TIMEOUT.has(code) ? { timeout: true as const } : {}),\n\t\t\t...(code === GRPC_QUOTA ? { quota: true as const } : {}),\n\t\t\t...retryAfterOf(link),\n\t\t}\n\t}\n\treturn null\n}\n\n/**\n * Classifies anything a read can throw: the plugin's own refusals first, anywhere in the cause\n * chain, then the first HTTP status or gRPC code; anything else is presumed `unavailable`.\n */\nexport const classifyError = (err: unknown): ReadFailure => {\n\tif (isReadFailed(err)) {\n\t\treturn err.failure\n\t}\n\tconst filter = refusedFilter(err)\n\tif (filter) {\n\t\treturn {\n\t\t\tkind: 'invalid_param',\n\t\t\tparam: 'filters',\n\t\t\tmessage: `analytics: this source cannot filter ${filter.dimension} with ${filter.operator}`,\n\t\t}\n\t}\n\tconst invalid = invalidQuery(err)\n\tif (invalid) {\n\t\treturn { kind: 'invalid_param', param: invalid.param, message: invalid.message }\n\t}\n\tif (isSourceMisconfigured(err)) {\n\t\treturn { kind: 'source_misconfigured', ...(isHostRefused(err) ? { hostRefused: true } : {}) }\n\t}\n\tlet current: unknown = err\n\tfor (let depth = 0; depth < MAX_CAUSE_DEPTH && isRecord(current); depth++) {\n\t\tconst found = classifyLink(current)\n\t\tif (found) {\n\t\t\treturn found\n\t\t}\n\t\tcurrent = Reflect.get(current, 'cause')\n\t}\n\treturn { kind: 'unavailable' }\n}\n\n/**\n * What a surface shows for a failed read; only `busy` (an outage, a timeout or a full queue) is\n * one a retry can fix.\n */\nexport type ReadFailureStatus = 'misconfigured' | 'host-refused' | 'invalid' | 'busy'\n\nexport interface ReadFailureState {\n\tstatus: ReadFailureStatus\n\t/** How long until a retry can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n}\n\n/** A failed read as a surface shows it. */\nexport const readFailureOf = (err: unknown): ReadFailureState => {\n\tconst failure = classifyError(err)\n\tswitch (failure.kind) {\n\t\tcase 'source_misconfigured':\n\t\t\treturn { status: failure.hostRefused ? 'host-refused' : 'misconfigured' }\n\t\tcase 'invalid_param':\n\t\t\treturn { status: 'invalid' }\n\t\tcase 'unavailable':\n\t\tcase 'rate_limited':\n\t\t\treturn {\n\t\t\t\tstatus: 'busy',\n\t\t\t\t...(failure.retryAfterMs === undefined ? {} : { retryAfterMs: failure.retryAfterMs }),\n\t\t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,QAAQ,QAAQ,cAAc,iBAAiB,gBAAgB;EACzE,KAAK,iBACJ,OAAO,EAAE,QAAQ,UAAU;EAC5B,KAAK;EACL,KAAK,gBACJ,OAAO;GACN,QAAQ;GACR,GAAI,QAAQ,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;EACpF;CACF;AACD"}
|
|
1
|
+
{"version":3,"file":"classifyError.js","names":[],"sources":["../../src/surfacing/classifyError.ts"],"sourcesContent":["import {\n\tinvalidQuery,\n\tisHostRefused,\n\tisSourceMisconfigured,\n\trefusedFilter,\n} from '../core/sourceErrors'\nimport { isRecord } from '../core/values'\nimport { BREAKER_MAX_MS } from './breaker'\n\n/**\n * What a failed read means: `invalid_param` refused as asked (no retry, never served stale),\n * `source_misconfigured` set up wrong, `unavailable` down or slow, `rate_limited` scope full.\n */\nexport type ReadFailureKind =\n\t| 'invalid_param'\n\t| 'source_misconfigured'\n\t| 'unavailable'\n\t| 'rate_limited'\n\nexport interface ReadFailure {\n\tkind: ReadFailureKind\n\t/** The source's host is refused: unlisted, private, or not https. */\n\thostRefused?: true\n\t/** The read ran out of time, so trying it again at once cannot help. */\n\ttimeout?: true\n\t/** Refused as too big before it ran: the source answered, so the breaker sees an answer. */\n\trefused?: true\n\t/** The source's quota is spent, so trying it again at once cannot help either. */\n\tquota?: true\n\t/**\n\t * How long until the same read can succeed, when the source or the plugin knows: never longer\n\t * than the breaker's longest wait, whatever a vendor's `Retry-After` asked.\n\t */\n\tretryAfterMs?: number\n\t/** The parameter at fault, set on an `invalid_param` the plugin itself raised. */\n\tparam?: string\n\t/** A message safe to show, set on an `invalid_param` the plugin itself raised. */\n\tmessage?: string\n}\n\n/** Reason message the engine's own read-timeout abort uses. */\nexport const PROVIDER_READ_TIMEOUT_MESSAGE = 'analytics: provider read timed out'\n\nconst READ_FAILED: unique symbol = Symbol.for('@10x-media/analytics/readFailed')\n\nconst LANE_REFUSED: unique symbol = Symbol.for('@10x-media/analytics/laneRefused')\n\n/**\n * A read that failed, already classified. The engine throws it with the source's own error as its\n * `cause`, so the cause-chain readers (`refusedFilter`, `isHostRefused`) keep working through it.\n */\nexport class ReadFailedError extends Error {\n\treadonly [READ_FAILED] = true\n\treadonly failure: ReadFailure\n\n\tconstructor(failure: ReadFailure, cause?: unknown) {\n\t\t// The cause's own message rides along for the logs; no endpoint ever answers with it.\n\t\tsuper(\n\t\t\t`analytics: read failed (${failure.kind})${cause instanceof Error ? `: ${cause.message}` : ''}`,\n\t\t\tcause === undefined ? undefined : { cause }\n\t\t)\n\t\tthis.name = 'ReadFailedError'\n\t\tthis.failure = failure\n\t}\n}\n\n/**\n * A lane that would not start a request (breaker open, or `Retry-After` past the read's deadline);\n * never sent, so never a failure. `opened` lets a source rested for its setup keep saying so.\n */\nexport class LaneRefusedError extends Error {\n\treadonly [LANE_REFUSED] = true\n\treadonly retryAfterMs: number\n\treadonly reason: 'open' | 'paused'\n\treadonly opened?: ReadFailure\n\n\tconstructor(reason: 'open' | 'paused', retryAfterMs: number, opened?: ReadFailure) {\n\t\tsuper(\n\t\t\treason === 'open'\n\t\t\t\t? 'analytics: the source failed too often and is rested for now'\n\t\t\t\t: 'analytics: the source asked to be left alone for now'\n\t\t)\n\t\tthis.name = 'LaneRefusedError'\n\t\tthis.reason = reason\n\t\tthis.retryAfterMs = retryAfterMs\n\t\tif (opened) {\n\t\t\tthis.opened = opened\n\t\t}\n\t}\n}\n\n/** A cold read refused: its scope already has `cache.concurrency.perScope` reads waiting. */\nexport class ScopeBusyError extends Error {\n\treadonly retryAfterMs: number\n\n\tconstructor(retryAfterMs: number) {\n\t\tsuper('analytics: this scope has too many reads waiting on their sources')\n\t\tthis.name = 'ScopeBusyError'\n\t\tthis.retryAfterMs = retryAfterMs\n\t}\n}\n\nexport const isLaneRefused = (err: unknown): err is LaneRefusedError =>\n\tisRecord(err) && Reflect.get(err, LANE_REFUSED) === true\n\nconst isReadFailed = (err: unknown): err is ReadFailedError =>\n\tisRecord(err) && Reflect.get(err, READ_FAILED) === true\n\n/**\n * Statuses that refuse the request as it was sent (bad, too large, its URI or headers too long):\n * the read is the caller's to change, and the source's setup is not at fault.\n */\nconst HTTP_INVALID: ReadonlySet<number> = new Set([400, 413, 414, 422, 431])\n\n/** What an HTTP status from a vendor means for the read. */\nexport const httpStatusKind = (status: number): ReadFailureKind => {\n\tif (HTTP_INVALID.has(status)) return 'invalid_param'\n\tif (status === 408 || status === 429) return 'unavailable'\n\tif (status >= 400 && status < 500) return 'source_misconfigured'\n\treturn 'unavailable'\n}\n\n/** gRPC status codes (GA4's Data API) that say the request itself is wrong. */\nconst GRPC_INVALID: ReadonlySet<number> = new Set([3])\n\n/** NOT_FOUND, PERMISSION_DENIED, UNAUTHENTICATED: the property or the credentials are wrong. */\nconst GRPC_MISCONFIGURED: ReadonlySet<number> = new Set([5, 7, 16])\n\n/** CANCELLED and DEADLINE_EXCEEDED: the call ran out of the time the read gave it. */\nconst GRPC_TIMEOUT: ReadonlySet<number> = new Set([1, 4])\n\n/** RESOURCE_EXHAUSTED: the quota is spent, which a retry a second later only spends again. */\nconst GRPC_QUOTA = 8\n\n/**\n * Codes the gRPC client sets itself when no answer came (CANCELLED, DEADLINE_EXCEEDED,\n * UNAVAILABLE), with its own words, which can name the address it tried.\n */\nconst GRPC_CLIENT_SIDE: ReadonlySet<number> = new Set([...GRPC_TIMEOUT, 14])\n\n/** What a gRPC status code means for the read; anything not named above is an outage. */\nexport const grpcCodeKind = (code: number): ReadFailureKind => {\n\tif (GRPC_INVALID.has(code)) return 'invalid_param'\n\tif (GRPC_MISCONFIGURED.has(code)) return 'source_misconfigured'\n\treturn 'unavailable'\n}\n\nconst TIMEOUT_NAMES: ReadonlySet<string> = new Set([\n\t'AbortError',\n\t'TimeoutError',\n\t'ReadTimeoutError',\n])\n\nconst numberAt = (value: object, key: string): number | undefined => {\n\tconst found: unknown = Reflect.get(value, key)\n\treturn typeof found === 'number' && Number.isFinite(found) ? found : undefined\n}\n\nconst textAt = (value: object, key: string): string | undefined => {\n\tconst found: unknown = Reflect.get(value, key)\n\treturn typeof found === 'string' ? found : undefined\n}\n\n/** What the plugin answers for a pattern the database's regex dialect refused. */\nconst PATTERN_REFUSED: ReadFailure = {\n\tkind: 'invalid_param',\n\tparam: 'filters',\n\tmessage: \"analytics: the database cannot read this filter's pattern\",\n}\n\n/** A query the database refused as written: the same read fails the same way every time. */\nconst QUERY_REFUSED: ReadFailure = { kind: 'invalid_param' }\n\nconst DATABASE_TIMEOUT: ReadFailure = { kind: 'unavailable', timeout: true }\n\nconst DATABASE_SETUP: ReadFailure = { kind: 'source_misconfigured' }\n\nconst mentionsPattern = (message: string | undefined): boolean =>\n\tmessage !== undefined && /regular expression|\\bregex/i.test(message)\n\n/** Mongo's codes for a `$regex` or `$regexMatch` it cannot compile, and related input errors. */\nconst MONGO_PATTERN_CODES: ReadonlySet<number> = new Set([51091, 51092, 51108, 51111])\nconst MONGO_INPUT_CODES: ReadonlySet<number> = new Set([2, 9, 14, 15, 16, 10334])\nconst MONGO_TIMEOUT_CODES: ReadonlySet<number> = new Set([50, 262])\nconst MONGO_SETUP_CODES: ReadonlySet<number> = new Set([13, 18])\n\nconst mongoFailure = (code: number, message: string | undefined): ReadFailure => {\n\tif (MONGO_PATTERN_CODES.has(code)) return PATTERN_REFUSED\n\tif (MONGO_TIMEOUT_CODES.has(code)) return DATABASE_TIMEOUT\n\tif (MONGO_SETUP_CODES.has(code)) return DATABASE_SETUP\n\tif (MONGO_INPUT_CODES.has(code)) return mentionsPattern(message) ? PATTERN_REFUSED : QUERY_REFUSED\n\treturn { kind: 'unavailable' }\n}\n\n/** Postgres SQLSTATEs a missing table, column, schema or grant raises: the install's to fix. */\nconst POSTGRES_SETUP: ReadonlySet<string> = new Set(['42501', '42P01', '42703', '3F000'])\n\n/**\n * Class 22 (data exception) and 42 (syntax or rule) refuse the statement as written, 54 says it is\n * too complex; 57014 is the statement timeout. Any other class (connections, locks) is transient.\n */\nconst postgresFailure = (sqlState: string): ReadFailure | null => {\n\tif (sqlState === '2201B') return PATTERN_REFUSED\n\tif (sqlState === '57014') return DATABASE_TIMEOUT\n\tif (POSTGRES_SETUP.has(sqlState)) return DATABASE_SETUP\n\tconst sqlClass = sqlState.slice(0, 2)\n\tif (sqlClass === '22' || sqlClass === '42' || sqlClass === '54') return QUERY_REFUSED\n\treturn null\n}\n\nconst SQLITE_TRANSIENT: ReadonlySet<string> = new Set([\n\t'SQLITE_BUSY',\n\t'SQLITE_LOCKED',\n\t'SQLITE_IOERR',\n\t'SQLITE_FULL',\n\t'SQLITE_CANTOPEN',\n\t'SQLITE_NOMEM',\n\t'SQLITE_PROTOCOL',\n\t'SQLITE_CORRUPT',\n\t'SQLITE_NOTADB',\n])\n\nconst sqliteFailure = (code: string, message: string | undefined): ReadFailure => {\n\tconst primary = code.match(/^SQLITE_[A-Z]+/)?.[0] ?? code\n\tif (primary === 'SQLITE_INTERRUPT') return DATABASE_TIMEOUT\n\tif (SQLITE_TRANSIENT.has(primary)) return { kind: 'unavailable' }\n\tif (primary === 'SQLITE_AUTH' || primary === 'SQLITE_PERM') return DATABASE_SETUP\n\tif (\n\t\tprimary === 'SQLITE_ERROR' &&\n\t\tmessage !== undefined &&\n\t\t/no such (table|column)/i.test(message)\n\t) {\n\t\treturn DATABASE_SETUP\n\t}\n\tif (mentionsPattern(message)) return PATTERN_REFUSED\n\tif (\n\t\tprimary === 'SQLITE_ERROR' ||\n\t\tprimary === 'SQLITE_TOOBIG' ||\n\t\tprimary === 'SQLITE_RANGE' ||\n\t\tprimary === 'SQLITE_MISMATCH'\n\t) {\n\t\treturn QUERY_REFUSED\n\t}\n\treturn { kind: 'unavailable' }\n}\n\n/**\n * A database driver's error (Mongo, node-postgres, libsql), read by its own code so a query the\n * database refuses is never taken for an outage, and Mongo's small numeric codes never for gRPC's.\n */\nconst databaseFailure = (link: object): ReadFailure | null => {\n\tconst message = textAt(link, 'message')\n\tconst code: unknown = Reflect.get(link, 'code')\n\tconst name = textAt(link, 'name')\n\tif (\n\t\ttypeof code === 'number' &&\n\t\t(textAt(link, 'codeName') !== undefined || name?.startsWith('Mongo') === true)\n\t) {\n\t\treturn mongoFailure(code, message)\n\t}\n\tif (typeof code !== 'string') {\n\t\treturn null\n\t}\n\tif (/^[0-9A-Z]{5}$/.test(code) && textAt(link, 'severity') !== undefined) {\n\t\treturn postgresFailure(code)\n\t}\n\tif (code.startsWith('SQLITE_')) {\n\t\treturn sqliteFailure(code, message)\n\t}\n\treturn null\n}\n\nconst retryAfterOf = (value: object): { retryAfterMs: number } | Record<string, never> => {\n\tconst retryAfterMs = numberAt(value, 'retryAfterMs')\n\treturn retryAfterMs !== undefined && retryAfterMs >= 0\n\t\t? { retryAfterMs: Math.min(retryAfterMs, BREAKER_MAX_MS) }\n\t\t: {}\n}\n\n/** A link's HTTP status, when it carries one. */\nconst httpStatusAt = (link: object): number | undefined => {\n\tconst status = numberAt(link, 'status')\n\treturn status !== undefined && status >= 100 && status < 600 ? status : undefined\n}\n\n/**\n * A link's gRPC status code, as GA4's client rejects with; Node's own network errors carry string\n * codes, and a DOMException's legacy numeric code means nothing here.\n */\nconst grpcCodeAt = (link: object): number | undefined => {\n\tconst code = link instanceof DOMException ? undefined : numberAt(link, 'code')\n\treturn code !== undefined && Number.isInteger(code) && code >= 1 && code <= 16 ? code : undefined\n}\n\n/** Links of an error's cause chain {@link classifyError} reads at most. */\nconst MAX_CAUSE_DEPTH = 5\n\n/** The signal one link of an error's cause chain carries, or null when it carries none. */\nconst classifyLink = (link: object): ReadFailure | null => {\n\tif (isReadFailed(link)) {\n\t\treturn link.failure\n\t}\n\tif (isLaneRefused(link)) {\n\t\t// A breaker opened by a refused key or host answers as that refusal, not as an outage: the\n\t\t// settings still need changing, and waiting out the rest will not do it.\n\t\treturn link.opened?.kind === 'source_misconfigured'\n\t\t\t? {\n\t\t\t\t\tkind: 'source_misconfigured',\n\t\t\t\t\t...(link.opened.hostRefused ? { hostRefused: true } : {}),\n\t\t\t\t\tretryAfterMs: link.retryAfterMs,\n\t\t\t\t}\n\t\t\t: { kind: 'unavailable', retryAfterMs: link.retryAfterMs }\n\t}\n\tif (link instanceof ScopeBusyError) {\n\t\treturn { kind: 'rate_limited', retryAfterMs: link.retryAfterMs }\n\t}\n\tconst name: unknown = Reflect.get(link, 'name')\n\tconst message: unknown = Reflect.get(link, 'message')\n\tif (name === 'DecryptFailedError') {\n\t\treturn { kind: 'source_misconfigured' }\n\t}\n\tif (\n\t\t(typeof name === 'string' && TIMEOUT_NAMES.has(name)) ||\n\t\tmessage === PROVIDER_READ_TIMEOUT_MESSAGE\n\t) {\n\t\treturn {\n\t\t\tkind: 'unavailable',\n\t\t\ttimeout: true,\n\t\t\t...(Reflect.get(link, 'refused') === true ? { refused: true as const } : {}),\n\t\t}\n\t}\n\tconst status = httpStatusAt(link)\n\tif (status !== undefined) {\n\t\treturn { kind: httpStatusKind(status), ...retryAfterOf(link) }\n\t}\n\tconst database = databaseFailure(link)\n\tif (database) {\n\t\treturn database\n\t}\n\tconst code = grpcCodeAt(link)\n\tif (code !== undefined) {\n\t\treturn {\n\t\t\tkind: grpcCodeKind(code),\n\t\t\t...(GRPC_TIMEOUT.has(code) ? { timeout: true as const } : {}),\n\t\t\t...(code === GRPC_QUOTA ? { quota: true as const } : {}),\n\t\t\t...retryAfterOf(link),\n\t\t}\n\t}\n\treturn null\n}\n\n/**\n * Classifies anything a read can throw: the plugin's own refusals first, anywhere in the cause\n * chain, then the first HTTP status or gRPC code; anything else is presumed `unavailable`.\n */\nexport const classifyError = (err: unknown): ReadFailure => {\n\tif (isReadFailed(err)) {\n\t\treturn err.failure\n\t}\n\tconst filter = refusedFilter(err)\n\tif (filter) {\n\t\treturn {\n\t\t\tkind: 'invalid_param',\n\t\t\tparam: 'filters',\n\t\t\tmessage: `analytics: this source cannot filter ${filter.dimension} with ${filter.operator}`,\n\t\t}\n\t}\n\tconst invalid = invalidQuery(err)\n\tif (invalid) {\n\t\treturn { kind: 'invalid_param', param: invalid.param, message: invalid.message }\n\t}\n\tif (isSourceMisconfigured(err)) {\n\t\treturn { kind: 'source_misconfigured', ...(isHostRefused(err) ? { hostRefused: true } : {}) }\n\t}\n\tlet current: unknown = err\n\tfor (let depth = 0; depth < MAX_CAUSE_DEPTH && isRecord(current); depth++) {\n\t\tconst found = classifyLink(current)\n\t\tif (found) {\n\t\t\treturn found\n\t\t}\n\t\tcurrent = Reflect.get(current, 'cause')\n\t}\n\treturn { kind: 'unavailable' }\n}\n\n/**\n * What the vendor itself said about a failure: the message of the first link in the cause chain\n * that carries an HTTP status or a gRPC code. The plugin's own refusals and the runtime's network\n * errors are not the vendor's words, so a surface shows its own translated text for them instead.\n */\nexport const vendorAnswerOf = (err: unknown): string | undefined => {\n\tlet current: unknown = err\n\tfor (let depth = 0; depth < MAX_CAUSE_DEPTH && isRecord(current); depth++) {\n\t\tconst code = grpcCodeAt(current)\n\t\tconst message: unknown = Reflect.get(current, 'message')\n\t\tif (\n\t\t\ttypeof message === 'string' &&\n\t\t\t(httpStatusAt(current) !== undefined || (code !== undefined && !GRPC_CLIENT_SIDE.has(code)))\n\t\t) {\n\t\t\treturn message\n\t\t}\n\t\tcurrent = Reflect.get(current, 'cause')\n\t}\n\treturn undefined\n}\n\n/**\n * What a surface shows for a failed read; only `busy` (an outage, a timeout or a full queue) is\n * one a retry can fix.\n */\nexport type ReadFailureStatus = 'misconfigured' | 'host-refused' | 'invalid' | 'busy'\n\nexport interface ReadFailureState {\n\tstatus: ReadFailureStatus\n\t/** How long until a retry can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n}\n\n/** A failed read as a surface shows it. */\nexport const readFailureOf = (err: unknown): ReadFailureState => {\n\tconst failure = classifyError(err)\n\tswitch (failure.kind) {\n\t\tcase 'source_misconfigured':\n\t\t\treturn { status: failure.hostRefused ? 'host-refused' : 'misconfigured' }\n\t\tcase 'invalid_param':\n\t\t\treturn { status: 'invalid' }\n\t\tcase 'unavailable':\n\t\tcase 'rate_limited':\n\t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G,IAAI,EAAE,aAAa,KAAK,IAAI,CAAC;CAAG;CAE7F,IAAI,UAAmB;CACvB,KAAK,IAAI,QAAQ,GAAG,QAAQ,mBAAmB,SAAS,OAAO,GAAG,SAAS;EAC1E,MAAM,QAAQ,aAAa,OAAO;EAClC,IAAI,OACH,OAAO;EAER,UAAU,QAAQ,IAAI,SAAS,OAAO;CACvC;CACA,OAAO,EAAE,MAAM,cAAc;AAC9B;;;;;;AAOA,MAAa,kBAAkB,QAAqC;CACnE,IAAI,UAAmB;CACvB,KAAK,IAAI,QAAQ,GAAG,QAAQ,mBAAmB,SAAS,OAAO,GAAG,SAAS;EAC1E,MAAM,OAAO,WAAW,OAAO;EAC/B,MAAM,UAAmB,QAAQ,IAAI,SAAS,SAAS;EACvD,IACC,OAAO,YAAY,aAClB,aAAa,OAAO,MAAM,KAAA,KAAc,SAAS,KAAA,KAAa,CAAC,iBAAiB,IAAI,IAAI,IAEzF,OAAO;EAER,UAAU,QAAQ,IAAI,SAAS,OAAO;CACvC;AAED;;AAeA,MAAa,iBAAiB,QAAmC;CAChE,MAAM,UAAU,cAAc,GAAG;CACjC,QAAQ,QAAQ,MAAhB;EACC,KAAK,wBACJ,OAAO,EAAE,QAAQ,QAAQ,cAAc,iBAAiB,gBAAgB;EACzE,KAAK,iBACJ,OAAO,EAAE,QAAQ,UAAU;EAC5B,KAAK;EACL,KAAK,gBACJ,OAAO;GACN,QAAQ;GACR,GAAI,QAAQ,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;EACpF;CACF;AACD"}
|
package/dist/surfacing/engine.js
CHANGED
|
@@ -337,7 +337,7 @@ function createEngine(opts) {
|
|
|
337
337
|
} catch (err) {
|
|
338
338
|
const failure = classifyError(err);
|
|
339
339
|
failures.set(key, failure, FAILURE_MEMO_MS);
|
|
340
|
-
if (!isLaneRefused(err)) opts.onError?.(err, adapter.id);
|
|
340
|
+
if (!isLaneRefused(err)) opts.onError?.(err, adapter.id, scope);
|
|
341
341
|
throw new ReadFailedError(withLaneRetryAfter(failure, lanes.for(adapter, scope).health()), err);
|
|
342
342
|
}
|
|
343
343
|
failures.delete(key);
|
|
@@ -523,7 +523,7 @@ function createEngine(opts) {
|
|
|
523
523
|
scope
|
|
524
524
|
}));
|
|
525
525
|
} catch (err) {
|
|
526
|
-
if (!isLaneRefused(err)) opts.onError?.(err, adapter.id);
|
|
526
|
+
if (!isLaneRefused(err)) opts.onError?.(err, adapter.id, scope);
|
|
527
527
|
throw new ReadFailedError(withLaneRetryAfter(classifyError(err), lanes.for(adapter, scope).health()), err);
|
|
528
528
|
}
|
|
529
529
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.js","names":[],"sources":["../../src/surfacing/engine.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { OVER_BUDGET, withinBudget } from '../core/budget'\nimport { buildCacheKey, type CacheKeyEpochs } from '../core/cacheKey'\nimport { unsupportedFilter } from '../core/capabilities'\nimport { currentTime } from '../core/clock'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tSourceErrorKind,\n} from '../core/contract'\nimport { monotonicMs } from '../core/monotonic'\nimport { UnsupportedFilterError } from '../core/sourceErrors'\nimport { earlierInstant, isRecord } from '../core/values'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DAY_MS, DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\nimport type { AfterReadAnswer, AfterReadHook, ReadOrigin } from './afterRead'\nimport {\n\ttype CacheEntry,\n\ttype CacheStore,\n\tisCachedResult,\n\ttype ReadRecipe,\n\tSTALE_WINDOW_SECONDS,\n} from './cacheStore'\nimport {\n\tclassifyError,\n\tisLaneRefused,\n\tPROVIDER_READ_TIMEOUT_MESSAGE,\n\tReadFailedError,\n\ttype ReadFailure,\n\tScopeBusyError,\n} from './classifyError'\nimport { createCoalescer } from './coalesce'\nimport { BUSY_RETRY_AFTER_MS, createColdBudget, DEFAULT_COLD_READS_PER_SCOPE } from './coldBudget'\nimport { type EpochSources, epochsFor } from './epoch'\nimport { createLanes, type LaneHealth, type Lanes, type Priority, runUpstream } from './lanes'\nimport { AGGREGATE_MEMO_MS, createMemo, type Memo } from './memo'\nimport { dayRead, foldResult, type RebucketPlan, rebucketPlan } from './rebucket'\nimport { RECIPE_WINDOWS, recipeWindow } from './recipe'\nimport { shapeResult } from './shape'\nimport { mergeAtToday, splitAtToday } from './todaySplit'\n\n/** How often a read carrying a recipe stamps the entry it was served as read. */\nconst TOUCH_EVERY_MS = 3_600_000\n\n/** How long a key's last failed refresh is remembered, to word or refuse its stale answers. */\nconst FAILURE_MEMO_MS = 60_000\n\n/** How long a peek waits on the store before it answers that nothing is there. */\nexport const PEEK_BUDGET_MS = 150\n\n/** How long a read waits on the store before reading the source as if nothing were cached. */\nconst STORE_GET_BUDGET_MS = 1_000\n\n/** An instant a store handed back: finite epoch milliseconds. */\nconst isInstant = (value: unknown): value is number =>\n\ttypeof value === 'number' && Number.isFinite(value)\n\n/** Whether an entry's instants are what the store contract says: finite epoch milliseconds. */\nconst hasInstants = (entry: CacheEntry): boolean =>\n\tisInstant(entry.fetchedAt) &&\n\tisInstant(entry.expiresAt) &&\n\tisInstant(entry.staleUntil) &&\n\t(entry.readAt === undefined || entry.readAt === null || isInstant(entry.readAt))\n\n/**\n * The clock deadlines, waits and durations run on: the one timers run on. The cache clock (`now`)\n * may be moved by a test, or by Payload's job-system globals, without any timer moving with it.\n */\nconst timerNow = monotonicMs\n\n/**\n * The window a source is asked for, from its lookback on; one that declares none still starts no\n * earlier than 1970, before which nothing was counted, so no read walks centuries of days.\n */\nconst clampRange = (\n\trange: AnalyticsQuery['dateRange'],\n\tmaxLookbackDays: number | null,\n\ttz: string = DEFAULT_TIMEZONE\n): { range: AnalyticsQuery['dateRange']; clamped: boolean } => {\n\tconst floor =\n\t\tmaxLookbackDays == null ? 0 : startOfDayInTz(range.end, tz).getTime() - maxLookbackDays * DAY_MS\n\tif (range.start.getTime() >= floor) {\n\t\treturn { range, clamped: false }\n\t}\n\treturn { range: { start: new Date(floor), end: range.end }, clamped: true }\n}\n\n/**\n * A breakdown cut by `limit` with no `order` asks its source for its first metric's top rows: a\n * source ranking by anything else would hand over a subset the engine cannot rank back.\n */\nconst rankedQuery = (query: AnalyticsQuery): AnalyticsQuery => {\n\tconst metric = query.metrics[0]\n\treturn query.limit !== undefined &&\n\t\tquery.order === undefined &&\n\t\t(query.dimensions?.length ?? 0) > 0 &&\n\t\tmetric !== undefined\n\t\t? { ...query, order: { metric, direction: 'desc' } }\n\t\t: query\n}\n\nexport type CacheOperation = 'get' | 'set' | 'touch'\n\nexport interface EngineOptions {\n\tstore: CacheStore\n\t/** The instance's in-process memo; a private one of the default size when absent. */\n\tmemo?: Memo<AnalyticsResult>\n\t/** Lanes reads reach their sources through; a private set with default caps when absent. */\n\tlanes?: Lanes\n\t/** Cold reads one scope may have waiting on its sources at once; default 8. */\n\tcoldReadsPerScope?: number\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/**\n\t * Budget for one fetch from a source, every wait and retry included; the request in flight is\n\t * aborted past it.\n\t */\n\ttimeoutMs: number\n\t/** Called once per failed fetch, before falling back to a stale cache entry. */\n\tonError?: (err: unknown, adapterId: string) => void\n\t/** Called when the store fails; the read carries on as if the entry were absent or unwritten. */\n\tonStoreError?: (err: unknown, operation: CacheOperation) => void\n\t/** Called after each value the store accepted. */\n\tonWrite?: () => void\n\t/**\n\t * The scope's refresh epoch, which every key carries. Absent, every read keys on the initial\n\t * token.\n\t */\n\tepoch?: EpochSources['refresh']\n\t/** The scope's configuration epoch, which every key carries; absent, a fixed one. */\n\tconfigEpoch?: EpochSources['config']\n\t/** The instance every read is for, handed to adapters as `AdapterContext.payload`. */\n\tpayload?: Payload\n\t/** Epoch milliseconds; the plugin's clock (`currentDate`) by default. */\n\tnow?: () => number\n\t/**\n\t * Keeps a background refresh running past the response that started it: Next's `after()` inside\n\t * a request. The engine tracks every refresh itself as well, so `idle()` waits for all of them.\n\t */\n\tkeepAlive?: (work: Promise<unknown>) => void | Promise<void>\n\t/** `hooks.afterRead`, run only on an engine built with `payload`, which the hook is handed. */\n\tafterRead?: AfterReadHook\n\t/** Told each time the hook throws; the read is answered as if it had returned nothing. */\n\tonHookError?: (err: unknown) => void\n\t/** Called as each read starts, before anything is looked up. */\n\tonRead?: () => void\n}\n\nexport interface ReadOptions {\n\t/**\n\t * False waits for an expired entry's refresh instead of answering with it, falling back to it\n\t * only when the refresh fails; for work that keeps what it reads (sync). Default true.\n\t */\n\tallowStale?: boolean\n\t/**\n\t * The named timeframe the read's window came from; when the window is that preset's as of now,\n\t * the read's recipe is stored with its entry so the warm task keeps it warm.\n\t */\n\ttimeframe?: TimeframePreset\n\t/**\n\t * `interactive` for an open panel or view, served first; `background` for work nobody waits on,\n\t * held to half a source's slots like every refresh. Default `normal`.\n\t */\n\tpriority?: Priority\n\t/**\n\t * On a full scope (`coldReadsPerScope`) a cold read waits within `timeoutMs` (default), or with\n\t * `refuse` fails at once as `rate_limited`; a read matching one already waiting joins it anyway.\n\t */\n\twhenBusy?: 'wait' | 'refuse'\n\t/**\n\t * False answers without `hooks.afterRead`: work that keeps what it reads (sync) stores the\n\t * source's own answer, never what the hook made of it for one reader. Default true.\n\t */\n\tafterRead?: boolean\n}\n\nexport interface RefreshOptions {\n\t/** An entry still fresh for this many more milliseconds is left as it is. */\n\tfreshForMs: number\n\t/** Default `background`. */\n\tpriority?: Priority\n}\n\n/** What a refresh did: left an entry fresh enough, or read the source again and stored it. */\nexport type RefreshOutcome = 'fresh' | 'refreshed'\n\nexport interface PeekOptions {\n\t/** Milliseconds the memo and the store may take to answer; default {@link PEEK_BUDGET_MS}. */\n\tbudgetMs?: number\n}\n\nexport interface Engine {\n\tread(\n\t\tadapter: AnalyticsAdapter,\n\t\tquery: AnalyticsQuery,\n\t\toptions?: ReadOptions\n\t): Promise<AnalyticsResult>\n\t/**\n\t * The warm task's read: re-reads `query` and stores the answer unless its entry stays fresh for\n\t * `freshForMs` more, never touching its recipe or read time. Absent when nothing caches.\n\t */\n\trefresh?(\n\t\tadapter: AnalyticsAdapter,\n\t\tquery: AnalyticsQuery,\n\t\toptions: RefreshOptions\n\t): Promise<RefreshOutcome>\n\t/**\n\t * What a read would answer from memory or the store, never asking the source or refreshing;\n\t * undefined when neither holds it within the budget. Absent on an engine that caches nothing.\n\t */\n\tpeek?(\n\t\tadapter: AnalyticsAdapter,\n\t\tquery: AnalyticsQuery,\n\t\toptions?: PeekOptions\n\t): Promise<AnalyticsResult | undefined>\n\t/**\n\t * A live count from the adapter's `realtime`, through its lane at interactive priority and\n\t * within the read timeout; never cached here. Absent on an engine without lanes.\n\t */\n\trealtime?(adapter: AnalyticsAdapter, query: AnalyticsQuery): Promise<AnalyticsResult>\n\t/** Settles once every background refresh has finished; absent on one starting none. */\n\tidle?(): Promise<void>\n\t/**\n\t * Keeps `work` a caller stopped waiting for running past the response, counted until it settles\n\t * so `idle()` and `close()` wait for it. Absent on an engine starting no background work.\n\t */\n\tkeep?(work: Promise<unknown>): void\n\t/**\n\t * Starts no background work from now on (refreshes, cache writes) and settles what is running:\n\t * the runtime holding the engine is retired. Reads still answer.\n\t */\n\tclose?(): Promise<void>\n\t/**\n\t * The state of the lane an adapter's reads go through for `scope`; absent on an engine without\n\t * lanes.\n\t */\n\thealth?(adapter: AnalyticsAdapter, scope?: string | null): LaneHealth\n}\n\n/**\n * An adapter drops a filter it cannot apply and answers unfiltered, which would read as filtered\n * numbers: every caller gates first, and this is the gate behind them all.\n */\nconst checkFilters = (adapter: AnalyticsAdapter, query: AnalyticsQuery): void => {\n\tconst refused = unsupportedFilter(adapter.capabilities, query.filters ?? [])\n\tif (refused) {\n\t\tthrow new UnsupportedFilterError(adapter.id, refused)\n\t}\n}\n\n/** A hook's answer that replaces the read's, rather than nothing. */\nconst replaces = (answer: AfterReadAnswer): answer is AnalyticsResult => isRecord(answer)\n\nconst emptyResult = (provider: string, at: number): AnalyticsResult => ({\n\trows: [],\n\tmeta: { provider, fetchedAt: new Date(at).toISOString() },\n})\n\n/** `result` with `meta.fetchedAt` no later than `answeredAt`, replacing a later or bad one. */\nconst readAt = (result: AnalyticsResult, answeredAt: number): AnalyticsResult => {\n\tconst stamped = Date.parse(result.meta.fetchedAt)\n\treturn Number.isFinite(stamped) && stamped <= answeredAt\n\t\t? result\n\t\t: { ...result, meta: { ...result.meta, fetchedAt: new Date(answeredAt).toISOString() } }\n}\n\n/** An expired entry as served: stale, dated to its fetch, and why its source needs a look. */\nconst staleResult = (entry: CacheEntry, sourceError?: SourceErrorKind): AnalyticsResult => ({\n\t...entry.value,\n\tmeta: {\n\t\t...entry.value.meta,\n\t\tstale: true,\n\t\tasOf: earlierInstant(entry.value.meta.asOf, new Date(entry.fetchedAt).toISOString()),\n\t\t...(sourceError ? { sourceError } : {}),\n\t},\n})\n\n/**\n * Why a stale answer's source needs a look: the key's own last failure when there is one, else the\n * failure its lane last counted, but only a failure about setup, never an outage.\n */\nconst sourceErrorOf = (\n\tfailure: ReadFailure | undefined,\n\thealth: LaneHealth\n): SourceErrorKind | undefined => {\n\tif (failure) {\n\t\tif (failure.kind !== 'source_misconfigured') {\n\t\t\treturn undefined\n\t\t}\n\t\treturn failure.hostRefused ? 'host-refused' : 'misconfigured'\n\t}\n\tif (health.lastFailure !== 'source_misconfigured') {\n\t\treturn undefined\n\t}\n\treturn health.hostRefused ? 'host-refused' : 'misconfigured'\n}\n\n/** A failure as it is thrown: an outage says how long to wait when its lane knows. */\nconst withLaneRetryAfter = (failure: ReadFailure, health: LaneHealth): ReadFailure =>\n\tfailure.kind === 'unavailable' &&\n\tfailure.retryAfterMs === undefined &&\n\thealth.retryAfterMs !== undefined\n\t\t? { ...failure, retryAfterMs: health.retryAfterMs }\n\t\t: failure\n\n/** What a peek found kept for a query, and where. */\ninterface Kept {\n\tq: AnalyticsQuery\n\tresult: AnalyticsResult\n\tfrom: ReadOrigin\n}\n\n/** One read made ready: its query as keyed, the request its source gets, and its cache key. */\ninterface Prepared {\n\t/** The query as asked, its window clamped to the source's lookback. */\n\tq: AnalyticsQuery\n\tclamped: boolean\n\trange: AnalyticsQuery['dateRange']\n\tplan: RebucketPlan | undefined\n\t/** What the adapter is asked: the query, or its days where weeks or months are folded here. */\n\tadapterQuery: AnalyticsQuery\n\tepochs: CacheKeyEpochs\n\tkey: string\n}\n\nexport function createEngine(opts: EngineOptions): Required<Engine> {\n\tconst now = opts.now ?? currentTime\n\tconst memo = opts.memo ?? createMemo<AnalyticsResult>({ now })\n\tconst failures = createMemo<ReadFailure>({ now })\n\tconst coalesce = createCoalescer<AnalyticsResult>()\n\tconst lanes = opts.lanes ?? createLanes()\n\tconst budget = createColdBudget(opts.coldReadsPerScope ?? DEFAULT_COLD_READS_PER_SCOPE)\n\tconst background = new Set<Promise<unknown>>()\n\tconst storeGetMs = Math.min(STORE_GET_BUDGET_MS, opts.timeoutMs)\n\tlet closed = false\n\n\t/**\n\t * The store's entry for `key`, or null: a store that fails, answers past\n\t * {@link STORE_GET_BUDGET_MS} or breaks the entry contract is reported and read as a miss.\n\t */\n\tconst cached = async (key: string): Promise<CacheEntry | null> => {\n\t\tlet entry: CacheEntry | null | typeof OVER_BUDGET\n\t\ttry {\n\t\t\tentry = await withinBudget(opts.store.get(key), storeGetMs)\n\t\t} catch (err) {\n\t\t\topts.onStoreError?.(err, 'get')\n\t\t\treturn null\n\t\t}\n\t\tif (entry === OVER_BUDGET) {\n\t\t\topts.onStoreError?.(\n\t\t\t\tnew Error(`analytics: the read cache did not answer within ${storeGetMs} ms`),\n\t\t\t\t'get'\n\t\t\t)\n\t\t\treturn null\n\t\t}\n\t\tif (!entry || !isCachedResult(entry.value)) {\n\t\t\treturn null\n\t\t}\n\t\tif (!hasInstants(entry)) {\n\t\t\topts.onStoreError?.(\n\t\t\t\tnew Error(\n\t\t\t\t\t'analytics: the read cache answered an entry whose fetchedAt, expiresAt or staleUntil is not a finite number of milliseconds'\n\t\t\t\t),\n\t\t\t\t'get'\n\t\t\t)\n\t\t\treturn null\n\t\t}\n\t\treturn entry\n\t}\n\n\t/** Tracks `work` until it settles, keeping it alive past the response; answers once settled. */\n\tconst inBackground = (work: Promise<unknown>): Promise<void> => {\n\t\tconst settled = work.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined\n\t\t)\n\t\tbackground.add(settled)\n\t\tvoid settled.finally(() => background.delete(settled))\n\t\ttry {\n\t\t\tconst kept = opts.keepAlive?.(settled)\n\t\t\tif (kept instanceof Promise) {\n\t\t\t\tkept.catch(() => {})\n\t\t\t}\n\t\t} catch {\n\t\t\t// Outside a request there is nothing to keep alive; the engine's own tracking still holds it.\n\t\t}\n\t\treturn settled\n\t}\n\n\tconst idle = async (): Promise<void> => {\n\t\twhile (background.size > 0) {\n\t\t\tawait Promise.all([...background])\n\t\t}\n\t}\n\n\t/** Writes an answer to the store, never failing the read: a store that fails is reported. */\n\tconst store = async (\n\t\tkey: string,\n\t\tresult: AnalyticsResult,\n\t\toptions: Parameters<CacheStore['set']>[2]\n\t): Promise<void> => {\n\t\ttry {\n\t\t\tawait opts.store.set(key, result, options)\n\t\t\topts.onWrite?.()\n\t\t} catch (err) {\n\t\t\topts.onStoreError?.(err, 'set')\n\t\t}\n\t}\n\n\t/**\n\t * One call to the source through the adapter's lane: per request when the adapter sends through\n\t * `upstream`, else one token and slot for the whole call.\n\t */\n\tconst throughLane = (\n\t\tadapter: AnalyticsAdapter,\n\t\tcall: (ctx: AdapterContext) => Promise<AnalyticsResult>,\n\t\trun: { signal: AbortSignal; priority: Priority; deadline: number; scope: string | null }\n\t): Promise<AnalyticsResult> => {\n\t\tconst lane = lanes.for(adapter, run.scope)\n\t\tconst options = { ...run, now: timerNow }\n\t\tconst base: AdapterContext = {\n\t\t\t...(opts.payload ? { payload: opts.payload } : {}),\n\t\t\tsignal: run.signal,\n\t\t\tnow: () => new Date(now()),\n\t\t\tremainingMs: () => Math.max(0, run.deadline - timerNow()),\n\t\t}\n\t\tif (adapter.capabilities.upstreamAware) {\n\t\t\treturn call({\n\t\t\t\t...base,\n\t\t\t\tupstream: <T>(fn: (signal?: AbortSignal) => Promise<T>) => runUpstream(lane, fn, options),\n\t\t\t})\n\t\t}\n\t\treturn runUpstream(\n\t\t\tlane,\n\t\t\t(signal) =>\n\t\t\t\tcall({\n\t\t\t\t\t...base,\n\t\t\t\t\tsignal,\n\t\t\t\t\tupstream: <T>(fn: (signal?: AbortSignal) => Promise<T>) => fn(signal),\n\t\t\t\t}),\n\t\t\toptions\n\t\t)\n\t}\n\n\t/** Runs `hooks.afterRead` on one answer; a hook that throws answers as if it returned nothing. */\n\tconst answered = async (args: {\n\t\tadapter: AnalyticsAdapter\n\t\tq: AnalyticsQuery\n\t\tresult: AnalyticsResult\n\t\tfrom: ReadOrigin\n\t\tstartedAt: number\n\t}): Promise<AnalyticsResult> => {\n\t\tconst { afterRead: hook, payload } = opts\n\t\tif (!hook || !payload) {\n\t\t\treturn args.result\n\t\t}\n\t\ttry {\n\t\t\tconst adjusted = await hook({\n\t\t\t\tadapterId: args.adapter.id,\n\t\t\t\tquery: args.q,\n\t\t\t\tresult: args.result,\n\t\t\t\tfrom: args.from,\n\t\t\t\tdurationMs: Math.max(0, timerNow() - args.startedAt),\n\t\t\t\tpayload,\n\t\t\t})\n\t\t\treturn replaces(adjusted) ? adjusted : args.result\n\t\t} catch (err) {\n\t\t\topts.onHookError?.(err)\n\t\t\treturn args.result\n\t\t}\n\t}\n\n\t/**\n\t * Settles with `work` or rejects after `timeoutMs`, aborting the signal; the race also bounds an\n\t * adapter that never checks it. Lane slots return once the request settles or is abandoned.\n\t */\n\tconst withinTimeout = async <T>(\n\t\twork: (run: { signal: AbortSignal; deadline: number }) => Promise<T>\n\t): Promise<T> => {\n\t\tconst controller = new AbortController()\n\t\tconst deadline = timerNow() + opts.timeoutMs\n\t\tconst timer = setTimeout(\n\t\t\t() => controller.abort(new Error(PROVIDER_READ_TIMEOUT_MESSAGE)),\n\t\t\topts.timeoutMs\n\t\t)\n\t\ttimer.unref?.()\n\t\ttry {\n\t\t\tconst aborted = new Promise<never>((_resolve, reject) => {\n\t\t\t\tcontroller.signal.addEventListener('abort', () => reject(controller.signal.reason), {\n\t\t\t\t\tonce: true,\n\t\t\t\t})\n\t\t\t})\n\t\t\tconst attempt = work({ signal: controller.signal, deadline })\n\t\t\tattempt.catch(() => {})\n\t\t\taborted.catch(() => {})\n\t\t\treturn await Promise.race([attempt, aborted])\n\t\t} finally {\n\t\t\tclearTimeout(timer)\n\t\t}\n\t}\n\n\tconst prepare = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tquery: AnalyticsQuery,\n\t\tknown?: CacheKeyEpochs\n\t): Promise<Prepared> => {\n\t\tconst { range, clamped } = clampRange(\n\t\t\tquery.dateRange,\n\t\t\tadapter.capabilities.maxLookbackDays,\n\t\t\tquery.timezone\n\t\t)\n\t\tconst ranked = rankedQuery(query)\n\t\tconst q = range === query.dateRange ? ranked : { ...ranked, dateRange: range }\n\t\t// Weeks and months are folded here from days, exactly the same way for every source\n\t\t// that cannot answer them itself; the cache keys on the bucket the caller asked for.\n\t\tconst plan = rebucketPlan(q, adapter.capabilities)\n\t\tconst adapterQuery = plan ? dayRead(q, plan) : q\n\t\t// Resolved before the key so the coalescer key carries the epochs too: two reads\n\t\t// across a bump must not share one in-flight answer.\n\t\tconst epochs =\n\t\t\tknown ?? (await epochsFor({ refresh: opts.epoch, config: opts.configEpoch }, q.scope))\n\t\treturn {\n\t\t\tq,\n\t\t\tclamped,\n\t\t\trange,\n\t\t\tplan,\n\t\t\tadapterQuery,\n\t\t\tepochs,\n\t\t\tkey: buildCacheKey(adapter.id, q, epochs),\n\t\t}\n\t}\n\n\t/** The instant today began in the read's zone. */\n\tconst todayStart = (q: AnalyticsQuery): number =>\n\t\tstartOfDayInTz(new Date(now()), q.timezone ?? DEFAULT_TIMEZONE).getTime()\n\n\t/**\n\t * How long the source's answer for `q` stays fresh, when the source bounds a window reaching into\n\t * the current day (native's `recommendedTtl.today`); undefined for every other read.\n\t */\n\tconst todayTtl = (adapter: AnalyticsAdapter, q: AnalyticsQuery): number | undefined => {\n\t\tconst bound = adapter.capabilities.recommendedTtl.today\n\t\tif (bound === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn q.dateRange.end.getTime() >= todayStart(q) ? bound : undefined\n\t}\n\n\t/** Holds a fresh store entry in memory until it expires, at most {@link AGGREGATE_MEMO_MS}. */\n\tconst memoizeEntry = (key: string, entry: CacheEntry, at: number): void => {\n\t\tmemo.set(key, entry.value, Math.min(AGGREGATE_MEMO_MS, entry.expiresAt - at))\n\t}\n\n\t/**\n\t * The read's recipe when its window is its timeframe's as of now, matched on the key a recipe\n\t * replayed now would read: the window as the key cuts it, after the same clamp.\n\t */\n\tconst recipeOf = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tprepared: Prepared,\n\t\ttimeframe: TimeframePreset | undefined\n\t): Promise<ReadRecipe | undefined> => {\n\t\tif (timeframe === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst at = new Date(now())\n\t\tconst { q } = prepared\n\t\tconst tz = q.timezone ?? DEFAULT_TIMEZONE\n\t\tconst { dateRange: _window, ...rest } = q\n\t\t// MongoDB stores an absent field as null, which a replay would then key on.\n\t\tfor (const key of Object.keys(rest)) {\n\t\t\tif (Reflect.get(rest, key) === undefined) {\n\t\t\t\tReflect.deleteProperty(rest, key)\n\t\t\t}\n\t\t}\n\t\tfor (const window of RECIPE_WINDOWS) {\n\t\t\tconst candidate = recipeWindow({ timeframe, window }, at, tz)\n\t\t\tif (!candidate) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst replayed = await prepare(adapter, { ...q, dateRange: candidate }, prepared.epochs)\n\t\t\tif (replayed.key === prepared.key) {\n\t\t\t\treturn { adapterRef: adapter.id, scope: q.scope ?? null, timeframe, window, query: rest }\n\t\t\t}\n\t\t}\n\t\treturn undefined\n\t}\n\n\t/**\n\t * Reads the source within the read timeout, memoizes and stores the answer (before answering\n\t * with `awaitStore`); a failure is remembered for a minute and thrown classified.\n\t */\n\tconst fetchFresh = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tprepared: Prepared,\n\t\trun: {\n\t\t\tpriority: Priority\n\t\t\tgate?: (signal: AbortSignal) => Promise<() => void>\n\t\t\trecipe?: ReadRecipe\n\t\t\tawaitStore?: boolean\n\t\t}\n\t): Promise<AnalyticsResult> => {\n\t\tconst { key, q, plan, clamped, range } = prepared\n\t\tconst scope = q.scope ?? null\n\t\tlet fresh: AnalyticsResult\n\t\ttry {\n\t\t\tfresh = await withinTimeout(async ({ signal, deadline }) => {\n\t\t\t\tconst release = await run.gate?.(signal)\n\t\t\t\ttry {\n\t\t\t\t\treturn await throughLane(adapter, (ctx) => adapter.query(prepared.adapterQuery, ctx), {\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tpriority: run.priority,\n\t\t\t\t\t\tdeadline,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t})\n\t\t\t\t} finally {\n\t\t\t\t\trelease?.()\n\t\t\t\t}\n\t\t\t})\n\t\t} catch (err) {\n\t\t\tconst failure = classifyError(err)\n\t\t\tfailures.set(key, failure, FAILURE_MEMO_MS)\n\t\t\t// A lane refusal sent nothing: the failure that opened or paused the lane was told already.\n\t\t\tif (!isLaneRefused(err)) {\n\t\t\t\topts.onError?.(err, adapter.id)\n\t\t\t}\n\t\t\tthrow new ReadFailedError(\n\t\t\t\twithLaneRetryAfter(failure, lanes.for(adapter, scope).health()),\n\t\t\t\terr\n\t\t\t)\n\t\t}\n\t\tfailures.delete(key)\n\t\tconst answered = readAt(fresh, now())\n\t\tconst folded = plan ? foldResult(answered, q, plan) : answered\n\t\tconst shaped = shapeResult(folded, q)\n\t\tconst result: AnalyticsResult = clamped\n\t\t\t? {\n\t\t\t\t\t...shaped,\n\t\t\t\t\tmeta: { ...shaped.meta, clamped: true, dataFrom: range.start.toISOString() },\n\t\t\t\t}\n\t\t\t: shaped\n\t\t// Each passes (a failed goal resolver, a stand-in zone, days still being counted) and would\n\t\t// stay pinned for the aggregate TTL; a capped read stays capped, so it keeps that TTL.\n\t\tconst degraded =\n\t\t\tresult.meta.goalsUnresolved === true ||\n\t\t\tresult.meta.timezoneUnresolved === true ||\n\t\t\t(result.meta.partial?.missingDays ?? 0) > 0\n\t\tconst kept = degraded\n\t\t\t? (opts.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime)\n\t\t\t: (opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate)\n\t\tconst today = todayTtl(adapter, q)\n\t\tconst ttl = today === undefined ? kept : Math.min(kept, today)\n\t\tmemo.set(key, result, Math.min(AGGREGATE_MEMO_MS, ttl * 1000))\n\t\t// A store that is slow or hangs never holds up an answer the source already gave, nor `idle()`\n\t\t// past the read timeout.\n\t\tif (!closed) {\n\t\t\tconst write = store(key, result, {\n\t\t\t\tttlSeconds: ttl,\n\t\t\t\tstaleSeconds: STALE_WINDOW_SECONDS,\n\t\t\t\t...(q.scope === undefined ? {} : { scope: q.scope }),\n\t\t\t\t...(run.recipe ? { recipe: run.recipe } : {}),\n\t\t\t})\n\t\t\tconst stored = inBackground(\n\t\t\t\twithinBudget(write, opts.timeoutMs).then((done) => {\n\t\t\t\t\tif (done === OVER_BUDGET) {\n\t\t\t\t\t\topts.onStoreError?.(\n\t\t\t\t\t\t\tnew Error(`analytics: the read cache did not store within ${opts.timeoutMs} ms`),\n\t\t\t\t\t\t\t'set'\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\tif (run.awaitStore) {\n\t\t\t\tawait stored\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\n\t/** One read's answer as kept or fetched, and where it came from, before `hooks.afterRead`. */\n\tconst keep = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tprepared: Prepared,\n\t\toptions: ReadOptions\n\t): Promise<Kept> => {\n\t\tconst { key, q } = prepared\n\t\tconst memoized = memo.get(key)\n\t\tif (memoized) return { q, result: memoized, from: 'memory' }\n\n\t\tconst scope = q.scope ?? null\n\t\tconst lane = lanes.for(adapter, scope)\n\t\tconst recipe = await recipeOf(adapter, prepared, options.timeframe)\n\t\tconst fetchFor = (\n\t\t\tpriority: Priority,\n\t\t\tgate?: (signal: AbortSignal) => Promise<() => void>\n\t\t): Promise<AnalyticsResult> =>\n\t\t\tfetchFresh(adapter, prepared, {\n\t\t\t\tpriority,\n\t\t\t\t...(gate ? { gate } : {}),\n\t\t\t\t...(recipe ? { recipe } : {}),\n\t\t\t})\n\t\tconst kept = (result: AnalyticsResult, from: ReadOrigin): Kept => ({ q, result, from })\n\n\t\tconst entry = await cached(key)\n\t\tconst at = now()\n\t\tif (entry && recipe && (entry.readAt == null || at - entry.readAt >= TOUCH_EVERY_MS)) {\n\t\t\topts.store\n\t\t\t\t.touch(key, new Date(at), recipe)\n\t\t\t\t.catch((err: unknown) => opts.onStoreError?.(err, 'touch'))\n\t\t}\n\t\tif (entry && entry.expiresAt > at) {\n\t\t\tmemoizeEntry(key, entry, at)\n\t\t\treturn kept(entry.value, 'store')\n\t\t}\n\t\tconst priority = options.priority ?? 'normal'\n\t\tconst usable = entry && entry.staleUntil > at ? entry : null\n\t\t// A source that bounds today's answers is read again before it answers one expired, rather\n\t\t// than serving it while a refresh runs: the expired one stands in only if that read fails.\n\t\tconst allowStale = options.allowStale !== false && todayTtl(adapter, q) === undefined\n\t\tif (usable && allowStale) {\n\t\t\tconst failure = failures.get(key)\n\t\t\t// A source that refuses the query as asked has nothing saved worth showing for it.\n\t\t\tif (failure?.kind === 'invalid_param') {\n\t\t\t\tthrow new ReadFailedError(failure)\n\t\t\t}\n\t\t\tconst health = lane.health()\n\t\t\t// An open breaker answers every refresh at once with a failure: skip it rather than log\n\t\t\t// one per read. Once its wait is over, the next refresh goes out as the probe.\n\t\t\tif (!health.open && !closed) {\n\t\t\t\tinBackground(coalesce(key, () => fetchFor('background')))\n\t\t\t}\n\t\t\treturn kept(staleResult(usable, sourceErrorOf(failure, health)), 'stale')\n\t\t}\n\t\tconst busy = options.whenBusy === 'refuse' && !coalesce.has(key) && !budget.available(scope)\n\t\tif (usable) {\n\t\t\t// Waiting for the source here is a cold read like any other, so it takes the scope's\n\t\t\t// place first; one refused a place falls back to the expired entry, as a failure does.\n\t\t\tif (busy) {\n\t\t\t\tconst failure = failures.get(key)\n\t\t\t\tif (failure?.kind === 'invalid_param') {\n\t\t\t\t\tthrow new ReadFailedError(failure)\n\t\t\t\t}\n\t\t\t\treturn kept(staleResult(usable, sourceErrorOf(failure, lane.health())), 'stale')\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn kept(\n\t\t\t\t\tawait coalesce(key, () => fetchFor(priority, (signal) => budget.take(scope, signal))),\n\t\t\t\t\t'source'\n\t\t\t\t)\n\t\t\t} catch (err) {\n\t\t\t\tconst failure = classifyError(err)\n\t\t\t\tif (failure.kind === 'invalid_param') {\n\t\t\t\t\tthrow err\n\t\t\t\t}\n\t\t\t\treturn kept(staleResult(usable, sourceErrorOf(failure, lane.health())), 'stale')\n\t\t\t}\n\t\t}\n\t\tif (busy) {\n\t\t\tthrow new ReadFailedError(\n\t\t\t\t{ kind: 'rate_limited', retryAfterMs: BUSY_RETRY_AFTER_MS },\n\t\t\t\tnew ScopeBusyError(BUSY_RETRY_AFTER_MS)\n\t\t\t)\n\t\t}\n\t\tconst fresh = await coalesce(key, () =>\n\t\t\tfetchFor(priority, (signal) => budget.take(scope, signal))\n\t\t)\n\t\treturn kept(fresh, 'source')\n\t}\n\n\t/**\n\t * A window from a closed day into today, on a source that bounds today's answers, read as its\n\t * closed days (kept for the aggregate TTL) and today (re-read as often as today's TTL asks).\n\t */\n\tconst keepSplit = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tprepared: Prepared,\n\t\toptions: ReadOptions\n\t): Promise<Kept | undefined> => {\n\t\tif (adapter.capabilities.recommendedTtl.today === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst { q } = prepared\n\t\tconst split = splitAtToday(q, todayStart(q))\n\t\tif (!split) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst { timeframe: _whole, ...partOptions } = options\n\t\tconst keepPart = async (part: AnalyticsQuery): Promise<Kept> =>\n\t\t\tkeep(adapter, await prepare(adapter, part, prepared.epochs), partOptions)\n\t\tconst [closedPart, todayPart] = await Promise.all([\n\t\t\tkeepPart(split.closed),\n\t\t\tkeepPart(split.today),\n\t\t])\n\t\tconst from: ReadOrigin =\n\t\t\tclosedPart.from === 'source' || todayPart.from === 'source'\n\t\t\t\t? 'source'\n\t\t\t\t: closedPart.from === 'stale' || todayPart.from === 'stale'\n\t\t\t\t\t? 'stale'\n\t\t\t\t\t: todayPart.from\n\t\treturn { q, result: mergeAtToday(closedPart.result, todayPart.result, q), from }\n\t}\n\n\treturn {\n\t\tasync read(adapter, query, options = {}) {\n\t\t\tconst startedAt = timerNow()\n\t\t\topts.onRead?.()\n\t\t\tif (!adapter.isConfigured()) return emptyResult(adapter.id, now())\n\t\t\tcheckFilters(adapter, query)\n\t\t\tconst prepared = await prepare(adapter, query)\n\t\t\tconst found =\n\t\t\t\t(await keepSplit(adapter, prepared, options)) ?? (await keep(adapter, prepared, options))\n\t\t\treturn options.afterRead === false ? found.result : answered({ adapter, ...found, startedAt })\n\t\t},\n\n\t\tasync refresh(adapter, query, options) {\n\t\t\tif (!adapter.isConfigured()) {\n\t\t\t\treturn 'fresh'\n\t\t\t}\n\t\t\tcheckFilters(adapter, query)\n\t\t\tconst prepared = await prepare(adapter, query)\n\t\t\tconst entry = await cached(prepared.key)\n\t\t\tif (entry && entry.expiresAt - now() > options.freshForMs) {\n\t\t\t\treturn 'fresh'\n\t\t\t}\n\t\t\tawait coalesce(prepared.key, () =>\n\t\t\t\tfetchFresh(adapter, prepared, {\n\t\t\t\t\tpriority: options.priority ?? 'background',\n\t\t\t\t\tawaitStore: true,\n\t\t\t\t})\n\t\t\t)\n\t\t\treturn 'refreshed'\n\t\t},\n\t\tasync peek(adapter, query, options = {}) {\n\t\t\tconst startedAt = timerNow()\n\t\t\tif (!adapter.isConfigured()) return emptyResult(adapter.id, now())\n\t\t\tcheckFilters(adapter, query)\n\t\t\tconst look = async (): Promise<Kept | null> => {\n\t\t\t\tconst prepared = await prepare(adapter, query)\n\t\t\t\tconst { key, q } = prepared\n\t\t\t\tconst memoized = memo.get(key)\n\t\t\t\tif (memoized) {\n\t\t\t\t\treturn { q, result: memoized, from: 'memory' }\n\t\t\t\t}\n\t\t\t\tconst entry = await cached(key)\n\t\t\t\tconst at = now()\n\t\t\t\tif (!entry || entry.staleUntil <= at) {\n\t\t\t\t\treturn null\n\t\t\t\t}\n\t\t\t\tif (entry.expiresAt > at) {\n\t\t\t\t\tmemoizeEntry(key, entry, at)\n\t\t\t\t\treturn { q, result: entry.value, from: 'store' }\n\t\t\t\t}\n\t\t\t\tconst failure = failures.get(key)\n\t\t\t\tif (failure?.kind === 'invalid_param') {\n\t\t\t\t\treturn null\n\t\t\t\t}\n\t\t\t\tconst result = staleResult(\n\t\t\t\t\tentry,\n\t\t\t\t\tsourceErrorOf(failure, lanes.for(adapter, q.scope ?? null).health())\n\t\t\t\t)\n\t\t\t\treturn { q, result, from: 'stale' }\n\t\t\t}\n\t\t\t// A store or an epoch lookup that fails is a miss like any other: the caller reads instead.\n\t\t\tconst found = await withinBudget(look(), options.budgetMs ?? PEEK_BUDGET_MS).catch(() => null)\n\t\t\treturn found && found !== OVER_BUDGET ? answered({ adapter, ...found, startedAt }) : undefined\n\t\t},\n\t\tasync realtime(adapter, query) {\n\t\t\tconst realtime = adapter.realtime\n\t\t\tif (!realtime) {\n\t\t\t\tthrow new Error(`analytics: the \"${adapter.id}\" source counts no live visitors`)\n\t\t\t}\n\t\t\tconst scope = query.scope ?? null\n\t\t\ttry {\n\t\t\t\treturn await withinTimeout(({ signal, deadline }) =>\n\t\t\t\t\tthroughLane(adapter, (ctx) => realtime.call(adapter, query, ctx), {\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tpriority: 'interactive',\n\t\t\t\t\t\tdeadline,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t} catch (err) {\n\t\t\t\tif (!isLaneRefused(err)) {\n\t\t\t\t\topts.onError?.(err, adapter.id)\n\t\t\t\t}\n\t\t\t\tthrow new ReadFailedError(\n\t\t\t\t\twithLaneRetryAfter(classifyError(err), lanes.for(adapter, scope).health()),\n\t\t\t\t\terr\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t\tidle,\n\t\tkeep(work) {\n\t\t\tinBackground(work)\n\t\t},\n\t\tasync close() {\n\t\t\tclosed = true\n\t\t\tawait idle()\n\t\t},\n\t\thealth(adapter, scope) {\n\t\t\treturn lanes.for(adapter, scope ?? null).health()\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,iBAAiB;;AAGvB,MAAM,kBAAkB;;AAMxB,MAAM,sBAAsB;;AAG5B,MAAM,aAAa,UAClB,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;;AAGnD,MAAM,eAAe,UACpB,UAAU,MAAM,SAAS,KACzB,UAAU,MAAM,SAAS,KACzB,UAAU,MAAM,UAAU,MACzB,MAAM,WAAW,KAAA,KAAa,MAAM,WAAW,QAAQ,UAAU,MAAM,MAAM;;;;;AAM/E,MAAM,WAAW;;;;;AAMjB,MAAM,cACL,OACA,iBACA,KAAA,UAC8D;CAC9D,MAAM,QACL,mBAAmB,OAAO,IAAI,eAAe,MAAM,KAAK,EAAE,EAAE,QAAQ,IAAI,kBAAkB;CAC3F,IAAI,MAAM,MAAM,QAAQ,KAAK,OAC5B,OAAO;EAAE;EAAO,SAAS;CAAM;CAEhC,OAAO;EAAE,OAAO;GAAE,OAAO,IAAI,KAAK,KAAK;GAAG,KAAK,MAAM;EAAI;EAAG,SAAS;CAAK;AAC3E;;;;;AAMA,MAAM,eA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eACrC,YAAY,UAAU,QAAQ,SAAS,KAAK,SAAS,OAAO,GAAG,GAAG;KACjE;KACA,UAAU;KACV;KACA;IACD,CAAC,CACF;GACD,SAAS,KAAK;IACb,IAAI,CAAC,cAAc,GAAG,GACrB,KAAK,UAAU,KAAK,QAAQ,EAAE;IAE/B,MAAM,IAAI,gBACT,mBAAmB,cAAc,GAAG,GAAG,MAAM,IAAI,SAAS,KAAK,EAAE,OAAO,CAAC,GACzE,GACD;GACD;EACD;EACA;EACA,KAAK,MAAM;GACV,aAAa,IAAI;EAClB;EACA,MAAM,QAAQ;GACb,SAAS;GACT,MAAM,KAAK;EACZ;EACA,OAAO,SAAS,OAAO;GACtB,OAAO,MAAM,IAAI,SAAS,SAAS,IAAI,EAAE,OAAO;EACjD;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"engine.js","names":[],"sources":["../../src/surfacing/engine.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { OVER_BUDGET, withinBudget } from '../core/budget'\nimport { buildCacheKey, type CacheKeyEpochs } from '../core/cacheKey'\nimport { unsupportedFilter } from '../core/capabilities'\nimport { currentTime } from '../core/clock'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tSourceErrorKind,\n} from '../core/contract'\nimport { monotonicMs } from '../core/monotonic'\nimport { UnsupportedFilterError } from '../core/sourceErrors'\nimport { earlierInstant, isRecord } from '../core/values'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DAY_MS, DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\nimport type { AfterReadAnswer, AfterReadHook, ReadOrigin } from './afterRead'\nimport {\n\ttype CacheEntry,\n\ttype CacheStore,\n\tisCachedResult,\n\ttype ReadRecipe,\n\tSTALE_WINDOW_SECONDS,\n} from './cacheStore'\nimport {\n\tclassifyError,\n\tisLaneRefused,\n\tPROVIDER_READ_TIMEOUT_MESSAGE,\n\tReadFailedError,\n\ttype ReadFailure,\n\tScopeBusyError,\n} from './classifyError'\nimport { createCoalescer } from './coalesce'\nimport { BUSY_RETRY_AFTER_MS, createColdBudget, DEFAULT_COLD_READS_PER_SCOPE } from './coldBudget'\nimport { type EpochSources, epochsFor } from './epoch'\nimport { createLanes, type LaneHealth, type Lanes, type Priority, runUpstream } from './lanes'\nimport { AGGREGATE_MEMO_MS, createMemo, type Memo } from './memo'\nimport { dayRead, foldResult, type RebucketPlan, rebucketPlan } from './rebucket'\nimport { RECIPE_WINDOWS, recipeWindow } from './recipe'\nimport { shapeResult } from './shape'\nimport { mergeAtToday, splitAtToday } from './todaySplit'\n\n/** How often a read carrying a recipe stamps the entry it was served as read. */\nconst TOUCH_EVERY_MS = 3_600_000\n\n/** How long a key's last failed refresh is remembered, to word or refuse its stale answers. */\nconst FAILURE_MEMO_MS = 60_000\n\n/** How long a peek waits on the store before it answers that nothing is there. */\nexport const PEEK_BUDGET_MS = 150\n\n/** How long a read waits on the store before reading the source as if nothing were cached. */\nconst STORE_GET_BUDGET_MS = 1_000\n\n/** An instant a store handed back: finite epoch milliseconds. */\nconst isInstant = (value: unknown): value is number =>\n\ttypeof value === 'number' && Number.isFinite(value)\n\n/** Whether an entry's instants are what the store contract says: finite epoch milliseconds. */\nconst hasInstants = (entry: CacheEntry): boolean =>\n\tisInstant(entry.fetchedAt) &&\n\tisInstant(entry.expiresAt) &&\n\tisInstant(entry.staleUntil) &&\n\t(entry.readAt === undefined || entry.readAt === null || isInstant(entry.readAt))\n\n/**\n * The clock deadlines, waits and durations run on: the one timers run on. The cache clock (`now`)\n * may be moved by a test, or by Payload's job-system globals, without any timer moving with it.\n */\nconst timerNow = monotonicMs\n\n/**\n * The window a source is asked for, from its lookback on; one that declares none still starts no\n * earlier than 1970, before which nothing was counted, so no read walks centuries of days.\n */\nconst clampRange = (\n\trange: AnalyticsQuery['dateRange'],\n\tmaxLookbackDays: number | null,\n\ttz: string = DEFAULT_TIMEZONE\n): { range: AnalyticsQuery['dateRange']; clamped: boolean } => {\n\tconst floor =\n\t\tmaxLookbackDays == null ? 0 : startOfDayInTz(range.end, tz).getTime() - maxLookbackDays * DAY_MS\n\tif (range.start.getTime() >= floor) {\n\t\treturn { range, clamped: false }\n\t}\n\treturn { range: { start: new Date(floor), end: range.end }, clamped: true }\n}\n\n/**\n * A breakdown cut by `limit` with no `order` asks its source for its first metric's top rows: a\n * source ranking by anything else would hand over a subset the engine cannot rank back.\n */\nconst rankedQuery = (query: AnalyticsQuery): AnalyticsQuery => {\n\tconst metric = query.metrics[0]\n\treturn query.limit !== undefined &&\n\t\tquery.order === undefined &&\n\t\t(query.dimensions?.length ?? 0) > 0 &&\n\t\tmetric !== undefined\n\t\t? { ...query, order: { metric, direction: 'desc' } }\n\t\t: query\n}\n\nexport type CacheOperation = 'get' | 'set' | 'touch'\n\nexport interface EngineOptions {\n\tstore: CacheStore\n\t/** The instance's in-process memo; a private one of the default size when absent. */\n\tmemo?: Memo<AnalyticsResult>\n\t/** Lanes reads reach their sources through; a private set with default caps when absent. */\n\tlanes?: Lanes\n\t/** Cold reads one scope may have waiting on its sources at once; default 8. */\n\tcoldReadsPerScope?: number\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/**\n\t * Budget for one fetch from a source, every wait and retry included; the request in flight is\n\t * aborted past it.\n\t */\n\ttimeoutMs: number\n\t/** Called once per failed fetch, before falling back to a stale cache entry; `scope` null is install-wide. */\n\tonError?: (err: unknown, adapterId: string, scope: string | null) => void\n\t/** Called when the store fails; the read carries on as if the entry were absent or unwritten. */\n\tonStoreError?: (err: unknown, operation: CacheOperation) => void\n\t/** Called after each value the store accepted. */\n\tonWrite?: () => void\n\t/**\n\t * The scope's refresh epoch, which every key carries. Absent, every read keys on the initial\n\t * token.\n\t */\n\tepoch?: EpochSources['refresh']\n\t/** The scope's configuration epoch, which every key carries; absent, a fixed one. */\n\tconfigEpoch?: EpochSources['config']\n\t/** The instance every read is for, handed to adapters as `AdapterContext.payload`. */\n\tpayload?: Payload\n\t/** Epoch milliseconds; the plugin's clock (`currentDate`) by default. */\n\tnow?: () => number\n\t/**\n\t * Keeps a background refresh running past the response that started it: Next's `after()` inside\n\t * a request. The engine tracks every refresh itself as well, so `idle()` waits for all of them.\n\t */\n\tkeepAlive?: (work: Promise<unknown>) => void | Promise<void>\n\t/** `hooks.afterRead`, run only on an engine built with `payload`, which the hook is handed. */\n\tafterRead?: AfterReadHook\n\t/** Told each time the hook throws; the read is answered as if it had returned nothing. */\n\tonHookError?: (err: unknown) => void\n\t/** Called as each read starts, before anything is looked up. */\n\tonRead?: () => void\n}\n\nexport interface ReadOptions {\n\t/**\n\t * False waits for an expired entry's refresh instead of answering with it, falling back to it\n\t * only when the refresh fails; for work that keeps what it reads (sync). Default true.\n\t */\n\tallowStale?: boolean\n\t/**\n\t * The named timeframe the read's window came from; when the window is that preset's as of now,\n\t * the read's recipe is stored with its entry so the warm task keeps it warm.\n\t */\n\ttimeframe?: TimeframePreset\n\t/**\n\t * `interactive` for an open panel or view, served first; `background` for work nobody waits on,\n\t * held to half a source's slots like every refresh. Default `normal`.\n\t */\n\tpriority?: Priority\n\t/**\n\t * On a full scope (`coldReadsPerScope`) a cold read waits within `timeoutMs` (default), or with\n\t * `refuse` fails at once as `rate_limited`; a read matching one already waiting joins it anyway.\n\t */\n\twhenBusy?: 'wait' | 'refuse'\n\t/**\n\t * False answers without `hooks.afterRead`: work that keeps what it reads (sync) stores the\n\t * source's own answer, never what the hook made of it for one reader. Default true.\n\t */\n\tafterRead?: boolean\n}\n\nexport interface RefreshOptions {\n\t/** An entry still fresh for this many more milliseconds is left as it is. */\n\tfreshForMs: number\n\t/** Default `background`. */\n\tpriority?: Priority\n}\n\n/** What a refresh did: left an entry fresh enough, or read the source again and stored it. */\nexport type RefreshOutcome = 'fresh' | 'refreshed'\n\nexport interface PeekOptions {\n\t/** Milliseconds the memo and the store may take to answer; default {@link PEEK_BUDGET_MS}. */\n\tbudgetMs?: number\n}\n\nexport interface Engine {\n\tread(\n\t\tadapter: AnalyticsAdapter,\n\t\tquery: AnalyticsQuery,\n\t\toptions?: ReadOptions\n\t): Promise<AnalyticsResult>\n\t/**\n\t * The warm task's read: re-reads `query` and stores the answer unless its entry stays fresh for\n\t * `freshForMs` more, never touching its recipe or read time. Absent when nothing caches.\n\t */\n\trefresh?(\n\t\tadapter: AnalyticsAdapter,\n\t\tquery: AnalyticsQuery,\n\t\toptions: RefreshOptions\n\t): Promise<RefreshOutcome>\n\t/**\n\t * What a read would answer from memory or the store, never asking the source or refreshing;\n\t * undefined when neither holds it within the budget. Absent on an engine that caches nothing.\n\t */\n\tpeek?(\n\t\tadapter: AnalyticsAdapter,\n\t\tquery: AnalyticsQuery,\n\t\toptions?: PeekOptions\n\t): Promise<AnalyticsResult | undefined>\n\t/**\n\t * A live count from the adapter's `realtime`, through its lane at interactive priority and\n\t * within the read timeout; never cached here. Absent on an engine without lanes.\n\t */\n\trealtime?(adapter: AnalyticsAdapter, query: AnalyticsQuery): Promise<AnalyticsResult>\n\t/** Settles once every background refresh has finished; absent on one starting none. */\n\tidle?(): Promise<void>\n\t/**\n\t * Keeps `work` a caller stopped waiting for running past the response, counted until it settles\n\t * so `idle()` and `close()` wait for it. Absent on an engine starting no background work.\n\t */\n\tkeep?(work: Promise<unknown>): void\n\t/**\n\t * Starts no background work from now on (refreshes, cache writes) and settles what is running:\n\t * the runtime holding the engine is retired. Reads still answer.\n\t */\n\tclose?(): Promise<void>\n\t/**\n\t * The state of the lane an adapter's reads go through for `scope`; absent on an engine without\n\t * lanes.\n\t */\n\thealth?(adapter: AnalyticsAdapter, scope?: string | null): LaneHealth\n}\n\n/**\n * An adapter drops a filter it cannot apply and answers unfiltered, which would read as filtered\n * numbers: every caller gates first, and this is the gate behind them all.\n */\nconst checkFilters = (adapter: AnalyticsAdapter, query: AnalyticsQuery): void => {\n\tconst refused = unsupportedFilter(adapter.capabilities, query.filters ?? [])\n\tif (refused) {\n\t\tthrow new UnsupportedFilterError(adapter.id, refused)\n\t}\n}\n\n/** A hook's answer that replaces the read's, rather than nothing. */\nconst replaces = (answer: AfterReadAnswer): answer is AnalyticsResult => isRecord(answer)\n\nconst emptyResult = (provider: string, at: number): AnalyticsResult => ({\n\trows: [],\n\tmeta: { provider, fetchedAt: new Date(at).toISOString() },\n})\n\n/** `result` with `meta.fetchedAt` no later than `answeredAt`, replacing a later or bad one. */\nconst readAt = (result: AnalyticsResult, answeredAt: number): AnalyticsResult => {\n\tconst stamped = Date.parse(result.meta.fetchedAt)\n\treturn Number.isFinite(stamped) && stamped <= answeredAt\n\t\t? result\n\t\t: { ...result, meta: { ...result.meta, fetchedAt: new Date(answeredAt).toISOString() } }\n}\n\n/** An expired entry as served: stale, dated to its fetch, and why its source needs a look. */\nconst staleResult = (entry: CacheEntry, sourceError?: SourceErrorKind): AnalyticsResult => ({\n\t...entry.value,\n\tmeta: {\n\t\t...entry.value.meta,\n\t\tstale: true,\n\t\tasOf: earlierInstant(entry.value.meta.asOf, new Date(entry.fetchedAt).toISOString()),\n\t\t...(sourceError ? { sourceError } : {}),\n\t},\n})\n\n/**\n * Why a stale answer's source needs a look: the key's own last failure when there is one, else the\n * failure its lane last counted, but only a failure about setup, never an outage.\n */\nconst sourceErrorOf = (\n\tfailure: ReadFailure | undefined,\n\thealth: LaneHealth\n): SourceErrorKind | undefined => {\n\tif (failure) {\n\t\tif (failure.kind !== 'source_misconfigured') {\n\t\t\treturn undefined\n\t\t}\n\t\treturn failure.hostRefused ? 'host-refused' : 'misconfigured'\n\t}\n\tif (health.lastFailure !== 'source_misconfigured') {\n\t\treturn undefined\n\t}\n\treturn health.hostRefused ? 'host-refused' : 'misconfigured'\n}\n\n/** A failure as it is thrown: an outage says how long to wait when its lane knows. */\nconst withLaneRetryAfter = (failure: ReadFailure, health: LaneHealth): ReadFailure =>\n\tfailure.kind === 'unavailable' &&\n\tfailure.retryAfterMs === undefined &&\n\thealth.retryAfterMs !== undefined\n\t\t? { ...failure, retryAfterMs: health.retryAfterMs }\n\t\t: failure\n\n/** What a peek found kept for a query, and where. */\ninterface Kept {\n\tq: AnalyticsQuery\n\tresult: AnalyticsResult\n\tfrom: ReadOrigin\n}\n\n/** One read made ready: its query as keyed, the request its source gets, and its cache key. */\ninterface Prepared {\n\t/** The query as asked, its window clamped to the source's lookback. */\n\tq: AnalyticsQuery\n\tclamped: boolean\n\trange: AnalyticsQuery['dateRange']\n\tplan: RebucketPlan | undefined\n\t/** What the adapter is asked: the query, or its days where weeks or months are folded here. */\n\tadapterQuery: AnalyticsQuery\n\tepochs: CacheKeyEpochs\n\tkey: string\n}\n\nexport function createEngine(opts: EngineOptions): Required<Engine> {\n\tconst now = opts.now ?? currentTime\n\tconst memo = opts.memo ?? createMemo<AnalyticsResult>({ now })\n\tconst failures = createMemo<ReadFailure>({ now })\n\tconst coalesce = createCoalescer<AnalyticsResult>()\n\tconst lanes = opts.lanes ?? createLanes()\n\tconst budget = createColdBudget(opts.coldReadsPerScope ?? DEFAULT_COLD_READS_PER_SCOPE)\n\tconst background = new Set<Promise<unknown>>()\n\tconst storeGetMs = Math.min(STORE_GET_BUDGET_MS, opts.timeoutMs)\n\tlet closed = false\n\n\t/**\n\t * The store's entry for `key`, or null: a store that fails, answers past\n\t * {@link STORE_GET_BUDGET_MS} or breaks the entry contract is reported and read as a miss.\n\t */\n\tconst cached = async (key: string): Promise<CacheEntry | null> => {\n\t\tlet entry: CacheEntry | null | typeof OVER_BUDGET\n\t\ttry {\n\t\t\tentry = await withinBudget(opts.store.get(key), storeGetMs)\n\t\t} catch (err) {\n\t\t\topts.onStoreError?.(err, 'get')\n\t\t\treturn null\n\t\t}\n\t\tif (entry === OVER_BUDGET) {\n\t\t\topts.onStoreError?.(\n\t\t\t\tnew Error(`analytics: the read cache did not answer within ${storeGetMs} ms`),\n\t\t\t\t'get'\n\t\t\t)\n\t\t\treturn null\n\t\t}\n\t\tif (!entry || !isCachedResult(entry.value)) {\n\t\t\treturn null\n\t\t}\n\t\tif (!hasInstants(entry)) {\n\t\t\topts.onStoreError?.(\n\t\t\t\tnew Error(\n\t\t\t\t\t'analytics: the read cache answered an entry whose fetchedAt, expiresAt or staleUntil is not a finite number of milliseconds'\n\t\t\t\t),\n\t\t\t\t'get'\n\t\t\t)\n\t\t\treturn null\n\t\t}\n\t\treturn entry\n\t}\n\n\t/** Tracks `work` until it settles, keeping it alive past the response; answers once settled. */\n\tconst inBackground = (work: Promise<unknown>): Promise<void> => {\n\t\tconst settled = work.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined\n\t\t)\n\t\tbackground.add(settled)\n\t\tvoid settled.finally(() => background.delete(settled))\n\t\ttry {\n\t\t\tconst kept = opts.keepAlive?.(settled)\n\t\t\tif (kept instanceof Promise) {\n\t\t\t\tkept.catch(() => {})\n\t\t\t}\n\t\t} catch {\n\t\t\t// Outside a request there is nothing to keep alive; the engine's own tracking still holds it.\n\t\t}\n\t\treturn settled\n\t}\n\n\tconst idle = async (): Promise<void> => {\n\t\twhile (background.size > 0) {\n\t\t\tawait Promise.all([...background])\n\t\t}\n\t}\n\n\t/** Writes an answer to the store, never failing the read: a store that fails is reported. */\n\tconst store = async (\n\t\tkey: string,\n\t\tresult: AnalyticsResult,\n\t\toptions: Parameters<CacheStore['set']>[2]\n\t): Promise<void> => {\n\t\ttry {\n\t\t\tawait opts.store.set(key, result, options)\n\t\t\topts.onWrite?.()\n\t\t} catch (err) {\n\t\t\topts.onStoreError?.(err, 'set')\n\t\t}\n\t}\n\n\t/**\n\t * One call to the source through the adapter's lane: per request when the adapter sends through\n\t * `upstream`, else one token and slot for the whole call.\n\t */\n\tconst throughLane = (\n\t\tadapter: AnalyticsAdapter,\n\t\tcall: (ctx: AdapterContext) => Promise<AnalyticsResult>,\n\t\trun: { signal: AbortSignal; priority: Priority; deadline: number; scope: string | null }\n\t): Promise<AnalyticsResult> => {\n\t\tconst lane = lanes.for(adapter, run.scope)\n\t\tconst options = { ...run, now: timerNow }\n\t\tconst base: AdapterContext = {\n\t\t\t...(opts.payload ? { payload: opts.payload } : {}),\n\t\t\tsignal: run.signal,\n\t\t\tnow: () => new Date(now()),\n\t\t\tremainingMs: () => Math.max(0, run.deadline - timerNow()),\n\t\t}\n\t\tif (adapter.capabilities.upstreamAware) {\n\t\t\treturn call({\n\t\t\t\t...base,\n\t\t\t\tupstream: <T>(fn: (signal?: AbortSignal) => Promise<T>) => runUpstream(lane, fn, options),\n\t\t\t})\n\t\t}\n\t\treturn runUpstream(\n\t\t\tlane,\n\t\t\t(signal) =>\n\t\t\t\tcall({\n\t\t\t\t\t...base,\n\t\t\t\t\tsignal,\n\t\t\t\t\tupstream: <T>(fn: (signal?: AbortSignal) => Promise<T>) => fn(signal),\n\t\t\t\t}),\n\t\t\toptions\n\t\t)\n\t}\n\n\t/** Runs `hooks.afterRead` on one answer; a hook that throws answers as if it returned nothing. */\n\tconst answered = async (args: {\n\t\tadapter: AnalyticsAdapter\n\t\tq: AnalyticsQuery\n\t\tresult: AnalyticsResult\n\t\tfrom: ReadOrigin\n\t\tstartedAt: number\n\t}): Promise<AnalyticsResult> => {\n\t\tconst { afterRead: hook, payload } = opts\n\t\tif (!hook || !payload) {\n\t\t\treturn args.result\n\t\t}\n\t\ttry {\n\t\t\tconst adjusted = await hook({\n\t\t\t\tadapterId: args.adapter.id,\n\t\t\t\tquery: args.q,\n\t\t\t\tresult: args.result,\n\t\t\t\tfrom: args.from,\n\t\t\t\tdurationMs: Math.max(0, timerNow() - args.startedAt),\n\t\t\t\tpayload,\n\t\t\t})\n\t\t\treturn replaces(adjusted) ? adjusted : args.result\n\t\t} catch (err) {\n\t\t\topts.onHookError?.(err)\n\t\t\treturn args.result\n\t\t}\n\t}\n\n\t/**\n\t * Settles with `work` or rejects after `timeoutMs`, aborting the signal; the race also bounds an\n\t * adapter that never checks it. Lane slots return once the request settles or is abandoned.\n\t */\n\tconst withinTimeout = async <T>(\n\t\twork: (run: { signal: AbortSignal; deadline: number }) => Promise<T>\n\t): Promise<T> => {\n\t\tconst controller = new AbortController()\n\t\tconst deadline = timerNow() + opts.timeoutMs\n\t\tconst timer = setTimeout(\n\t\t\t() => controller.abort(new Error(PROVIDER_READ_TIMEOUT_MESSAGE)),\n\t\t\topts.timeoutMs\n\t\t)\n\t\ttimer.unref?.()\n\t\ttry {\n\t\t\tconst aborted = new Promise<never>((_resolve, reject) => {\n\t\t\t\tcontroller.signal.addEventListener('abort', () => reject(controller.signal.reason), {\n\t\t\t\t\tonce: true,\n\t\t\t\t})\n\t\t\t})\n\t\t\tconst attempt = work({ signal: controller.signal, deadline })\n\t\t\tattempt.catch(() => {})\n\t\t\taborted.catch(() => {})\n\t\t\treturn await Promise.race([attempt, aborted])\n\t\t} finally {\n\t\t\tclearTimeout(timer)\n\t\t}\n\t}\n\n\tconst prepare = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tquery: AnalyticsQuery,\n\t\tknown?: CacheKeyEpochs\n\t): Promise<Prepared> => {\n\t\tconst { range, clamped } = clampRange(\n\t\t\tquery.dateRange,\n\t\t\tadapter.capabilities.maxLookbackDays,\n\t\t\tquery.timezone\n\t\t)\n\t\tconst ranked = rankedQuery(query)\n\t\tconst q = range === query.dateRange ? ranked : { ...ranked, dateRange: range }\n\t\t// Weeks and months are folded here from days, exactly the same way for every source\n\t\t// that cannot answer them itself; the cache keys on the bucket the caller asked for.\n\t\tconst plan = rebucketPlan(q, adapter.capabilities)\n\t\tconst adapterQuery = plan ? dayRead(q, plan) : q\n\t\t// Resolved before the key so the coalescer key carries the epochs too: two reads\n\t\t// across a bump must not share one in-flight answer.\n\t\tconst epochs =\n\t\t\tknown ?? (await epochsFor({ refresh: opts.epoch, config: opts.configEpoch }, q.scope))\n\t\treturn {\n\t\t\tq,\n\t\t\tclamped,\n\t\t\trange,\n\t\t\tplan,\n\t\t\tadapterQuery,\n\t\t\tepochs,\n\t\t\tkey: buildCacheKey(adapter.id, q, epochs),\n\t\t}\n\t}\n\n\t/** The instant today began in the read's zone. */\n\tconst todayStart = (q: AnalyticsQuery): number =>\n\t\tstartOfDayInTz(new Date(now()), q.timezone ?? DEFAULT_TIMEZONE).getTime()\n\n\t/**\n\t * How long the source's answer for `q` stays fresh, when the source bounds a window reaching into\n\t * the current day (native's `recommendedTtl.today`); undefined for every other read.\n\t */\n\tconst todayTtl = (adapter: AnalyticsAdapter, q: AnalyticsQuery): number | undefined => {\n\t\tconst bound = adapter.capabilities.recommendedTtl.today\n\t\tif (bound === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn q.dateRange.end.getTime() >= todayStart(q) ? bound : undefined\n\t}\n\n\t/** Holds a fresh store entry in memory until it expires, at most {@link AGGREGATE_MEMO_MS}. */\n\tconst memoizeEntry = (key: string, entry: CacheEntry, at: number): void => {\n\t\tmemo.set(key, entry.value, Math.min(AGGREGATE_MEMO_MS, entry.expiresAt - at))\n\t}\n\n\t/**\n\t * The read's recipe when its window is its timeframe's as of now, matched on the key a recipe\n\t * replayed now would read: the window as the key cuts it, after the same clamp.\n\t */\n\tconst recipeOf = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tprepared: Prepared,\n\t\ttimeframe: TimeframePreset | undefined\n\t): Promise<ReadRecipe | undefined> => {\n\t\tif (timeframe === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst at = new Date(now())\n\t\tconst { q } = prepared\n\t\tconst tz = q.timezone ?? DEFAULT_TIMEZONE\n\t\tconst { dateRange: _window, ...rest } = q\n\t\t// MongoDB stores an absent field as null, which a replay would then key on.\n\t\tfor (const key of Object.keys(rest)) {\n\t\t\tif (Reflect.get(rest, key) === undefined) {\n\t\t\t\tReflect.deleteProperty(rest, key)\n\t\t\t}\n\t\t}\n\t\tfor (const window of RECIPE_WINDOWS) {\n\t\t\tconst candidate = recipeWindow({ timeframe, window }, at, tz)\n\t\t\tif (!candidate) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst replayed = await prepare(adapter, { ...q, dateRange: candidate }, prepared.epochs)\n\t\t\tif (replayed.key === prepared.key) {\n\t\t\t\treturn { adapterRef: adapter.id, scope: q.scope ?? null, timeframe, window, query: rest }\n\t\t\t}\n\t\t}\n\t\treturn undefined\n\t}\n\n\t/**\n\t * Reads the source within the read timeout, memoizes and stores the answer (before answering\n\t * with `awaitStore`); a failure is remembered for a minute and thrown classified.\n\t */\n\tconst fetchFresh = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tprepared: Prepared,\n\t\trun: {\n\t\t\tpriority: Priority\n\t\t\tgate?: (signal: AbortSignal) => Promise<() => void>\n\t\t\trecipe?: ReadRecipe\n\t\t\tawaitStore?: boolean\n\t\t}\n\t): Promise<AnalyticsResult> => {\n\t\tconst { key, q, plan, clamped, range } = prepared\n\t\tconst scope = q.scope ?? null\n\t\tlet fresh: AnalyticsResult\n\t\ttry {\n\t\t\tfresh = await withinTimeout(async ({ signal, deadline }) => {\n\t\t\t\tconst release = await run.gate?.(signal)\n\t\t\t\ttry {\n\t\t\t\t\treturn await throughLane(adapter, (ctx) => adapter.query(prepared.adapterQuery, ctx), {\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tpriority: run.priority,\n\t\t\t\t\t\tdeadline,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t})\n\t\t\t\t} finally {\n\t\t\t\t\trelease?.()\n\t\t\t\t}\n\t\t\t})\n\t\t} catch (err) {\n\t\t\tconst failure = classifyError(err)\n\t\t\tfailures.set(key, failure, FAILURE_MEMO_MS)\n\t\t\t// A lane refusal sent nothing: the failure that opened or paused the lane was told already.\n\t\t\tif (!isLaneRefused(err)) {\n\t\t\t\topts.onError?.(err, adapter.id, scope)\n\t\t\t}\n\t\t\tthrow new ReadFailedError(\n\t\t\t\twithLaneRetryAfter(failure, lanes.for(adapter, scope).health()),\n\t\t\t\terr\n\t\t\t)\n\t\t}\n\t\tfailures.delete(key)\n\t\tconst answered = readAt(fresh, now())\n\t\tconst folded = plan ? foldResult(answered, q, plan) : answered\n\t\tconst shaped = shapeResult(folded, q)\n\t\tconst result: AnalyticsResult = clamped\n\t\t\t? {\n\t\t\t\t\t...shaped,\n\t\t\t\t\tmeta: { ...shaped.meta, clamped: true, dataFrom: range.start.toISOString() },\n\t\t\t\t}\n\t\t\t: shaped\n\t\t// Each passes (a failed goal resolver, a stand-in zone, days still being counted) and would\n\t\t// stay pinned for the aggregate TTL; a capped read stays capped, so it keeps that TTL.\n\t\tconst degraded =\n\t\t\tresult.meta.goalsUnresolved === true ||\n\t\t\tresult.meta.timezoneUnresolved === true ||\n\t\t\t(result.meta.partial?.missingDays ?? 0) > 0\n\t\tconst kept = degraded\n\t\t\t? (opts.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime)\n\t\t\t: (opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate)\n\t\tconst today = todayTtl(adapter, q)\n\t\tconst ttl = today === undefined ? kept : Math.min(kept, today)\n\t\tmemo.set(key, result, Math.min(AGGREGATE_MEMO_MS, ttl * 1000))\n\t\t// A store that is slow or hangs never holds up an answer the source already gave, nor `idle()`\n\t\t// past the read timeout.\n\t\tif (!closed) {\n\t\t\tconst write = store(key, result, {\n\t\t\t\tttlSeconds: ttl,\n\t\t\t\tstaleSeconds: STALE_WINDOW_SECONDS,\n\t\t\t\t...(q.scope === undefined ? {} : { scope: q.scope }),\n\t\t\t\t...(run.recipe ? { recipe: run.recipe } : {}),\n\t\t\t})\n\t\t\tconst stored = inBackground(\n\t\t\t\twithinBudget(write, opts.timeoutMs).then((done) => {\n\t\t\t\t\tif (done === OVER_BUDGET) {\n\t\t\t\t\t\topts.onStoreError?.(\n\t\t\t\t\t\t\tnew Error(`analytics: the read cache did not store within ${opts.timeoutMs} ms`),\n\t\t\t\t\t\t\t'set'\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t)\n\t\t\tif (run.awaitStore) {\n\t\t\t\tawait stored\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\n\t/** One read's answer as kept or fetched, and where it came from, before `hooks.afterRead`. */\n\tconst keep = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tprepared: Prepared,\n\t\toptions: ReadOptions\n\t): Promise<Kept> => {\n\t\tconst { key, q } = prepared\n\t\tconst memoized = memo.get(key)\n\t\tif (memoized) return { q, result: memoized, from: 'memory' }\n\n\t\tconst scope = q.scope ?? null\n\t\tconst lane = lanes.for(adapter, scope)\n\t\tconst recipe = await recipeOf(adapter, prepared, options.timeframe)\n\t\tconst fetchFor = (\n\t\t\tpriority: Priority,\n\t\t\tgate?: (signal: AbortSignal) => Promise<() => void>\n\t\t): Promise<AnalyticsResult> =>\n\t\t\tfetchFresh(adapter, prepared, {\n\t\t\t\tpriority,\n\t\t\t\t...(gate ? { gate } : {}),\n\t\t\t\t...(recipe ? { recipe } : {}),\n\t\t\t})\n\t\tconst kept = (result: AnalyticsResult, from: ReadOrigin): Kept => ({ q, result, from })\n\n\t\tconst entry = await cached(key)\n\t\tconst at = now()\n\t\tif (entry && recipe && (entry.readAt == null || at - entry.readAt >= TOUCH_EVERY_MS)) {\n\t\t\topts.store\n\t\t\t\t.touch(key, new Date(at), recipe)\n\t\t\t\t.catch((err: unknown) => opts.onStoreError?.(err, 'touch'))\n\t\t}\n\t\tif (entry && entry.expiresAt > at) {\n\t\t\tmemoizeEntry(key, entry, at)\n\t\t\treturn kept(entry.value, 'store')\n\t\t}\n\t\tconst priority = options.priority ?? 'normal'\n\t\tconst usable = entry && entry.staleUntil > at ? entry : null\n\t\t// A source that bounds today's answers is read again before it answers one expired, rather\n\t\t// than serving it while a refresh runs: the expired one stands in only if that read fails.\n\t\tconst allowStale = options.allowStale !== false && todayTtl(adapter, q) === undefined\n\t\tif (usable && allowStale) {\n\t\t\tconst failure = failures.get(key)\n\t\t\t// A source that refuses the query as asked has nothing saved worth showing for it.\n\t\t\tif (failure?.kind === 'invalid_param') {\n\t\t\t\tthrow new ReadFailedError(failure)\n\t\t\t}\n\t\t\tconst health = lane.health()\n\t\t\t// An open breaker answers every refresh at once with a failure: skip it rather than log\n\t\t\t// one per read. Once its wait is over, the next refresh goes out as the probe.\n\t\t\tif (!health.open && !closed) {\n\t\t\t\tinBackground(coalesce(key, () => fetchFor('background')))\n\t\t\t}\n\t\t\treturn kept(staleResult(usable, sourceErrorOf(failure, health)), 'stale')\n\t\t}\n\t\tconst busy = options.whenBusy === 'refuse' && !coalesce.has(key) && !budget.available(scope)\n\t\tif (usable) {\n\t\t\t// Waiting for the source here is a cold read like any other, so it takes the scope's\n\t\t\t// place first; one refused a place falls back to the expired entry, as a failure does.\n\t\t\tif (busy) {\n\t\t\t\tconst failure = failures.get(key)\n\t\t\t\tif (failure?.kind === 'invalid_param') {\n\t\t\t\t\tthrow new ReadFailedError(failure)\n\t\t\t\t}\n\t\t\t\treturn kept(staleResult(usable, sourceErrorOf(failure, lane.health())), 'stale')\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn kept(\n\t\t\t\t\tawait coalesce(key, () => fetchFor(priority, (signal) => budget.take(scope, signal))),\n\t\t\t\t\t'source'\n\t\t\t\t)\n\t\t\t} catch (err) {\n\t\t\t\tconst failure = classifyError(err)\n\t\t\t\tif (failure.kind === 'invalid_param') {\n\t\t\t\t\tthrow err\n\t\t\t\t}\n\t\t\t\treturn kept(staleResult(usable, sourceErrorOf(failure, lane.health())), 'stale')\n\t\t\t}\n\t\t}\n\t\tif (busy) {\n\t\t\tthrow new ReadFailedError(\n\t\t\t\t{ kind: 'rate_limited', retryAfterMs: BUSY_RETRY_AFTER_MS },\n\t\t\t\tnew ScopeBusyError(BUSY_RETRY_AFTER_MS)\n\t\t\t)\n\t\t}\n\t\tconst fresh = await coalesce(key, () =>\n\t\t\tfetchFor(priority, (signal) => budget.take(scope, signal))\n\t\t)\n\t\treturn kept(fresh, 'source')\n\t}\n\n\t/**\n\t * A window from a closed day into today, on a source that bounds today's answers, read as its\n\t * closed days (kept for the aggregate TTL) and today (re-read as often as today's TTL asks).\n\t */\n\tconst keepSplit = async (\n\t\tadapter: AnalyticsAdapter,\n\t\tprepared: Prepared,\n\t\toptions: ReadOptions\n\t): Promise<Kept | undefined> => {\n\t\tif (adapter.capabilities.recommendedTtl.today === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst { q } = prepared\n\t\tconst split = splitAtToday(q, todayStart(q))\n\t\tif (!split) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst { timeframe: _whole, ...partOptions } = options\n\t\tconst keepPart = async (part: AnalyticsQuery): Promise<Kept> =>\n\t\t\tkeep(adapter, await prepare(adapter, part, prepared.epochs), partOptions)\n\t\tconst [closedPart, todayPart] = await Promise.all([\n\t\t\tkeepPart(split.closed),\n\t\t\tkeepPart(split.today),\n\t\t])\n\t\tconst from: ReadOrigin =\n\t\t\tclosedPart.from === 'source' || todayPart.from === 'source'\n\t\t\t\t? 'source'\n\t\t\t\t: closedPart.from === 'stale' || todayPart.from === 'stale'\n\t\t\t\t\t? 'stale'\n\t\t\t\t\t: todayPart.from\n\t\treturn { q, result: mergeAtToday(closedPart.result, todayPart.result, q), from }\n\t}\n\n\treturn {\n\t\tasync read(adapter, query, options = {}) {\n\t\t\tconst startedAt = timerNow()\n\t\t\topts.onRead?.()\n\t\t\tif (!adapter.isConfigured()) return emptyResult(adapter.id, now())\n\t\t\tcheckFilters(adapter, query)\n\t\t\tconst prepared = await prepare(adapter, query)\n\t\t\tconst found =\n\t\t\t\t(await keepSplit(adapter, prepared, options)) ?? (await keep(adapter, prepared, options))\n\t\t\treturn options.afterRead === false ? found.result : answered({ adapter, ...found, startedAt })\n\t\t},\n\n\t\tasync refresh(adapter, query, options) {\n\t\t\tif (!adapter.isConfigured()) {\n\t\t\t\treturn 'fresh'\n\t\t\t}\n\t\t\tcheckFilters(adapter, query)\n\t\t\tconst prepared = await prepare(adapter, query)\n\t\t\tconst entry = await cached(prepared.key)\n\t\t\tif (entry && entry.expiresAt - now() > options.freshForMs) {\n\t\t\t\treturn 'fresh'\n\t\t\t}\n\t\t\tawait coalesce(prepared.key, () =>\n\t\t\t\tfetchFresh(adapter, prepared, {\n\t\t\t\t\tpriority: options.priority ?? 'background',\n\t\t\t\t\tawaitStore: true,\n\t\t\t\t})\n\t\t\t)\n\t\t\treturn 'refreshed'\n\t\t},\n\t\tasync peek(adapter, query, options = {}) {\n\t\t\tconst startedAt = timerNow()\n\t\t\tif (!adapter.isConfigured()) return emptyResult(adapter.id, now())\n\t\t\tcheckFilters(adapter, query)\n\t\t\tconst look = async (): Promise<Kept | null> => {\n\t\t\t\tconst prepared = await prepare(adapter, query)\n\t\t\t\tconst { key, q } = prepared\n\t\t\t\tconst memoized = memo.get(key)\n\t\t\t\tif (memoized) {\n\t\t\t\t\treturn { q, result: memoized, from: 'memory' }\n\t\t\t\t}\n\t\t\t\tconst entry = await cached(key)\n\t\t\t\tconst at = now()\n\t\t\t\tif (!entry || entry.staleUntil <= at) {\n\t\t\t\t\treturn null\n\t\t\t\t}\n\t\t\t\tif (entry.expiresAt > at) {\n\t\t\t\t\tmemoizeEntry(key, entry, at)\n\t\t\t\t\treturn { q, result: entry.value, from: 'store' }\n\t\t\t\t}\n\t\t\t\tconst failure = failures.get(key)\n\t\t\t\tif (failure?.kind === 'invalid_param') {\n\t\t\t\t\treturn null\n\t\t\t\t}\n\t\t\t\tconst result = staleResult(\n\t\t\t\t\tentry,\n\t\t\t\t\tsourceErrorOf(failure, lanes.for(adapter, q.scope ?? null).health())\n\t\t\t\t)\n\t\t\t\treturn { q, result, from: 'stale' }\n\t\t\t}\n\t\t\t// A store or an epoch lookup that fails is a miss like any other: the caller reads instead.\n\t\t\tconst found = await withinBudget(look(), options.budgetMs ?? PEEK_BUDGET_MS).catch(() => null)\n\t\t\treturn found && found !== OVER_BUDGET ? answered({ adapter, ...found, startedAt }) : undefined\n\t\t},\n\t\tasync realtime(adapter, query) {\n\t\t\tconst realtime = adapter.realtime\n\t\t\tif (!realtime) {\n\t\t\t\tthrow new Error(`analytics: the \"${adapter.id}\" source counts no live visitors`)\n\t\t\t}\n\t\t\tconst scope = query.scope ?? null\n\t\t\ttry {\n\t\t\t\treturn await withinTimeout(({ signal, deadline }) =>\n\t\t\t\t\tthroughLane(adapter, (ctx) => realtime.call(adapter, query, ctx), {\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tpriority: 'interactive',\n\t\t\t\t\t\tdeadline,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t} catch (err) {\n\t\t\t\tif (!isLaneRefused(err)) {\n\t\t\t\t\topts.onError?.(err, adapter.id, scope)\n\t\t\t\t}\n\t\t\t\tthrow new ReadFailedError(\n\t\t\t\t\twithLaneRetryAfter(classifyError(err), lanes.for(adapter, scope).health()),\n\t\t\t\t\terr\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t\tidle,\n\t\tkeep(work) {\n\t\t\tinBackground(work)\n\t\t},\n\t\tasync close() {\n\t\t\tclosed = true\n\t\t\tawait idle()\n\t\t},\n\t\thealth(adapter, scope) {\n\t\t\treturn lanes.for(adapter, scope ?? null).health()\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,iBAAiB;;AAGvB,MAAM,kBAAkB;;AAMxB,MAAM,sBAAsB;;AAG5B,MAAM,aAAa,UAClB,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;;AAGnD,MAAM,eAAe,UACpB,UAAU,MAAM,SAAS,KACzB,UAAU,MAAM,SAAS,KACzB,UAAU,MAAM,UAAU,MACzB,MAAM,WAAW,KAAA,KAAa,MAAM,WAAW,QAAQ,UAAU,MAAM,MAAM;;;;;AAM/E,MAAM,WAAW;;;;;AAMjB,MAAM,cACL,OACA,iBACA,KAAA,UAC8D;CAC9D,MAAM,QACL,mBAAmB,OAAO,IAAI,eAAe,MAAM,KAAK,EAAE,EAAE,QAAQ,IAAI,kBAAkB;CAC3F,IAAI,MAAM,MAAM,QAAQ,KAAK,OAC5B,OAAO;EAAE;EAAO,SAAS;CAAM;CAEhC,OAAO;EAAE,OA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AmB,QAAQ,GAAG,iCAAiC;GAEhF,MAAM,QAAQ,MAAM,SAAS;GAC7B,IAAI;IACH,OAAO,MAAM,eAAe,EAAE,QAAQ,eACrC,YAAY,UAAU,QAAQ,SAAS,KAAK,SAAS,OAAO,GAAG,GAAG;KACjE;KACA,UAAU;KACV;KACA;IACD,CAAC,CACF;GACD,SAAS,KAAK;IACb,IAAI,CAAC,cAAc,GAAG,GACrB,KAAK,UAAU,KAAK,QAAQ,IAAI,KAAK;IAEtC,MAAM,IAAI,gBACT,mBAAmB,cAAc,GAAG,GAAG,MAAM,IAAI,SAAS,KAAK,EAAE,OAAO,CAAC,GACzE,GACD;GACD;EACD;EACA;EACA,KAAK,MAAM;GACV,aAAa,IAAI;EAClB;EACA,MAAM,QAAQ;GACb,SAAS;GACT,MAAM,KAAK;EACZ;EACA,OAAO,SAAS,OAAO;GACtB,OAAO,MAAM,IAAI,SAAS,SAAS,IAAI,EAAE,OAAO;EACjD;CACD;AACD"}
|
package/dist/surfacing/lanes.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { recallOr } from "./bounded.js";
|
|
2
|
-
import { monotonicMs } from "../core/monotonic.js";
|
|
3
2
|
import { BREAKER_MAX_MS, createBreaker } from "./breaker.js";
|
|
3
|
+
import { monotonicMs } from "../core/monotonic.js";
|
|
4
4
|
import { LaneRefusedError, classifyError, isLaneRefused } from "./classifyError.js";
|
|
5
5
|
import { createTokenSource, mostUrgent } from "./rateLimiter.js";
|
|
6
6
|
/** Reads in flight on a local source (native), which stays outside the global cap. */
|
|
@@ -144,6 +144,24 @@ const createLaneCore = (setup) => {
|
|
|
144
144
|
await sleep(pausedFor, options.signal);
|
|
145
145
|
}
|
|
146
146
|
};
|
|
147
|
+
const healthOf = (key) => {
|
|
148
|
+
const breaker = breakers.get(key);
|
|
149
|
+
const snapshot = breaker?.snapshot();
|
|
150
|
+
const peek = breaker?.peek() ?? {
|
|
151
|
+
ok: true,
|
|
152
|
+
probe: false
|
|
153
|
+
};
|
|
154
|
+
const pausedFor = pausedUntil - now();
|
|
155
|
+
const retryAfterMs = Math.max(peek.ok ? 0 : peek.retryAfterMs, pausedFor > 0 ? pausedFor : 0);
|
|
156
|
+
const last = snapshot?.lastFailure;
|
|
157
|
+
return {
|
|
158
|
+
open: !peek.ok,
|
|
159
|
+
...retryAfterMs > 0 ? { retryAfterMs } : {},
|
|
160
|
+
...last ? { lastFailure: last.kind } : {},
|
|
161
|
+
...last?.hostRefused ? { hostRefused: true } : {},
|
|
162
|
+
...abandoned > 0 ? { abandoned } : {}
|
|
163
|
+
};
|
|
164
|
+
};
|
|
147
165
|
const viewOf = (key) => ({
|
|
148
166
|
async run(fn, options) {
|
|
149
167
|
const { signal, priority } = options;
|
|
@@ -179,10 +197,15 @@ const createLaneCore = (setup) => {
|
|
|
179
197
|
throw refusedOpen(admission.retryAfterMs);
|
|
180
198
|
}
|
|
181
199
|
let counted = false;
|
|
182
|
-
const record = (outcome) => {
|
|
200
|
+
const record = (outcome, error) => {
|
|
183
201
|
if (!counted) {
|
|
184
202
|
counted = true;
|
|
185
203
|
breaker.record(outcome, admission.probe);
|
|
204
|
+
setup.onOutcome?.(setup.adapter, outcome === "success" ? { ok: true } : {
|
|
205
|
+
ok: false,
|
|
206
|
+
failure: outcome,
|
|
207
|
+
...error === void 0 ? {} : { error }
|
|
208
|
+
}, healthOf(key));
|
|
186
209
|
}
|
|
187
210
|
};
|
|
188
211
|
const settled = (async () => fn(signal))().then((value) => {
|
|
@@ -190,8 +213,8 @@ const createLaneCore = (setup) => {
|
|
|
190
213
|
return value;
|
|
191
214
|
}, (err) => {
|
|
192
215
|
const failure = classifyError(err);
|
|
193
|
-
record(failure);
|
|
194
216
|
if (failure.kind === "unavailable" && failure.retryAfterMs !== void 0) pausedUntil = Math.max(pausedUntil, now() + Math.min(failure.retryAfterMs, BREAKER_MAX_MS));
|
|
217
|
+
record(failure, err);
|
|
195
218
|
throw err;
|
|
196
219
|
});
|
|
197
220
|
let abandonTimer;
|
|
@@ -214,24 +237,7 @@ const createLaneCore = (setup) => {
|
|
|
214
237
|
done.catch(() => {});
|
|
215
238
|
return untilAborted(done, signal);
|
|
216
239
|
},
|
|
217
|
-
health()
|
|
218
|
-
const breaker = breakers.get(key);
|
|
219
|
-
const snapshot = breaker?.snapshot();
|
|
220
|
-
const peek = breaker?.peek() ?? {
|
|
221
|
-
ok: true,
|
|
222
|
-
probe: false
|
|
223
|
-
};
|
|
224
|
-
const pausedFor = pausedUntil - now();
|
|
225
|
-
const retryAfterMs = Math.max(peek.ok ? 0 : peek.retryAfterMs, pausedFor > 0 ? pausedFor : 0);
|
|
226
|
-
const last = snapshot?.lastFailure;
|
|
227
|
-
return {
|
|
228
|
-
open: !peek.ok,
|
|
229
|
-
...retryAfterMs > 0 ? { retryAfterMs } : {},
|
|
230
|
-
...last ? { lastFailure: last.kind } : {},
|
|
231
|
-
...last?.hostRefused ? { hostRefused: true } : {},
|
|
232
|
-
...abandoned > 0 ? { abandoned } : {}
|
|
233
|
-
};
|
|
234
|
-
}
|
|
240
|
+
health: () => healthOf(key)
|
|
235
241
|
});
|
|
236
242
|
return (scope) => {
|
|
237
243
|
const key = scopeKeyOf(scope);
|
|
@@ -260,7 +266,8 @@ const createLanes = (options = {}) => {
|
|
|
260
266
|
shared: options.shared?.(adapter) === true,
|
|
261
267
|
...options.breaker ? { breaker: options.breaker } : {},
|
|
262
268
|
abandonAfterMs: options.abandonAfterMs ?? 5e3,
|
|
263
|
-
...options.onAbandon ? { onAbandon: options.onAbandon } : {}
|
|
269
|
+
...options.onAbandon ? { onAbandon: options.onAbandon } : {},
|
|
270
|
+
...options.onOutcome ? { onOutcome: options.onOutcome } : {}
|
|
264
271
|
});
|
|
265
272
|
};
|
|
266
273
|
return { for(adapter, scope) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lanes.js","names":[],"sources":["../../src/surfacing/lanes.ts"],"sourcesContent":["import type { AnalyticsAdapter } from '../core/contract'\nimport { monotonicMs } from '../core/monotonic'\nimport { recallOr } from './bounded'\nimport { BREAKER_MAX_MS, type Breaker, type BreakerOptions, createBreaker } from './breaker'\nimport {\n\tclassifyError,\n\tisLaneRefused,\n\tLaneRefusedError,\n\ttype ReadFailure,\n\ttype ReadFailureKind,\n} from './classifyError'\nimport { createTokenSource, mostUrgent, type Priority } from './rateLimiter'\n\nexport type { Priority } from './rateLimiter'\n\n/** Upstream requests in flight across every vendor source of one instance, by default. */\nexport const DEFAULT_GLOBAL_CONCURRENCY = 16\n\n/** Upstream requests in flight per vendor source that declares no `rateLimit.maxConcurrent`. */\nexport const DEFAULT_SOURCE_CONCURRENCY = 4\n\n/** Reads in flight on a local source (native), which stays outside the global cap. */\nconst DEFAULT_LOCAL_CONCURRENCY = 8\n\n/** The fewest and most native reads in flight when the lane is sized from a Postgres pool. */\nconst MIN_POOLED_CONCURRENCY = 1\nexport const MAX_POOLED_CONCURRENCY = 8\n\n/**\n * Native lane size on a host Postgres pool of `poolMax`: a third, capped at the engine's long-work\n * share, so reads queue in the lane (deadline and priority aware), not unseen for a connection.\n */\nexport const pooledConcurrency = (poolMax: number): number =>\n\tMath.min(MAX_POOLED_CONCURRENCY, Math.max(MIN_POOLED_CONCURRENCY, Math.floor(poolMax / 3)))\n\n/** The slots one scope may hold at once in a lane every scope shares: half, rounded up. */\nconst scopeShareOf = (capacity: number): number => Math.max(1, Math.ceil(capacity / 2))\n\n/** Retries of an upstream request that failed as `unavailable`, with backoff between them. */\nconst MAX_RETRIES = 2\n\n/** The first backoff, 0.5 s; the second is 1.25 s (see {@link runUpstream}). */\nexport const RETRY_BASE_MS = 500\n\n/**\n * How long a request may stay out after its signal aborted before its slots are given back: one\n * that honours the signal settles at once, and GA4's own gRPC deadline ends with the read.\n */\nexport const ABANDON_AFTER_MS = 5_000\n\nexport interface LaneRunOptions {\n\tsignal: AbortSignal\n\tpriority: Priority\n\t/** Epoch milliseconds the caller gives up at: a wait that would outlast it is refused at once. */\n\tdeadline?: number\n}\n\nexport interface LaneHealth {\n\t/** The lane refuses new requests right now: its breaker is open. */\n\topen: boolean\n\t/** Until the lane takes requests again, when open or the vendor asked it to wait. */\n\tretryAfterMs?: number\n\t/** What the failure that last counted against the lane meant, cleared by a success. */\n\tlastFailure?: ReadFailureKind\n\t/** That failure was a refused host. */\n\thostRefused?: true\n\t/**\n\t * Requests whose slots were given back while they were still out, having ignored their abort\n\t * signal for {@link ABANDON_AFTER_MS}; absent while there are none.\n\t */\n\tabandoned?: number\n}\n\n/**\n * One adapter's requests for one scope. A `run` takes a rate token, a lane slot and a global slot\n * in that order; the pause, tokens and slots are the adapter's, the breaker each scope's own.\n */\nexport interface Lane {\n\trun<T>(fn: (signal: AbortSignal) => Promise<T>, options: LaneRunOptions): Promise<T>\n\thealth(): LaneHealth\n}\n\nexport interface Lanes {\n\t/**\n\t * The lane of one adapter instance for `scope`, made on first use; for an adapter built anew on\n\t * every read, the lane of its id within `scope`.\n\t */\n\tfor(adapter: AnalyticsAdapter, scope?: string | null): Lane\n}\n\nexport interface LanesOptions {\n\t/** Slots shared by every vendor source; default {@link DEFAULT_GLOBAL_CONCURRENCY}. */\n\tglobal?: number\n\t/** Slots of a source without `maxConcurrent`; default {@link DEFAULT_SOURCE_CONCURRENCY}. */\n\tperSource?: number\n\t/** Which sources are local (native), which get their own lane outside the global cap. */\n\tlocal?: { is: (adapter: AnalyticsAdapter) => boolean; capacity?: number }\n\t/** Clock for waits and deadlines; the timers' monotonic one (`monotonicMs`) by default. */\n\tnow?: () => number\n\t/**\n\t * Adapters built anew per read (`providers.resolve`): keyed by scope and id rather than object,\n\t * so each keeps one lane, and two tenants' sources of one id never share a breaker.\n\t */\n\trebuilt?: (adapter: AnalyticsAdapter) => boolean\n\t/**\n\t * Which adapters serve every scope through one lane (the config adapters of a scoped install):\n\t * one scope holds at most {@link scopeShareOf} of their slots, so another always gets one.\n\t */\n\tshared?: (adapter: AnalyticsAdapter) => boolean\n\tbreaker?: Omit<BreakerOptions, 'now'>\n\t/** How long a request may ignore its abort before its slots return; {@link ABANDON_AFTER_MS}. */\n\tabandonAfterMs?: number\n\t/** Told the first time a lane gives back the slots of a request that ignored its abort signal. */\n\tonAbandon?: (adapter: AnalyticsAdapter) => void\n}\n\ntype Release = () => void\n\n/** The install-wide scope (null) is keyed `''`; it never counts against a scope's share. */\nconst UNSCOPED = ''\n\nconst scopeKeyOf = (scope: string | null | undefined): string =>\n\tscope === null || scope === undefined ? UNSCOPED : `s:${scope}`\n\ninterface Slots {\n\tacquire(priority: Priority, signal: AbortSignal, scope?: string): Promise<Release>\n}\n\ninterface SlotWaiter {\n\tpriority: Priority\n\tscope: string\n\tgrant: () => void\n}\n\n/**\n * A counting semaphore serving the most urgent waiter first, never more than `backgroundCap` slots\n * to background work, and, given a `scopeCap`, never more than that many to one scope.\n */\nconst createSlots = (capacity: number, backgroundCap: number, scopeCap?: number): Slots => {\n\tlet active = 0\n\tlet background = 0\n\tconst waiters: SlotWaiter[] = []\n\tconst heldBy = new Map<string, number>()\n\n\tconst withinShare = (waiter: SlotWaiter): boolean =>\n\t\tscopeCap === undefined ||\n\t\twaiter.scope === UNSCOPED ||\n\t\t(heldBy.get(waiter.scope) ?? 0) < scopeCap\n\n\tconst pick = (): SlotWaiter | undefined =>\n\t\tmostUrgent(\n\t\t\twaiters.filter(\n\t\t\t\t(waiter) =>\n\t\t\t\t\twithinShare(waiter) && (waiter.priority !== 'background' || background < backgroundCap)\n\t\t\t)\n\t\t)\n\n\tconst hold = (scope: string, by: number): void => {\n\t\tconst next = (heldBy.get(scope) ?? 0) + by\n\t\tif (next > 0) {\n\t\t\theldBy.set(scope, next)\n\t\t} else {\n\t\t\theldBy.delete(scope)\n\t\t}\n\t}\n\n\tconst pump = (): void => {\n\t\twhile (active < capacity) {\n\t\t\tconst chosen = pick()\n\t\t\tif (!chosen) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twaiters.splice(waiters.indexOf(chosen), 1)\n\t\t\tactive++\n\t\t\thold(chosen.scope, 1)\n\t\t\tif (chosen.priority === 'background') {\n\t\t\t\tbackground++\n\t\t\t}\n\t\t\tchosen.grant()\n\t\t}\n\t}\n\n\treturn {\n\t\tacquire(priority, signal, scope = UNSCOPED) {\n\t\t\tif (signal.aborted) {\n\t\t\t\treturn Promise.reject(signal.reason)\n\t\t\t}\n\t\t\treturn new Promise<Release>((resolve, reject) => {\n\t\t\t\tlet released = false\n\t\t\t\tconst release = (): void => {\n\t\t\t\t\tif (released) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treleased = true\n\t\t\t\t\tactive--\n\t\t\t\t\thold(scope, -1)\n\t\t\t\t\tif (priority === 'background') {\n\t\t\t\t\t\tbackground--\n\t\t\t\t\t}\n\t\t\t\t\tpump()\n\t\t\t\t}\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\tconst index = waiters.indexOf(waiter)\n\t\t\t\t\tif (index !== -1) {\n\t\t\t\t\t\twaiters.splice(index, 1)\n\t\t\t\t\t}\n\t\t\t\t\treject(signal.reason)\n\t\t\t\t}\n\t\t\t\tconst waiter: SlotWaiter = {\n\t\t\t\t\tpriority,\n\t\t\t\t\tscope,\n\t\t\t\t\tgrant: () => {\n\t\t\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\t\t\tresolve(release)\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\twaiters.push(waiter)\n\t\t\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\t\t\tpump()\n\t\t\t})\n\t\t},\n\t}\n}\n\n/** Resolves after `ms`, or rejects with the signal's reason once it aborts. */\nconst sleep = (ms: number, signal: AbortSignal): Promise<void> => {\n\tif (signal.aborted) {\n\t\treturn Promise.reject(signal.reason)\n\t}\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst onAbort = (): void => {\n\t\t\tclearTimeout(timer)\n\t\t\treject(signal.reason)\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\tresolve()\n\t\t}, ms)\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t})\n}\n\n/**\n * Settles with `work`, or rejects with the signal's reason first: the slot stays held until `work`\n * settles, or until {@link ABANDON_AFTER_MS} after the abort for work that never does.\n */\nconst untilAborted = <T>(work: Promise<T>, signal: AbortSignal): Promise<T> => {\n\tif (signal.aborted) {\n\t\treturn Promise.reject(signal.reason)\n\t}\n\tlet onAbort: (() => void) | undefined\n\tconst aborted = new Promise<never>((_resolve, reject) => {\n\t\tonAbort = () => reject(signal.reason)\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t})\n\treturn Promise.race([work, aborted]).finally(() => {\n\t\tif (onAbort) {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t}\n\t})\n}\n\nconst noRelease: Release = () => {}\n\ninterface LaneSetup {\n\tadapter: AnalyticsAdapter\n\tcapacity: number\n\tglobal: Slots | undefined\n\tnow: () => number\n\t/** Every scope reads through this lane: each holds at most its share of the slots. */\n\tshared: boolean\n\tbreaker?: Omit<BreakerOptions, 'now'>\n\tabandonAfterMs: number\n\tonAbandon?: (adapter: AnalyticsAdapter) => void\n}\n\n/** What a request that ignored its abort counts as against the breaker. */\nconst ABANDONED: ReadFailure = { kind: 'unavailable', timeout: true }\n\n/** A breaker with nothing to remember: closed, no failure counted since its last answer. */\nconst isClean = (breaker: Breaker): boolean => {\n\tconst snapshot = breaker.snapshot()\n\treturn snapshot.state === 'closed' && snapshot.lastFailure === undefined\n}\n\n/** One adapter's pause, tokens and slots, and one breaker per scope reading through them. */\nconst createLaneCore = (setup: LaneSetup): ((scope: string | null | undefined) => Lane) => {\n\tconst { now } = setup\n\tconst tokens = createTokenSource(setup.adapter.capabilities.rateLimit, now)\n\tconst slots = createSlots(\n\t\tsetup.capacity,\n\t\tMath.max(1, Math.floor(setup.capacity / 2)),\n\t\tsetup.shared ? scopeShareOf(setup.capacity) : undefined\n\t)\n\tconst breakers = new Map<string, Breaker>()\n\tconst views = new Map<string, Lane>()\n\tlet pausedUntil = 0\n\tlet abandoned = 0\n\n\tconst breakerOf = (key: string): Breaker =>\n\t\trecallOr(\n\t\t\tbreakers,\n\t\t\t[key, () => createBreaker({ now, ...setup.breaker })],\n\t\t\t(breaker) => !isClean(breaker)\n\t\t)\n\n\tconst waitOutPause = async (options: LaneRunOptions): Promise<void> => {\n\t\tfor (;;) {\n\t\t\tconst pausedFor = pausedUntil - now()\n\t\t\tif (pausedFor <= 0) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (options.deadline !== undefined && pausedUntil > options.deadline) {\n\t\t\t\tthrow new LaneRefusedError('paused', pausedFor)\n\t\t\t}\n\t\t\tawait sleep(pausedFor, options.signal)\n\t\t}\n\t}\n\n\tconst viewOf = (key: string): Lane => ({\n\t\tasync run(fn, options) {\n\t\t\tconst { signal, priority } = options\n\t\t\tif (signal.aborted) {\n\t\t\t\tthrow signal.reason\n\t\t\t}\n\t\t\tconst breaker = breakerOf(key)\n\t\t\tconst refusedOpen = (retryAfterMs: number): LaneRefusedError =>\n\t\t\t\tnew LaneRefusedError('open', retryAfterMs, breaker.snapshot().lastFailure)\n\t\t\tconst peek = breaker.peek()\n\t\t\tif (!peek.ok) {\n\t\t\t\tthrow refusedOpen(peek.retryAfterMs)\n\t\t\t}\n\t\t\t// A breaker due its probe lets one run through: it is claimed before the run spends a rate\n\t\t\t// token or waits for a slot, so the runs it turns away spend nothing.\n\t\t\tconst claimed = peek.probe ? breaker.admit() : undefined\n\t\t\tif (claimed && !claimed.ok) {\n\t\t\t\tthrow refusedOpen(claimed.retryAfterMs)\n\t\t\t}\n\t\t\tlet releaseLane = noRelease\n\t\t\tlet releaseGlobal = noRelease\n\t\t\tconst releaseSlots = (): void => {\n\t\t\t\treleaseGlobal()\n\t\t\t\treleaseLane()\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait waitOutPause(options)\n\t\t\t\tawait tokens.take({ signal, priority })\n\t\t\t\treleaseLane = await slots.acquire(priority, signal, key)\n\t\t\t\treleaseGlobal = setup.global ? await setup.global.acquire(priority, signal) : noRelease\n\t\t\t} catch (err) {\n\t\t\t\treleaseSlots()\n\t\t\t\tif (claimed?.probe) {\n\t\t\t\t\tbreaker.release()\n\t\t\t\t}\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\tconst admission = claimed ?? breaker.admit()\n\t\t\tif (!admission.ok) {\n\t\t\t\treleaseSlots()\n\t\t\t\tthrow refusedOpen(admission.retryAfterMs)\n\t\t\t}\n\t\t\tlet counted = false\n\t\t\tconst record = (outcome: 'success' | ReadFailure): void => {\n\t\t\t\tif (!counted) {\n\t\t\t\t\tcounted = true\n\t\t\t\t\tbreaker.record(outcome, admission.probe)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst settled = (async () => fn(signal))().then(\n\t\t\t\t(value) => {\n\t\t\t\t\trecord('success')\n\t\t\t\t\treturn value\n\t\t\t\t},\n\t\t\t\t(err: unknown) => {\n\t\t\t\t\tconst failure = classifyError(err)\n\t\t\t\t\trecord(failure)\n\t\t\t\t\tif (failure.kind === 'unavailable' && failure.retryAfterMs !== undefined) {\n\t\t\t\t\t\tpausedUntil = Math.max(\n\t\t\t\t\t\t\tpausedUntil,\n\t\t\t\t\t\t\tnow() + Math.min(failure.retryAfterMs, BREAKER_MAX_MS)\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tthrow err\n\t\t\t\t}\n\t\t\t)\n\t\t\tlet abandonTimer: ReturnType<typeof setTimeout> | undefined\n\t\t\t// Past the grace a request that ignores its abort gives its slots back, counted as a timeout.\n\t\t\tconst abandon = (): void => {\n\t\t\t\tabandonTimer = setTimeout(() => {\n\t\t\t\t\treleaseSlots()\n\t\t\t\t\trecord(ABANDONED)\n\t\t\t\t\tabandoned++\n\t\t\t\t\tif (abandoned === 1) {\n\t\t\t\t\t\tsetup.onAbandon?.(setup.adapter)\n\t\t\t\t\t}\n\t\t\t\t}, setup.abandonAfterMs)\n\t\t\t\tabandonTimer.unref?.()\n\t\t\t}\n\t\t\tif (signal.aborted) {\n\t\t\t\tabandon()\n\t\t\t} else {\n\t\t\t\tsignal.addEventListener('abort', abandon, { once: true })\n\t\t\t}\n\t\t\tconst done = settled.finally(() => {\n\t\t\t\tsignal.removeEventListener('abort', abandon)\n\t\t\t\tclearTimeout(abandonTimer)\n\t\t\t\treleaseSlots()\n\t\t\t})\n\t\t\t// The caller may stop waiting at the abort; the request still settles, and is not unhandled.\n\t\t\tdone.catch(() => {})\n\t\t\treturn untilAborted(done, signal)\n\t\t},\n\t\thealth() {\n\t\t\tconst breaker = breakers.get(key)\n\t\t\tconst snapshot = breaker?.snapshot()\n\t\t\tconst peek = breaker?.peek() ?? { ok: true as const, probe: false }\n\t\t\tconst pausedFor = pausedUntil - now()\n\t\t\tconst retryAfterMs = Math.max(peek.ok ? 0 : peek.retryAfterMs, pausedFor > 0 ? pausedFor : 0)\n\t\t\tconst last = snapshot?.lastFailure\n\t\t\treturn {\n\t\t\t\topen: !peek.ok,\n\t\t\t\t...(retryAfterMs > 0 ? { retryAfterMs } : {}),\n\t\t\t\t...(last ? { lastFailure: last.kind } : {}),\n\t\t\t\t...(last?.hostRefused ? { hostRefused: true as const } : {}),\n\t\t\t\t...(abandoned > 0 ? { abandoned } : {}),\n\t\t\t}\n\t\t},\n\t})\n\n\treturn (scope) => {\n\t\tconst key = scopeKeyOf(scope)\n\t\treturn recallOr(views, [key, () => viewOf(key)])\n\t}\n}\n\n/**\n * One lane per adapter object, so a re-saved provider starts fresh. Vendor lanes share the global\n * slots; local (native) lanes do not, so a slow vendor never queues the plugin's own reads.\n */\nexport const createLanes = (options: LanesOptions = {}): Lanes => {\n\tconst now = options.now ?? monotonicMs\n\tconst globalCapacity = options.global ?? DEFAULT_GLOBAL_CONCURRENCY\n\tconst global = createSlots(globalCapacity, globalCapacity)\n\tconst cores = new WeakMap<AnalyticsAdapter, (scope: string | null | undefined) => Lane>()\n\tconst lanesById = new Map<string, Lane>()\n\n\tconst coreFor = (adapter: AnalyticsAdapter): ((scope: string | null | undefined) => Lane) => {\n\t\tconst local = options.local?.is(adapter) === true\n\t\tconst declared = adapter.capabilities.rateLimit?.maxConcurrent\n\t\tconst fallback = local\n\t\t\t? (options.local?.capacity ?? DEFAULT_LOCAL_CONCURRENCY)\n\t\t\t: (options.perSource ?? DEFAULT_SOURCE_CONCURRENCY)\n\t\treturn createLaneCore({\n\t\t\tadapter,\n\t\t\tcapacity: declared !== undefined && declared > 0 ? declared : fallback,\n\t\t\tglobal: local ? undefined : global,\n\t\t\tnow,\n\t\t\tshared: options.shared?.(adapter) === true,\n\t\t\t...(options.breaker ? { breaker: options.breaker } : {}),\n\t\t\tabandonAfterMs: options.abandonAfterMs ?? ABANDON_AFTER_MS,\n\t\t\t...(options.onAbandon ? { onAbandon: options.onAbandon } : {}),\n\t\t})\n\t}\n\n\treturn {\n\t\tfor(adapter, scope) {\n\t\t\tif (options.rebuilt?.(adapter) === true) {\n\t\t\t\tconst id = JSON.stringify([scope ?? null, adapter.id])\n\t\t\t\treturn recallOr(lanesById, [id, () => coreFor(adapter)(scope)])\n\t\t\t}\n\t\t\tconst core = cores.get(adapter) ?? coreFor(adapter)\n\t\t\tcores.set(adapter, core)\n\t\t\treturn core(scope)\n\t\t},\n\t}\n}\n\n/**\n * One upstream request, retried up to {@link MAX_RETRIES} times on a transient `unavailable` but\n * never after a timeout or spent quota, nor past the deadline; a lane refusal ends it at once.\n */\nexport const runUpstream = async <T>(\n\tlane: Lane,\n\tfn: (signal: AbortSignal) => Promise<T>,\n\toptions: LaneRunOptions & { now: () => number; baseDelayMs?: number }\n): Promise<T> => {\n\tconst base = options.baseDelayMs ?? RETRY_BASE_MS\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\treturn await lane.run(fn, options)\n\t\t} catch (err) {\n\t\t\tif (isLaneRefused(err) || options.signal.aborted) {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\tconst failure = classifyError(err)\n\t\t\tif (\n\t\t\t\tfailure.kind !== 'unavailable' ||\n\t\t\t\tfailure.timeout ||\n\t\t\t\tfailure.quota ||\n\t\t\t\tattempt >= MAX_RETRIES\n\t\t\t) {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\t// Fixed rather than random, so the schedule is testable: 0.5 s, then 1.25 s.\n\t\t\tconst delay = base * 2 ** attempt + base * 0.5 * attempt\n\t\t\tif (options.deadline !== undefined && options.now() + delay >= options.deadline) {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait sleep(delay, options.signal)\n\t\t\t} catch {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;AAsBA,MAAM,4BAA4B;;AAGlC,MAAM,yBAAyB;;;;;AAO/B,MAAa,qBAAqB,YACjC,KAAK,IAAA,GAA4B,KAAK,IAAI,wBAAwB,KAAK,MAAM,UAAU,CAAC,CAAC,CAAC;;AAG3F,MAAM,gBAAgB,aAA6B,KAAK,IAAI,GAAG,KAAK,KAAK,WAAW,CAAC,CAAC;;AAGtF,MAAM,cAAc;;;;;AASpB,MAAa,mBAAmB;;AAuEhC,MAAM,WAAW;AAEjB,MAAM,cAAc,UACnB,UAAU,QAAQ,UAAU,KAAA,IAAY,WAAW,KAAK;;;;;AAgBzD,MAAM,eAAe,UAAkB,eAAuB,aAA6B;CAC1F,IAAI,SAAS;CACb,IAAI,aAAa;CACjB,MAAM,UAAwB,CAAC;CAC/B,MAAM,yBAAS,IAAI,IAAoB;CAEvC,MAAM,eAAe,WACpB,aAAa,KAAA,KACb,OAAO,UAAU,aAChB,OAAO,IAAI,OAAO,KAAK,KAAK,KAAK;CAEnC,MAAM,aACL,WACC,QAAQ,QACN,WACA,YAAY,MAAM,MAAM,OAAO,aAAa,gBAAgB,aAAa,cAC3E,CACD;CAED,MAAM,QAAQ,OAAe,OAAqB;EACjD,MAAM,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK;EACxC,IAAI,OAAO,GACV,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eAAA;CACrB,KAAK,IAAI,UAAU,IAAK,WACvB,IAAI;EACH,OAAO,MAAM,KAAK,IAAI,IAAI,OAAO;CAClC,SAAS,KAAK;EACb,IAAI,cAAc,GAAG,KAAK,QAAQ,OAAO,SACxC,MAAM;EAEP,MAAM,UAAU,cAAc,GAAG;EACjC,IACC,QAAQ,SAAS,iBACjB,QAAQ,WACR,QAAQ,SACR,WAAW,aAEX,MAAM;EAGP,MAAM,QAAQ,OAAO,KAAK,UAAU,OAAO,KAAM;EACjD,IAAI,QAAQ,aAAa,KAAA,KAAa,QAAQ,IAAI,IAAI,SAAS,QAAQ,UACtE,MAAM;EAEP,IAAI;GACH,MAAM,MAAM,OAAO,QAAQ,MAAM;EAClC,QAAQ;GACP,MAAM;EACP;CACD;AAEF"}
|
|
1
|
+
{"version":3,"file":"lanes.js","names":[],"sources":["../../src/surfacing/lanes.ts"],"sourcesContent":["import type { AnalyticsAdapter } from '../core/contract'\nimport { monotonicMs } from '../core/monotonic'\nimport { recallOr } from './bounded'\nimport { BREAKER_MAX_MS, type Breaker, type BreakerOptions, createBreaker } from './breaker'\nimport {\n\tclassifyError,\n\tisLaneRefused,\n\tLaneRefusedError,\n\ttype ReadFailure,\n\ttype ReadFailureKind,\n} from './classifyError'\nimport { createTokenSource, mostUrgent, type Priority } from './rateLimiter'\n\nexport type { Priority } from './rateLimiter'\n\n/** Upstream requests in flight across every vendor source of one instance, by default. */\nexport const DEFAULT_GLOBAL_CONCURRENCY = 16\n\n/** Upstream requests in flight per vendor source that declares no `rateLimit.maxConcurrent`. */\nexport const DEFAULT_SOURCE_CONCURRENCY = 4\n\n/** Reads in flight on a local source (native), which stays outside the global cap. */\nconst DEFAULT_LOCAL_CONCURRENCY = 8\n\n/** The fewest and most native reads in flight when the lane is sized from a Postgres pool. */\nconst MIN_POOLED_CONCURRENCY = 1\nexport const MAX_POOLED_CONCURRENCY = 8\n\n/**\n * Native lane size on a host Postgres pool of `poolMax`: a third, capped at the engine's long-work\n * share, so reads queue in the lane (deadline and priority aware), not unseen for a connection.\n */\nexport const pooledConcurrency = (poolMax: number): number =>\n\tMath.min(MAX_POOLED_CONCURRENCY, Math.max(MIN_POOLED_CONCURRENCY, Math.floor(poolMax / 3)))\n\n/** The slots one scope may hold at once in a lane every scope shares: half, rounded up. */\nconst scopeShareOf = (capacity: number): number => Math.max(1, Math.ceil(capacity / 2))\n\n/** Retries of an upstream request that failed as `unavailable`, with backoff between them. */\nconst MAX_RETRIES = 2\n\n/** The first backoff, 0.5 s; the second is 1.25 s (see {@link runUpstream}). */\nexport const RETRY_BASE_MS = 500\n\n/**\n * How long a request may stay out after its signal aborted before its slots are given back: one\n * that honours the signal settles at once, and GA4's own gRPC deadline ends with the read.\n */\nexport const ABANDON_AFTER_MS = 5_000\n\nexport interface LaneRunOptions {\n\tsignal: AbortSignal\n\tpriority: Priority\n\t/** Epoch milliseconds the caller gives up at: a wait that would outlast it is refused at once. */\n\tdeadline?: number\n}\n\nexport interface LaneHealth {\n\t/** The lane refuses new requests right now: its breaker is open. */\n\topen: boolean\n\t/** Until the lane takes requests again, when open or the vendor asked it to wait. */\n\tretryAfterMs?: number\n\t/** What the failure that last counted against the lane meant, cleared by a success. */\n\tlastFailure?: ReadFailureKind\n\t/** That failure was a refused host. */\n\thostRefused?: true\n\t/**\n\t * Requests whose slots were given back while they were still out, having ignored their abort\n\t * signal for {@link ABANDON_AFTER_MS}; absent while there are none.\n\t */\n\tabandoned?: number\n}\n\n/**\n * One adapter's requests for one scope. A `run` takes a rate token, a lane slot and a global slot\n * in that order; the pause, tokens and slots are the adapter's, the breaker each scope's own.\n */\nexport interface Lane {\n\trun<T>(fn: (signal: AbortSignal) => Promise<T>, options: LaneRunOptions): Promise<T>\n\thealth(): LaneHealth\n}\n\n/** What a request that reached the source came to; one the lane turned away never did. */\nexport type LaneOutcome = { ok: true } | { ok: false; failure: ReadFailure; error?: unknown }\n\nexport interface Lanes {\n\t/**\n\t * The lane of one adapter instance for `scope`, made on first use; for an adapter built anew on\n\t * every read, the lane of its id within `scope`.\n\t */\n\tfor(adapter: AnalyticsAdapter, scope?: string | null): Lane\n}\n\nexport interface LanesOptions {\n\t/** Slots shared by every vendor source; default {@link DEFAULT_GLOBAL_CONCURRENCY}. */\n\tglobal?: number\n\t/** Slots of a source without `maxConcurrent`; default {@link DEFAULT_SOURCE_CONCURRENCY}. */\n\tperSource?: number\n\t/** Which sources are local (native), which get their own lane outside the global cap. */\n\tlocal?: { is: (adapter: AnalyticsAdapter) => boolean; capacity?: number }\n\t/** Clock for waits and deadlines; the timers' monotonic one (`monotonicMs`) by default. */\n\tnow?: () => number\n\t/**\n\t * Adapters built anew per read (`providers.resolve`): keyed by scope and id rather than object,\n\t * so each keeps one lane, and two tenants' sources of one id never share a breaker.\n\t */\n\trebuilt?: (adapter: AnalyticsAdapter) => boolean\n\t/**\n\t * Which adapters serve every scope through one lane (the config adapters of a scoped install):\n\t * one scope holds at most {@link scopeShareOf} of their slots, so another always gets one.\n\t */\n\tshared?: (adapter: AnalyticsAdapter) => boolean\n\tbreaker?: Omit<BreakerOptions, 'now'>\n\t/** How long a request may ignore its abort before its slots return; {@link ABANDON_AFTER_MS}. */\n\tabandonAfterMs?: number\n\t/** Told the first time a lane gives back the slots of a request that ignored its abort signal. */\n\tonAbandon?: (adapter: AnalyticsAdapter) => void\n\t/** Told each request's outcome once it counted, with the lane's health after it. */\n\tonOutcome?: (adapter: AnalyticsAdapter, outcome: LaneOutcome, health: LaneHealth) => void\n}\n\ntype Release = () => void\n\n/** The install-wide scope (null) is keyed `''`; it never counts against a scope's share. */\nconst UNSCOPED = ''\n\nconst scopeKeyOf = (scope: string | null | undefined): string =>\n\tscope === null || scope === undefined ? UNSCOPED : `s:${scope}`\n\ninterface Slots {\n\tacquire(priority: Priority, signal: AbortSignal, scope?: string): Promise<Release>\n}\n\ninterface SlotWaiter {\n\tpriority: Priority\n\tscope: string\n\tgrant: () => void\n}\n\n/**\n * A counting semaphore serving the most urgent waiter first, never more than `backgroundCap` slots\n * to background work, and, given a `scopeCap`, never more than that many to one scope.\n */\nconst createSlots = (capacity: number, backgroundCap: number, scopeCap?: number): Slots => {\n\tlet active = 0\n\tlet background = 0\n\tconst waiters: SlotWaiter[] = []\n\tconst heldBy = new Map<string, number>()\n\n\tconst withinShare = (waiter: SlotWaiter): boolean =>\n\t\tscopeCap === undefined ||\n\t\twaiter.scope === UNSCOPED ||\n\t\t(heldBy.get(waiter.scope) ?? 0) < scopeCap\n\n\tconst pick = (): SlotWaiter | undefined =>\n\t\tmostUrgent(\n\t\t\twaiters.filter(\n\t\t\t\t(waiter) =>\n\t\t\t\t\twithinShare(waiter) && (waiter.priority !== 'background' || background < backgroundCap)\n\t\t\t)\n\t\t)\n\n\tconst hold = (scope: string, by: number): void => {\n\t\tconst next = (heldBy.get(scope) ?? 0) + by\n\t\tif (next > 0) {\n\t\t\theldBy.set(scope, next)\n\t\t} else {\n\t\t\theldBy.delete(scope)\n\t\t}\n\t}\n\n\tconst pump = (): void => {\n\t\twhile (active < capacity) {\n\t\t\tconst chosen = pick()\n\t\t\tif (!chosen) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twaiters.splice(waiters.indexOf(chosen), 1)\n\t\t\tactive++\n\t\t\thold(chosen.scope, 1)\n\t\t\tif (chosen.priority === 'background') {\n\t\t\t\tbackground++\n\t\t\t}\n\t\t\tchosen.grant()\n\t\t}\n\t}\n\n\treturn {\n\t\tacquire(priority, signal, scope = UNSCOPED) {\n\t\t\tif (signal.aborted) {\n\t\t\t\treturn Promise.reject(signal.reason)\n\t\t\t}\n\t\t\treturn new Promise<Release>((resolve, reject) => {\n\t\t\t\tlet released = false\n\t\t\t\tconst release = (): void => {\n\t\t\t\t\tif (released) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treleased = true\n\t\t\t\t\tactive--\n\t\t\t\t\thold(scope, -1)\n\t\t\t\t\tif (priority === 'background') {\n\t\t\t\t\t\tbackground--\n\t\t\t\t\t}\n\t\t\t\t\tpump()\n\t\t\t\t}\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\tconst index = waiters.indexOf(waiter)\n\t\t\t\t\tif (index !== -1) {\n\t\t\t\t\t\twaiters.splice(index, 1)\n\t\t\t\t\t}\n\t\t\t\t\treject(signal.reason)\n\t\t\t\t}\n\t\t\t\tconst waiter: SlotWaiter = {\n\t\t\t\t\tpriority,\n\t\t\t\t\tscope,\n\t\t\t\t\tgrant: () => {\n\t\t\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\t\t\tresolve(release)\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\twaiters.push(waiter)\n\t\t\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\t\t\tpump()\n\t\t\t})\n\t\t},\n\t}\n}\n\n/** Resolves after `ms`, or rejects with the signal's reason once it aborts. */\nconst sleep = (ms: number, signal: AbortSignal): Promise<void> => {\n\tif (signal.aborted) {\n\t\treturn Promise.reject(signal.reason)\n\t}\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst onAbort = (): void => {\n\t\t\tclearTimeout(timer)\n\t\t\treject(signal.reason)\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\tresolve()\n\t\t}, ms)\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t})\n}\n\n/**\n * Settles with `work`, or rejects with the signal's reason first: the slot stays held until `work`\n * settles, or until {@link ABANDON_AFTER_MS} after the abort for work that never does.\n */\nconst untilAborted = <T>(work: Promise<T>, signal: AbortSignal): Promise<T> => {\n\tif (signal.aborted) {\n\t\treturn Promise.reject(signal.reason)\n\t}\n\tlet onAbort: (() => void) | undefined\n\tconst aborted = new Promise<never>((_resolve, reject) => {\n\t\tonAbort = () => reject(signal.reason)\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t})\n\treturn Promise.race([work, aborted]).finally(() => {\n\t\tif (onAbort) {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t}\n\t})\n}\n\nconst noRelease: Release = () => {}\n\ninterface LaneSetup {\n\tadapter: AnalyticsAdapter\n\tcapacity: number\n\tglobal: Slots | undefined\n\tnow: () => number\n\t/** Every scope reads through this lane: each holds at most its share of the slots. */\n\tshared: boolean\n\tbreaker?: Omit<BreakerOptions, 'now'>\n\tabandonAfterMs: number\n\tonAbandon?: (adapter: AnalyticsAdapter) => void\n\tonOutcome?: LanesOptions['onOutcome']\n}\n\n/** What a request that ignored its abort counts as against the breaker. */\nconst ABANDONED: ReadFailure = { kind: 'unavailable', timeout: true }\n\n/** A breaker with nothing to remember: closed, no failure counted since its last answer. */\nconst isClean = (breaker: Breaker): boolean => {\n\tconst snapshot = breaker.snapshot()\n\treturn snapshot.state === 'closed' && snapshot.lastFailure === undefined\n}\n\n/** One adapter's pause, tokens and slots, and one breaker per scope reading through them. */\nconst createLaneCore = (setup: LaneSetup): ((scope: string | null | undefined) => Lane) => {\n\tconst { now } = setup\n\tconst tokens = createTokenSource(setup.adapter.capabilities.rateLimit, now)\n\tconst slots = createSlots(\n\t\tsetup.capacity,\n\t\tMath.max(1, Math.floor(setup.capacity / 2)),\n\t\tsetup.shared ? scopeShareOf(setup.capacity) : undefined\n\t)\n\tconst breakers = new Map<string, Breaker>()\n\tconst views = new Map<string, Lane>()\n\tlet pausedUntil = 0\n\tlet abandoned = 0\n\n\tconst breakerOf = (key: string): Breaker =>\n\t\trecallOr(\n\t\t\tbreakers,\n\t\t\t[key, () => createBreaker({ now, ...setup.breaker })],\n\t\t\t(breaker) => !isClean(breaker)\n\t\t)\n\n\tconst waitOutPause = async (options: LaneRunOptions): Promise<void> => {\n\t\tfor (;;) {\n\t\t\tconst pausedFor = pausedUntil - now()\n\t\t\tif (pausedFor <= 0) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (options.deadline !== undefined && pausedUntil > options.deadline) {\n\t\t\t\tthrow new LaneRefusedError('paused', pausedFor)\n\t\t\t}\n\t\t\tawait sleep(pausedFor, options.signal)\n\t\t}\n\t}\n\n\tconst healthOf = (key: string): LaneHealth => {\n\t\tconst breaker = breakers.get(key)\n\t\tconst snapshot = breaker?.snapshot()\n\t\tconst peek = breaker?.peek() ?? { ok: true as const, probe: false }\n\t\tconst pausedFor = pausedUntil - now()\n\t\tconst retryAfterMs = Math.max(peek.ok ? 0 : peek.retryAfterMs, pausedFor > 0 ? pausedFor : 0)\n\t\tconst last = snapshot?.lastFailure\n\t\treturn {\n\t\t\topen: !peek.ok,\n\t\t\t...(retryAfterMs > 0 ? { retryAfterMs } : {}),\n\t\t\t...(last ? { lastFailure: last.kind } : {}),\n\t\t\t...(last?.hostRefused ? { hostRefused: true as const } : {}),\n\t\t\t...(abandoned > 0 ? { abandoned } : {}),\n\t\t}\n\t}\n\n\tconst viewOf = (key: string): Lane => ({\n\t\tasync run(fn, options) {\n\t\t\tconst { signal, priority } = options\n\t\t\tif (signal.aborted) {\n\t\t\t\tthrow signal.reason\n\t\t\t}\n\t\t\tconst breaker = breakerOf(key)\n\t\t\tconst refusedOpen = (retryAfterMs: number): LaneRefusedError =>\n\t\t\t\tnew LaneRefusedError('open', retryAfterMs, breaker.snapshot().lastFailure)\n\t\t\tconst peek = breaker.peek()\n\t\t\tif (!peek.ok) {\n\t\t\t\tthrow refusedOpen(peek.retryAfterMs)\n\t\t\t}\n\t\t\t// A breaker due its probe lets one run through: it is claimed before the run spends a rate\n\t\t\t// token or waits for a slot, so the runs it turns away spend nothing.\n\t\t\tconst claimed = peek.probe ? breaker.admit() : undefined\n\t\t\tif (claimed && !claimed.ok) {\n\t\t\t\tthrow refusedOpen(claimed.retryAfterMs)\n\t\t\t}\n\t\t\tlet releaseLane = noRelease\n\t\t\tlet releaseGlobal = noRelease\n\t\t\tconst releaseSlots = (): void => {\n\t\t\t\treleaseGlobal()\n\t\t\t\treleaseLane()\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait waitOutPause(options)\n\t\t\t\tawait tokens.take({ signal, priority })\n\t\t\t\treleaseLane = await slots.acquire(priority, signal, key)\n\t\t\t\treleaseGlobal = setup.global ? await setup.global.acquire(priority, signal) : noRelease\n\t\t\t} catch (err) {\n\t\t\t\treleaseSlots()\n\t\t\t\tif (claimed?.probe) {\n\t\t\t\t\tbreaker.release()\n\t\t\t\t}\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\tconst admission = claimed ?? breaker.admit()\n\t\t\tif (!admission.ok) {\n\t\t\t\treleaseSlots()\n\t\t\t\tthrow refusedOpen(admission.retryAfterMs)\n\t\t\t}\n\t\t\tlet counted = false\n\t\t\tconst record = (outcome: 'success' | ReadFailure, error?: unknown): void => {\n\t\t\t\tif (!counted) {\n\t\t\t\t\tcounted = true\n\t\t\t\t\tbreaker.record(outcome, admission.probe)\n\t\t\t\t\tsetup.onOutcome?.(\n\t\t\t\t\t\tsetup.adapter,\n\t\t\t\t\t\toutcome === 'success'\n\t\t\t\t\t\t\t? { ok: true }\n\t\t\t\t\t\t\t: { ok: false, failure: outcome, ...(error === undefined ? {} : { error }) },\n\t\t\t\t\t\thealthOf(key)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst settled = (async () => fn(signal))().then(\n\t\t\t\t(value) => {\n\t\t\t\t\trecord('success')\n\t\t\t\t\treturn value\n\t\t\t\t},\n\t\t\t\t(err: unknown) => {\n\t\t\t\t\tconst failure = classifyError(err)\n\t\t\t\t\t// Paused first, so the health the outcome is told with carries the pause.\n\t\t\t\t\tif (failure.kind === 'unavailable' && failure.retryAfterMs !== undefined) {\n\t\t\t\t\t\tpausedUntil = Math.max(\n\t\t\t\t\t\t\tpausedUntil,\n\t\t\t\t\t\t\tnow() + Math.min(failure.retryAfterMs, BREAKER_MAX_MS)\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\trecord(failure, err)\n\t\t\t\t\tthrow err\n\t\t\t\t}\n\t\t\t)\n\t\t\tlet abandonTimer: ReturnType<typeof setTimeout> | undefined\n\t\t\t// Past the grace a request that ignores its abort gives its slots back, counted as a timeout.\n\t\t\tconst abandon = (): void => {\n\t\t\t\tabandonTimer = setTimeout(() => {\n\t\t\t\t\treleaseSlots()\n\t\t\t\t\trecord(ABANDONED)\n\t\t\t\t\tabandoned++\n\t\t\t\t\tif (abandoned === 1) {\n\t\t\t\t\t\tsetup.onAbandon?.(setup.adapter)\n\t\t\t\t\t}\n\t\t\t\t}, setup.abandonAfterMs)\n\t\t\t\tabandonTimer.unref?.()\n\t\t\t}\n\t\t\tif (signal.aborted) {\n\t\t\t\tabandon()\n\t\t\t} else {\n\t\t\t\tsignal.addEventListener('abort', abandon, { once: true })\n\t\t\t}\n\t\t\tconst done = settled.finally(() => {\n\t\t\t\tsignal.removeEventListener('abort', abandon)\n\t\t\t\tclearTimeout(abandonTimer)\n\t\t\t\treleaseSlots()\n\t\t\t})\n\t\t\t// The caller may stop waiting at the abort; the request still settles, and is not unhandled.\n\t\t\tdone.catch(() => {})\n\t\t\treturn untilAborted(done, signal)\n\t\t},\n\t\thealth: () => healthOf(key),\n\t})\n\n\treturn (scope) => {\n\t\tconst key = scopeKeyOf(scope)\n\t\treturn recallOr(views, [key, () => viewOf(key)])\n\t}\n}\n\n/**\n * One lane per adapter object, so a re-saved provider starts fresh. Vendor lanes share the global\n * slots; local (native) lanes do not, so a slow vendor never queues the plugin's own reads.\n */\nexport const createLanes = (options: LanesOptions = {}): Lanes => {\n\tconst now = options.now ?? monotonicMs\n\tconst globalCapacity = options.global ?? DEFAULT_GLOBAL_CONCURRENCY\n\tconst global = createSlots(globalCapacity, globalCapacity)\n\tconst cores = new WeakMap<AnalyticsAdapter, (scope: string | null | undefined) => Lane>()\n\tconst lanesById = new Map<string, Lane>()\n\n\tconst coreFor = (adapter: AnalyticsAdapter): ((scope: string | null | undefined) => Lane) => {\n\t\tconst local = options.local?.is(adapter) === true\n\t\tconst declared = adapter.capabilities.rateLimit?.maxConcurrent\n\t\tconst fallback = local\n\t\t\t? (options.local?.capacity ?? DEFAULT_LOCAL_CONCURRENCY)\n\t\t\t: (options.perSource ?? DEFAULT_SOURCE_CONCURRENCY)\n\t\treturn createLaneCore({\n\t\t\tadapter,\n\t\t\tcapacity: declared !== undefined && declared > 0 ? declared : fallback,\n\t\t\tglobal: local ? undefined : global,\n\t\t\tnow,\n\t\t\tshared: options.shared?.(adapter) === true,\n\t\t\t...(options.breaker ? { breaker: options.breaker } : {}),\n\t\t\tabandonAfterMs: options.abandonAfterMs ?? ABANDON_AFTER_MS,\n\t\t\t...(options.onAbandon ? { onAbandon: options.onAbandon } : {}),\n\t\t\t...(options.onOutcome ? { onOutcome: options.onOutcome } : {}),\n\t\t})\n\t}\n\n\treturn {\n\t\tfor(adapter, scope) {\n\t\t\tif (options.rebuilt?.(adapter) === true) {\n\t\t\t\tconst id = JSON.stringify([scope ?? null, adapter.id])\n\t\t\t\treturn recallOr(lanesById, [id, () => coreFor(adapter)(scope)])\n\t\t\t}\n\t\t\tconst core = cores.get(adapter) ?? coreFor(adapter)\n\t\t\tcores.set(adapter, core)\n\t\t\treturn core(scope)\n\t\t},\n\t}\n}\n\n/**\n * One upstream request, retried up to {@link MAX_RETRIES} times on a transient `unavailable` but\n * never after a timeout or spent quota, nor past the deadline; a lane refusal ends it at once.\n */\nexport const runUpstream = async <T>(\n\tlane: Lane,\n\tfn: (signal: AbortSignal) => Promise<T>,\n\toptions: LaneRunOptions & { now: () => number; baseDelayMs?: number }\n): Promise<T> => {\n\tconst base = options.baseDelayMs ?? RETRY_BASE_MS\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\treturn await lane.run(fn, options)\n\t\t} catch (err) {\n\t\t\tif (isLaneRefused(err) || options.signal.aborted) {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\tconst failure = classifyError(err)\n\t\t\tif (\n\t\t\t\tfailure.kind !== 'unavailable' ||\n\t\t\t\tfailure.timeout ||\n\t\t\t\tfailure.quota ||\n\t\t\t\tattempt >= MAX_RETRIES\n\t\t\t) {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\t// Fixed rather than random, so the schedule is testable: 0.5 s, then 1.25 s.\n\t\t\tconst delay = base * 2 ** attempt + base * 0.5 * attempt\n\t\t\tif (options.deadline !== undefined && options.now() + delay >= options.deadline) {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait sleep(delay, options.signal)\n\t\t\t} catch {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;AAsBA,MAAM,4BAA4B;;AAGlC,MAAM,yBAAyB;;;;;AAO/B,MAAa,qBAAqB,YACjC,KAAK,IAAA,GAA4B,KAAK,IAAI,wBAAwB,KAAK,MAAM,UAAU,CAAC,CAAC,CAAC;;AAG3F,MAAM,gBAAgB,aAA6B,KAAK,IAAI,GAAG,KAAK,KAAK,WAAW,CAAC,CAAC;;AAGtF,MAAM,cAAc;;;;;AASpB,MAAa,mBAAmB;;AA4EhC,MAAM,WAAW;AAEjB,MAAM,cAAc,UACnB,UAAU,QAAQ,UAAU,KAAA,IAAY,WAAW,KAAK;;;;;AAgBzD,MAAM,eAAe,UAAkB,eAAuB,aAA6B;CAC1F,IAAI,SAAS;CACb,IAAI,aAAa;CACjB,MAAM,UAAwB,CAAC;CAC/B,MAAM,yBAAS,IAAI,IAAoB;CAEvC,MAAM,eAAe,WACpB,aAAa,KAAA,KACb,OAAO,UAAU,aAChB,OAAO,IAAI,OAAO,KAAK,KAAK,KAAK;CAEnC,MAAM,aACL,WACC,QAAQ,QACN,WACA,YAAY,MAAM,MAAM,OAAO,aAAa,gBAAgB,aAAa,cAC3E,CACD;CAED,MAAM,QAAQ,OAAe,OAAqB;EACjD,MAAM,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK;EACxC,IAAI,OAAO,GACV,OAAO,IAAI,OAAO,IAAI;OAEtB,OAAO,OAAO,KAAK;CAErB;CAEA,MAAM,aAAmB;EACxB,OAAO,SAAS,UAAU;GACzB,MAAM,SAAS,KA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,IAAI,OAAO,KAAK,QAAQ,OAAO;EAClD,MAAM,IAAI,SAAS,IAAI;EACvB,OAAO,KAAK,KAAK;CAClB,EACD;AACD;;;;;AAMA,MAAa,cAAc,OAC1B,MACA,IACA,YACgB;CAChB,MAAM,OAAO,QAAQ,eAAA;CACrB,KAAK,IAAI,UAAU,IAAK,WACvB,IAAI;EACH,OAAO,MAAM,KAAK,IAAI,IAAI,OAAO;CAClC,SAAS,KAAK;EACb,IAAI,cAAc,GAAG,KAAK,QAAQ,OAAO,SACxC,MAAM;EAEP,MAAM,UAAU,cAAc,GAAG;EACjC,IACC,QAAQ,SAAS,iBACjB,QAAQ,WACR,QAAQ,SACR,WAAW,aAEX,MAAM;EAGP,MAAM,QAAQ,OAAO,KAAK,UAAU,OAAO,KAAM;EACjD,IAAI,QAAQ,aAAa,KAAA,KAAa,QAAQ,IAAI,IAAI,SAAS,QAAQ,UACtE,MAAM;EAEP,IAAI;GACH,MAAM,MAAM,OAAO,QAAQ,MAAM;EAClC,QAAQ;GACP,MAAM;EACP;CACD;AAEF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { supportsGranularity } from "../core/granularity.js";
|
|
2
2
|
import "../timeframe/tz.js";
|
|
3
|
-
import { isAverageMetric } from "../core/metricValues.js";
|
|
4
3
|
import { calendarDayOf, parseCalendarDay } from "../timeframe/calendar.js";
|
|
5
4
|
import { bucketInstant, bucketStartOf } from "../native/engine/buckets.js";
|
|
5
|
+
import { isAverageMetric } from "../core/metricValues.js";
|
|
6
6
|
//#region src/surfacing/rebucket.ts
|
|
7
7
|
/**
|
|
8
8
|
* The count an average is taken over, for a row that does not say (`AnalyticsRow.samples`):
|
package/dist/testing/settle.d.ts
CHANGED
|
@@ -3,7 +3,8 @@ import { Payload } from "payload";
|
|
|
3
3
|
//#region src/testing/settle.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Waits until the plugin's background work on `payload` is done (cache writes, native upkeep, the
|
|
6
|
-
* write buffer, which it flushes), for a test before it reads
|
|
6
|
+
* write buffer, which it flushes, connection checks and status writes), for a test before it reads
|
|
7
|
+
* back or calls `payload.destroy()`.
|
|
7
8
|
*/
|
|
8
9
|
declare const settleAnalytics: (payload: Payload) => Promise<void>;
|
|
9
10
|
//#endregion
|