@lenne.tech/nest-server 12.10.1 → 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.
Files changed (108) hide show
  1. package/.claude/rules/better-auth.md +19 -0
  2. package/.claude/rules/configurable-features.md +11 -9
  3. package/.claude/rules/package-management.md +1 -1
  4. package/.claude/rules/role-system.md +4 -1
  5. package/.claude/rules/testing.md +4 -4
  6. package/CLAUDE.md +5 -0
  7. package/FRAMEWORK-API.md +2 -1
  8. package/dist/core/common/decorators/unified-field.decorator.js +5 -2
  9. package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
  10. package/dist/core/common/helpers/config.helper.js +31 -9
  11. package/dist/core/common/helpers/config.helper.js.map +1 -1
  12. package/dist/core/common/helpers/graceful-shutdown.helper.js +3 -1
  13. package/dist/core/common/helpers/graceful-shutdown.helper.js.map +1 -1
  14. package/dist/core/common/helpers/graphql-ws-connection.helper.d.ts +8 -3
  15. package/dist/core/common/helpers/graphql-ws-connection.helper.js +44 -0
  16. package/dist/core/common/helpers/graphql-ws-connection.helper.js.map +1 -1
  17. package/dist/core/common/helpers/http-stream-auth.helper.d.ts +13 -0
  18. package/dist/core/common/helpers/http-stream-auth.helper.js +90 -0
  19. package/dist/core/common/helpers/http-stream-auth.helper.js.map +1 -0
  20. package/dist/core/common/helpers/shutdown-state.helper.d.ts +3 -0
  21. package/dist/core/common/helpers/shutdown-state.helper.js +11 -0
  22. package/dist/core/common/helpers/shutdown-state.helper.js.map +1 -0
  23. package/dist/core/common/interfaces/cron-job-config-with-utc-offset.interface.d.ts +1 -1
  24. package/dist/core/common/interfaces/cron-job-config.interface.d.ts +1 -1
  25. package/dist/core/common/interfaces/server-options.interface.d.ts +14 -0
  26. package/dist/core/common/services/core-cron-jobs.service.d.ts +13 -0
  27. package/dist/core/common/services/core-cron-jobs.service.js +129 -4
  28. package/dist/core/common/services/core-cron-jobs.service.js.map +1 -1
  29. package/dist/core/modules/better-auth/better-auth.config.js +48 -4
  30. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  31. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.d.ts +8 -0
  32. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js +47 -0
  33. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js.map +1 -0
  34. package/dist/core/modules/better-auth/core-better-auth-models.d.ts +1 -0
  35. package/dist/core/modules/better-auth/core-better-auth-models.js +7 -0
  36. package/dist/core/modules/better-auth/core-better-auth-models.js.map +1 -1
  37. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.d.ts +11 -0
  38. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js +62 -0
  39. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js.map +1 -0
  40. package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +1 -0
  41. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +28 -1
  42. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  43. package/dist/core/modules/better-auth/core-better-auth.controller.js +2 -1
  44. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  45. package/dist/core/modules/better-auth/core-better-auth.middleware.js +2 -2
  46. package/dist/core/modules/better-auth/core-better-auth.middleware.js.map +1 -1
  47. package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -0
  48. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  49. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +10 -0
  50. package/dist/core/modules/better-auth/core-better-auth.service.js +105 -19
  51. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  52. package/dist/core/modules/health-check/core-health-check-readiness.controller.d.ts +6 -0
  53. package/dist/core/modules/health-check/core-health-check-readiness.controller.js +36 -0
  54. package/dist/core/modules/health-check/core-health-check-readiness.controller.js.map +1 -0
  55. package/dist/core/modules/health-check/core-health-check.helpers.d.ts +10 -0
  56. package/dist/core/modules/health-check/core-health-check.helpers.js +31 -0
  57. package/dist/core/modules/health-check/core-health-check.helpers.js.map +1 -0
  58. package/dist/core/modules/health-check/core-health-check.module.d.ts +9 -0
  59. package/dist/core/modules/health-check/core-health-check.module.js +13 -2
  60. package/dist/core/modules/health-check/core-health-check.module.js.map +1 -1
  61. package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -1
  62. package/dist/core/modules/health-check/core-health-check.service.js +66 -29
  63. package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
  64. package/dist/core/modules/sync/core-sync.service.d.ts +2 -0
  65. package/dist/core/modules/sync/core-sync.service.js +11 -1
  66. package/dist/core/modules/sync/core-sync.service.js.map +1 -1
  67. package/dist/core.module.js +5 -1
  68. package/dist/core.module.js.map +1 -1
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +4 -0
  71. package/dist/index.js.map +1 -1
  72. package/dist/main.js.map +1 -1
  73. package/docs/REQUEST-LIFECYCLE.md +4 -4
  74. package/docs/offline-sync-protocol.md +5 -3
  75. package/migration-guides/12.10.x-to-12.11.x.md +295 -0
  76. package/package.json +17 -17
  77. package/src/core/common/decorators/unified-field.decorator.ts +14 -4
  78. package/src/core/common/helpers/config.helper.ts +55 -8
  79. package/src/core/common/helpers/graceful-shutdown.helper.ts +10 -3
  80. package/src/core/common/helpers/graphql-ws-connection.helper.ts +99 -4
  81. package/src/core/common/helpers/http-stream-auth.helper.ts +197 -0
  82. package/src/core/common/helpers/shutdown-state.helper.ts +28 -0
  83. package/src/core/common/interfaces/cron-job-config-with-utc-offset.interface.ts +1 -1
  84. package/src/core/common/interfaces/cron-job-config.interface.ts +1 -1
  85. package/src/core/common/interfaces/server-options.interface.ts +113 -1
  86. package/src/core/common/services/core-cron-jobs.service.ts +241 -14
  87. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +26 -10
  88. package/src/core/modules/better-auth/README.md +37 -8
  89. package/src/core/modules/better-auth/better-auth.config.ts +83 -12
  90. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +1 -1
  91. package/src/core/modules/better-auth/core-better-auth-jwt-session.cache.ts +104 -0
  92. package/src/core/modules/better-auth/core-better-auth-models.ts +5 -0
  93. package/src/core/modules/better-auth/core-better-auth-sign-in-factors.helper.ts +105 -0
  94. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +37 -1
  95. package/src/core/modules/better-auth/core-better-auth.controller.ts +6 -3
  96. package/src/core/modules/better-auth/core-better-auth.middleware.ts +4 -3
  97. package/src/core/modules/better-auth/core-better-auth.module.ts +1 -1
  98. package/src/core/modules/better-auth/core-better-auth.resolver.ts +1 -0
  99. package/src/core/modules/better-auth/core-better-auth.service.ts +160 -27
  100. package/src/core/modules/health-check/core-health-check-readiness.controller.ts +27 -0
  101. package/src/core/modules/health-check/core-health-check.helpers.ts +65 -0
  102. package/src/core/modules/health-check/core-health-check.module.ts +37 -2
  103. package/src/core/modules/health-check/core-health-check.service.ts +154 -59
  104. package/src/core/modules/sync/README.md +18 -6
  105. package/src/core/modules/sync/core-sync.service.ts +35 -6
  106. package/src/core.module.ts +9 -1
  107. package/src/index.ts +4 -0
  108. package/src/main.ts +2 -1
