@lenne.tech/nest-server 12.10.0 → 12.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/rules/better-auth.md +19 -0
- package/.claude/rules/configurable-features.md +12 -10
- package/.claude/rules/package-management.md +10 -8
- package/.claude/rules/role-system.md +4 -1
- package/.claude/rules/testing.md +4 -4
- package/CLAUDE.md +5 -0
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/decorators/unified-field.decorator.js +5 -2
- package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
- package/dist/core/common/helpers/config.helper.js +31 -9
- package/dist/core/common/helpers/config.helper.js.map +1 -1
- package/dist/core/common/helpers/graceful-shutdown.helper.js +3 -1
- package/dist/core/common/helpers/graceful-shutdown.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +2 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +31 -0
- package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-ws-connection.helper.d.ts +8 -3
- package/dist/core/common/helpers/graphql-ws-connection.helper.js +44 -0
- package/dist/core/common/helpers/graphql-ws-connection.helper.js.map +1 -1
- package/dist/core/common/helpers/http-stream-auth.helper.d.ts +13 -0
- package/dist/core/common/helpers/http-stream-auth.helper.js +90 -0
- package/dist/core/common/helpers/http-stream-auth.helper.js.map +1 -0
- package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
- package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
- package/dist/core/common/helpers/shutdown-state.helper.d.ts +3 -0
- package/dist/core/common/helpers/shutdown-state.helper.js +11 -0
- package/dist/core/common/helpers/shutdown-state.helper.js.map +1 -0
- package/dist/core/common/interfaces/cron-job-config-with-utc-offset.interface.d.ts +1 -1
- package/dist/core/common/interfaces/cron-job-config.interface.d.ts +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +14 -0
- package/dist/core/common/plugins/complexity.plugin.js +73 -9
- package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
- package/dist/core/common/services/core-cron-jobs.service.d.ts +13 -0
- package/dist/core/common/services/core-cron-jobs.service.js +129 -4
- package/dist/core/common/services/core-cron-jobs.service.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js +48 -4
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.d.ts +8 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js +47 -0
- package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-models.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-models.js +7 -0
- package/dist/core/modules/better-auth/core-better-auth-models.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.d.ts +11 -0
- package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js +62 -0
- package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +28 -1
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.controller.js +2 -1
- package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.middleware.js +2 -2
- package/dist/core/modules/better-auth/core-better-auth.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -0
- package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +10 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js +105 -19
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/core/modules/health-check/core-health-check-readiness.controller.d.ts +6 -0
- package/dist/core/modules/health-check/core-health-check-readiness.controller.js +36 -0
- package/dist/core/modules/health-check/core-health-check-readiness.controller.js.map +1 -0
- package/dist/core/modules/health-check/core-health-check.helpers.d.ts +10 -0
- package/dist/core/modules/health-check/core-health-check.helpers.js +31 -0
- package/dist/core/modules/health-check/core-health-check.helpers.js.map +1 -0
- package/dist/core/modules/health-check/core-health-check.module.d.ts +9 -0
- package/dist/core/modules/health-check/core-health-check.module.js +13 -2
- package/dist/core/modules/health-check/core-health-check.module.js.map +1 -1
- package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -1
- package/dist/core/modules/health-check/core-health-check.service.js +66 -29
- package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
- package/dist/core/modules/sync/core-sync.service.d.ts +2 -0
- package/dist/core/modules/sync/core-sync.service.js +11 -1
- package/dist/core/modules/sync/core-sync.service.js.map +1 -1
- package/dist/core.module.js +5 -1
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +18 -6
- package/docs/offline-sync-protocol.md +5 -3
- package/migration-guides/12.10.0-to-12.10.1.md +182 -0
- package/migration-guides/12.10.x-to-12.11.x.md +295 -0
- package/package.json +17 -17
- package/src/core/common/decorators/unified-field.decorator.ts +14 -4
- package/src/core/common/helpers/config.helper.ts +55 -8
- package/src/core/common/helpers/graceful-shutdown.helper.ts +10 -3
- package/src/core/common/helpers/graphql-upload.helper.ts +93 -0
- package/src/core/common/helpers/graphql-ws-connection.helper.ts +99 -4
- package/src/core/common/helpers/http-stream-auth.helper.ts +197 -0
- package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
- package/src/core/common/helpers/shutdown-state.helper.ts +28 -0
- package/src/core/common/interfaces/cron-job-config-with-utc-offset.interface.ts +1 -1
- package/src/core/common/interfaces/cron-job-config.interface.ts +1 -1
- package/src/core/common/interfaces/server-options.interface.ts +113 -1
- package/src/core/common/plugins/complexity.plugin.ts +150 -9
- package/src/core/common/services/core-cron-jobs.service.ts +241 -14
- package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +26 -10
- package/src/core/modules/better-auth/README.md +37 -8
- package/src/core/modules/better-auth/better-auth.config.ts +83 -12
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +1 -1
- package/src/core/modules/better-auth/core-better-auth-jwt-session.cache.ts +104 -0
- package/src/core/modules/better-auth/core-better-auth-models.ts +5 -0
- package/src/core/modules/better-auth/core-better-auth-sign-in-factors.helper.ts +105 -0
- package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +37 -1
- package/src/core/modules/better-auth/core-better-auth.controller.ts +6 -3
- package/src/core/modules/better-auth/core-better-auth.middleware.ts +4 -3
- package/src/core/modules/better-auth/core-better-auth.module.ts +1 -1
- package/src/core/modules/better-auth/core-better-auth.resolver.ts +1 -0
- package/src/core/modules/better-auth/core-better-auth.service.ts +160 -27
- package/src/core/modules/health-check/core-health-check-readiness.controller.ts +27 -0
- package/src/core/modules/health-check/core-health-check.helpers.ts +65 -0
- package/src/core/modules/health-check/core-health-check.module.ts +37 -2
- package/src/core/modules/health-check/core-health-check.service.ts +154 -59
- package/src/core/modules/sync/README.md +18 -6
- package/src/core/modules/sync/core-sync.service.ts +35 -6
- package/src/core.module.ts +9 -1
- package/src/index.ts +4 -0
- package/src/main.ts +2 -1
|
@@ -1040,6 +1040,20 @@ export interface IBetterAuthSocialProvider {
|
|
|
1040
1040
|
*/
|
|
1041
1041
|
disableDefaultScope?: boolean;
|
|
1042
1042
|
|
|
1043
|
+
/**
|
|
1044
|
+
* Whether a client may NOT sign in or link an account with an id token it submits itself (`POST /iam/sign-in/social`
|
|
1045
|
+
* or `/iam/link-social` with `idToken`), answered with `ID_TOKEN_NOT_SUPPORTED`.
|
|
1046
|
+
*
|
|
1047
|
+
* On by default since 12.11.0: Better-Auth verifies such a token's signature, audience and expiry and asks the
|
|
1048
|
+
* provider nothing, so an id token kept from an earlier sign-in (`/iam/get-access-token` hands it out) signed its
|
|
1049
|
+
* owner in again for its whole lifetime — about an hour at Microsoft — after the provider had withdrawn the
|
|
1050
|
+
* assignment or role. The redirect flow (`signIn.social` with a `callbackURL`) never uses it. Native apps and Google
|
|
1051
|
+
* One Tap send the provider's id token themselves and need `false`. Only `false` opens it; any other value keeps it
|
|
1052
|
+
* closed.
|
|
1053
|
+
* @default true
|
|
1054
|
+
*/
|
|
1055
|
+
disableIdTokenSignIn?: boolean;
|
|
1056
|
+
|
|
1043
1057
|
/**
|
|
1044
1058
|
* Whether a first sign-in through this provider may create an account.
|
|
1045
1059
|
*
|
|
@@ -1086,6 +1100,26 @@ export interface IBetterAuthSocialProvider {
|
|
|
1086
1100
|
tenantId?: string;
|
|
1087
1101
|
}
|
|
1088
1102
|
|
|
1103
|
+
/**
|
|
1104
|
+
* Session lifetime of Better-Auth (`betterAuth.session`, 12.11.0).
|
|
1105
|
+
*/
|
|
1106
|
+
export interface IBetterAuthSessionConfig {
|
|
1107
|
+
/**
|
|
1108
|
+
* Whether a session is extended while it is used. Better-Auth renews its expiry once per day of use (`updateAge`).
|
|
1109
|
+
* `false`: the session ends `expiresInHours` after the sign-in, used or not (Better-Auth's `disableSessionRefresh`).
|
|
1110
|
+
* Only `false` switches the extension off.
|
|
1111
|
+
* @default true
|
|
1112
|
+
*/
|
|
1113
|
+
extendOnUse?: boolean;
|
|
1114
|
+
|
|
1115
|
+
/**
|
|
1116
|
+
* Lifetime of a session in hours, counted from the sign-in (with `extendOnUse`, from the last extension). A value
|
|
1117
|
+
* that is not a positive number is ignored with a warning and the default applies — never "unlimited".
|
|
1118
|
+
* @default 168 (7 days, Better-Auth's default)
|
|
1119
|
+
*/
|
|
1120
|
+
expiresInHours?: number;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1089
1123
|
/**
|
|
1090
1124
|
* Two-factor authentication plugin configuration for Better-Auth
|
|
1091
1125
|
*
|
|
@@ -3073,6 +3107,11 @@ export interface IServerOptions {
|
|
|
3073
3107
|
|
|
3074
3108
|
/**
|
|
3075
3109
|
* Whether to activate health check endpoints
|
|
3110
|
+
*
|
|
3111
|
+
* Presence implies enabled: the block registers `GET /health-check` (liveness) and the `healthCheck` query. With
|
|
3112
|
+
* `readiness` (12.11.0) a readiness endpoint `GET /health-check/ready` sits beside it. A project adds checks of its
|
|
3113
|
+
* own by extending `CoreHealthCheckService` and overriding `additionalHealthIndicators(kind)` — registered through
|
|
3114
|
+
* `CoreModule.forRoot(env, { healthCheck: { service: HealthCheckService } })`.
|
|
3076
3115
|
*/
|
|
3077
3116
|
healthCheck?: {
|
|
3078
3117
|
/**
|
|
@@ -3186,6 +3225,42 @@ export interface IServerOptions {
|
|
|
3186
3225
|
* @default true (when `healthCheck` is set)
|
|
3187
3226
|
*/
|
|
3188
3227
|
enabled?: boolean;
|
|
3228
|
+
|
|
3229
|
+
/**
|
|
3230
|
+
* Readiness endpoint `GET /health-check/ready` beside the liveness check `GET /health-check` (12.11.0).
|
|
3231
|
+
*
|
|
3232
|
+
* Boolean shorthand, presence implies enabled: absent, `false` or `{ enabled: false }` registers nothing (the
|
|
3233
|
+
* route answers 404) and leaves the health check as it was; `true` or `{}` registers it with the default checks.
|
|
3234
|
+
* Public like the liveness check (`@Roles(S_EVERYONE)`), REST only. It answers 200 while every check is up and
|
|
3235
|
+
* 503 when one is down — and `shutting_down` from the first SIGTERM / SIGINT on when `installGracefulShutdown(app)`
|
|
3236
|
+
* handles the signals with a `shutdownDelayMs`: it marks the shutdown before its `shutdownDelayMs` wait, so a load balancer polling readiness
|
|
3237
|
+
* stops routing to the replica while it still serves (without it, only Terminus' own state applies, which comes
|
|
3238
|
+
* inside `app.close()`, right before the server closes). Add checks of your own through
|
|
3239
|
+
* `CoreHealthCheckService.additionalHealthIndicators('readiness')`.
|
|
3240
|
+
*
|
|
3241
|
+
* @default undefined (no readiness endpoint)
|
|
3242
|
+
* @since 12.11.0
|
|
3243
|
+
*/
|
|
3244
|
+
readiness?:
|
|
3245
|
+
| boolean
|
|
3246
|
+
| {
|
|
3247
|
+
/**
|
|
3248
|
+
* The checks of `configs` the readiness check runs, with the key, thresholds and options configured there:
|
|
3249
|
+
* any of `database` (MongoDB ping and every SQL source), `memoryHeap`, `memoryRss`, `storage`, `build`. A
|
|
3250
|
+
* listed check runs whatever `configs.<check>.enabled` says — that flag decides for `GET /health-check`.
|
|
3251
|
+
* A comma-separated string is read as a list (what `NSC__HEALTH_CHECK__READINESS__CHECKS` gives); unknown
|
|
3252
|
+
* names are ignored with a warning; `[]` runs only the project's own readiness indicators.
|
|
3253
|
+
*
|
|
3254
|
+
* @default ['database', 'build']
|
|
3255
|
+
*/
|
|
3256
|
+
checks?: ('build' | 'database' | 'memoryHeap' | 'memoryRss' | 'storage')[] | string;
|
|
3257
|
+
|
|
3258
|
+
/**
|
|
3259
|
+
* `false` pre-configures the readiness endpoint without registering it.
|
|
3260
|
+
* @default true (when `readiness` is set)
|
|
3261
|
+
*/
|
|
3262
|
+
enabled?: boolean;
|
|
3263
|
+
};
|
|
3189
3264
|
};
|
|
3190
3265
|
|
|
3191
3266
|
/**
|
|
@@ -4788,7 +4863,10 @@ interface IBetterAuthBase {
|
|
|
4788
4863
|
/**
|
|
4789
4864
|
* Email/password authentication configuration.
|
|
4790
4865
|
* Enabled by default.
|
|
4791
|
-
* Set `enabled: false` to explicitly disable email/password auth.
|
|
4866
|
+
* Set `enabled: false` to explicitly disable email/password auth. Since 12.11.0 Passkey and two-factor are then off
|
|
4867
|
+
* too unless switched on explicitly (`passkey: true`, `twoFactor: true`) — when no plugin of `plugins` adds a sign-in
|
|
4868
|
+
* route of its own (`username()`, `phoneNumber()` keep both on): with sign-in through a provider alone, a passkey
|
|
4869
|
+
* registered once would keep signing its owner in after the provider withdrew the assignment.
|
|
4792
4870
|
*/
|
|
4793
4871
|
emailAndPassword?: {
|
|
4794
4872
|
/**
|
|
@@ -5165,6 +5243,21 @@ interface IBetterAuthBase {
|
|
|
5165
5243
|
*/
|
|
5166
5244
|
socialProviders?: Record<string, IBetterAuthSocialProvider>;
|
|
5167
5245
|
|
|
5246
|
+
/**
|
|
5247
|
+
* How long a session lasts, and whether using it extends it (12.11.0).
|
|
5248
|
+
*
|
|
5249
|
+
* Without it Better-Auth's defaults apply: 7 days, extended once a day while the session is used — so a session that
|
|
5250
|
+
* is used every day never ends, and a withdrawal at a sign-in provider (an Entra assignment) never reaches it. With
|
|
5251
|
+
* `extendOnUse: false` a session ends `expiresInHours` after its sign-in, whatever happens in between.
|
|
5252
|
+
* `betterAuth.options.session` still wins key by key.
|
|
5253
|
+
*
|
|
5254
|
+
* @example
|
|
5255
|
+
* ```typescript
|
|
5256
|
+
* session: { expiresInHours: 8, extendOnUse: false }, // sign in again after 8 hours, every time
|
|
5257
|
+
* ```
|
|
5258
|
+
*/
|
|
5259
|
+
session?: IBetterAuthSessionConfig;
|
|
5260
|
+
|
|
5168
5261
|
/**
|
|
5169
5262
|
* Two-factor authentication configuration.
|
|
5170
5263
|
*
|
|
@@ -5520,6 +5613,25 @@ export interface ICoreModuleOverrides {
|
|
|
5520
5613
|
service?: Type<any>;
|
|
5521
5614
|
};
|
|
5522
5615
|
|
|
5616
|
+
/**
|
|
5617
|
+
* Override the health check service and/or the readiness controller (12.11.0).
|
|
5618
|
+
*
|
|
5619
|
+
* - `service` must extend `CoreHealthCheckService` — the extension point for checks of a project's own:
|
|
5620
|
+
* override `additionalHealthIndicators(kind)` and return Terminus indicators for `'liveness'`
|
|
5621
|
+
* (`GET /health-check`, the `healthCheck` query) and/or `'readiness'` (`GET /health-check/ready`)
|
|
5622
|
+
* - `readinessController` must extend `CoreHealthCheckReadinessController` (registered only with
|
|
5623
|
+
* `healthCheck.readiness`)
|
|
5624
|
+
*
|
|
5625
|
+
* @example
|
|
5626
|
+
* ```typescript
|
|
5627
|
+
* { healthCheck: { service: HealthCheckService } }
|
|
5628
|
+
* ```
|
|
5629
|
+
*/
|
|
5630
|
+
healthCheck?: {
|
|
5631
|
+
readinessController?: Type<any>;
|
|
5632
|
+
service?: Type<any>;
|
|
5633
|
+
};
|
|
5634
|
+
|
|
5523
5635
|
/**
|
|
5524
5636
|
* Override Hub controllers and/or services with project-specific subclasses.
|
|
5525
5637
|
*
|
|
@@ -1,11 +1,127 @@
|
|
|
1
1
|
import { Plugin } from '@nestjs/apollo';
|
|
2
2
|
import { GraphQLSchemaHost } from '@nestjs/graphql';
|
|
3
3
|
import type { ApolloServerPlugin, BaseContext, GraphQLRequestListener } from '@apollo/server';
|
|
4
|
-
import { GraphQLError } from 'graphql';
|
|
5
|
-
import {
|
|
4
|
+
import { getVariableValues, GraphQLError, Kind, TypeInfo, ValidationContext, visit, visitWithTypeInfo } from 'graphql';
|
|
5
|
+
import type {
|
|
6
|
+
ASTVisitor,
|
|
7
|
+
DefinitionNode,
|
|
8
|
+
DocumentNode,
|
|
9
|
+
FragmentDefinitionNode,
|
|
10
|
+
GraphQLSchema,
|
|
11
|
+
OperationDefinitionNode,
|
|
12
|
+
SelectionSetNode,
|
|
13
|
+
} from 'graphql';
|
|
14
|
+
import { createComplexityRule, fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity';
|
|
6
15
|
|
|
7
16
|
import { ConfigService } from '../services/config.service.js';
|
|
8
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Most variable coercion errors the pre-check collects before it stops. It only needs to know WHETHER the variables
|
|
20
|
+
* coerce, and one error answers that. Every error graphql creates for a variable computes its line and column by
|
|
21
|
+
* scanning the query up to the variable's definition: with execution's cap of 50 the pre-check cost 550 ms for a
|
|
22
|
+
* 959 KiB multipart request whose definitions stood after 490,000 line breaks (12.10.1).
|
|
23
|
+
*/
|
|
24
|
+
const VARIABLE_COERCION_MAX_ERRORS = 1;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Most visits × declared variables the complexity analysis may cost (12.10.1, SEC-4). graphql-query-complexity runs
|
|
28
|
+
* `Object.keys()` over the operation's variables at every field and every `@skip` / `@include` it visits — measured on
|
|
29
|
+
* Node 24 at 12–90 ns per variable and visit, so the limit is reached after at most about 23 ms. 38,000 declared
|
|
30
|
+
* variables and 4,900 visits blocked the event loop for 17 s before. With the default cost of 1 per field, a query
|
|
31
|
+
* `maxComplexity: 1000` accepts has at most 1,000 fields; with 30 variables that is at most 30,000.
|
|
32
|
+
*/
|
|
33
|
+
const COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK = 250_000;
|
|
34
|
+
|
|
35
|
+
/** The visitor graphql-query-complexity builds (the class itself is not exported). */
|
|
36
|
+
type ComplexityVisitor = ReturnType<ReturnType<typeof createComplexityRule>>;
|
|
37
|
+
|
|
38
|
+
/** Fields and `@skip` / `@include` directives in the selection sets — each one a visit with the variables walked. */
|
|
39
|
+
function variableVisits(definitions: readonly (FragmentDefinitionNode | OperationDefinitionNode)[]): number {
|
|
40
|
+
let visits = 0;
|
|
41
|
+
const pending: SelectionSetNode[] = definitions.map((definition) => definition.selectionSet);
|
|
42
|
+
while (pending.length) {
|
|
43
|
+
const selectionSet = pending.pop()!;
|
|
44
|
+
for (const selection of selectionSet.selections) {
|
|
45
|
+
for (const directive of selection.directives ?? []) {
|
|
46
|
+
if (directive.name.value === 'include' || directive.name.value === 'skip') {
|
|
47
|
+
visits++;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (selection.kind === Kind.FIELD) {
|
|
51
|
+
visits++;
|
|
52
|
+
}
|
|
53
|
+
if (selection.kind !== Kind.FRAGMENT_SPREAD && selection.selectionSet) {
|
|
54
|
+
pending.push(selection.selectionSet);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return visits;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The complexity graphql-query-complexity's `getComplexity()` computes, with each fragment evaluated once (12.10.1,
|
|
63
|
+
* SEC-4).
|
|
64
|
+
*
|
|
65
|
+
* The library evaluates a fragment again at EVERY spread, without caching, and at every visit coerces the field's
|
|
66
|
+
* literal arguments again. Its node cap (10,000 visits) bounds the visits, not their cost:
|
|
67
|
+
* `{...F ×3300} fragment F on Query { findUsers(filter: { … value: [0,0,…41,667 items] }) }` blocked the event loop
|
|
68
|
+
* for 2.2 s from a 100 KB JSON POST and for 22.5 s from a 990 KB multipart request — before any guard, with variables
|
|
69
|
+
* that coerce.
|
|
70
|
+
*
|
|
71
|
+
* A fragment's complexity depends on the fragment alone: its type is its type condition, and the variables and the
|
|
72
|
+
* estimators are the same for every spread. So the first spread evaluates it, every further spread reuses the result
|
|
73
|
+
* and adds the nodes the evaluation visited to the library's node count, so a query over 10,000 nodes is refused as
|
|
74
|
+
* before. The number this returns is the one `getComplexity()` returns; the work is that of the document, each
|
|
75
|
+
* fragment once. A field's `complexity` extension (read by `fieldExtensionsEstimator`) must therefore depend only on its
|
|
76
|
+
* arguments and `childComplexity` — as a function it runs once per fragment, not once per spread.
|
|
77
|
+
*
|
|
78
|
+
* The analysis stops at the first error it reports. The library catches the coercion error of every field's arguments
|
|
79
|
+
* and goes on, and `getComplexity()` throws the last one at the end — but every error with a node computes its line and
|
|
80
|
+
* column by scanning the query up to it. `query($x: String = "a") { a: getUser(id: $x) { id } b: … }` with
|
|
81
|
+
* `{"x": null}` is valid, passes the variable check and fails at every one of up to 9,999 fields: 1.4 s from a 98 KiB
|
|
82
|
+
* JSON POST, 86 s from a 993 KiB multipart request with the fields after 395,000 line breaks (12.10.1). The request is
|
|
83
|
+
* refused either way; now with the first error instead of the last.
|
|
84
|
+
*
|
|
85
|
+
* Built like `getComplexity()` (graphql-query-complexity 2.0.0, `QueryComplexity.js`), through the public
|
|
86
|
+
* `createComplexityRule()`; the cache wraps `nodeComplexity` of this one visitor, which the library calls through
|
|
87
|
+
* `this` for every fragment spread.
|
|
88
|
+
*/
|
|
89
|
+
function computeComplexity(schema: GraphQLSchema, query: DocumentNode, variables: Record<string, unknown>): number {
|
|
90
|
+
const typeInfo = new TypeInfo(schema);
|
|
91
|
+
const context = new ValidationContext(schema, query, typeInfo, (error) => {
|
|
92
|
+
throw error;
|
|
93
|
+
});
|
|
94
|
+
const visitor: ComplexityVisitor = createComplexityRule({
|
|
95
|
+
estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
|
|
96
|
+
// The maximum is checked by the plugin; the visitor only computes.
|
|
97
|
+
maximumComplexity: Infinity,
|
|
98
|
+
variables,
|
|
99
|
+
})(context);
|
|
100
|
+
|
|
101
|
+
const evaluate = visitor.nodeComplexity.bind(visitor);
|
|
102
|
+
const fragments = new Map<string, { complexity: number; nodes: number }>();
|
|
103
|
+
visitor.nodeComplexity = (node, typeDef, activeFragments) => {
|
|
104
|
+
if (node.kind !== Kind.FRAGMENT_DEFINITION) {
|
|
105
|
+
return evaluate(node, typeDef, activeFragments);
|
|
106
|
+
}
|
|
107
|
+
const known = fragments.get(node.name.value);
|
|
108
|
+
if (known) {
|
|
109
|
+
visitor.evaluatedNodes += known.nodes;
|
|
110
|
+
if (visitor.evaluatedNodes >= visitor.maxQueryNodes) {
|
|
111
|
+
throw new GraphQLError('Query exceeds the maximum allowed number of nodes.');
|
|
112
|
+
}
|
|
113
|
+
return known.complexity;
|
|
114
|
+
}
|
|
115
|
+
const before = visitor.evaluatedNodes;
|
|
116
|
+
const complexity = evaluate(node, typeDef, activeFragments);
|
|
117
|
+
fragments.set(node.name.value, { complexity, nodes: visitor.evaluatedNodes - before });
|
|
118
|
+
return complexity;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
visit(query, visitWithTypeInfo(typeInfo, visitor as unknown as ASTVisitor));
|
|
122
|
+
return visitor.complexity;
|
|
123
|
+
}
|
|
124
|
+
|
|
9
125
|
@Plugin()
|
|
10
126
|
export class ComplexityPlugin implements ApolloServerPlugin {
|
|
11
127
|
constructor(
|
|
@@ -18,14 +134,39 @@ export class ComplexityPlugin implements ApolloServerPlugin {
|
|
|
18
134
|
const { schema } = this.gqlSchemaHost;
|
|
19
135
|
|
|
20
136
|
return {
|
|
21
|
-
async didResolveOperation({ document, request }) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
137
|
+
async didResolveOperation({ document, operation, request }) {
|
|
138
|
+
// No operation resolved: several operations and no `operationName` naming one of them. Apollo still calls this
|
|
139
|
+
// hook, and graphql's `execute()` refuses the request afterwards, before it coerces a single variable.
|
|
140
|
+
// getComplexity() instead evaluated EVERY operation of such a document and coerced the variables for each
|
|
141
|
+
// (12.10.1, SEC-3): 860 operations sharing one 16,000-item variable blocked the event loop for 5.9 s from a
|
|
142
|
+
// 100 KB JSON POST, 1,720 operations for 25.5 s from 200 KB.
|
|
143
|
+
if (!operation) {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Invalid variables (12.10.1, SEC-2): getComplexity() coerces without an error cap, so a list of invalid items
|
|
148
|
+
// created one error per item — 1.5 s and 300 MB for 100 KB, 15 s and 2 GB for 1 MB. Execution refuses such
|
|
149
|
+
// variables itself, with graphql's cap of 50, before any resolver runs, so there is no complexity to compute.
|
|
150
|
+
const { errors } = getVariableValues(schema, operation.variableDefinitions ?? [], request.variables ?? {}, {
|
|
151
|
+
maxErrors: VARIABLE_COERCION_MAX_ERRORS,
|
|
28
152
|
});
|
|
153
|
+
if (errors?.length) {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// The resolved operation alone, with the fragments it may spread: the analysis evaluates exactly the operation
|
|
158
|
+
// execution runs, and coerces its variables once.
|
|
159
|
+
const fragments = document.definitions.filter(
|
|
160
|
+
(definition: DefinitionNode): definition is FragmentDefinitionNode =>
|
|
161
|
+
definition.kind === Kind.FRAGMENT_DEFINITION,
|
|
162
|
+
);
|
|
163
|
+
const variableCount = operation.variableDefinitions?.length ?? 0;
|
|
164
|
+
if (variableVisits([operation, ...fragments]) * variableCount > COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK) {
|
|
165
|
+
throw new GraphQLError('Query is too complex: too many fields for its number of variables');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const query: DocumentNode = { definitions: [operation, ...fragments], kind: Kind.DOCUMENT };
|
|
169
|
+
const complexity = computeComplexity(schema, query, request.variables ?? {});
|
|
29
170
|
if (maxComplexity !== undefined && complexity > maxComplexity) {
|
|
30
171
|
throw new GraphQLError(`Query is too complex: ${complexity}. Maximum allowed complexity: ${maxComplexity}`);
|
|
31
172
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
|
|
2
2
|
import { CronExpression, SchedulerRegistry } from '@nestjs/schedule';
|
|
3
|
-
import { CronJob } from 'cron';
|
|
3
|
+
import { CronJob, CronTime } from 'cron';
|
|
4
4
|
|
|
5
5
|
import { CronJobConfigWithTimeZone } from '../interfaces/cron-job-config-with-time-zone.interface.js';
|
|
6
6
|
import { CronJobConfigWithUtcOffset } from '../interfaces/cron-job-config-with-utc-offset.interface.js';
|
|
@@ -98,6 +98,18 @@ export interface CoreCronJobsOptions {
|
|
|
98
98
|
redisService?: CoreRedisService;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
/**
|
|
102
|
+
* A new schedule for {@link CoreCronJobs.rescheduleCronJob}: a cron expression or a date (the job keeps its time zone
|
|
103
|
+
* or UTC offset), or the schedule fields of a job config. Only the schedule changes — `distributed`, `runParallel`,
|
|
104
|
+
* `throwException` and the job function stay as configured.
|
|
105
|
+
*/
|
|
106
|
+
export type CronJobSchedule =
|
|
107
|
+
| CronExpression
|
|
108
|
+
| Date
|
|
109
|
+
| Pick<CronJobConfigWithTimeZone, 'cronTime' | 'timeZone' | 'utcOffset'>
|
|
110
|
+
| Pick<CronJobConfigWithUtcOffset, 'cronTime' | 'timeZone' | 'utcOffset'>
|
|
111
|
+
| string;
|
|
112
|
+
|
|
101
113
|
/**
|
|
102
114
|
* Cron jobs service to extend
|
|
103
115
|
*
|
|
@@ -108,6 +120,8 @@ export interface CoreCronJobsOptions {
|
|
|
108
120
|
* - Otherwise: the local cron timer stays, but each tick first acquires a lease
|
|
109
121
|
* (Redis `SET NX` when available, else the SQL lease table of the default source, else a `cron-locks` document in
|
|
110
122
|
* MongoDB).
|
|
123
|
+
*
|
|
124
|
+
* A job's schedule can be changed at runtime with {@link CoreCronJobs.rescheduleCronJob} (12.11.0), in both modes.
|
|
111
125
|
*/
|
|
112
126
|
export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicationShutdown {
|
|
113
127
|
/**
|
|
@@ -159,6 +173,9 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
|
|
|
159
173
|
/** Shared BullMQ worker, created only in BullMQ mode */
|
|
160
174
|
protected bullWorker?: any;
|
|
161
175
|
|
|
176
|
+
/** Set when the application shuts down: no job is (re)scheduled after that */
|
|
177
|
+
protected cronJobsClosed = false;
|
|
178
|
+
|
|
162
179
|
/** Whether the "deduplication inactive" warning was already emitted */
|
|
163
180
|
protected dedupWarned = false;
|
|
164
181
|
|
|
@@ -183,6 +200,9 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
|
|
|
183
200
|
void this.restoreBullSchedulers();
|
|
184
201
|
};
|
|
185
202
|
|
|
203
|
+
/** The reschedule in progress; rescheduleCronJob() calls run one after the other */
|
|
204
|
+
protected rescheduling: Promise<void> = Promise.resolve();
|
|
205
|
+
|
|
186
206
|
// ===================================================================================================================
|
|
187
207
|
// Initializations
|
|
188
208
|
// ===================================================================================================================
|
|
@@ -219,6 +239,9 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
|
|
|
219
239
|
* Close the BullMQ worker and queue
|
|
220
240
|
*/
|
|
221
241
|
async onApplicationShutdown(): Promise<void> {
|
|
242
|
+
this.cronJobsClosed = true;
|
|
243
|
+
// A reschedule already running finishes first; it never rejects here (rescheduleCronJob() reports to its caller)
|
|
244
|
+
await this.rescheduling;
|
|
222
245
|
this.stopBullSchedulerCheck();
|
|
223
246
|
// A check already running finishes its current job before the queue closes; it never rejects.
|
|
224
247
|
await this.bullSchedulerCheck;
|
|
@@ -237,6 +260,221 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
|
|
|
237
260
|
this.bullQueue = undefined;
|
|
238
261
|
}
|
|
239
262
|
|
|
263
|
+
// ===================================================================================================================
|
|
264
|
+
// Runtime changes
|
|
265
|
+
// ===================================================================================================================
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Change the schedule of a registered cron job at runtime (12.11.0) — for a schedule a project keeps in its own
|
|
269
|
+
* settings rather than in the `cronJobs` configuration.
|
|
270
|
+
*
|
|
271
|
+
* `schedule` is a cron expression or a date (the job keeps its time zone or UTC offset), or `{ cronTime, timeZone }` /
|
|
272
|
+
* `{ cronTime, utcOffset }`. It is validated before anything changes: an invalid expression, an unknown time zone or
|
|
273
|
+
* a date in the past rejects and leaves the job as it was. Only the schedule changes; `distributed`, `runParallel`
|
|
274
|
+
* and `throwException` stay as configured, and so do the leases, the running lease and the BullMQ job options.
|
|
275
|
+
*
|
|
276
|
+
* - Local timer: the timer is replaced. The next tick follows the new schedule, a distributed job takes its tick
|
|
277
|
+
* lease keyed on the new schedule's instant, a tick that is running finishes. A recurring job the Hub stopped on
|
|
278
|
+
* this replica stays stopped.
|
|
279
|
+
* - BullMQ job scheduler: the scheduler is written to Redis with the new pattern and `bullJobOptions` — skipped when
|
|
280
|
+
* Redis already holds exactly this pattern and time zone, so calling this on every replica plans no tick twice —
|
|
281
|
+
* and restoreBullSchedulers() brings the NEW schedule back after a data loss. A schedule BullMQ cannot express (a
|
|
282
|
+
* date, a UTC offset) moves the job to a local timer with lease: its scheduler is removed with the removal marker,
|
|
283
|
+
* so a replica that still schedules the job through BullMQ does not bring it back. A cron expression moves the job
|
|
284
|
+
* back to BullMQ.
|
|
285
|
+
*
|
|
286
|
+
* WHERE IT APPLIES: a BullMQ scheduler lives in Redis and changes for the whole fleet at once, a local timer only in
|
|
287
|
+
* this process. Call it on EVERY replica (from the settings change each replica observes, and at startup), or the
|
|
288
|
+
* replicas run the job on different schedules. A reschedule is not stored: the next bootstrap schedules the job from
|
|
289
|
+
* the configuration again, so a project re-applies a stored schedule after `super.onApplicationBootstrap()`.
|
|
290
|
+
*
|
|
291
|
+
* `runOnInit` is not repeated — a reschedule is not a start. Calls run one after the other. Rejects for a job that is
|
|
292
|
+
* not registered: unknown, disabled, without `cronTime` or job method, before bootstrap or after shutdown.
|
|
293
|
+
*/
|
|
294
|
+
async rescheduleCronJob(name: string, schedule: CronJobSchedule): Promise<void> {
|
|
295
|
+
const run = this.rescheduling.then(() => this.applyCronJobSchedule(name, schedule));
|
|
296
|
+
this.rescheduling = run.catch(() => undefined);
|
|
297
|
+
return run;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Apply a new schedule to a registered job: validate it, then move the job to the mode the schedule needs — the same
|
|
302
|
+
* rule initCronJobs() applies (BullMQ for a distributed job with a cron expression and no UTC offset while BullMQ is
|
|
303
|
+
* active, a local timer otherwise). See rescheduleCronJob().
|
|
304
|
+
*/
|
|
305
|
+
protected async applyCronJobSchedule(name: string, schedule: CronJobSchedule): Promise<void> {
|
|
306
|
+
const current = this.jobConfigs[name];
|
|
307
|
+
const scheduledWithBull = this.bullScheduledJobs.has(name);
|
|
308
|
+
if (this.cronJobsClosed || !current || (!scheduledWithBull && !this.schedulerRegistry.doesExist('cron', name))) {
|
|
309
|
+
throw new Error(`CronJob ${name} is not registered and cannot be rescheduled`);
|
|
310
|
+
}
|
|
311
|
+
const next = this.withSchedule(name, current, schedule);
|
|
312
|
+
// sendAt() refuses what has no next instant (a date in the past); the constructor an invalid expression or zone
|
|
313
|
+
new CronTime(next.cronTime as any, next.timeZone as any, next.utcOffset as any).sendAt();
|
|
314
|
+
|
|
315
|
+
// A scheduler check that runs finishes before the job changes under it
|
|
316
|
+
await this.bullSchedulerCheck;
|
|
317
|
+
const withBull = !!this.bullQueue && next.distributed !== false && this.canUseBullScheduler(next);
|
|
318
|
+
if (withBull) {
|
|
319
|
+
await this.rescheduleWithBull(name, next);
|
|
320
|
+
} else {
|
|
321
|
+
await this.rescheduleLocally(name, next, scheduledWithBull);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (this.config.log) {
|
|
325
|
+
const cronTime = next.cronTime instanceof Date ? next.cronTime.toISOString() : String(next.cronTime);
|
|
326
|
+
cronLogger.log(`CronJob ${name} rescheduled to "${cronTime}" (${withBull ? 'BullMQ scheduler' : 'local timer'})`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** The job's config with the new schedule; a cron expression or date keeps the time zone or UTC offset */
|
|
331
|
+
protected withSchedule(
|
|
332
|
+
name: string,
|
|
333
|
+
current: CronJobConfigWithTimeZone,
|
|
334
|
+
schedule: CronJobSchedule,
|
|
335
|
+
): CronJobConfigWithTimeZone {
|
|
336
|
+
if (typeof schedule === 'string' || schedule instanceof Date) {
|
|
337
|
+
return { ...current, cronTime: schedule };
|
|
338
|
+
}
|
|
339
|
+
if (!schedule || typeof schedule !== 'object' || !schedule.cronTime) {
|
|
340
|
+
throw new Error(`CronJob ${name} cannot be rescheduled without a cronTime`);
|
|
341
|
+
}
|
|
342
|
+
const next: Record<string, unknown> = { ...current, cronTime: schedule.cronTime };
|
|
343
|
+
if (schedule.utcOffset !== undefined && schedule.utcOffset !== null) {
|
|
344
|
+
// timeZone and utcOffset exclude each other, as in initCronJobs()
|
|
345
|
+
next.timeZone = null;
|
|
346
|
+
next.utcOffset = schedule.utcOffset;
|
|
347
|
+
} else if (schedule.timeZone) {
|
|
348
|
+
next.timeZone = schedule.timeZone;
|
|
349
|
+
next.utcOffset = undefined;
|
|
350
|
+
}
|
|
351
|
+
return next as unknown as CronJobConfigWithTimeZone;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Whether BullMQ can express a schedule: a cron expression without a UTC offset (BullMQ knows only time zones) */
|
|
355
|
+
protected canUseBullScheduler(config: CronJobConfigWithTimeZone): boolean {
|
|
356
|
+
return typeof config.cronTime === 'string' && !config.utcOffset;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Reschedule a job through its BullMQ scheduler — or move it there from a local timer. Redis is written first: when
|
|
361
|
+
* that fails, the job keeps running as it did and the call rejects.
|
|
362
|
+
*/
|
|
363
|
+
protected async rescheduleWithBull(name: string, config: CronJobConfigWithTimeZone): Promise<void> {
|
|
364
|
+
const previous = this.jobConfigs[name];
|
|
365
|
+
// The schedule restoreBullSchedulers() brings back after a data loss
|
|
366
|
+
this.jobConfigs[name] = config;
|
|
367
|
+
try {
|
|
368
|
+
// The job runs through BullMQ again, so a removal marker an earlier schedule left no longer applies
|
|
369
|
+
const removedKey = this.bullSchedulerRemovedKey(name);
|
|
370
|
+
if (removedKey) {
|
|
371
|
+
await this.getRedisClient()?.del(removedKey);
|
|
372
|
+
}
|
|
373
|
+
if (!(await this.bullSchedulerMatches(name, config))) {
|
|
374
|
+
await this.upsertBullScheduler(name, config);
|
|
375
|
+
}
|
|
376
|
+
} catch (error) {
|
|
377
|
+
this.jobConfigs[name] = previous;
|
|
378
|
+
throw error;
|
|
379
|
+
}
|
|
380
|
+
this.bullScheduledJobs.add(name);
|
|
381
|
+
// The local timer the job ran on, or the stopped registry entry of its previous schedule
|
|
382
|
+
this.removeCronJobRegistryEntry(name);
|
|
383
|
+
this.schedulerRegistry.addCronJob(name, this.createBullRegistryEntry(name, config));
|
|
384
|
+
if (!this.bullSchedulerCheckTimer) {
|
|
385
|
+
this.startBullSchedulerCheck();
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Reschedule a job on a local timer — or move it there from its BullMQ scheduler, which is removed with the removal
|
|
391
|
+
* marker first: a replica that still schedules the job through BullMQ must not register it again.
|
|
392
|
+
*/
|
|
393
|
+
protected async rescheduleLocally(
|
|
394
|
+
name: string,
|
|
395
|
+
config: CronJobConfigWithTimeZone,
|
|
396
|
+
scheduledWithBull: boolean,
|
|
397
|
+
): Promise<void> {
|
|
398
|
+
if (scheduledWithBull) {
|
|
399
|
+
this.bullScheduledJobs.delete(name);
|
|
400
|
+
try {
|
|
401
|
+
await this.markBullSchedulerRemoved(name);
|
|
402
|
+
await this.bullQueue?.removeJobScheduler(name);
|
|
403
|
+
} catch (error) {
|
|
404
|
+
// The job stays with its scheduler; a marker written before the removal failed would hide a later data loss
|
|
405
|
+
this.bullScheduledJobs.add(name);
|
|
406
|
+
try {
|
|
407
|
+
const removedKey = this.bullSchedulerRemovedKey(name);
|
|
408
|
+
if (removedKey) {
|
|
409
|
+
await this.getRedisClient()?.del(removedKey);
|
|
410
|
+
}
|
|
411
|
+
} catch {
|
|
412
|
+
// Redis is not answering — the next registerBullJob() deletes the marker
|
|
413
|
+
}
|
|
414
|
+
throw error;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const previous = scheduledWithBull ? undefined : this.registeredCronJob(name);
|
|
418
|
+
// The Hub stopped a recurring job on this replica: the new timer stays stopped too (a one-shot date stops itself)
|
|
419
|
+
const keepStopped = !!previous && !previous.isActive && !previous.cronTime?.realDate;
|
|
420
|
+
this.removeCronJobRegistryEntry(name);
|
|
421
|
+
this.jobConfigs[name] = config;
|
|
422
|
+
// A reschedule is not a start: no runOnInit
|
|
423
|
+
this.registerLocalJob(name, { ...config, runOnInit: false }, config.distributed !== false);
|
|
424
|
+
if (keepStopped) {
|
|
425
|
+
void this.registeredCronJob(name)?.stop();
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Whether Redis already holds this job's scheduler with exactly this pattern and time zone. An upsert is not free —
|
|
431
|
+
* BullMQ drops the tick the scheduler planned last and plans from now — so an unchanged schedule is not written again.
|
|
432
|
+
* A listing that fails answers `false`: the schedule is then written.
|
|
433
|
+
*/
|
|
434
|
+
protected async bullSchedulerMatches(name: string, config: CronJobConfigWithTimeZone): Promise<boolean> {
|
|
435
|
+
try {
|
|
436
|
+
const listed: { key?: string; pattern?: string; tz?: null | string }[] = await this.bullQueue.getJobSchedulers();
|
|
437
|
+
const scheduler = listed.find((entry) => entry?.key === name);
|
|
438
|
+
return (
|
|
439
|
+
!!scheduler &&
|
|
440
|
+
scheduler.pattern === config.cronTime &&
|
|
441
|
+
(scheduler.tz ?? undefined) === (config.timeZone ?? undefined)
|
|
442
|
+
);
|
|
443
|
+
} catch {
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* The STOPPED CronJob that stands for a BullMQ-scheduled job in the SchedulerRegistry — see registerBullJob(). It never
|
|
450
|
+
* fires on its own; the Hub reads its schedule, and a manual trigger runs the leased tick.
|
|
451
|
+
*/
|
|
452
|
+
protected createBullRegistryEntry(name: string, config: CronJobConfigWithTimeZone): CronJob {
|
|
453
|
+
return new CronJob(
|
|
454
|
+
config.cronTime,
|
|
455
|
+
() => this.runInitTick(name),
|
|
456
|
+
null,
|
|
457
|
+
false,
|
|
458
|
+
config.timeZone,
|
|
459
|
+
config.context,
|
|
460
|
+
false,
|
|
461
|
+
config.utcOffset,
|
|
462
|
+
config.unrefTimeout,
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** The job's CronJob in the SchedulerRegistry, if it has one */
|
|
467
|
+
protected registeredCronJob(name: string): CronJob | undefined {
|
|
468
|
+
return this.schedulerRegistry.doesExist('cron', name) ? this.schedulerRegistry.getCronJob(name) : undefined;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** Stop the job's CronJob and take it out of the SchedulerRegistry (deleteCronJob() stops it) */
|
|
472
|
+
protected removeCronJobRegistryEntry(name: string): void {
|
|
473
|
+
if (this.schedulerRegistry.doesExist('cron', name)) {
|
|
474
|
+
this.schedulerRegistry.deleteCronJob(name);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
240
478
|
/**
|
|
241
479
|
* Init cron jobs
|
|
242
480
|
*/
|
|
@@ -308,7 +546,7 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
|
|
|
308
546
|
|
|
309
547
|
// Init cron job as BullMQ job scheduler, when possible
|
|
310
548
|
if (bullMqActive && distributed) {
|
|
311
|
-
if (
|
|
549
|
+
if (this.canUseBullScheduler(config)) {
|
|
312
550
|
await this.registerBullJob(name, config);
|
|
313
551
|
this.bullScheduledJobs.add(name);
|
|
314
552
|
continue;
|
|
@@ -815,18 +1053,7 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
|
|
|
815
1053
|
// the BullMQ scheduler owns the schedule — while `nextDate()`/`lastDate()` still answer for
|
|
816
1054
|
// the panel, and a manual trigger goes through the same leased tick as everywhere else.
|
|
817
1055
|
if (!this.schedulerRegistry.doesExist('cron', name)) {
|
|
818
|
-
|
|
819
|
-
config.cronTime,
|
|
820
|
-
() => this.runInitTick(name),
|
|
821
|
-
null,
|
|
822
|
-
false,
|
|
823
|
-
config.timeZone,
|
|
824
|
-
config.context,
|
|
825
|
-
false,
|
|
826
|
-
config.utcOffset,
|
|
827
|
-
config.unrefTimeout,
|
|
828
|
-
);
|
|
829
|
-
this.schedulerRegistry.addCronJob(name, registryJob);
|
|
1056
|
+
this.schedulerRegistry.addCronJob(name, this.createBullRegistryEntry(name, config));
|
|
830
1057
|
}
|
|
831
1058
|
|
|
832
1059
|
if (this.config.log) {
|