@ahoo-wang/wow-client 10.0.0-alpha.7 → 10.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -5
- package/README.zh-CN.md +4 -3
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.d.cts +9 -13
- package/dist/commands.d.ts +9 -13
- package/dist/commands.es.js +60 -54
- package/dist/commands.es.js.map +1 -1
- package/dist/dsl/aggregation/admit.cjs +1 -1
- package/dist/dsl/aggregation/admit.cjs.map +1 -1
- package/dist/dsl/aggregation/admit.es.js +73 -69
- package/dist/dsl/aggregation/admit.es.js.map +1 -1
- package/dist/dsl/aggregation/aliases.cjs +2 -0
- package/dist/dsl/aggregation/aliases.cjs.map +1 -0
- package/dist/dsl/aggregation/aliases.d.cts +2 -0
- package/dist/dsl/aggregation/aliases.d.ts +2 -0
- package/dist/dsl/aggregation/aliases.es.js +13 -0
- package/dist/dsl/aggregation/aliases.es.js.map +1 -0
- package/dist/dsl/aggregation/builders.cjs +1 -1
- package/dist/dsl/aggregation/builders.cjs.map +1 -1
- package/dist/dsl/aggregation/builders.d.cts +17 -243
- package/dist/dsl/aggregation/builders.d.ts +17 -243
- package/dist/dsl/aggregation/builders.es.js +36 -171
- package/dist/dsl/aggregation/builders.es.js.map +1 -1
- package/dist/dsl/aggregation/derived.cjs +1 -1
- package/dist/dsl/aggregation/derived.cjs.map +1 -1
- package/dist/dsl/aggregation/derived.d.cts +123 -1
- package/dist/dsl/aggregation/derived.d.ts +123 -1
- package/dist/dsl/aggregation/derived.es.js +43 -28
- package/dist/dsl/aggregation/derived.es.js.map +1 -1
- package/dist/dsl/aggregation/groups.cjs +2 -0
- package/dist/dsl/aggregation/groups.cjs.map +1 -0
- package/dist/dsl/aggregation/groups.d.cts +325 -0
- package/dist/dsl/aggregation/groups.d.ts +325 -0
- package/dist/dsl/aggregation/groups.es.js +80 -0
- package/dist/dsl/aggregation/groups.es.js.map +1 -0
- package/dist/dsl/aggregation/having.cjs +1 -1
- package/dist/dsl/aggregation/having.cjs.map +1 -1
- package/dist/dsl/aggregation/having.d.cts +63 -1
- package/dist/dsl/aggregation/having.d.ts +63 -1
- package/dist/dsl/aggregation/having.es.js +33 -30
- package/dist/dsl/aggregation/having.es.js.map +1 -1
- package/dist/dsl/aggregation/index.d.cts +4 -2
- package/dist/dsl/aggregation/index.d.ts +4 -2
- package/dist/dsl/aggregation/metrics.cjs +2 -0
- package/dist/dsl/aggregation/metrics.cjs.map +1 -0
- package/dist/dsl/aggregation/metrics.d.cts +279 -0
- package/dist/dsl/aggregation/metrics.d.ts +279 -0
- package/dist/dsl/aggregation/metrics.es.js +75 -0
- package/dist/dsl/aggregation/metrics.es.js.map +1 -0
- package/dist/dsl/aggregation/types.cjs +1 -1
- package/dist/dsl/aggregation/types.cjs.map +1 -1
- package/dist/dsl/aggregation/types.d.cts +4 -524
- package/dist/dsl/aggregation/types.d.ts +4 -524
- package/dist/dsl/aggregation/types.es.js +5 -25
- package/dist/dsl/aggregation/types.es.js.map +1 -1
- package/dist/dsl/cursorQuery.cjs +1 -1
- package/dist/dsl/cursorQuery.cjs.map +1 -1
- package/dist/dsl/cursorQuery.d.cts +18 -7
- package/dist/dsl/cursorQuery.d.ts +18 -7
- package/dist/dsl/cursorQuery.es.js +13 -12
- package/dist/dsl/cursorQuery.es.js.map +1 -1
- package/dist/dsl/descriptor.cjs +1 -1
- package/dist/dsl/descriptor.cjs.map +1 -1
- package/dist/dsl/descriptor.d.cts +24 -379
- package/dist/dsl/descriptor.d.ts +24 -379
- package/dist/dsl/descriptor.es.js +6 -32
- package/dist/dsl/descriptor.es.js.map +1 -1
- package/dist/dsl/fieldDescriptor.cjs +2 -0
- package/dist/dsl/fieldDescriptor.cjs.map +1 -0
- package/dist/dsl/fieldDescriptor.d.cts +246 -0
- package/dist/dsl/fieldDescriptor.d.ts +246 -0
- package/dist/dsl/fieldDescriptor.es.js +24 -0
- package/dist/dsl/fieldDescriptor.es.js.map +1 -0
- package/dist/dsl/filter/builders.cjs +1 -1
- package/dist/dsl/filter/builders.cjs.map +1 -1
- package/dist/dsl/filter/builders.d.cts +7 -949
- package/dist/dsl/filter/builders.d.ts +7 -949
- package/dist/dsl/filter/builders.es.js +14 -285
- package/dist/dsl/filter/builders.es.js.map +1 -1
- package/dist/dsl/filter/expressionFilter.cjs +2 -0
- package/dist/dsl/filter/expressionFilter.cjs.map +1 -0
- package/dist/dsl/filter/expressionFilter.d.cts +35 -0
- package/dist/dsl/filter/expressionFilter.d.ts +35 -0
- package/dist/dsl/filter/expressionFilter.es.js +18 -0
- package/dist/dsl/filter/expressionFilter.es.js.map +1 -0
- package/dist/dsl/filter/fieldFilters.cjs +2 -0
- package/dist/dsl/filter/fieldFilters.cjs.map +1 -0
- package/dist/dsl/filter/fieldFilters.d.cts +297 -0
- package/dist/dsl/filter/fieldFilters.d.ts +297 -0
- package/dist/dsl/filter/fieldFilters.es.js +110 -0
- package/dist/dsl/filter/fieldFilters.es.js.map +1 -0
- package/dist/dsl/filter/index.d.cts +2 -1
- package/dist/dsl/filter/index.d.ts +2 -1
- package/dist/dsl/filter/logicalFilters.cjs +2 -0
- package/dist/dsl/filter/logicalFilters.cjs.map +1 -0
- package/dist/dsl/filter/logicalFilters.d.cts +109 -0
- package/dist/dsl/filter/logicalFilters.d.ts +109 -0
- package/dist/dsl/filter/logicalFilters.es.js +36 -0
- package/dist/dsl/filter/logicalFilters.es.js.map +1 -0
- package/dist/dsl/filter/metadataFilters.cjs +2 -0
- package/dist/dsl/filter/metadataFilters.cjs.map +1 -0
- package/dist/dsl/filter/metadataFilters.d.cts +132 -0
- package/dist/dsl/filter/metadataFilters.d.ts +132 -0
- package/dist/dsl/filter/metadataFilters.es.js +56 -0
- package/dist/dsl/filter/metadataFilters.es.js.map +1 -0
- package/dist/dsl/filter/operator.cjs +1 -1
- package/dist/dsl/filter/operator.cjs.map +1 -1
- package/dist/dsl/filter/operator.d.cts +11 -9
- package/dist/dsl/filter/operator.d.ts +11 -9
- package/dist/dsl/filter/operator.es.js +1 -1
- package/dist/dsl/filter/operator.es.js.map +1 -1
- package/dist/dsl/filter/searchFilter.cjs +2 -0
- package/dist/dsl/filter/searchFilter.cjs.map +1 -0
- package/dist/dsl/filter/searchFilter.d.cts +39 -0
- package/dist/dsl/filter/searchFilter.d.ts +39 -0
- package/dist/dsl/filter/searchFilter.es.js +19 -0
- package/dist/dsl/filter/searchFilter.es.js.map +1 -0
- package/dist/dsl/filter/timeFilters.cjs +2 -0
- package/dist/dsl/filter/timeFilters.cjs.map +1 -0
- package/dist/dsl/filter/timeFilters.d.cts +290 -0
- package/dist/dsl/filter/timeFilters.d.ts +290 -0
- package/dist/dsl/filter/timeFilters.es.js +89 -0
- package/dist/dsl/filter/timeFilters.es.js.map +1 -0
- package/dist/dsl/filter/types.d.cts +4 -14
- package/dist/dsl/filter/types.d.ts +4 -14
- package/dist/dsl/filter/validate.cjs +1 -1
- package/dist/dsl/filter/validate.cjs.map +1 -1
- package/dist/dsl/filter/validate.d.cts +2 -4
- package/dist/dsl/filter/validate.d.ts +2 -4
- package/dist/dsl/filter/validate.es.js +25 -31
- package/dist/dsl/filter/validate.es.js.map +1 -1
- package/dist/dsl/queryErrorCodes.cjs +1 -1
- package/dist/dsl/queryErrorCodes.cjs.map +1 -1
- package/dist/dsl/queryErrorCodes.d.cts +0 -2
- package/dist/dsl/queryErrorCodes.d.ts +0 -2
- package/dist/dsl/queryErrorCodes.es.js +0 -1
- package/dist/dsl/queryErrorCodes.es.js.map +1 -1
- package/dist/dsl/queryFilter.cjs +2 -0
- package/dist/dsl/queryFilter.cjs.map +1 -0
- package/dist/dsl/queryFilter.d.cts +3 -0
- package/dist/dsl/queryFilter.d.ts +3 -0
- package/dist/dsl/queryFilter.es.js +9 -0
- package/dist/dsl/queryFilter.es.js.map +1 -0
- package/dist/dsl/queryable.cjs +1 -1
- package/dist/dsl/queryable.cjs.map +1 -1
- package/dist/dsl/queryable.es.js +12 -16
- package/dist/dsl/queryable.es.js.map +1 -1
- package/dist/dsl/semanticTypes.cjs +2 -0
- package/dist/dsl/semanticTypes.cjs.map +1 -0
- package/dist/dsl/semanticTypes.d.cts +128 -0
- package/dist/dsl/semanticTypes.d.ts +128 -0
- package/dist/dsl/semanticTypes.es.js +13 -0
- package/dist/dsl/semanticTypes.es.js.map +1 -0
- package/dist/dsl.cjs +1 -1
- package/dist/dsl.d.cts +2 -0
- package/dist/dsl.d.ts +2 -0
- package/dist/dsl.es.js +14 -8
- package/dist/exactJson.cjs +2 -2
- package/dist/exactJson.cjs.map +1 -1
- package/dist/exactJson.d.cts +41 -16
- package/dist/exactJson.d.ts +41 -16
- package/dist/exactJson.es.js +104 -102
- package/dist/exactJson.es.js.map +1 -1
- package/dist/frameworkErrors.cjs.map +1 -1
- package/dist/frameworkErrors.d.cts +5 -5
- package/dist/frameworkErrors.d.ts +5 -5
- package/dist/frameworkErrors.es.js.map +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +29 -9
- package/dist/http.d.ts +29 -9
- package/dist/http.es.js +24 -19
- package/dist/http.es.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.es.js +12 -12
- package/dist/manifest.cjs +1 -1
- package/dist/manifest.cjs.map +1 -1
- package/dist/manifest.d.cts +30 -2
- package/dist/manifest.d.ts +30 -2
- package/dist/manifest.es.js +34 -6
- package/dist/manifest.es.js.map +1 -1
- package/dist/manifestTypes.d.cts +21 -4
- package/dist/manifestTypes.d.ts +21 -4
- package/dist/queries.cjs +1 -1
- package/dist/queries.cjs.map +1 -1
- package/dist/queries.d.cts +18 -8
- package/dist/queries.d.ts +18 -8
- package/dist/queries.es.js +46 -35
- package/dist/queries.es.js.map +1 -1
- package/dist/routes.cjs +1 -1
- package/dist/routes.cjs.map +1 -1
- package/dist/routes.d.cts +16 -3
- package/dist/routes.d.ts +16 -3
- package/dist/routes.es.js +24 -25
- package/dist/routes.es.js.map +1 -1
- package/dist/state.cjs +1 -1
- package/dist/state.cjs.map +1 -1
- package/dist/state.d.cts +21 -19
- package/dist/state.d.ts +21 -19
- package/dist/state.es.js +27 -22
- package/dist/state.es.js.map +1 -1
- package/dist/streams.cjs +1 -1
- package/dist/streams.cjs.map +1 -1
- package/dist/streams.d.cts +14 -7
- package/dist/streams.d.ts +14 -7
- package/dist/streams.es.js +65 -50
- package/dist/streams.es.js.map +1 -1
- package/dist/testing/wire.cjs +1 -1
- package/dist/testing/wire.cjs.map +1 -1
- package/dist/testing/wire.es.js +1 -1
- package/dist/testing/wire.es.js.map +1 -1
- package/dist/wait.cjs +1 -1
- package/dist/wait.cjs.map +1 -1
- package/dist/wait.d.cts +18 -5
- package/dist/wait.d.ts +18 -5
- package/dist/wait.es.js +36 -34
- package/dist/wait.es.js.map +1 -1
- package/dist/wire.cjs +1 -1
- package/dist/wire.cjs.map +1 -1
- package/dist/wire.d.cts +76 -31
- package/dist/wire.d.ts +76 -31
- package/dist/wire.es.js +1 -3
- package/dist/wire.es.js.map +1 -1
- package/package.json +5 -5
- package/dist/dsl/filter/datePattern.cjs +0 -2
- package/dist/dsl/filter/datePattern.cjs.map +0 -1
- package/dist/dsl/filter/datePattern.d.cts +0 -8
- package/dist/dsl/filter/datePattern.d.ts +0 -8
- package/dist/dsl/filter/datePattern.es.js +0 -96
- package/dist/dsl/filter/datePattern.es.js.map +0 -1
package/dist/commands.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commands.es.js","names":["LifecycleCommands","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","rememberRequestId","requestId","SYSTEM_PREFIX","ID","acceptedOnly","plan","Stage","planOf","request","WaitPlan","routeOf","id","route","routes","item","method","typeNamed","parts","command","part","commandHeaders","WowHeaders","formatWaitPlan","formatWaitTimeout","accept","targetOf","CommandClient","client","options","checkManifest","commandResults","result","json","WowProblemError","CommandResultStatus","CommandRejectedError","settled","scope","bodyNumbers","send","system","type","prefix","name","context","declared","aggregate","fetchManifest","KNOWN_STATUSES","FrameworkErrorCodes"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n json,\n type RequestOptions,\n send,\n type TargetScope,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport {\n type AggregateType,\n type CommandResult,\n CommandResultStatus,\n type RefusedResult,\n Stage,\n} from './wire.js';\nimport {\n checkManifest,\n fetchManifest,\n type RouteManifest,\n type RoutingManifest,\n} from './manifest.js';\nimport {\n CommandRejectedError,\n FrameworkErrorCodes,\n rememberRequestId,\n WowProblemError,\n} from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, WaitPlan } from './wait.js';\n\n/**\n * One command a {@link CommandClient} sends, and how: the TypeScript\n * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same\n * fields. Kotlin's `command` is the command object, whose class names it;\n * here `command` is the command's name and `body` its payload, as the wire\n * carries them.\n *\n * - `command`: the full type name, `context.aggregate.Command`, which names\n * the aggregate type too; or a system command (`wow.*`, a lifecycle command\n * of {@link LifecycleCommands} among them), which needs `type`.\n * - `id`: the aggregate's id. Absent when the command names no aggregate id:\n * a creation, whose id the server assigns, an `@Unaddressed` command, or\n * any command of an aggregate whose id is its owner's (the Manifest's\n * `idSource: \"owner\"`), which goes to the caller's own; the route without\n * `{id}` then sends it.\n * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to\n * act across scopes acts in (`Wow-Scope`); the caller's own when absent.\n * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds\n * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command\n * waits with is `wait` within `timeout`, the server's default plan when\n * only a timeout is given, and the server's default without either.\n * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).\n */\nexport interface CommandRequest extends Omit<RequestOptions, 'scope'> {\n /** The command's full type name, or a system command's. */\n readonly command: string;\n /** The command's body; `{}` when absent. */\n readonly body?: object;\n /**\n * The aggregate's id; absent for a creation, an unaddressed command or the\n * caller's own aggregate of one whose id is its owner's.\n */\n readonly id?: string;\n /**\n * The aggregate type, which `command` names unless it is a system command:\n * then it is required.\n */\n readonly type?: AggregateType;\n /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetTenant?: string;\n /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetScope?: Omit<TargetScope, 'tenantId'>;\n /**\n * Not a command's: a query's `Wow-Scope`. A command names the scope it acts\n * in with `targetTenant` and `targetScope`, so a query's options spread into\n * a command's fail to compile rather than drop their scope.\n */\n readonly scope?: never;\n /** How far to wait for the command (`Wow-Wait`). */\n readonly wait?: WaitPlan;\n /** How long to wait, in milliseconds, over the plan's own timeout. */\n readonly timeout?: number;\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * client generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}). A request sent again without one is another\n * request: for an application-level retry, set it (or keep the one the\n * failure or the first result carries) and send that request again.\n */\n readonly requestId?: string;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n}\n\n/** How a {@link CommandClient} sends, beside how it reaches the service. */\nexport interface CommandClientOptions {\n /**\n * The Manifest whose routes send each command: a whole Manifest, or the\n * routing part a generated client carries (`manifest.ts`). Without it the\n * client fetches the service's once, when it first sends\n * (`GET /wow/manifest`), and again after a failed fetch.\n */\n readonly manifest?: RoutingManifest;\n /**\n * The body numbers each command writes as their exact text, unquoted JSON\n * numbers (decision D122), by the command's full type name: a generated\n * client sets them for commands with `int64`, `bigint` or `decimal` fields,\n * which it types as `string`.\n */\n readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;\n}\n\n/**\n * The options of a generated client's command method: a {@link CommandRequest}\n * without what the method fixes, its command, body and type.\n */\nexport type CommandOptions = Omit<\n CommandRequest,\n 'command' | 'body' | 'type' | 'id'\n>;\n\n/** The options of a command that may create its aggregate, with its id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list. */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n APPLY_TAGS: 'wow.lifecycle.ApplyTags',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */\nexport interface ApplyTags {\n readonly tags: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The client generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\n/** The prefix of the system commands' names, the lifecycle commands' among them. */\nconst SYSTEM_PREFIX = 'wow.';\n\n/** The aggregate id of a route's path. */\nconst ID = '{id}';\n\n/** Whether `plan` waits for acceptance alone. */\nfunction acceptedOnly(plan: WaitPlan): boolean {\n return plan.hops.length === 1 && plan.hops[0].stage === Stage.ACCEPTED;\n}\n\n/**\n * The plan `request` waits with, as Kotlin's `CommandRequest.plan`: its\n * `wait` within its `timeout`, the default plan when only a timeout is given.\n */\nfunction planOf(request: CommandRequest): WaitPlan | undefined {\n if (request.timeout === undefined) return request.wait;\n return (request.wait ?? WaitPlan.DEFAULT).within(request.timeout);\n}\n\n/** The route of `request` among `routes`: its method and path, the id in it. */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n): { method: 'POST' | 'DELETE'; path: string } {\n const id = request.id;\n const route = routes.find(\n item => item.path.includes(ID) === (id !== undefined),\n );\n if (route === undefined) {\n throw new TypeError(\n id === undefined\n ? `${request.command} has no route without an aggregate id: set the request's id.`\n : `${request.command} has no route to an aggregate by its id: send it without an id.`,\n );\n }\n const method = route.method;\n if (method !== 'POST' && method !== 'DELETE') {\n throw new TypeError(\n `${request.command} is routed by ${method}: a command is sent by POST or DELETE.`,\n );\n }\n return {\n method,\n path:\n id === undefined\n ? route.path\n : route.path.replace(ID, encodeURIComponent(id)),\n };\n}\n\n/** The aggregate type a full type name `context.aggregate.Command` names. */\nfunction typeNamed(command: string): AggregateType {\n const parts = command.split('.');\n if (parts.length < 3 || parts.some(part => part === '')) {\n throw new TypeError(\n `${command} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`,\n );\n }\n return { context: parts[0], name: parts[1] };\n}\n\nfunction commandHeaders(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n // The default plan is the service's to pick: it sends no plan.\n [WowHeaders.WAIT]:\n plan === undefined || plan.isDefault ? undefined : formatWaitPlan(plan),\n // A plan's own timeout, or the request's; the service's default otherwise.\n [WowHeaders.WAIT_TIMEOUT]:\n plan !== undefined &&\n (request.timeout !== undefined ||\n plan.timeout !== WaitPlan.DEFAULT_TIMEOUT)\n ? formatWaitTimeout(plan.timeout)\n : undefined,\n [WowHeaders.IF_MATCH]:\n request.expectedVersion === undefined\n ? undefined\n : `\"${request.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/** The `Wow-Scope` a request targets, when it targets one. */\nfunction targetOf(request: CommandRequest): TargetScope | undefined {\n if (request.targetTenant === undefined && request.targetScope === undefined) {\n return undefined;\n }\n return { tenantId: request.targetTenant, ...request.targetScope };\n}\n\n/**\n * Sends commands to the command routes of a Wow service as its Manifest lists\n * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without\n * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`\n * for `DeleteAggregate`): the Manifest the client is given, else the\n * service's, fetched once (`GET /wow/manifest`). The TypeScript\n * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers\n * once the command is accepted, {@link wait} with the result its wait plan\n * ends with, {@link stream} with one result per hop. Generated aggregate\n * clients build on it.\n *\n * `send` and `wait` resolve only a result that succeeded. A rejected one,\n * by the aggregate or at admission, rejects with a\n * {@link CommandRejectedError}; anything else that did not succeed with a\n * {@link WowProblemError} (the table on {@link CommandRejectedError} says\n * which). Every command carries a request id, the request's or a generated\n * one, and whatever it rejects with carries that id ({@link requestIdOf}).\n */\nexport class CommandClient {\n private manifest: Promise<RoutingManifest> | undefined;\n private readonly bodyNumbers: Readonly<Record<string, TextNumbers>>;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest, and the commands' exact numbers\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: CommandClientOptions = {},\n ) {\n this.manifest =\n options.manifest === undefined\n ? undefined\n : Promise.resolve(checkManifest(options.manifest));\n this.bodyNumbers = options.bodyNumbers ?? {};\n }\n\n /**\n * Sends a command and answers once it is accepted (202), within the\n * request's timeout (10 seconds without one), as Kotlin's\n * `CommandClient.send`. A request whose `wait` waits for more rejects with a\n * `TypeError` before it is sent: {@link wait} answers with that plan's result.\n *\n * @param request - The command and how to send it\n */\n async send<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n const plan = planOf(request);\n if (plan !== undefined && !plan.isDefault && !acceptedOnly(plan)) {\n throw new TypeError(\n `send answers on acceptance: use wait() for the plan ${formatWaitPlan(plan)}.`,\n );\n }\n return this.exchange<R>(\n request,\n WaitPlan.ACCEPTED.within(request.timeout ?? WaitPlan.DEFAULT_TIMEOUT),\n );\n }\n\n /**\n * Sends a command and answers the result its wait plan ends with: 200, or\n * 202 for a plan that ends at `accepted`. Without a plan, the server's\n * default: the snapshot, or the commit where the aggregate keeps no\n * snapshot (decision D69).\n *\n * @param request - The command and how to send it\n */\n wait<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n return this.exchange<R>(request, planOf(request));\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances, whatever its status. An admission refusal\n * rejects with its problem; a rejection after admission is the stream's\n * last result.\n *\n * @param request - The command and how to send it\n */\n async stream<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResultStream<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(\n request,\n planOf(request),\n requestId,\n 'text/event-stream',\n ),\n ),\n );\n }\n\n private async exchange<R>(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n ): Promise<CommandResult<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n let result: CommandResult<R>;\n try {\n result = await json<CommandResult<R>>(\n await this.post(request, plan, requestId),\n );\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.result?.status === CommandResultStatus.REJECTED\n ) {\n throw new CommandRejectedError(error.result, {\n problem: error.problem,\n cause: error,\n });\n }\n throw error;\n }\n return settled(result);\n });\n }\n\n private async post(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n ): Promise<Response> {\n const route = routeOf(request, await this.routesOf(request));\n const scope = targetOf(request);\n const bodyNumbers = this.bodyNumbers[request.command];\n return send(this.client, {\n method: route.method,\n path: route.path,\n headers: commandHeaders(request, plan, requestId, accept),\n ...(route.method === 'DELETE' ? {} : { body: request.body ?? {} }),\n ...(bodyNumbers === undefined ? {} : { bodyNumbers }),\n options: {\n ...(scope === undefined ? {} : { scope }),\n ...(request.space === undefined ? {} : { space: request.space }),\n ...(request.headers === undefined ? {} : { headers: request.headers }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n },\n });\n }\n\n /**\n * The routes of `request`'s command in the Manifest: a domain command's\n * among its aggregate's commands, by name or former name; a system\n * command's among its type's, else among its context's (a job's).\n */\n private async routesOf(\n request: CommandRequest,\n ): Promise<readonly RouteManifest[]> {\n const command = request.command;\n const system = command.startsWith(SYSTEM_PREFIX);\n const type = request.type ?? (system ? undefined : typeNamed(command));\n if (type === undefined) {\n throw new TypeError(\n `${command} is a system command every aggregate takes: set the request's type.`,\n );\n }\n const prefix = `${type.context}.${type.name}.`;\n const name = command.startsWith(prefix)\n ? command.slice(prefix.length)\n : command;\n const context = (await this.manifestOf()).contexts.find(\n item => item.name === type.context,\n );\n const declared =\n context?.aggregates\n ?.find(aggregate => aggregate.name === type.name)\n ?.commands?.find(\n item => item.name === name || item.aliases?.includes(name) === true,\n ) ??\n (system\n ? context?.commands?.find(item => item.name === name)\n : undefined);\n if (declared?.routes === undefined) {\n throw new TypeError(\n `The Manifest lists no command ${name} of ${type.context}.${type.name}.`,\n );\n }\n return declared.routes;\n }\n\n /** The Manifest given, or the service's, fetched once (again after a failure). */\n private manifestOf(): Promise<RoutingManifest> {\n this.manifest ??= fetchManifest(this.client).catch((error: unknown) => {\n this.manifest = undefined;\n throw error;\n });\n return this.manifest;\n }\n}\n\n/**\n * The result a command was answered with, when it succeeded; else the error\n * that says why it did not, as Kotlin's `HttpCommandClient` settles one: a\n * rejected result rejects with a {@link CommandRejectedError}, a status this\n * client does not know (a newer service's) with a {@link WowProblemError}.\n */\nfunction settled<R>(result: CommandResult<R>): CommandResult<R> {\n if (result.status === CommandResultStatus.REJECTED) {\n throw new CommandRejectedError(result as RefusedResult);\n }\n if (!KNOWN_STATUSES.has(result.status)) {\n throw new WowProblemError({\n type: `urn:wow:error:${FrameworkErrorCodes.COMMAND_FAILED}`,\n title: 'Unknown command status',\n status: 200,\n code: FrameworkErrorCodes.COMMAND_FAILED,\n detail: `The command was answered with the status ${result.status}, which this client does not know: the service is newer than this client, so upgrade it.`,\n result: result as RefusedResult,\n });\n }\n return result;\n}\n\nconst KNOWN_STATUSES: ReadonlySet<string> = new Set(\n Object.values(CommandResultStatus),\n);\n"],"mappings":";;;;;;;;AAkJA,IAAaA,IAAoB;CAC/B,kBAAkB;CAClB,mBAAmB;CACnB,gBAAgB;CAChB,gBAAgB;CAChB,YAAY;AACd;AA0BA,SAAgBC,IAAuB;CACrC,IAAMC,IAAS,WAAW;CAC1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,EACjE,MACDH,IACGI,GAAS,UAAU,MAAK,MAAQ9B,EAAK,SAAS6B,CAAI,IAClD,KAAA;EACN,IAAIE,GAAU,WAAW,KAAA,GACvB,MAAU,UACR,iCAAiCF,EAAK,MAAMF,EAAK,QAAQ,GAAGA,EAAK,KAAK,EACxE;EAEF,OAAOI,EAAS;CAClB;CAGA,aAA+C;EAK7C,OAJA,KAAK,aAAaE,EAAc,KAAK,MAAM,CAAC,CAAC,OAAO,MAAmB;GAErE,MADA,KAAK,WAAW,KAAA,GACVhD;EACR,CAAC,GACM,KAAK;CACd;AACF;AAQA,SAASqC,EAAW,GAA4C;CAC9D,IAAIL,EAAO,WAAWG,EAAoB,UACxC,MAAM,IAAIC,EAAqBJ,CAAuB;CAExD,IAAI,CAACiB,EAAe,IAAIjB,EAAO,MAAM,GACnC,MAAM,IAAIE,EAAgB;EACxB,MAAM,iBAAiBgB,EAAoB;EAC3C,OAAO;EACP,QAAQ;EACR,MAAMA,EAAoB;EAC1B,QAAQ,4CAA4ClB,EAAO,OAAO;EAC1D;CACV,CAAC;CAEH,OAAOA;AACT;AAEA,IAAMiB,IAAsC,IAAI,IAC9C,OAAO,OAAOd,CAAmB,CACnC"}
|
|
1
|
+
{"version":3,"file":"commands.es.js","names":["LifecycleCommands","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","rememberRequestId","requestId","SYSTEM_PREFIX","ID","acceptedOnly","plan","Stage","planOf","request","WaitPlan","routeOf","route","routes","item","id","method","bodyOf","body","idProperty","named","typeNamed","parts","command","part","commandHeaders","WowHeaders","formatWaitPlan","formatWaitTimeout","accept","targetOf","CommandClient","client","ManifestSource","options","commandResults","result","WowProblemError","CommandResultStatus","CommandRejectedError","settled","declared","scope","bodyNumbers","send","system","type","prefix","name","context","aggregate","KNOWN_STATUSES","FrameworkErrorCodes"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n type Answer,\n type RequestOptions,\n send,\n type TargetScope,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport {\n type AggregateType,\n type CommandResult,\n CommandResultStatus,\n type RefusedResult,\n Stage,\n} from './wire.js';\nimport {\n ManifestSource,\n type RouteManifest,\n type RoutingCommand,\n type RoutingManifest,\n} from './manifest.js';\nimport {\n CommandRejectedError,\n FrameworkErrorCodes,\n rememberRequestId,\n WowProblemError,\n} from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, WaitPlan } from './wait.js';\n\n/**\n * One command a {@link CommandClient} sends, and how: the TypeScript\n * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same\n * fields. Kotlin's `command` is the command object, whose class names it;\n * here `command` is the command's name and `body` its payload, as the wire\n * carries them.\n *\n * - `command`: the full type name, `context.aggregate.Command`, which names\n * the aggregate type too; or a system command (`wow.*`, a lifecycle command\n * of {@link LifecycleCommands} among them), which needs `type`.\n * - `id`: the aggregate's id. Absent when the command names no aggregate id:\n * a creation, whose id the server assigns, an `@Unaddressed` command, or\n * any command of an aggregate whose id is its owner's (the Manifest's\n * `idSource: \"owner\"`), which goes to the caller's own; the route without\n * `{id}` then sends it. A command whose body names its aggregate (the\n * Manifest's `idProperty`) goes by that route too, whether `id` is given or\n * not: a given one is the one its body names, or is written into a body\n * that names none.\n * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to\n * act across scopes acts in (`Wow-Scope`); the caller's own when absent.\n * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds\n * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command\n * waits with is `wait` within `timeout`, the server's default plan when\n * only a timeout is given, and the server's default without either.\n * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).\n */\nexport interface CommandRequest extends Omit<RequestOptions, 'scope'> {\n /** The command's full type name, or a system command's. */\n readonly command: string;\n /** The command's body; `{}` when absent. */\n readonly body?: object;\n /**\n * The aggregate's id; absent for a creation, an unaddressed command or the\n * caller's own aggregate of one whose id is its owner's.\n */\n readonly id?: string;\n /**\n * The aggregate type, which `command` names unless it is a system command:\n * then it is required.\n */\n readonly type?: AggregateType;\n /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetTenant?: string;\n /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetScope?: Omit<TargetScope, 'tenantId'>;\n /**\n * Not a command's: a query's `Wow-Scope`. A command names the scope it acts\n * in with `targetTenant` and `targetScope`, so a query's options spread into\n * a command's fail to compile rather than drop their scope.\n */\n readonly scope?: never;\n /** How far to wait for the command (`Wow-Wait`). */\n readonly wait?: WaitPlan;\n /** How long to wait, in milliseconds, over the plan's own timeout. */\n readonly timeout?: number;\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * client generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}). A request sent again without one is another\n * request: for an application-level retry, set it (or keep the one the\n * failure or the first result carries) and send that request again.\n */\n readonly requestId?: string;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n}\n\n/** How a {@link CommandClient} sends, beside how it reaches the service. */\nexport interface CommandClientOptions {\n /**\n * The Manifest whose routes send each command: a whole Manifest, or the\n * routing part a generated client carries (`manifest.ts`). Without it the\n * client fetches the service's once, when it first sends\n * (`GET /wow/manifest`), and again after a failed fetch.\n */\n readonly manifest?: RoutingManifest;\n /**\n * The body numbers each command writes as their exact text, unquoted JSON\n * numbers (decision D122), by the command's full type name: a generated\n * client sets them for commands with `int64`, `bigint` or `decimal` fields,\n * which it types as `string`.\n */\n readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;\n}\n\n/**\n * The options of a generated client's command method: a {@link CommandRequest}\n * without what the method fixes, its command, body and type.\n */\nexport type CommandOptions = Omit<\n CommandRequest,\n 'command' | 'body' | 'type' | 'id'\n>;\n\n/** The options of a command that may create its aggregate, with its id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list. */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The client generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\n/** The prefix of the system commands' names, the lifecycle commands' among them. */\nconst SYSTEM_PREFIX = 'wow.';\n\n/** The aggregate id of a route's path. */\nconst ID = '{id}';\n\n/** Whether `plan` waits for acceptance alone. */\nfunction acceptedOnly(plan: WaitPlan): boolean {\n return plan.hops.length === 1 && plan.hops[0].stage === Stage.ACCEPTED;\n}\n\n/**\n * The plan `request` waits with, as Kotlin's `CommandRequest.plan`: its\n * `wait` within its `timeout`, the default plan when only a timeout is given.\n */\nfunction planOf(request: CommandRequest): WaitPlan | undefined {\n if (request.timeout === undefined) return request.wait;\n return (request.wait ?? WaitPlan.DEFAULT).within(request.timeout);\n}\n\n/**\n * The route of `request` among `routes`, by `id` (the request's, none for a\n * command whose body names its aggregate): its method and path, the id in it.\n * An empty id is refused before anything is sent: it would leave the path's\n * segment empty (`/<context>/<aggregate>//…`), a route no service has.\n */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n id: string | undefined,\n): { method: 'POST' | 'DELETE'; path: string } {\n const route = routes.find(\n item => item.path.includes(ID) === (id !== undefined),\n );\n if (route === undefined) {\n throw new TypeError(\n id === undefined\n ? `${request.command} has no route without an aggregate id: set the request's id.`\n : `${request.command} has no route to an aggregate by its id: send it without an id.`,\n );\n }\n if (id === '') {\n throw new TypeError(\n `The path ${route.path} of ${request.command} needs id.`,\n );\n }\n const method = route.method;\n if (method !== 'POST' && method !== 'DELETE') {\n throw new TypeError(\n `${request.command} is routed by ${method}: a command is sent by POST or DELETE.`,\n );\n }\n return {\n method,\n path:\n id === undefined\n ? route.path\n : route.path.replace(ID, encodeURIComponent(id)),\n };\n}\n\n/**\n * The body `request` sends, `{}` when it has none. Of a command whose body\n * names its aggregate in `idProperty`, the route has no id: the request's id,\n * when it names one, is the body's too, written into a body that names none.\n *\n * @throws TypeError when the body names another aggregate than the request\n */\nfunction bodyOf(\n request: CommandRequest,\n idProperty: string | undefined,\n): object {\n const body = request.body ?? {};\n const id = request.id;\n if (idProperty === undefined || id === undefined) return body;\n const named: unknown = (body as Record<string, unknown>)[idProperty];\n if (named === undefined || named === null) {\n return { ...body, [idProperty]: id };\n }\n if (named !== id) {\n throw new TypeError(\n `The request names the aggregate ${id}, but the body of ${request.command} names ${String(named)}: send it without an id.`,\n );\n }\n return body;\n}\n\n/** The aggregate type a full type name `context.aggregate.Command` names. */\nfunction typeNamed(command: string): AggregateType {\n const parts = command.split('.');\n if (parts.length < 3 || parts.some(part => part === '')) {\n throw new TypeError(\n `${command} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`,\n );\n }\n return { context: parts[0], name: parts[1] };\n}\n\nfunction commandHeaders(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n // The default plan is the service's to pick: it sends no plan.\n [WowHeaders.WAIT]:\n plan === undefined || plan.isDefault ? undefined : formatWaitPlan(plan),\n // A plan's own timeout, or the request's; the service's default otherwise.\n [WowHeaders.WAIT_TIMEOUT]:\n plan !== undefined &&\n (request.timeout !== undefined ||\n plan.timeout !== WaitPlan.DEFAULT_TIMEOUT)\n ? formatWaitTimeout(plan.timeout)\n : undefined,\n [WowHeaders.IF_MATCH]:\n request.expectedVersion === undefined\n ? undefined\n : `\"${request.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/** The `Wow-Scope` a request targets, when it targets one. */\nfunction targetOf(request: CommandRequest): TargetScope | undefined {\n if (request.targetTenant === undefined && request.targetScope === undefined) {\n return undefined;\n }\n return { tenantId: request.targetTenant, ...request.targetScope };\n}\n\n/**\n * Sends commands to the command routes of a Wow service as its Manifest lists\n * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without\n * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`\n * for `DeleteAggregate`): the Manifest the client is given, else the\n * service's, fetched once (`GET /wow/manifest`). The TypeScript\n * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers\n * once the command is accepted, {@link wait} with the result its wait plan\n * ends with, {@link stream} with one result per hop. Generated aggregate\n * clients build on it.\n *\n * `send` and `wait` resolve only a result that succeeded. A rejected one,\n * by the aggregate or at admission, rejects with a\n * {@link CommandRejectedError}; anything else that did not succeed with a\n * {@link WowProblemError} (the table on {@link CommandRejectedError} says\n * which). Every command carries a request id, the request's or a generated\n * one, and whatever it rejects with carries that id ({@link requestIdOf}).\n */\nexport class CommandClient {\n private readonly manifest: ManifestSource;\n private readonly bodyNumbers: Readonly<Record<string, TextNumbers>>;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest, and the commands' exact numbers\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: CommandClientOptions = {},\n ) {\n this.manifest = new ManifestSource(client, options.manifest);\n this.bodyNumbers = options.bodyNumbers ?? {};\n }\n\n /**\n * Sends a command and answers once it is accepted (202), within the\n * request's timeout (10 seconds without one), as Kotlin's\n * `CommandClient.send`. A request whose `wait` waits for more rejects with a\n * `TypeError` before it is sent: {@link wait} answers with that plan's result.\n *\n * @param request - The command and how to send it\n */\n async send<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n const plan = planOf(request);\n if (plan !== undefined && !plan.isDefault && !acceptedOnly(plan)) {\n throw new TypeError(\n `send answers on acceptance: use wait() for the plan ${formatWaitPlan(plan)}.`,\n );\n }\n return this.exchange<R>(\n request,\n WaitPlan.ACCEPTED.within(request.timeout ?? WaitPlan.DEFAULT_TIMEOUT),\n );\n }\n\n /**\n * Sends a command and answers the result its wait plan ends with: 200, or\n * 202 for a plan that ends at `accepted`. Without a plan, the server's\n * default: the snapshot, or the commit where the aggregate keeps no\n * snapshot (decision D69).\n *\n * @param request - The command and how to send it\n */\n wait<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n return this.exchange<R>(request, planOf(request));\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances, whatever its status. An admission refusal\n * rejects with its problem; a rejection after admission is the stream's\n * last result.\n *\n * @param request - The command and how to send it\n */\n async stream<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResultStream<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(\n request,\n planOf(request),\n requestId,\n 'text/event-stream',\n ),\n requestId,\n ),\n );\n }\n\n private async exchange<R>(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n ): Promise<CommandResult<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n let result: CommandResult<R>;\n try {\n result = await (\n await this.post(request, plan, requestId)\n ).json<CommandResult<R>>();\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.result?.status === CommandResultStatus.REJECTED\n ) {\n throw new CommandRejectedError(error.result, {\n problem: error.problem,\n cause: error,\n });\n }\n throw error;\n }\n return settled(result);\n });\n }\n\n private async post(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n ): Promise<Answer> {\n const declared = await this.commandOf(request);\n const idProperty = declared.idProperty;\n const route = routeOf(\n request,\n declared.routes,\n idProperty === undefined ? request.id : undefined,\n );\n const scope = targetOf(request);\n const bodyNumbers = this.bodyNumbers[request.command];\n return send(this.client, {\n method: route.method,\n path: route.path,\n headers: commandHeaders(request, plan, requestId, accept),\n ...(route.method === 'DELETE'\n ? {}\n : { body: bodyOf(request, idProperty) }),\n // A result's numbers are the framework's; its `results` are the\n // service's own, which the Manifest gives no schema.\n numbers: { body: bodyNumbers },\n options: {\n ...(scope === undefined ? {} : { scope }),\n ...(request.space === undefined ? {} : { space: request.space }),\n ...(request.headers === undefined ? {} : { headers: request.headers }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n },\n });\n }\n\n /**\n * `request`'s command as the Manifest lists it, with its routes: a domain\n * command among its aggregate's commands, by name or former name; a system\n * command among its type's, else among its context's (a job's).\n */\n private async commandOf(request: CommandRequest): Promise<RoutingCommand> {\n const command = request.command;\n const system = command.startsWith(SYSTEM_PREFIX);\n const type = request.type ?? (system ? undefined : typeNamed(command));\n if (type === undefined) {\n throw new TypeError(\n `${command} is a system command every aggregate takes: set the request's type.`,\n );\n }\n const prefix = `${type.context}.${type.name}.`;\n const name = command.startsWith(prefix)\n ? command.slice(prefix.length)\n : command;\n const context = (await this.manifest.read(request.signal)).contexts.find(\n item => item.name === type.context,\n );\n const declared =\n context?.aggregates\n ?.find(aggregate => aggregate.name === type.name)\n ?.commands?.find(\n item => item.name === name || item.aliases?.includes(name) === true,\n ) ??\n (system\n ? context?.commands?.find(item => item.name === name)\n : undefined);\n if (declared?.routes === undefined) {\n throw new TypeError(\n `The Manifest lists no command ${name} of ${type.context}.${type.name}.`,\n );\n }\n return declared;\n }\n}\n\n/**\n * The result a command was answered with, when it succeeded; else the error\n * that says why it did not, as Kotlin's `HttpCommandClient` settles one: a\n * rejected result rejects with a {@link CommandRejectedError}, a status this\n * client does not know (a newer service's) with a {@link WowProblemError}.\n */\nfunction settled<R>(result: CommandResult<R>): CommandResult<R> {\n if (result.status === CommandResultStatus.REJECTED) {\n throw new CommandRejectedError(result as RefusedResult);\n }\n if (!KNOWN_STATUSES.has(result.status)) {\n throw new WowProblemError({\n type: `urn:wow:error:${FrameworkErrorCodes.COMMAND_FAILED}`,\n title: 'Unknown command status',\n status: 200,\n code: FrameworkErrorCodes.COMMAND_FAILED,\n detail: `The command was answered with the status ${result.status}, which this client does not know: the service is newer than this client, so upgrade it.`,\n result: result as RefusedResult,\n });\n }\n return result;\n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A,IAAMe,IAAsC,IAAI,IAC9C,OAAO,OAAOb,CAAmB,CACnC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../filter/operator.cjs"),t=require("
|
|
1
|
+
const e=require("../filter/operator.cjs"),t=require("./types.cjs"),n=require("./expressionTrees.cjs"),r=require("../constantName.cjs"),i=require("./groups.cjs"),a=require("./metrics.cjs"),o=require("./derived.cjs"),s=require("./having.cjs"),c=require("./sort.cjs");function l(e,t,n,r){if(n.length>r)throw TypeError(`${e} must contain at most ${r} ${t}.`)}function u(t){switch(t.op){case e.FilterOperator.SEARCH:throw TypeError(`Aggregation metric filters do not support search filters.`);case e.FilterOperator.ELEMENT_MATCH:throw TypeError(`Aggregation metric filters do not support [ELEMENT_MATCH].`);case e.FilterOperator.AND:case e.FilterOperator.OR:case e.FilterOperator.NOR:t.operands.forEach(u)}}function d(e,t){n.requireValidExpressionTrees(e.flatMap(e=>e.type===a.AggregationMetricType.NUMERIC||e.type===a.AggregationMetricType.DISTINCT_COUNT||e.type===a.AggregationMetricType.PERCENTILE?[e.expression]:[])),t.forEach(e=>{if(e.type===i.AggregationGroupType.TERMS||e.type===i.AggregationGroupType.HISTOGRAM){if(e.field===void 0==(e.expression===void 0))throw TypeError(`${r.constantName(e.type)} group requires exactly one of field and expression.`);if(e.expression&&n.requireValidExpressionTrees([e.expression]),e.type===i.AggregationGroupType.TERMS&&e.missingKey!==void 0&&e.expression)throw TypeError(`terms missingKey requires a field input.`);if(e.scope===i.AggregationGroupScope.ROOT&&e.expression)throw TypeError(`${r.constantName(e.type)} with a ROOT scope requires a field input.`)}})}var f=new Set([a.AggregationMetricType.ANY,a.AggregationMetricType.FIRST,a.AggregationMetricType.LAST]);function p(e){let t=new Map,n=new Set,r={nodes:0,windows:0};e.forEach(e=>{e.type===a.AggregationMetricType.DERIVED&&(m(e,t,n,r),n.add(e.alias)),t.set(e.alias,f.has(e.type)?e.type:void 0)})}function m(e,n,i,a){let s=[{expression:e.expression,depth:1}];for(;s.length>0;){let{expression:c,depth:l}=s.pop();if(l>t.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH)throw TypeError(`derived expression depth must be at most ${t.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`);if(a.nodes++,a.nodes>t.AGGREGATION_LIMITS.MAX_EXPRESSION_NODES)throw TypeError(`derived expressions must contain at most ${t.AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`);switch(c.type){case o.DerivedExpressionType.METRIC_REF:{let t=c.metric;if(!n.has(t))throw TypeError(`derived metric [${e.alias}] must reference a metric declared before it, but was [${t}].`);let i=n.get(t);if(i!==void 0)throw TypeError(`derived metric [${e.alias}] cannot reference ${r.constantName(i)} metric [${t}].`);break}case o.DerivedExpressionType.CONSTANT:if(!Number.isFinite(c.value))throw TypeError(`derived constant must be finite.`);break;case o.DerivedExpressionType.BINARY:s.push({expression:c.left,depth:l+1}),s.push({expression:c.right,depth:l+1});break;case o.DerivedExpressionType.TOTAL:case o.DerivedExpressionType.RUNNING:case o.DerivedExpressionType.PREVIOUS:case o.DerivedExpressionType.RANK:if(a.windows++,a.windows>t.AGGREGATION_LIMITS.MAX_WINDOWS)throw TypeError(`an aggregation must compute at most ${t.AGGREGATION_LIMITS.MAX_WINDOWS} windows.`);h(e.alias,c,n,i);break;default:throw TypeError(`Unsupported derived expression: ${String(c.type)}.`)}}}function h(e,t,n,i){let a=t.metric;if(!n.has(a))throw TypeError(`${r.constantName(t.type)} window of derived metric [${e}] must read a metric declared before it, but was [${a}].`);if(n.get(a)!==void 0||i.has(a))throw TypeError(`${r.constantName(t.type)} window of derived metric [${e}] must read a non-derived numeric metric, but was [${a}].`)}function g(e,t,n,r){if(!t.has(e))throw TypeError(`having condition [${e}] must reference a declared metric alias.`);if(n.has(e))throw TypeError(`having condition [${e}] cannot reference ANY metric.`);if(r.has(e))throw TypeError(`having condition [${e}] cannot reference FIRST or LAST metric.`)}function _(e,n,i){if(e===void 0)return;if(n.length===0)throw TypeError(`having requires at least one groupBy.`);let o=new Set(i.map(e=>e.alias)),c=new Set(i.filter(e=>e.type===a.AggregationMetricType.ANY).map(e=>e.alias)),l=new Set(i.filter(e=>e.type===a.AggregationMetricType.FIRST||e.type===a.AggregationMetricType.LAST).map(e=>e.alias)),u=[{expression:e,depth:1}];for(;u.length>0;){let{expression:e,depth:n}=u.pop();if(n>t.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH)throw TypeError(`having expression depth must be at most ${t.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`);switch(e.type){case s.HavingExpressionType.CONDITION:if(g(e.metric,o,c,l),!Number.isFinite(e.value))throw TypeError(`having condition [${e.metric}] value must be finite.`);break;case s.HavingExpressionType.BETWEEN:if(g(e.metric,o,c,l),!Number.isFinite(e.lower)||!Number.isFinite(e.upper))throw TypeError(`having between [${e.metric}] bounds must be finite.`);if(e.lower>e.upper)throw TypeError(`having between [${e.metric}] lower bound must not exceed upper bound.`);break;case s.HavingExpressionType.IN:if(g(e.metric,o,c,l),e.values.length===0)throw TypeError(`having in [${e.metric}] values must not be empty.`);if(!e.values.every(Number.isFinite))throw TypeError(`having in [${e.metric}] values must be finite.`);break;case s.HavingExpressionType.IS_NULL:g(e.metric,o,c,l);break;case s.HavingExpressionType.AND:case s.HavingExpressionType.OR:if(e.operands.length===0)throw TypeError(`having ${r.constantName(e.type)} operands must not be empty.`);e.operands.forEach(e=>u.push({expression:e,depth:n+1}));break;default:throw TypeError(`Unsupported having expression: ${String(e.type)}.`)}}}function v(e,n,r){if(l(`sort`,`fields`,e,t.AGGREGATION_LIMITS.MAX_SORT_FIELDS),n.length===0&&e.length>0)throw TypeError(`sort requires at least one groupBy.`);let i=e.map(e=>e.field);if(new Set(i).size!==i.length)throw TypeError(`sort fields must be unique.`);if(!i.every(e=>r.includes(e)))throw TypeError(`sort fields must reference aggregation aliases.`);l(`effective sort`,`fields`,c.effectiveSort({groupBy:[...n],sort:[...e]}),t.AGGREGATION_LIMITS.MAX_SORT_FIELDS)}function y(e){let t=new Map((e.groupBy??[]).map(e=>[e.alias,e.scope===i.AggregationGroupScope.ROOT])),n=c.effectiveSort(e).flatMap(e=>t.has(e.field)?[t.get(e.field)]:[]),r=n.indexOf(!1);if(r>=0&&n.slice(r).includes(!0))throw TypeError(`groups with a ROOT scope must sort before the element groups.`)}function b(e){let n=e.elements??[],a=e.groupBy??[],o=e.metrics,s=e.sort??[];if(l(`elements`,`paths`,n,t.AGGREGATION_LIMITS.MAX_ELEMENTS),l(`groupBy`,`dimensions`,a,t.AGGREGATION_LIMITS.MAX_GROUPS),!Array.isArray(o)||o.length===0)throw TypeError(`metrics must not be empty.`);if(l(`metrics`,`entries`,o,t.AGGREGATION_LIMITS.MAX_METRICS),e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t.AGGREGATION_LIMITS.MAX_LIMIT))throw TypeError(`limit must be between 1 and ${t.AGGREGATION_LIMITS.MAX_LIMIT}.`);d(o,a),p(o),_(e.having,a,o),o.forEach(e=>{`filter`in e&&e.filter&&u(e.filter)}),a.forEach(e=>{if((e.type===i.AggregationGroupType.DATE_HISTOGRAM||e.type===i.AggregationGroupType.DATE_PART)&&e.dense===!0&&a.length!==1)throw TypeError(`dense requires ${r.constantName(e.type)} to be the only groupBy.`)});let c=[...a.map(e=>e.alias),...o.map(e=>e.alias)];if(new Set(c).size!==c.length)throw TypeError(`aggregation aliases must be unique.`);return v(s,a,c),n.length>0&&y(e),{...e,metrics:[...o]}}exports.admitAggregationQuery=b;
|
|
2
2
|
//# sourceMappingURL=admit.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admit.cjs","names":["FilterOperator","AggregationMetricType","AggregationGroupType","constantName","AggregationGroupScope","AGGREGATION_LIMITS","DerivedExpressionType","HavingExpressionType","effectiveSort","require_operator","require_constantName","require_types","require_expressionTrees","require_sort","requireAtMost","items","max","name","noun","validateMetricFilter","filter","validateExpressions","metrics","metric","groupBy","group","NON_NUMERIC","validateDerivedMetrics","declared","derived","counter","validateDerivedExpression","pending","depth","expression","reference","nonNumeric","requireWindowMetric","target","window","alias","requireValidHavingMetric","metricAliases","anyAliases","edgeAliases","validateHaving","having","operand","validateSort","sort","fields","entry","aliases","field","requireRootGroupsFirst","root","query","order","firstElement","admitAggregationQuery","elements"],"sources":["../../../src/dsl/aggregation/admit.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { constantName } from '../constantName.js';\nimport { FilterOperator, type FilterExpression } from '../filter/index.js';\nimport type { FieldSort } from '../sort.js';\nimport { requireValidExpressionTrees } from './expressionTrees.js';\nimport { effectiveSort } from './sort.js';\nimport {\n AGGREGATION_LIMITS,\n AggregationGroupScope,\n AggregationGroupType,\n AggregationMetricType,\n DerivedExpressionType,\n HavingExpressionType,\n type AggregationGroup,\n type AggregationMetric,\n type AggregationQuery,\n type DerivedAggregationMetric,\n type DerivedExpression,\n type DerivedWindow,\n type HavingExpression,\n} from './types.js';\n\n// Internal: the rules `aggregation.query()` checks across the parts of a\n// query. index.ts does not re-export this file.\n\nfunction requireAtMost(\n name: string,\n noun: string,\n items: readonly unknown[],\n max: number,\n): void {\n if (items.length > max) {\n throw new TypeError(`${name} must contain at most ${max} ${noun}.`);\n }\n}\n\n/**\n * Refuses the filters a metric cannot carry, whatever the aggregate holds.\n *\n * A metric filter is a whole-value predicate on one record — MongoDB turns it\n * into a `$cond` guard and Elasticsearch into a filter aggregation — and\n * element matching and full text have no whole-value reading. Both backends\n * refuse them before touching a schema, so the shape alone settles it. What a\n * schema would add, refusing an array-valued field, stays on the server.\n */\nfunction validateMetricFilter(filter: FilterExpression): void {\n switch (filter.op) {\n case FilterOperator.SEARCH:\n throw new TypeError(\n 'Aggregation metric filters do not support search filters.',\n );\n case FilterOperator.ELEMENT_MATCH:\n throw new TypeError(\n 'Aggregation metric filters do not support [ELEMENT_MATCH].',\n );\n case FilterOperator.AND:\n case FilterOperator.OR:\n case FilterOperator.NOR:\n filter.operands.forEach(validateMetricFilter);\n break;\n }\n}\n\n/**\n * Walks the arithmetic of every metric that carries an expression, as one\n * budget, and of each expression group on its own, as Wow does.\n */\nfunction validateExpressions(\n metrics: readonly AggregationMetric[],\n groupBy: readonly AggregationGroup[],\n): void {\n requireValidExpressionTrees(\n metrics.flatMap(metric =>\n metric.type === AggregationMetricType.NUMERIC ||\n metric.type === AggregationMetricType.DISTINCT_COUNT ||\n metric.type === AggregationMetricType.PERCENTILE\n ? [metric.expression]\n : [],\n ),\n );\n groupBy.forEach(group => {\n if (\n group.type !== AggregationGroupType.TERMS &&\n group.type !== AggregationGroupType.HISTOGRAM\n )\n return;\n if ((group.field === undefined) === (group.expression === undefined)) {\n throw new TypeError(\n `${constantName(group.type)} group requires exactly one of field and expression.`,\n );\n }\n if (group.expression) requireValidExpressionTrees([group.expression]);\n if (\n group.type === AggregationGroupType.TERMS &&\n group.missingKey !== undefined &&\n group.expression\n ) {\n throw new TypeError('terms missingKey requires a field input.');\n }\n if (group.scope === AggregationGroupScope.ROOT && group.expression) {\n throw new TypeError(\n `${constantName(group.type)} with a ROOT scope requires a field input.`,\n );\n }\n });\n}\n\n/** The metric types whose value is not a number: derived and having refuse them. */\nconst NON_NUMERIC: ReadonlySet<string> = new Set([\n AggregationMetricType.ANY,\n AggregationMetricType.FIRST,\n AggregationMetricType.LAST,\n]);\n\n/**\n * Admits the derived metrics against what was declared before each of them.\n *\n * Derived arithmetic runs after the aggregation, over values the query has\n * already produced, so a reference may only name a metric declared earlier —\n * that is what makes the list evaluable in one pass — and never an `ANY`,\n * `FIRST` or `LAST` metric, whose value is a field's value rather than a\n * number.\n */\nfunction validateDerivedMetrics(metrics: readonly AggregationMetric[]): void {\n // Each earlier alias, with its type when that is not a number.\n const declared = new Map<string, string | undefined>();\n const derived = new Set<string>();\n const counter = { nodes: 0, windows: 0 };\n metrics.forEach(metric => {\n if (metric.type === AggregationMetricType.DERIVED) {\n validateDerivedExpression(metric, declared, derived, counter);\n derived.add(metric.alias);\n }\n declared.set(\n metric.alias,\n NON_NUMERIC.has(metric.type) ? metric.type : undefined,\n );\n });\n}\n\nfunction validateDerivedExpression(\n metric: DerivedAggregationMetric,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n counter: { nodes: number; windows: number },\n): void {\n const pending: { expression: DerivedExpression; depth: number }[] = [\n { expression: metric.expression, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `derived expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n counter.nodes++;\n if (counter.nodes > AGGREGATION_LIMITS.MAX_EXPRESSION_NODES) {\n throw new TypeError(\n `derived expressions must contain at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`,\n );\n }\n switch (expression.type) {\n case DerivedExpressionType.METRIC_REF: {\n const reference = expression.metric;\n if (!declared.has(reference)) {\n throw new TypeError(\n `derived metric [${metric.alias}] must reference a metric declared before it, but was [${reference}].`,\n );\n }\n const nonNumeric = declared.get(reference);\n if (nonNumeric !== undefined) {\n throw new TypeError(\n `derived metric [${metric.alias}] cannot reference ${constantName(nonNumeric)} metric [${reference}].`,\n );\n }\n break;\n }\n case DerivedExpressionType.CONSTANT:\n if (!Number.isFinite(expression.value)) {\n throw new TypeError('derived constant must be finite.');\n }\n break;\n case DerivedExpressionType.BINARY:\n pending.push({ expression: expression.left, depth: depth + 1 });\n pending.push({ expression: expression.right, depth: depth + 1 });\n break;\n case DerivedExpressionType.TOTAL:\n case DerivedExpressionType.RUNNING:\n case DerivedExpressionType.PREVIOUS:\n case DerivedExpressionType.RANK:\n counter.windows++;\n if (counter.windows > AGGREGATION_LIMITS.MAX_WINDOWS) {\n throw new TypeError(\n `an aggregation must compute at most ${AGGREGATION_LIMITS.MAX_WINDOWS} windows.`,\n );\n }\n requireWindowMetric(metric.alias, expression, declared, derived);\n break;\n default:\n throw new TypeError(\n `Unsupported derived expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\n/**\n * A window reads a non-derived numeric metric declared before the derived\n * one; the rest of its rules (which metrics add up, which groups it names)\n * the server checks against the whole query.\n */\nfunction requireWindowMetric(\n alias: string,\n window: DerivedWindow,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n): void {\n const target = window.metric;\n if (!declared.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a metric declared before it, but was [${target}].`,\n );\n }\n if (declared.get(target) !== undefined || derived.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a non-derived numeric metric, but was [${target}].`,\n );\n }\n}\n\nfunction requireValidHavingMetric(\n metric: string,\n metricAliases: ReadonlySet<string>,\n anyAliases: ReadonlySet<string>,\n edgeAliases: ReadonlySet<string>,\n): void {\n if (!metricAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] must reference a declared metric alias.`,\n );\n }\n if (anyAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference ANY metric.`,\n );\n }\n if (edgeAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference FIRST or LAST metric.`,\n );\n }\n}\n\n/**\n * `having` filters the grouped rows, so it needs rows to filter: a query with\n * no `groupBy` produces one row and has nothing to select from.\n */\nfunction validateHaving(\n having: HavingExpression | undefined,\n groupBy: readonly AggregationGroup[],\n metrics: readonly AggregationMetric[],\n): void {\n if (having === undefined) return;\n if (groupBy.length === 0) {\n throw new TypeError('having requires at least one groupBy.');\n }\n const metricAliases = new Set(metrics.map(metric => metric.alias));\n const anyAliases = new Set(\n metrics\n .filter(metric => metric.type === AggregationMetricType.ANY)\n .map(metric => metric.alias),\n );\n const edgeAliases = new Set(\n metrics\n .filter(\n metric =>\n metric.type === AggregationMetricType.FIRST ||\n metric.type === AggregationMetricType.LAST,\n )\n .map(metric => metric.alias),\n );\n\n const pending: { expression: HavingExpression; depth: number }[] = [\n { expression: having, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `having expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n switch (expression.type) {\n case HavingExpressionType.CONDITION:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (!Number.isFinite(expression.value)) {\n throw new TypeError(\n `having condition [${expression.metric}] value must be finite.`,\n );\n }\n break;\n case HavingExpressionType.BETWEEN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (\n !Number.isFinite(expression.lower) ||\n !Number.isFinite(expression.upper)\n ) {\n throw new TypeError(\n `having between [${expression.metric}] bounds must be finite.`,\n );\n }\n if (expression.lower > expression.upper) {\n throw new TypeError(\n `having between [${expression.metric}] lower bound must not exceed upper bound.`,\n );\n }\n break;\n case HavingExpressionType.IN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (expression.values.length === 0) {\n throw new TypeError(\n `having in [${expression.metric}] values must not be empty.`,\n );\n }\n if (!expression.values.every(Number.isFinite)) {\n throw new TypeError(\n `having in [${expression.metric}] values must be finite.`,\n );\n }\n break;\n case HavingExpressionType.IS_NULL:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n break;\n case HavingExpressionType.AND:\n case HavingExpressionType.OR:\n if (expression.operands.length === 0) {\n throw new TypeError(\n `having ${constantName(expression.type)} operands must not be empty.`,\n );\n }\n expression.operands.forEach(operand =>\n pending.push({ expression: operand, depth: depth + 1 }),\n );\n break;\n default:\n throw new TypeError(\n `Unsupported having expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\nfunction validateSort(\n sort: readonly FieldSort[],\n groupBy: readonly AggregationGroup[],\n aliases: readonly string[],\n): void {\n requireAtMost('sort', 'fields', sort, AGGREGATION_LIMITS.MAX_SORT_FIELDS);\n if (groupBy.length === 0 && sort.length > 0) {\n throw new TypeError('sort requires at least one groupBy.');\n }\n const fields = sort.map(entry => entry.field);\n if (new Set(fields).size !== fields.length) {\n throw new TypeError('sort fields must be unique.');\n }\n if (!fields.every(field => aliases.includes(field))) {\n throw new TypeError('sort fields must reference aggregation aliases.');\n }\n requireAtMost(\n 'effective sort',\n 'fields',\n effectiveSort({ groupBy: [...groupBy], sort: [...sort] }),\n AGGREGATION_LIMITS.MAX_SORT_FIELDS,\n );\n}\n\n/**\n * With elements, the groups of a ROOT scope lead the effective sort: a storage\n * reads the root records' keys before the keys of their elements.\n */\nfunction requireRootGroupsFirst(\n query: Pick<AggregationQuery<string, string>, 'groupBy' | 'sort'>,\n): void {\n const root = new Map(\n (query.groupBy ?? []).map(group => [\n group.alias,\n group.scope === AggregationGroupScope.ROOT,\n ]),\n );\n const order = effectiveSort(query).flatMap(entry =>\n root.has(entry.field) ? [root.get(entry.field)] : [],\n );\n const firstElement = order.indexOf(false);\n if (firstElement >= 0 && order.slice(firstElement).includes(true)) {\n throw new TypeError(\n 'groups with a ROOT scope must sort before the element groups.',\n );\n }\n}\n\n/**\n * Admits a whole aggregation query against the rules Wow enforces on arrival;\n * {@link aggregation.query} is its public face.\n */\nexport function admitAggregationQuery<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n>(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n const elements = query.elements ?? [];\n const groupBy = query.groupBy ?? [];\n const metrics = query.metrics;\n const sort = query.sort ?? [];\n\n requireAtMost('elements', 'paths', elements, AGGREGATION_LIMITS.MAX_ELEMENTS);\n requireAtMost(\n 'groupBy',\n 'dimensions',\n groupBy,\n AGGREGATION_LIMITS.MAX_GROUPS,\n );\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new TypeError('metrics must not be empty.');\n }\n requireAtMost('metrics', 'entries', metrics, AGGREGATION_LIMITS.MAX_METRICS);\n if (query.limit !== undefined) {\n if (\n !Number.isInteger(query.limit) ||\n query.limit < 1 ||\n query.limit > AGGREGATION_LIMITS.MAX_LIMIT\n ) {\n throw new TypeError(\n `limit must be between 1 and ${AGGREGATION_LIMITS.MAX_LIMIT}.`,\n );\n }\n }\n\n validateExpressions(metrics, groupBy);\n validateDerivedMetrics(metrics);\n validateHaving(query.having, groupBy, metrics);\n metrics.forEach(metric => {\n if ('filter' in metric && metric.filter)\n validateMetricFilter(metric.filter);\n });\n\n // A dense DATE_HISTOGRAM fills in the buckets its range implies, and a\n // dense DATE_PART every key of its part's domain, rather than only the ones\n // with rows; a second dimension would multiply that filling out across\n // every one of its own keys.\n groupBy.forEach(group => {\n if (\n (group.type === AggregationGroupType.DATE_HISTOGRAM ||\n group.type === AggregationGroupType.DATE_PART) &&\n group.dense === true &&\n groupBy.length !== 1\n ) {\n throw new TypeError(\n `dense requires ${constantName(group.type)} to be the only groupBy.`,\n );\n }\n });\n\n const aliases = [\n ...groupBy.map(group => group.alias),\n ...metrics.map(metric => metric.alias),\n ];\n if (new Set(aliases).size !== aliases.length) {\n throw new TypeError('aggregation aliases must be unique.');\n }\n validateSort(sort, groupBy, aliases);\n if (elements.length > 0) requireRootGroupsFirst(query);\n\n return {\n ...query,\n metrics: [...metrics] as typeof query.metrics,\n };\n}\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,CACvB,IACGC,EAAM,OAASvB,EAAAA,qBAAqB,gBACnCuB,EAAM,OAASvB,EAAAA,qBAAqB,YACtCuB,EAAM,QAAU,IAChBD,EAAQ,SAAW,EAEnB,MAAU,UACR,kBAAkBrB,EAAAA,aAAasB,EAAM,IAAI,EAAE,yBAC7C,CAEJ,CAAC,EAED,IAAM2B,EAAU,CACd,GAAG5B,EAAQ,IAAI,GAASC,EAAM,KAAK,EACnC,GAAGH,EAAQ,IAAI,GAAUC,EAAO,KAAK,CACvC,EACA,GAAI,IAAI,IAAI6B,CAAO,CAAC,CAAC,OAASA,EAAQ,OACpC,MAAU,UAAU,qCAAqC,EAK3D,OAHAJ,EAAaC,EAAMzB,EAAS4B,CAAO,EAC/BQ,EAAS,OAAS,GAAGN,EAAuBE,CAAK,EAE9C,CACL,GAAGA,EACH,QAAS,CAAC,GAAGlC,CAAO,CACtB,CACF,C"}
|
|
1
|
+
{"version":3,"file":"admit.cjs","names":["FilterOperator","AggregationMetricType","AggregationGroupType","constantName","AggregationGroupScope","AGGREGATION_LIMITS","DerivedExpressionType","HavingExpressionType","effectiveSort","require_operator","require_types","require_expressionTrees","require_constantName","require_groups","require_metrics","require_derived","require_having","require_sort","requireAtMost","items","max","name","noun","validateMetricFilter","filter","validateExpressions","metrics","metric","groupBy","group","NON_NUMERIC","validateDerivedMetrics","declared","derived","counter","validateDerivedExpression","pending","depth","expression","reference","nonNumeric","requireWindowMetric","target","window","alias","requireValidHavingMetric","metricAliases","anyAliases","edgeAliases","validateHaving","having","operand","validateSort","sort","fields","entry","aliases","field","requireRootGroupsFirst","root","query","order","firstElement","admitAggregationQuery","elements"],"sources":["../../../src/dsl/aggregation/admit.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { constantName } from '../constantName.js';\nimport { FilterOperator, type FilterExpression } from '../filter/index.js';\nimport type { FieldSort } from '../sort.js';\nimport { requireValidExpressionTrees } from './expressionTrees.js';\nimport { effectiveSort } from './sort.js';\nimport {\n DerivedExpressionType,\n type DerivedAggregationMetric,\n type DerivedExpression,\n type DerivedWindow,\n} from './derived.js';\nimport {\n AggregationGroupScope,\n AggregationGroupType,\n type AggregationGroup,\n} from './groups.js';\nimport { HavingExpressionType, type HavingExpression } from './having.js';\nimport { AggregationMetricType, type AggregationMetric } from './metrics.js';\nimport { AGGREGATION_LIMITS, type AggregationQuery } from './types.js';\n\n// Internal: the rules `aggregation.query()` checks across the parts of a\n// query. index.ts does not re-export this file.\n\nfunction requireAtMost(\n name: string,\n noun: string,\n items: readonly unknown[],\n max: number,\n): void {\n if (items.length > max) {\n throw new TypeError(`${name} must contain at most ${max} ${noun}.`);\n }\n}\n\n/**\n * Refuses the filters a metric cannot carry, whatever the aggregate holds.\n *\n * A metric filter is a whole-value predicate on one record — MongoDB turns it\n * into a `$cond` guard and Elasticsearch into a filter aggregation — and\n * element matching and full text have no whole-value reading. Both backends\n * refuse them before touching a schema, so the shape alone settles it. What a\n * schema would add, refusing an array-valued field, stays on the server.\n */\nfunction validateMetricFilter(filter: FilterExpression): void {\n switch (filter.op) {\n case FilterOperator.SEARCH:\n throw new TypeError(\n 'Aggregation metric filters do not support search filters.',\n );\n case FilterOperator.ELEMENT_MATCH:\n throw new TypeError(\n 'Aggregation metric filters do not support [ELEMENT_MATCH].',\n );\n case FilterOperator.AND:\n case FilterOperator.OR:\n case FilterOperator.NOR:\n filter.operands.forEach(validateMetricFilter);\n break;\n }\n}\n\n/**\n * Walks the arithmetic of every metric that carries an expression, as one\n * budget, and of each expression group on its own, as Wow does.\n */\nfunction validateExpressions(\n metrics: readonly AggregationMetric[],\n groupBy: readonly AggregationGroup[],\n): void {\n requireValidExpressionTrees(\n metrics.flatMap(metric =>\n metric.type === AggregationMetricType.NUMERIC ||\n metric.type === AggregationMetricType.DISTINCT_COUNT ||\n metric.type === AggregationMetricType.PERCENTILE\n ? [metric.expression]\n : [],\n ),\n );\n groupBy.forEach(group => {\n if (\n group.type !== AggregationGroupType.TERMS &&\n group.type !== AggregationGroupType.HISTOGRAM\n )\n return;\n if ((group.field === undefined) === (group.expression === undefined)) {\n throw new TypeError(\n `${constantName(group.type)} group requires exactly one of field and expression.`,\n );\n }\n if (group.expression) requireValidExpressionTrees([group.expression]);\n if (\n group.type === AggregationGroupType.TERMS &&\n group.missingKey !== undefined &&\n group.expression\n ) {\n throw new TypeError('terms missingKey requires a field input.');\n }\n if (group.scope === AggregationGroupScope.ROOT && group.expression) {\n throw new TypeError(\n `${constantName(group.type)} with a ROOT scope requires a field input.`,\n );\n }\n });\n}\n\n/** The metric types whose value is not a number: derived and having refuse them. */\nconst NON_NUMERIC: ReadonlySet<string> = new Set([\n AggregationMetricType.ANY,\n AggregationMetricType.FIRST,\n AggregationMetricType.LAST,\n]);\n\n/**\n * Admits the derived metrics against what was declared before each of them.\n *\n * Derived arithmetic runs after the aggregation, over values the query has\n * already produced, so a reference may only name a metric declared earlier —\n * that is what makes the list evaluable in one pass — and never an `ANY`,\n * `FIRST` or `LAST` metric, whose value is a field's value rather than a\n * number.\n */\nfunction validateDerivedMetrics(metrics: readonly AggregationMetric[]): void {\n // Each earlier alias, with its type when that is not a number.\n const declared = new Map<string, string | undefined>();\n const derived = new Set<string>();\n const counter = { nodes: 0, windows: 0 };\n metrics.forEach(metric => {\n if (metric.type === AggregationMetricType.DERIVED) {\n validateDerivedExpression(metric, declared, derived, counter);\n derived.add(metric.alias);\n }\n declared.set(\n metric.alias,\n NON_NUMERIC.has(metric.type) ? metric.type : undefined,\n );\n });\n}\n\nfunction validateDerivedExpression(\n metric: DerivedAggregationMetric,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n counter: { nodes: number; windows: number },\n): void {\n const pending: { expression: DerivedExpression; depth: number }[] = [\n { expression: metric.expression, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `derived expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n counter.nodes++;\n if (counter.nodes > AGGREGATION_LIMITS.MAX_EXPRESSION_NODES) {\n throw new TypeError(\n `derived expressions must contain at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`,\n );\n }\n switch (expression.type) {\n case DerivedExpressionType.METRIC_REF: {\n const reference = expression.metric;\n if (!declared.has(reference)) {\n throw new TypeError(\n `derived metric [${metric.alias}] must reference a metric declared before it, but was [${reference}].`,\n );\n }\n const nonNumeric = declared.get(reference);\n if (nonNumeric !== undefined) {\n throw new TypeError(\n `derived metric [${metric.alias}] cannot reference ${constantName(nonNumeric)} metric [${reference}].`,\n );\n }\n break;\n }\n case DerivedExpressionType.CONSTANT:\n if (!Number.isFinite(expression.value)) {\n throw new TypeError('derived constant must be finite.');\n }\n break;\n case DerivedExpressionType.BINARY:\n pending.push({ expression: expression.left, depth: depth + 1 });\n pending.push({ expression: expression.right, depth: depth + 1 });\n break;\n case DerivedExpressionType.TOTAL:\n case DerivedExpressionType.RUNNING:\n case DerivedExpressionType.PREVIOUS:\n case DerivedExpressionType.RANK:\n counter.windows++;\n if (counter.windows > AGGREGATION_LIMITS.MAX_WINDOWS) {\n throw new TypeError(\n `an aggregation must compute at most ${AGGREGATION_LIMITS.MAX_WINDOWS} windows.`,\n );\n }\n requireWindowMetric(metric.alias, expression, declared, derived);\n break;\n default:\n throw new TypeError(\n `Unsupported derived expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\n/**\n * A window reads a non-derived numeric metric declared before the derived\n * one; the rest of its rules (which metrics add up, which groups it names)\n * the server checks against the whole query.\n */\nfunction requireWindowMetric(\n alias: string,\n window: DerivedWindow,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n): void {\n const target = window.metric;\n if (!declared.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a metric declared before it, but was [${target}].`,\n );\n }\n if (declared.get(target) !== undefined || derived.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a non-derived numeric metric, but was [${target}].`,\n );\n }\n}\n\nfunction requireValidHavingMetric(\n metric: string,\n metricAliases: ReadonlySet<string>,\n anyAliases: ReadonlySet<string>,\n edgeAliases: ReadonlySet<string>,\n): void {\n if (!metricAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] must reference a declared metric alias.`,\n );\n }\n if (anyAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference ANY metric.`,\n );\n }\n if (edgeAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference FIRST or LAST metric.`,\n );\n }\n}\n\n/**\n * `having` filters the grouped rows, so it needs rows to filter: a query with\n * no `groupBy` produces one row and has nothing to select from.\n */\nfunction validateHaving(\n having: HavingExpression | undefined,\n groupBy: readonly AggregationGroup[],\n metrics: readonly AggregationMetric[],\n): void {\n if (having === undefined) return;\n if (groupBy.length === 0) {\n throw new TypeError('having requires at least one groupBy.');\n }\n const metricAliases = new Set(metrics.map(metric => metric.alias));\n const anyAliases = new Set(\n metrics\n .filter(metric => metric.type === AggregationMetricType.ANY)\n .map(metric => metric.alias),\n );\n const edgeAliases = new Set(\n metrics\n .filter(\n metric =>\n metric.type === AggregationMetricType.FIRST ||\n metric.type === AggregationMetricType.LAST,\n )\n .map(metric => metric.alias),\n );\n\n const pending: { expression: HavingExpression; depth: number }[] = [\n { expression: having, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `having expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n switch (expression.type) {\n case HavingExpressionType.CONDITION:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (!Number.isFinite(expression.value)) {\n throw new TypeError(\n `having condition [${expression.metric}] value must be finite.`,\n );\n }\n break;\n case HavingExpressionType.BETWEEN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (\n !Number.isFinite(expression.lower) ||\n !Number.isFinite(expression.upper)\n ) {\n throw new TypeError(\n `having between [${expression.metric}] bounds must be finite.`,\n );\n }\n if (expression.lower > expression.upper) {\n throw new TypeError(\n `having between [${expression.metric}] lower bound must not exceed upper bound.`,\n );\n }\n break;\n case HavingExpressionType.IN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (expression.values.length === 0) {\n throw new TypeError(\n `having in [${expression.metric}] values must not be empty.`,\n );\n }\n if (!expression.values.every(Number.isFinite)) {\n throw new TypeError(\n `having in [${expression.metric}] values must be finite.`,\n );\n }\n break;\n case HavingExpressionType.IS_NULL:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n break;\n case HavingExpressionType.AND:\n case HavingExpressionType.OR:\n if (expression.operands.length === 0) {\n throw new TypeError(\n `having ${constantName(expression.type)} operands must not be empty.`,\n );\n }\n expression.operands.forEach(operand =>\n pending.push({ expression: operand, depth: depth + 1 }),\n );\n break;\n default:\n throw new TypeError(\n `Unsupported having expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\nfunction validateSort(\n sort: readonly FieldSort[],\n groupBy: readonly AggregationGroup[],\n aliases: readonly string[],\n): void {\n requireAtMost('sort', 'fields', sort, AGGREGATION_LIMITS.MAX_SORT_FIELDS);\n if (groupBy.length === 0 && sort.length > 0) {\n throw new TypeError('sort requires at least one groupBy.');\n }\n const fields = sort.map(entry => entry.field);\n if (new Set(fields).size !== fields.length) {\n throw new TypeError('sort fields must be unique.');\n }\n if (!fields.every(field => aliases.includes(field))) {\n throw new TypeError('sort fields must reference aggregation aliases.');\n }\n requireAtMost(\n 'effective sort',\n 'fields',\n effectiveSort({ groupBy: [...groupBy], sort: [...sort] }),\n AGGREGATION_LIMITS.MAX_SORT_FIELDS,\n );\n}\n\n/**\n * With elements, the groups of a ROOT scope lead the effective sort: a storage\n * reads the root records' keys before the keys of their elements.\n */\nfunction requireRootGroupsFirst(\n query: Pick<AggregationQuery<string, string>, 'groupBy' | 'sort'>,\n): void {\n const root = new Map(\n (query.groupBy ?? []).map(group => [\n group.alias,\n group.scope === AggregationGroupScope.ROOT,\n ]),\n );\n const order = effectiveSort(query).flatMap(entry =>\n root.has(entry.field) ? [root.get(entry.field)] : [],\n );\n const firstElement = order.indexOf(false);\n if (firstElement >= 0 && order.slice(firstElement).includes(true)) {\n throw new TypeError(\n 'groups with a ROOT scope must sort before the element groups.',\n );\n }\n}\n\n/**\n * Admits a whole aggregation query against the rules Wow enforces on arrival;\n * {@link aggregation.query} is its public face.\n */\nexport function admitAggregationQuery<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n>(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n const elements = query.elements ?? [];\n const groupBy = query.groupBy ?? [];\n const metrics = query.metrics;\n const sort = query.sort ?? [];\n\n requireAtMost('elements', 'paths', elements, AGGREGATION_LIMITS.MAX_ELEMENTS);\n requireAtMost(\n 'groupBy',\n 'dimensions',\n groupBy,\n AGGREGATION_LIMITS.MAX_GROUPS,\n );\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new TypeError('metrics must not be empty.');\n }\n requireAtMost('metrics', 'entries', metrics, AGGREGATION_LIMITS.MAX_METRICS);\n if (query.limit !== undefined) {\n if (\n !Number.isInteger(query.limit) ||\n query.limit < 1 ||\n query.limit > AGGREGATION_LIMITS.MAX_LIMIT\n ) {\n throw new TypeError(\n `limit must be between 1 and ${AGGREGATION_LIMITS.MAX_LIMIT}.`,\n );\n }\n }\n\n validateExpressions(metrics, groupBy);\n validateDerivedMetrics(metrics);\n validateHaving(query.having, groupBy, metrics);\n metrics.forEach(metric => {\n if ('filter' in metric && metric.filter)\n validateMetricFilter(metric.filter);\n });\n\n // A dense DATE_HISTOGRAM fills in the buckets its range implies, and a\n // dense DATE_PART every key of its part's domain, rather than only the ones\n // with rows; a second dimension would multiply that filling out across\n // every one of its own keys.\n groupBy.forEach(group => {\n if (\n (group.type === AggregationGroupType.DATE_HISTOGRAM ||\n group.type === AggregationGroupType.DATE_PART) &&\n group.dense === true &&\n groupBy.length !== 1\n ) {\n throw new TypeError(\n `dense requires ${constantName(group.type)} to be the only groupBy.`,\n );\n }\n });\n\n const aliases = [\n ...groupBy.map(group => group.alias),\n ...metrics.map(metric => metric.alias),\n ];\n if (new Set(aliases).size !== aliases.length) {\n throw new TypeError('aggregation aliases must be unique.');\n }\n validateSort(sort, groupBy, aliases);\n if (elements.length > 0) requireRootGroupsFirst(query);\n\n return {\n ...query,\n metrics: [...metrics] as typeof query.metrics,\n };\n}\n"],"mappings":"A,yQAoCA,SAASkB,EACP,EACA,EACA,EACA,EACM,CACN,GAAIC,EAAM,OAASC,EACjB,MAAU,UAAU,GAAGC,EAAK,wBAAwBD,EAAI,GAAGE,EAAK,EAAE,CAEtE,CAWA,SAASC,EAAqB,EAAgC,CAC5D,OAAQC,EAAO,GAAf,CACE,KAAKxB,EAAAA,eAAe,OAClB,MAAU,UACR,2DACF,EACF,KAAKA,EAAAA,eAAe,cAClB,MAAU,UACR,4DACF,EACF,KAAKA,EAAAA,eAAe,IACpB,KAAKA,EAAAA,eAAe,GACpB,KAAKA,EAAAA,eA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CAAC,OAASA,EAAQ,OACpC,MAAU,UAAU,qCAAqC,EAK3D,OAHAJ,EAAaC,EAAMzB,EAAS4B,CAAO,EAC/BQ,EAAS,OAAS,GAAGN,EAAuBE,CAAK,EAE9C,CACL,GAAGA,EACH,QAAS,CAAC,GAAGlC,CAAO,CACtB,CACF,C"}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { FilterOperator as e } from "../filter/operator.es.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { AGGREGATION_LIMITS as t } from "./types.es.js";
|
|
3
|
+
import { requireValidExpressionTrees as n } from "./expressionTrees.es.js";
|
|
4
|
+
import { constantName as r } from "../constantName.es.js";
|
|
5
|
+
import { AggregationGroupScope as i, AggregationGroupType as a } from "./groups.es.js";
|
|
6
|
+
import { AggregationMetricType as o } from "./metrics.es.js";
|
|
7
|
+
import { DerivedExpressionType as s } from "./derived.es.js";
|
|
8
|
+
import { HavingExpressionType as c } from "./having.es.js";
|
|
5
9
|
import { effectiveSort as l } from "./sort.es.js";
|
|
6
10
|
// src/dsl/aggregation/admit.ts
|
|
7
11
|
function u(e, t, n, r) {
|
|
@@ -16,19 +20,19 @@ function d(t) {
|
|
|
16
20
|
case e.NOR: t.operands.forEach(d);
|
|
17
21
|
}
|
|
18
22
|
}
|
|
19
|
-
function f(e,
|
|
20
|
-
|
|
21
|
-
if (e.type ===
|
|
22
|
-
if (e.field === void 0 == (e.expression === void 0)) throw TypeError(`${
|
|
23
|
-
if (e.expression &&
|
|
24
|
-
if (e.scope ===
|
|
23
|
+
function f(e, t) {
|
|
24
|
+
n(e.flatMap((e) => e.type === o.NUMERIC || e.type === o.DISTINCT_COUNT || e.type === o.PERCENTILE ? [e.expression] : [])), t.forEach((e) => {
|
|
25
|
+
if (e.type === a.TERMS || e.type === a.HISTOGRAM) {
|
|
26
|
+
if (e.field === void 0 == (e.expression === void 0)) throw TypeError(`${r(e.type)} group requires exactly one of field and expression.`);
|
|
27
|
+
if (e.expression && n([e.expression]), e.type === a.TERMS && e.missingKey !== void 0 && e.expression) throw TypeError("terms missingKey requires a field input.");
|
|
28
|
+
if (e.scope === i.ROOT && e.expression) throw TypeError(`${r(e.type)} with a ROOT scope requires a field input.`);
|
|
25
29
|
}
|
|
26
30
|
});
|
|
27
31
|
}
|
|
28
32
|
var p = /* @__PURE__ */ new Set([
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
33
|
+
o.ANY,
|
|
34
|
+
o.FIRST,
|
|
35
|
+
o.LAST
|
|
32
36
|
]);
|
|
33
37
|
function m(e) {
|
|
34
38
|
let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Set(), r = {
|
|
@@ -36,122 +40,122 @@ function m(e) {
|
|
|
36
40
|
windows: 0
|
|
37
41
|
};
|
|
38
42
|
e.forEach((e) => {
|
|
39
|
-
e.type ===
|
|
43
|
+
e.type === o.DERIVED && (h(e, t, n, r), n.add(e.alias)), t.set(e.alias, p.has(e.type) ? e.type : void 0);
|
|
40
44
|
});
|
|
41
45
|
}
|
|
42
|
-
function h(e,
|
|
43
|
-
let
|
|
46
|
+
function h(e, n, i, a) {
|
|
47
|
+
let o = [{
|
|
44
48
|
expression: e.expression,
|
|
45
49
|
depth: 1
|
|
46
50
|
}];
|
|
47
|
-
for (;
|
|
48
|
-
let { expression: c, depth: l } =
|
|
49
|
-
if (l >
|
|
50
|
-
if (a.nodes++, a.nodes >
|
|
51
|
+
for (; o.length > 0;) {
|
|
52
|
+
let { expression: c, depth: l } = o.pop();
|
|
53
|
+
if (l > t.MAX_EXPRESSION_DEPTH) throw TypeError(`derived expression depth must be at most ${t.MAX_EXPRESSION_DEPTH}.`);
|
|
54
|
+
if (a.nodes++, a.nodes > t.MAX_EXPRESSION_NODES) throw TypeError(`derived expressions must contain at most ${t.MAX_EXPRESSION_NODES} nodes.`);
|
|
51
55
|
switch (c.type) {
|
|
52
|
-
case
|
|
53
|
-
let
|
|
54
|
-
if (!
|
|
55
|
-
let i =
|
|
56
|
-
if (i !== void 0) throw TypeError(`derived metric [${e.alias}] cannot reference ${
|
|
56
|
+
case s.METRIC_REF: {
|
|
57
|
+
let t = c.metric;
|
|
58
|
+
if (!n.has(t)) throw TypeError(`derived metric [${e.alias}] must reference a metric declared before it, but was [${t}].`);
|
|
59
|
+
let i = n.get(t);
|
|
60
|
+
if (i !== void 0) throw TypeError(`derived metric [${e.alias}] cannot reference ${r(i)} metric [${t}].`);
|
|
57
61
|
break;
|
|
58
62
|
}
|
|
59
|
-
case
|
|
63
|
+
case s.CONSTANT:
|
|
60
64
|
if (!Number.isFinite(c.value)) throw TypeError("derived constant must be finite.");
|
|
61
65
|
break;
|
|
62
|
-
case
|
|
63
|
-
|
|
66
|
+
case s.BINARY:
|
|
67
|
+
o.push({
|
|
64
68
|
expression: c.left,
|
|
65
69
|
depth: l + 1
|
|
66
|
-
}),
|
|
70
|
+
}), o.push({
|
|
67
71
|
expression: c.right,
|
|
68
72
|
depth: l + 1
|
|
69
73
|
});
|
|
70
74
|
break;
|
|
71
|
-
case
|
|
72
|
-
case
|
|
73
|
-
case
|
|
74
|
-
case
|
|
75
|
-
if (a.windows++, a.windows >
|
|
76
|
-
g(e.alias, c,
|
|
75
|
+
case s.TOTAL:
|
|
76
|
+
case s.RUNNING:
|
|
77
|
+
case s.PREVIOUS:
|
|
78
|
+
case s.RANK:
|
|
79
|
+
if (a.windows++, a.windows > t.MAX_WINDOWS) throw TypeError(`an aggregation must compute at most ${t.MAX_WINDOWS} windows.`);
|
|
80
|
+
g(e.alias, c, n, i);
|
|
77
81
|
break;
|
|
78
82
|
default: throw TypeError(`Unsupported derived expression: ${String(c.type)}.`);
|
|
79
83
|
}
|
|
80
84
|
}
|
|
81
85
|
}
|
|
82
|
-
function g(e,
|
|
83
|
-
let a =
|
|
84
|
-
if (!
|
|
85
|
-
if (
|
|
86
|
+
function g(e, t, n, i) {
|
|
87
|
+
let a = t.metric;
|
|
88
|
+
if (!n.has(a)) throw TypeError(`${r(t.type)} window of derived metric [${e}] must read a metric declared before it, but was [${a}].`);
|
|
89
|
+
if (n.get(a) !== void 0 || i.has(a)) throw TypeError(`${r(t.type)} window of derived metric [${e}] must read a non-derived numeric metric, but was [${a}].`);
|
|
86
90
|
}
|
|
87
91
|
function _(e, t, n, r) {
|
|
88
92
|
if (!t.has(e)) throw TypeError(`having condition [${e}] must reference a declared metric alias.`);
|
|
89
93
|
if (n.has(e)) throw TypeError(`having condition [${e}] cannot reference ANY metric.`);
|
|
90
94
|
if (r.has(e)) throw TypeError(`having condition [${e}] cannot reference FIRST or LAST metric.`);
|
|
91
95
|
}
|
|
92
|
-
function v(e,
|
|
96
|
+
function v(e, n, i) {
|
|
93
97
|
if (e === void 0) return;
|
|
94
|
-
if (
|
|
95
|
-
let
|
|
98
|
+
if (n.length === 0) throw TypeError("having requires at least one groupBy.");
|
|
99
|
+
let a = new Set(i.map((e) => e.alias)), s = new Set(i.filter((e) => e.type === o.ANY).map((e) => e.alias)), l = new Set(i.filter((e) => e.type === o.FIRST || e.type === o.LAST).map((e) => e.alias)), u = [{
|
|
96
100
|
expression: e,
|
|
97
101
|
depth: 1
|
|
98
102
|
}];
|
|
99
103
|
for (; u.length > 0;) {
|
|
100
|
-
let { expression: e, depth:
|
|
101
|
-
if (
|
|
104
|
+
let { expression: e, depth: n } = u.pop();
|
|
105
|
+
if (n > t.MAX_EXPRESSION_DEPTH) throw TypeError(`having expression depth must be at most ${t.MAX_EXPRESSION_DEPTH}.`);
|
|
102
106
|
switch (e.type) {
|
|
103
|
-
case
|
|
104
|
-
if (_(e.metric,
|
|
107
|
+
case c.CONDITION:
|
|
108
|
+
if (_(e.metric, a, s, l), !Number.isFinite(e.value)) throw TypeError(`having condition [${e.metric}] value must be finite.`);
|
|
105
109
|
break;
|
|
106
|
-
case
|
|
107
|
-
if (_(e.metric,
|
|
110
|
+
case c.BETWEEN:
|
|
111
|
+
if (_(e.metric, a, s, l), !Number.isFinite(e.lower) || !Number.isFinite(e.upper)) throw TypeError(`having between [${e.metric}] bounds must be finite.`);
|
|
108
112
|
if (e.lower > e.upper) throw TypeError(`having between [${e.metric}] lower bound must not exceed upper bound.`);
|
|
109
113
|
break;
|
|
110
|
-
case
|
|
111
|
-
if (_(e.metric,
|
|
114
|
+
case c.IN:
|
|
115
|
+
if (_(e.metric, a, s, l), e.values.length === 0) throw TypeError(`having in [${e.metric}] values must not be empty.`);
|
|
112
116
|
if (!e.values.every(Number.isFinite)) throw TypeError(`having in [${e.metric}] values must be finite.`);
|
|
113
117
|
break;
|
|
114
|
-
case
|
|
115
|
-
_(e.metric,
|
|
118
|
+
case c.IS_NULL:
|
|
119
|
+
_(e.metric, a, s, l);
|
|
116
120
|
break;
|
|
117
|
-
case
|
|
118
|
-
case
|
|
119
|
-
if (e.operands.length === 0) throw TypeError(`having ${
|
|
121
|
+
case c.AND:
|
|
122
|
+
case c.OR:
|
|
123
|
+
if (e.operands.length === 0) throw TypeError(`having ${r(e.type)} operands must not be empty.`);
|
|
120
124
|
e.operands.forEach((e) => u.push({
|
|
121
125
|
expression: e,
|
|
122
|
-
depth:
|
|
126
|
+
depth: n + 1
|
|
123
127
|
}));
|
|
124
128
|
break;
|
|
125
129
|
default: throw TypeError(`Unsupported having expression: ${String(e.type)}.`);
|
|
126
130
|
}
|
|
127
131
|
}
|
|
128
132
|
}
|
|
129
|
-
function y(e,
|
|
130
|
-
if (u("sort", "fields", e,
|
|
133
|
+
function y(e, n, r) {
|
|
134
|
+
if (u("sort", "fields", e, t.MAX_SORT_FIELDS), n.length === 0 && e.length > 0) throw TypeError("sort requires at least one groupBy.");
|
|
131
135
|
let i = e.map((e) => e.field);
|
|
132
136
|
if (new Set(i).size !== i.length) throw TypeError("sort fields must be unique.");
|
|
133
137
|
if (!i.every((e) => r.includes(e))) throw TypeError("sort fields must reference aggregation aliases.");
|
|
134
138
|
u("effective sort", "fields", l({
|
|
135
|
-
groupBy: [...
|
|
139
|
+
groupBy: [...n],
|
|
136
140
|
sort: [...e]
|
|
137
|
-
}),
|
|
141
|
+
}), t.MAX_SORT_FIELDS);
|
|
138
142
|
}
|
|
139
143
|
function b(e) {
|
|
140
|
-
let t = new Map((e.groupBy ?? []).map((e) => [e.alias, e.scope ===
|
|
141
|
-
if (
|
|
144
|
+
let t = new Map((e.groupBy ?? []).map((e) => [e.alias, e.scope === i.ROOT])), n = l(e).flatMap((e) => t.has(e.field) ? [t.get(e.field)] : []), r = n.indexOf(!1);
|
|
145
|
+
if (r >= 0 && n.slice(r).includes(!0)) throw TypeError("groups with a ROOT scope must sort before the element groups.");
|
|
142
146
|
}
|
|
143
147
|
function x(e) {
|
|
144
|
-
let
|
|
145
|
-
if (u("elements", "paths",
|
|
146
|
-
if (u("metrics", "entries", o,
|
|
147
|
-
f(o,
|
|
148
|
+
let n = e.elements ?? [], i = e.groupBy ?? [], o = e.metrics, s = e.sort ?? [];
|
|
149
|
+
if (u("elements", "paths", n, t.MAX_ELEMENTS), u("groupBy", "dimensions", i, t.MAX_GROUPS), !Array.isArray(o) || o.length === 0) throw TypeError("metrics must not be empty.");
|
|
150
|
+
if (u("metrics", "entries", o, t.MAX_METRICS), e.limit !== void 0 && (!Number.isInteger(e.limit) || e.limit < 1 || e.limit > t.MAX_LIMIT)) throw TypeError(`limit must be between 1 and ${t.MAX_LIMIT}.`);
|
|
151
|
+
f(o, i), m(o), v(e.having, i, o), o.forEach((e) => {
|
|
148
152
|
"filter" in e && e.filter && d(e.filter);
|
|
149
|
-
}),
|
|
150
|
-
if ((e.type ===
|
|
153
|
+
}), i.forEach((e) => {
|
|
154
|
+
if ((e.type === a.DATE_HISTOGRAM || e.type === a.DATE_PART) && e.dense === !0 && i.length !== 1) throw TypeError(`dense requires ${r(e.type)} to be the only groupBy.`);
|
|
151
155
|
});
|
|
152
|
-
let c = [...
|
|
156
|
+
let c = [...i.map((e) => e.alias), ...o.map((e) => e.alias)];
|
|
153
157
|
if (new Set(c).size !== c.length) throw TypeError("aggregation aliases must be unique.");
|
|
154
|
-
return y(s,
|
|
158
|
+
return y(s, i, c), n.length > 0 && b(e), {
|
|
155
159
|
...e,
|
|
156
160
|
metrics: [...o]
|
|
157
161
|
};
|