@@ -0,0 +1,65 @@
1
+ import { Logger } from '@nestjs/common';
2
+
3
+ import type { IServerOptions } from '../../common/interfaces/server-options.interface.js';
4
+
5
+ /** The checks `healthCheck.configs` configures, in the order they report */
6
+ export const CORE_HEALTH_CHECK_NAMES = ['database', 'memoryHeap', 'memoryRss', 'storage', 'build'] as const;
7
+
8
+ /** A check `healthCheck.configs` configures */
9
+ export type CoreHealthCheckName = (typeof CORE_HEALTH_CHECK_NAMES)[number];
10
+
11
+ /** Which endpoint a health check answers for: `GET /health-check` (liveness) or `GET /health-check/ready` (readiness) */
12
+ export type CoreHealthCheckKind = 'liveness' | 'readiness';
13
+
14
+ /** The checks the readiness endpoint runs without `healthCheck.readiness.checks` */
15
+ export const DEFAULT_READINESS_CHECKS: readonly CoreHealthCheckName[] = ['database', 'build'];
16
+
17
+ /** The readiness endpoint as the configuration describes it */
18
+ export interface IResolvedHealthCheckReadiness {
19
+ /** The configured checks the readiness endpoint runs, in report order */
20
+ checks: CoreHealthCheckName[];
21
+ /** Whether `GET /health-check/ready` is registered */
22
+ enabled: boolean;
23
+ }
24
+
25
+ const logger = new Logger('CoreHealthCheck');
26
+ const warnedUnknownChecks = new Set<string>();
27
+
28
+ /**
29
+ * Resolve `healthCheck.readiness` (12.11.0): boolean shorthand and "presence implies enabled".
30
+ *
31
+ * - absent (or `false`, `{ enabled: false }`): no readiness endpoint — the health check is what it was
32
+ * - `true` / `{}`: `GET /health-check/ready` with the default checks (`database`, `build`)
33
+ * - `{ checks: [...] }`: the listed checks of `healthCheck.configs` — a list (or a comma-separated string, which is
34
+ * what an `NSC__HEALTH_CHECK__READINESS__CHECKS` variable gives) of `database`, `memoryHeap`, `memoryRss`, `storage`,
35
+ * `build`. Unknown names are ignored with one warning each; `[]` runs only the project's own readiness indicators.
36
+ *
37
+ * A listed check runs in the readiness check whatever `configs.<check>.enabled` says: that flag decides for
38
+ * `GET /health-check`. Key, thresholds and options come from `configs.<check>`.
39
+ */
40
+ export function resolveHealthCheckReadiness(healthCheck: IServerOptions['healthCheck']): IResolvedHealthCheckReadiness {
41
+ const readiness = healthCheck?.readiness;
42
+ const enabled = readiness === true || (!!readiness && typeof readiness === 'object' && readiness.enabled !== false);
43
+ if (!enabled || typeof readiness !== 'object' || readiness.checks === undefined || readiness.checks === null) {
44
+ return { checks: enabled ? [...DEFAULT_READINESS_CHECKS] : [], enabled };
45
+ }
46
+ const listed = typeof readiness.checks === 'string' ? readiness.checks.split(',') : readiness.checks;
47
+ if (!Array.isArray(listed)) {
48
+ warnOnce(`healthCheck.readiness.checks is neither a list nor a string — the default checks run`);
49
+ return { checks: [...DEFAULT_READINESS_CHECKS], enabled };
50
+ }
51
+ const names = listed.map((name) => (typeof name === 'string' ? name.trim() : name)).filter((name) => name !== '');
52
+ for (const name of names) {
53
+ if (!(CORE_HEALTH_CHECK_NAMES as readonly unknown[]).includes(name)) {
54
+ warnOnce(`healthCheck.readiness.checks names an unknown check "${String(name)}" — it is ignored`);
55
+ }
56
+ }
57
+ return { checks: CORE_HEALTH_CHECK_NAMES.filter((name) => names.includes(name)), enabled };
58
+ }
59
+
60
+ function warnOnce(message: string): void {
61
+ if (!warnedUnknownChecks.has(message)) {
62
+ warnedUnknownChecks.add(message);
63
+ logger.warn(message);
64
+ }
65
+ }
@@ -1,16 +1,35 @@
1
- import { Module } from '@nestjs/common';
1
+ import { type DynamicModule, Module, type Type } from '@nestjs/common';
2
2
  import { ModuleRef } from '@nestjs/core';
3
3
  import { HealthIndicatorService, MongooseHealthIndicator, TerminusModule } from '@nestjs/terminus';
4
4
 
5
+ import type { IServerOptions } from '../../common/interfaces/server-options.interface.js';
5
6
  import { getConnectionToken } from '../../common/persistence/mongo/mongoose-compat.js';
6
7
 
8
+ import { CoreHealthCheckReadinessController } from './core-health-check-readiness.controller.js';
7
9
  import { CoreHealthCheckController } from './core-health-check.controller.js';
10
+ import { resolveHealthCheckReadiness } from './core-health-check.helpers.js';
8
11
  import { CoreHealthCheckResolver } from './core-health-check.resolver.js';
9
12
  import { CoreHealthCheckService } from './core-health-check.service.js';
10
13
 
14
+ /** Options of {@link CoreHealthCheckModule.forRoot} — what `CoreModule.forRoot()` passes on */
15
+ export interface ICoreHealthCheckModuleOptions {
16
+ /** `healthCheck.readiness`: registers `GET /health-check/ready` when set (boolean shorthand) */
17
+ readiness?: NonNullable<IServerOptions['healthCheck']>['readiness'];
18
+
19
+ /** Replaces `CoreHealthCheckReadinessController`; must extend it */
20
+ readinessController?: Type<any>;
21
+
22
+ /** Replaces `CoreHealthCheckService`; must extend it — the way to add checks (`additionalHealthIndicators()`) */
23
+ service?: Type<CoreHealthCheckService>;
24
+ }
25
+
11
26
  /**
12
27
  * This is a module that imports the TerminusModule and includes a HealthController.
13
28
  * Inspired by https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2
29
+ *
30
+ * Imported as it is, the module registers the liveness check (`GET /health-check`, the `healthCheck` query) exactly as
31
+ * before 12.11.0. `forRoot()` adds what the configuration and the overrides ask for: the readiness endpoint and a
32
+ * project's subclass of `CoreHealthCheckService`.
14
33
  */
15
34
  @Module({
16
35
  controllers: [CoreHealthCheckController],
@@ -28,4 +47,20 @@ import { CoreHealthCheckService } from './core-health-check.service.js';
28
47
  },
29
48
  ],
30
49
  })
31
- export class CoreHealthCheckModule {}
50
+ export class CoreHealthCheckModule {
51
+ /**
52
+ * The module with the readiness endpoint and the service override (12.11.0). A dynamic module EXTENDS the static
53
+ * metadata above, so only what is not there is added: the readiness controller (only with `readiness`), and a project
54
+ * service registered under its own class and — replacing the core one — under `CoreHealthCheckService`, which the
55
+ * controllers and the resolver inject.
56
+ */
57
+ static forRoot(options: ICoreHealthCheckModuleOptions = {}): DynamicModule {
58
+ const readiness = resolveHealthCheckReadiness({ readiness: options.readiness });
59
+ const controllers = readiness.enabled ? [options.readinessController || CoreHealthCheckReadinessController] : [];
60
+ const providers =
61
+ options.service && options.service !== CoreHealthCheckService
62
+ ? [options.service, { provide: CoreHealthCheckService, useExisting: options.service }]
63
+ : [];
64
+ return { controllers, module: CoreHealthCheckModule, providers };
65
+ }
66
+ }
@@ -1,9 +1,10 @@
1
- import { Inject, Injectable, Optional } from '@nestjs/common';
1
+ import { Inject, Injectable, Optional, ServiceUnavailableException } from '@nestjs/common';
2
2
  import {
3
3
  DiskHealthIndicator,
4
4
  type DiskHealthIndicatorOptions,
5
5
  HealthCheckResult,
6
6
  HealthCheckService,
7
+ type HealthIndicatorFunction,
7
8
  HealthIndicatorService,
8
9
  MemoryHealthIndicator,
9
10
  MongooseHealthIndicator,
@@ -11,12 +12,25 @@ import {
11
12
  } from '@nestjs/terminus';
12
13
 
13
14
  import { getBuildInfo } from '../../common/helpers/meta.helper.js';
15
+ import { isShutdownDraining } from '../../common/helpers/shutdown-state.helper.js';
14
16
  import { getPersistenceRuntime } from '../../common/persistence/persistence-runtime.registry.js';
15
17
  import { ConfigService } from '../../common/services/config.service.js';
18
+ import {
19
+ CORE_HEALTH_CHECK_NAMES,
20
+ type CoreHealthCheckKind,
21
+ type CoreHealthCheckName,
22
+ resolveHealthCheckReadiness,
23
+ } from './core-health-check.helpers.js';
16
24
 
17
25
  /**
18
26
  * Core health check service
19
27
  * Inspired by https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2
28
+ *
29
+ * Two checks (12.11.0): {@link healthCheck} answers `GET /health-check` and the `healthCheck` query (liveness), with
30
+ * the checks `healthCheck.configs` enables; {@link readinessCheck} answers `GET /health-check/ready`, registered with
31
+ * `healthCheck.readiness`, with the checks `healthCheck.readiness.checks` lists. A project adds checks of its own by
32
+ * extending this class and overriding {@link additionalHealthIndicators} — see there — and registers the subclass with
33
+ * `CoreModule.forRoot(env, { healthCheck: { service: HealthCheckService } })`.
20
34
  */
21
35
  @Injectable()
22
36
  export class CoreHealthCheckService {
@@ -30,10 +44,123 @@ export class CoreHealthCheckService {
30
44
  @Optional() protected indicators?: HealthIndicatorService,
31
45
  ) {}
32
46
 
33
- healthCheck(): Promise<HealthCheckResult> {
34
- const healthIndicatorFunctions = [];
47
+ /**
48
+ * The liveness check (`GET /health-check`, the `healthCheck` query): every check `healthCheck.configs` enables, then
49
+ * the project's own (`additionalHealthIndicators('liveness')`). Answers the Terminus result; rejects with 503 when a
50
+ * check is down.
51
+ */
52
+ async healthCheck(): Promise<HealthCheckResult> {
53
+ const checks = CORE_HEALTH_CHECK_NAMES.filter((check) => this.isLivenessCheckEnabled(check));
54
+ return this.health.check([
55
+ ...checks.flatMap((check) => this.configuredHealthIndicators(check)),
56
+ ...(await this.additionalHealthIndicators('liveness')),
57
+ ]);
58
+ }
59
+
60
+ /**
61
+ * The readiness check (`GET /health-check/ready`, 12.11.0): the checks `healthCheck.readiness.checks` lists (default
62
+ * `database` and `build`), then the project's own (`additionalHealthIndicators('readiness')`). Rejects with 503 when
63
+ * a check is down — and from the first shutdown signal on (`shutting_down`): `installGracefulShutdown()` marks it
64
+ * before its `shutdownDelayMs` wait, so a load balancer polling readiness stops routing to the replica while it is
65
+ * still serving. Without `installGracefulShutdown()` only Terminus' own state applies, which comes inside
66
+ * `app.close()`, right before the server closes.
67
+ */
68
+ async readinessCheck(): Promise<HealthCheckResult> {
69
+ if (isShutdownDraining()) {
70
+ throw new ServiceUnavailableException({ details: {}, error: {}, info: {}, status: 'shutting_down' });
71
+ }
72
+ const { checks } = resolveHealthCheckReadiness(this.config.get('healthCheck'));
73
+ return this.health.check([
74
+ ...checks.flatMap((check) => this.configuredHealthIndicators(check)),
75
+ ...(await this.additionalHealthIndicators('readiness')),
76
+ ]);
77
+ }
78
+
79
+ /**
80
+ * The extension point for checks of a project's own (12.11.0): override it in a subclass and return Terminus health
81
+ * indicators for the check that asks — `'liveness'` (`GET /health-check`, the `healthCheck` query) or `'readiness'`
82
+ * (`GET /health-check/ready`). They run after the configured checks; one that is down turns the check red (503).
83
+ *
84
+ * Keep liveness to what restarting the process would cure; what the process needs from outside (a queue, a third-
85
+ * party API) belongs to readiness, so an outage there takes the replica out of rotation instead of restarting it.
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * @Injectable()
90
+ * export class HealthCheckService extends CoreHealthCheckService {
91
+ * protected override additionalHealthIndicators(kind: CoreHealthCheckKind): HealthIndicatorFunction[] {
92
+ * return kind === 'readiness'
93
+ * ? [() => this.indicators.check('erp').attempt(() => this.erpClient.ping()).withTimeout(1000)]
94
+ * : [];
95
+ * }
96
+ * }
97
+ * ```
98
+ * The injected `indicators` (`HealthIndicatorService`) builds an indicator from any check; `memory`, `disk` and `db`
99
+ * are Terminus' own indicators.
100
+ *
101
+ * @default no additional indicators
102
+ */
103
+ protected additionalHealthIndicators(
104
+ _kind: CoreHealthCheckKind,
105
+ ): HealthIndicatorFunction[] | Promise<HealthIndicatorFunction[]> {
106
+ return [];
107
+ }
108
+
109
+ /**
110
+ * Whether `GET /health-check` runs a configured check: `configs.<check>.enabled` — set, except for `build`, which runs
111
+ * unless switched off
112
+ */
113
+ protected isLivenessCheckEnabled(check: CoreHealthCheckName): boolean {
114
+ const enabled = this.config.get<boolean>(`healthCheck.configs.${check}.enabled`);
115
+ return check === 'build' ? enabled !== false : !!enabled;
116
+ }
117
+
118
+ /** The indicators of one check of `healthCheck.configs`, with its key, thresholds and options from there */
119
+ protected configuredHealthIndicators(check: CoreHealthCheckName): HealthIndicatorFunction[] {
120
+ switch (check) {
121
+ case 'build':
122
+ return this.buildHealthIndicators();
123
+ case 'database':
124
+ return this.databaseHealthIndicators();
125
+ case 'memoryHeap':
126
+ return [
127
+ () =>
128
+ this.memory.checkHeap(
129
+ this.config.get<string>('healthCheck.configs.memoryHeap.key') ?? 'memoryHeap',
130
+ // memory in bytes (4GB default)
131
+ this.config.get<number>('healthCheck.configs.memoryHeap.heapUsedThreshold') ?? 4 * 1024 * 1024 * 1024,
132
+ ),
133
+ ];
134
+ case 'memoryRss':
135
+ return [
136
+ () =>
137
+ this.memory.checkRSS(
138
+ this.config.get<string>('healthCheck.configs.memoryRss.key') ?? 'memoryRss',
139
+ // memory in bytes (4GB default)
140
+ this.config.get<number>('healthCheck.configs.memoryRss.rssThreshold') ?? 4 * 1024 * 1024 * 1024,
141
+ ),
142
+ ];
143
+ case 'storage':
144
+ return [
145
+ () =>
146
+ this.disk.checkStorage(
147
+ this.config.get<string>('healthCheck.configs.storage.key') ?? 'storage',
148
+ this.config.get<DiskHealthIndicatorOptions>('healthCheck.configs.storage.options') ?? {
149
+ path: '/',
150
+ thresholdPercent: 0.8,
151
+ },
152
+ ),
153
+ ];
154
+ default:
155
+ return [];
156
+ }
157
+ }
158
+
159
+ /** The MongoDB ping where MongoDB is configured, and every SQL source on its own key */
160
+ protected databaseHealthIndicators(): HealthIndicatorFunction[] {
161
+ const healthIndicatorFunctions: HealthIndicatorFunction[] = [];
35
162
  // The MongoDB ping where MongoDB is configured — a project on PostgreSQL alone has no MongoDB to ping
36
- if (this.db && this.config.get<boolean>('healthCheck.configs.database.enabled')) {
163
+ if (this.db) {
37
164
  healthIndicatorFunctions.push(() => {
38
165
  // `timeout` stays part of the config contract, but @nestjs/terminus 12 deprecated it on the
39
166
  // indicator in favour of `.withTimeout()` on the returned attempt — translate it here, so the
@@ -50,64 +177,32 @@ export class CoreHealthCheckService {
50
177
  return timeout === undefined ? attempt : attempt.withTimeout(timeout);
51
178
  });
52
179
  }
53
- if (this.config.get<boolean>('healthCheck.configs.database.enabled')) {
54
- // Every SQL source answers on its own key, next to the MongoDB ping: `<key>:<source>` (`database:default`). A
55
- // database the application cannot reach is down, whichever one it is
56
- const key = this.config.get<string>('healthCheck.configs.database.key') ?? 'database';
57
- const timeout =
58
- this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options')?.timeout ?? 1000;
180
+ // Every SQL source answers on its own key, next to the MongoDB ping: `<key>:<source>` (`database:default`). A
181
+ // database the application cannot reach is down, whichever one it is
182
+ const key = this.config.get<string>('healthCheck.configs.database.key') ?? 'database';
183
+ const timeout = this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options')?.timeout ?? 1000;
184
+ if (this.indicators) {
59
185
  for (const source of getPersistenceRuntime()?.sqlSources() ?? []) {
60
- if (this.indicators) {
61
- healthIndicatorFunctions.push(() =>
62
- this.indicators
63
- .check(`${key}:${source.name}`)
64
- .attempt(() => source.ping())
65
- .withTimeout(timeout),
66
- );
67
- }
186
+ healthIndicatorFunctions.push(() =>
187
+ this.indicators
188
+ .check(`${key}:${source.name}`)
189
+ .attempt(() => source.ping())
190
+ .withTimeout(timeout),
191
+ );
68
192
  }
69
193
  }
70
- if (this.config.get<boolean>('healthCheck.configs.memoryHeap.enabled')) {
71
- healthIndicatorFunctions.push(() =>
72
- this.memory.checkHeap(
73
- this.config.get<string>('healthCheck.configs.memoryHeap.key') ?? 'memoryHeap',
74
- // memory in bytes (4GB default)
75
- this.config.get<number>('healthCheck.configs.memoryHeap.heapUsedThreshold') ?? 4 * 1024 * 1024 * 1024,
76
- ),
77
- );
78
- }
79
- if (this.config.get<boolean>('healthCheck.configs.memoryRss.enabled')) {
80
- healthIndicatorFunctions.push(() =>
81
- this.memory.checkRSS(
82
- this.config.get<string>('healthCheck.configs.memoryRss.key') ?? 'memoryRss',
83
- // memory in bytes (4GB default)
84
- this.config.get<number>('healthCheck.configs.memoryRss.rssThreshold') ?? 4 * 1024 * 1024 * 1024,
85
- ),
86
- );
87
- }
88
- if (this.config.get<boolean>('healthCheck.configs.storage.enabled')) {
89
- healthIndicatorFunctions.push(() =>
90
- this.disk.checkStorage(
91
- this.config.get<string>('healthCheck.configs.storage.key') ?? 'storage',
92
- this.config.get<DiskHealthIndicatorOptions>('healthCheck.configs.storage.options') ?? {
93
- path: '/',
94
- thresholdPercent: 0.8,
95
- },
96
- ),
97
- );
98
- }
99
- // Build identity (commit / version / env) — always reported as "up", so it
100
- // surfaces under `info`/`details` without ever affecting the overall health
101
- // status. Lets ops/monitoring detect a drifted or stale container after a
102
- // partial rollout (the same commit-SHA signal the admin UI compares). The
103
- // commit is baked into the image at build time (APP_VERSION_COMMIT, fed from
104
- // the CI commit SHA); `version`/`env` come from the config. Opt out with
105
- // `healthCheck.configs.build.enabled: false`.
106
- if (this.config.get<boolean>('healthCheck.configs.build.enabled') !== false) {
107
- const build = getBuildInfo({ env: this.config.get<string>('env'), version: this.config.get<string>('version') });
108
- healthIndicatorFunctions.push(async () => ({ build: { ...build, status: 'up' as const } }));
109
- }
194
+ return healthIndicatorFunctions;
195
+ }
110
196
 
111
- return this.health.check(healthIndicatorFunctions);
197
+ /**
198
+ * Build identity (commit / version / env) — always reported as "up", so it surfaces under `info`/`details` without
199
+ * ever affecting the overall health status. Lets ops/monitoring detect a drifted or stale container after a partial
200
+ * rollout (the same commit-SHA signal the admin UI compares). The commit is baked into the image at build time
201
+ * (APP_VERSION_COMMIT, fed from the CI commit SHA); `version`/`env` come from the config. Opt out with
202
+ * `healthCheck.configs.build.enabled: false`.
203
+ */
204
+ protected buildHealthIndicators(): HealthIndicatorFunction[] {
205
+ const build = getBuildInfo({ env: this.config.get<string>('env'), version: this.config.get<string>('version') });
206
+ return [async () => ({ build: { ...build, status: 'up' as const } })];
112
207
  }
113
208
  }
@@ -138,12 +138,24 @@ A hint tells a connected client that pulling is worthwhile; sync works without t
138
138
  every replica receives every hint through one channel and delivers it to its own subscribers; without Redis a hint
139
139
  stays on its replica.
140
140
  - **Long-lived channels are re-checked:** the GraphQL subscription runs on the WebSocket `CoreModule` re-checks; an SSE
141
- stream is registered in the same registry and ends at once on an invalidation naming the caller or their tenant, and
142
- otherwise before the first hint after `graphQl.subscriptionRevalidationMs` — the EventSource reconnects (`retry`) and
143
- the new request passes the guards. A client pulls once after every (re)connect. In the log the planned end after the
144
- interval is a debug line (`Closing SSE hint stream of user …: re-check interval reached, client reconnects`); an end
145
- an invalidation brings stays at `log` (`… authorization invalidated, client reconnects`), so a real revocation stands
146
- out (12.3.0; before, every planned end read `Closing GraphQL WebSocket …: Session no longer valid`).
141
+ stream is registered in the same registry and re-checked at once on an invalidation naming the caller or their
142
+ tenant, and otherwise before the first hint after `graphQl.subscriptionRevalidationMs`.
143
+ - **In place (12.11.0)** when the stream was opened with a Better-Auth credential — the session cookie, a bearer
144
+ session token or Better-Auth JWT, the `lt-jwt-token` cookie: the re-check runs that credential again
145
+ (`createHttpStreamReauthenticator()`) and the tenant resolution, like a WebSocket's. Unchanged rights keep the
146
+ stream open and the hint is delivered without a reconnect; changed user id, roles, verification or tenant scope
147
+ close it (`Closing SSE hint stream of user …: User authorization changed` / `Session no longer valid` /
148
+ `Tenant access changed`), and the reconnect passes the guards. Before 12.11.0 every re-check ended the stream, and
149
+ the hint reached the client only after its reconnect (~3 s).
150
+ - **By ending the stream** when the credential cannot be run again — a legacy JWT, an API token: the EventSource
151
+ reconnects (`retry`) and the new request passes the guards. In the log the planned end after the interval is a debug
152
+ line (`Closing SSE hint stream of user …: re-check interval reached, client reconnects`); an end an invalidation
153
+ brings stays at `log` (`… authorization invalidated, client reconnects`), so a real revocation stands out (12.3.0;
154
+ before, every planned end read `Closing GraphQL WebSocket …: Session no longer valid`).
155
+
156
+ A client pulls once after every (re)connect. `CoreSyncService.recheckHintStreamInPlace()` decides between the two; a
157
+ project overrides it to keep every stream ending on every re-check (`return false`), or to re-run a credential the
158
+ framework cannot (a legacy JWT through the project's AuthService) with `recheckHttpStreamInPlace()`.
147
159
 
148
160
  ## Tombstone purge
149
161
 
@@ -21,8 +21,12 @@ import {
21
21
  ensureWsConnectionCurrent,
22
22
  getWsConnection,
23
23
  noteWsConnectionTenant,
24
+ readWsTenantHeader,
25
+ recheckHttpStreamInPlace,
24
26
  registerWsConnection,
27
+ type WsConnection,
25
28
  } from '../../common/helpers/graphql-ws-connection.helper.js';
29
+ import { createHttpStreamReauthenticator } from '../../common/helpers/http-stream-auth.helper.js';
26
30
  import {
27
31
  buildCorsConfig,
28
32
  isCookiesEnabled,
@@ -1416,11 +1420,14 @@ export class CoreSyncService implements OnApplicationBootstrap, OnModuleDestroy,
1416
1420
  * The SSE stream of `GET /sync/hints`: an `event: change` with `{ model, at }` for every hint the caller may receive
1417
1421
  * (protocol §9), for the `models` named or all.
1418
1422
  *
1419
- * The stream is registered like a GraphQL WebSocket (`registerWsConnection()`): an invalidation that names the
1420
- * caller or one of their tenants ends it at once, and otherwise it ends before the first hint after
1421
- * `graphQl.subscriptionRevalidationMs`. An HTTP stream has no handshake to repeat, so it is not re-checked in place —
1422
- * the EventSource reconnects (`retry`) and the new request passes the guards like every request. A client loses
1423
- * nothing by it: a hint only means "pull now".
1423
+ * The stream is registered like a GraphQL WebSocket (`registerWsConnection()`) and re-checked when an invalidation
1424
+ * names the caller or one of their tenants, and otherwise before the first hint after
1425
+ * `graphQl.subscriptionRevalidationMs`. Since 12.11.0 that re-check runs IN PLACE when the request's credential can
1426
+ * be re-run — a Better-Auth session cookie or bearer token (`recheckHintStreamInPlace()`): the stream stays open and
1427
+ * the hint is delivered while the caller's rights are unchanged, and is closed only when they changed. A stream
1428
+ * opened with a credential that cannot be re-run (a legacy JWT, an API token) ends on every re-check as before: the
1429
+ * EventSource reconnects (`retry`) and the new request passes the guards like every request. A client loses nothing
1430
+ * by either: a hint only means "pull now".
1424
1431
  */
1425
1432
  async openHintStream(request: any, response: any, currentUser: any, models?: readonly string[]): Promise<void> {
1426
1433
  const accepts = await this.hintFilter(currentUser, models);
@@ -1457,7 +1464,8 @@ export class CoreSyncService implements OnApplicationBootstrap, OnModuleDestroy,
1457
1464
  registerWsConnection({
1458
1465
  carrier,
1459
1466
  channel: 'SSE hint stream',
1460
- // No credential to check again: every re-check ends the stream, and the reconnect is checked by the guards
1467
+ // Every re-check ends the stream and the reconnect is checked by the guards — until recheckHintStreamInPlace()
1468
+ // below finds a credential it can re-run
1461
1469
  endsOnRecheck: true,
1462
1470
  socket: {
1463
1471
  close: () => end(),
@@ -1478,6 +1486,11 @@ export class CoreSyncService implements OnApplicationBootstrap, OnModuleDestroy,
1478
1486
  tenantRole: context.tenantRole,
1479
1487
  });
1480
1488
  }
1489
+ // After the tenant is noted: the switch compares the re-run credential's tenant scope with it. A failure keeps the
1490
+ // stream ending on every re-check — the behaviour that needs nothing to work
1491
+ if (connection) {
1492
+ await this.recheckHintStreamInPlace(connection, request).catch(() => false);
1493
+ }
1481
1494
  // The client may have gone while the guards and the filter ran — `close` has fired then and comes no more
1482
1495
  if (request?.destroyed || response?.destroyed || response?.writableEnded) {
1483
1496
  end();
@@ -1519,6 +1532,22 @@ export class CoreSyncService implements OnApplicationBootstrap, OnModuleDestroy,
1519
1532
  keepalive.unref?.();
1520
1533
  }
1521
1534
 
1535
+ /**
1536
+ * Let the hint stream be re-checked in place instead of ending on every re-check (12.11.0): the credential of the
1537
+ * request that opened it — a Better-Auth session cookie or bearer token — is run again on each re-check
1538
+ * (`createHttpStreamReauthenticator()`, `recheckHttpStreamInPlace()`), and the stream is closed only when the caller's
1539
+ * user id, roles, verification or tenant scope changed. Answers whether the stream is re-checked in place.
1540
+ *
1541
+ * An extension point: return `false` to keep every stream ending on every re-check, or re-run a credential the
1542
+ * framework cannot (a legacy JWT, through the project's AuthService) and hand it to `recheckHttpStreamInPlace()`.
1543
+ */
1544
+ protected async recheckHintStreamInPlace(connection: WsConnection, request: any): Promise<boolean> {
1545
+ const reauthenticate = createHttpStreamReauthenticator(request);
1546
+ return reauthenticate
1547
+ ? recheckHttpStreamInPlace(connection, { reauthenticate, tenantHeader: readWsTenantHeader(request) })
1548
+ : false;
1549
+ }
1550
+
1522
1551
  /**
1523
1552
  * The GraphQL subscription `syncHint`: every hint the subscriber may receive. The socket it runs on is re-checked by
1524
1553
  * `CoreModule` (`registerWsConnection()`), so a change of the subscriber's rights closes it. `models` narrows it as
@@ -521,7 +521,15 @@ export class CoreModule implements NestModule {
521
521
 
522
522
  // Presence implies enabled; `enabled: false` keeps the configured checks without the endpoints.
523
523
  if (config.healthCheck && config.healthCheck.enabled !== false) {
524
- imports.push(CoreHealthCheckModule);
524
+ // forRoot() adds the readiness endpoint (`healthCheck.readiness`) and a project's service; without either the
525
+ // module is what it was (12.11.0)
526
+ imports.push(
527
+ CoreHealthCheckModule.forRoot({
528
+ readiness: config.healthCheck.readiness,
529
+ readinessController: overrides?.healthCheck?.readinessController,
530
+ service: overrides?.healthCheck?.service,
531
+ }),
532
+ );
525
533
  }
526
534
 
527
535
  // Permissions report (development tool)
package/src/index.ts CHANGED
@@ -38,6 +38,7 @@ export * from './core/common/helpers/content-disposition.helper.js';
38
38
  export * from './core/common/helpers/context.helper.js';
39
39
  export * from './core/common/helpers/cookies.helper.js';
40
40
  export * from './core/common/helpers/graceful-shutdown.helper.js';
41
+ export * from './core/common/helpers/shutdown-state.helper.js';
41
42
  export * from './core/common/helpers/db.helper.js';
42
43
  export * from './core/common/helpers/decorator.helper.js';
43
44
  export * from './core/common/helpers/execution-context-request.helper.js';
@@ -47,6 +48,7 @@ export * from './core/common/helpers/graphql.helper.js';
47
48
  export * from './core/common/helpers/graphql-upload.helper.js';
48
49
  export * from './core/common/helpers/graphql-ws-connection.helper.js';
49
50
  export * from './core/common/helpers/graphql-ws-context.helper.js';
51
+ export * from './core/common/helpers/http-stream-auth.helper.js';
50
52
  export * from './core/common/helpers/idle-stream.helper.js';
51
53
  export * from './core/common/helpers/interceptor.helper.js';
52
54
  export * from './core/common/helpers/gridfs.helper.js';
@@ -250,8 +252,10 @@ export * from './core/modules/file/interfaces/file-upload.interface.js';
250
252
  // Core - Modules - HealthCheck
251
253
  // =====================================================================================================================
252
254
 
255
+ export * from './core/modules/health-check/core-health-check-readiness.controller.js';
253
256
  export * from './core/modules/health-check/core-health-check-result.model.js';
254
257
  export * from './core/modules/health-check/core-health-check.controller.js';
258
+ export * from './core/modules/health-check/core-health-check.helpers.js';
255
259
  export * from './core/modules/health-check/core-health-check.module.js';
256
260
  export * from './core/modules/health-check/core-health-check.resolver.js';
257
261
  export * from './core/modules/health-check/core-health-check.service.js';
package/src/main.ts CHANGED
@@ -123,7 +123,8 @@ async function bootstrap() {
123
123
  // the loop; installProcessDiagnostics() then correctly defers to it instead of re-raising.
124
124
  //
125
125
  // installGracefulShutdown() IS enableShutdownHooks() when no `shutdownDelayMs` is configured.
126
- // With one, it additionally keeps the instance fully healthy for that long before closing —
126
+ // With one, it additionally keeps the instance serving for that long before closing (readiness
127
+ // already answers 503) —
127
128
  // which a NestJS lifecycle hook cannot do, because every one of them already runs inside
128
129
  // close(), after the modules are destroyed. See the helper for the ordering.
129
130
  installGracefulShutdown(server);