@lenne.tech/nest-server 12.1.0 → 12.2.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/architecture.md +1 -0
- package/.claude/rules/better-auth.md +18 -6
- package/.claude/rules/configurable-features.md +5 -4
- package/.claude/rules/package-management.md +16 -1
- package/.claude/rules/persistence.md +26 -0
- package/.claude/rules/testing.md +102 -28
- package/CLAUDE.md +3 -2
- package/FRAMEWORK-API.md +17 -2
- package/README.md +24 -3
- package/dist/core/common/helpers/file.helper.js +3 -4
- package/dist/core/common/helpers/file.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-ws-connection.helper.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +41 -0
- package/dist/core/common/interfaces/service-options.interface.d.ts +3 -0
- package/dist/core/common/persistence/core-persistence.module.js +12 -2
- package/dist/core/common/persistence/core-persistence.module.js.map +1 -1
- package/dist/core/common/persistence/data-source.runtime.js +14 -19
- package/dist/core/common/persistence/data-source.runtime.js.map +1 -1
- package/dist/core/common/persistence/data-store.interface.d.ts +24 -9
- package/dist/core/common/persistence/id-format.d.ts +2 -0
- package/dist/core/common/persistence/id-format.js +14 -0
- package/dist/core/common/persistence/id-format.js.map +1 -1
- package/dist/core/common/persistence/model-descriptor.interface.d.ts +6 -0
- package/dist/core/common/persistence/model-metadata.registry.d.ts +2 -1
- package/dist/core/common/persistence/model-metadata.registry.js +20 -2
- package/dist/core/common/persistence/model-metadata.registry.js.map +1 -1
- package/dist/core/common/persistence/mongo/sync-schema.plugin.d.ts +18 -0
- package/dist/core/common/persistence/mongo/sync-schema.plugin.js +368 -0
- package/dist/core/common/persistence/mongo/sync-schema.plugin.js.map +1 -0
- package/dist/core/common/persistence/mongoose-data-store.d.ts +19 -9
- package/dist/core/common/persistence/mongoose-data-store.js +107 -31
- package/dist/core/common/persistence/mongoose-data-store.js.map +1 -1
- package/dist/core/common/persistence/persisted-model.decorator.d.ts +3 -0
- package/dist/core/common/persistence/persisted-model.decorator.js +9 -0
- package/dist/core/common/persistence/persisted-model.decorator.js.map +1 -1
- package/dist/core/common/persistence/persistence-runtime.registry.d.ts +5 -1
- package/dist/core/common/persistence/persistence-runtime.registry.js.map +1 -1
- package/dist/core/common/persistence/policies/sync.policy.d.ts +17 -0
- package/dist/core/common/persistence/policies/sync.policy.js +77 -0
- package/dist/core/common/persistence/policies/sync.policy.js.map +1 -0
- package/dist/core/common/persistence/sql/mysql/mysql-data-store.d.ts +12 -8
- package/dist/core/common/persistence/sql/mysql/mysql-data-store.js +82 -29
- package/dist/core/common/persistence/sql/mysql/mysql-data-store.js.map +1 -1
- package/dist/core/common/persistence/sql/mysql/mysql-schema.compiler.d.ts +10 -0
- package/dist/core/common/persistence/sql/mysql/mysql-schema.compiler.js +61 -4
- package/dist/core/common/persistence/sql/mysql/mysql-schema.compiler.js.map +1 -1
- package/dist/core/common/persistence/sql/mysql/mysql-schema.migrator.d.ts +2 -0
- package/dist/core/common/persistence/sql/mysql/mysql-schema.migrator.js +145 -4
- package/dist/core/common/persistence/sql/mysql/mysql-schema.migrator.js.map +1 -1
- package/dist/core/common/persistence/sql/postgres/postgres-schema.compiler.d.ts +10 -0
- package/dist/core/common/persistence/sql/postgres/postgres-schema.compiler.js +41 -2
- package/dist/core/common/persistence/sql/postgres/postgres-schema.compiler.js.map +1 -1
- package/dist/core/common/persistence/sql/postgres/postgres-schema.migrator.js +98 -10
- package/dist/core/common/persistence/sql/postgres/postgres-schema.migrator.js.map +1 -1
- package/dist/core/common/persistence/sql/sql-data-store.d.ts +38 -14
- package/dist/core/common/persistence/sql/sql-data-store.js +212 -38
- package/dist/core/common/persistence/sql/sql-data-store.js.map +1 -1
- package/dist/core/common/persistence/sql/sql-dialect.d.ts +2 -0
- package/dist/core/common/persistence/sql/sql-dialect.js +14 -2
- package/dist/core/common/persistence/sql/sql-dialect.js.map +1 -1
- package/dist/core/common/persistence/sql/sql-errors.d.ts +2 -1
- package/dist/core/common/persistence/sql/sql-errors.js +3 -1
- package/dist/core/common/persistence/sql/sql-errors.js.map +1 -1
- package/dist/core/common/persistence/sync-access.registry.d.ts +17 -0
- package/dist/core/common/persistence/sync-access.registry.js +8 -0
- package/dist/core/common/persistence/sync-access.registry.js.map +1 -0
- package/dist/core/common/persistence/sync-model.d.ts +29 -0
- package/dist/core/common/persistence/sync-model.js +138 -0
- package/dist/core/common/persistence/sync-model.js.map +1 -0
- package/dist/core/common/services/core-cron-jobs.service.d.ts +27 -0
- package/dist/core/common/services/core-cron-jobs.service.js +269 -13
- package/dist/core/common/services/core-cron-jobs.service.js.map +1 -1
- package/dist/core/common/services/core-redis-pubsub.js +5 -5
- package/dist/core/common/services/core-redis-pubsub.js.map +1 -1
- package/dist/core/common/services/core-redis.service.d.ts +6 -0
- package/dist/core/common/services/core-redis.service.js +57 -0
- package/dist/core/common/services/core-redis.service.js.map +1 -1
- package/dist/core/common/services/crud.service.d.ts +13 -1
- package/dist/core/common/services/crud.service.js +174 -16
- package/dist/core/common/services/crud.service.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth-sql.helper.d.ts +1 -0
- package/dist/core/modules/better-auth/better-auth-sql.helper.js +41 -14
- package/dist/core/modules/better-auth/better-auth-sql.helper.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-sql.store.d.ts +4 -7
- package/dist/core/modules/better-auth/core-better-auth-sql.store.js +23 -16
- package/dist/core/modules/better-auth/core-better-auth-sql.store.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +12 -2
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +82 -5
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.module.js +1 -1
- package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
- package/dist/core/modules/error-code/error-codes.d.ts +54 -0
- package/dist/core/modules/error-code/error-codes.js +48 -0
- package/dist/core/modules/error-code/error-codes.js.map +1 -1
- package/dist/core/modules/hub/hub-buffer.js +3 -4
- package/dist/core/modules/hub/hub-buffer.js.map +1 -1
- package/dist/core/modules/migrate/index.js.map +1 -1
- package/dist/core/modules/migrate/migration-runner.d.ts +6 -0
- package/dist/core/modules/migrate/migration-runner.js +28 -2
- package/dist/core/modules/migrate/migration-runner.js.map +1 -1
- package/dist/core/modules/migrate/mongo-state-store.d.ts +0 -1
- package/dist/core/modules/migrate/mongo-state-store.js +0 -5
- package/dist/core/modules/migrate/mongo-state-store.js.map +1 -1
- package/dist/core/modules/migrate/sql-migration.helper.d.ts +15 -1
- package/dist/core/modules/migrate/sql-migration.helper.js +90 -5
- package/dist/core/modules/migrate/sql-migration.helper.js.map +1 -1
- package/dist/core/modules/sync/core-sync-base.controller.d.ts +7 -0
- package/dist/core/modules/sync/core-sync-base.controller.js +44 -0
- package/dist/core/modules/sync/core-sync-base.controller.js.map +1 -0
- package/dist/core/modules/sync/core-sync-cursor.d.ts +19 -0
- package/dist/core/modules/sync/core-sync-cursor.js +77 -0
- package/dist/core/modules/sync/core-sync-cursor.js.map +1 -0
- package/dist/core/modules/sync/core-sync-hints.controller.d.ts +4 -0
- package/dist/core/modules/sync/core-sync-hints.controller.js +55 -0
- package/dist/core/modules/sync/core-sync-hints.controller.js.map +1 -0
- package/dist/core/modules/sync/core-sync-hints.service.d.ts +28 -0
- package/dist/core/modules/sync/core-sync-hints.service.js +155 -0
- package/dist/core/modules/sync/core-sync-hints.service.js.map +1 -0
- package/dist/core/modules/sync/core-sync-infrastructure.models.d.ts +2 -0
- package/dist/core/modules/sync/core-sync-infrastructure.models.js +17 -0
- package/dist/core/modules/sync/core-sync-infrastructure.models.js.map +1 -0
- package/dist/core/modules/sync/core-sync-mutation.store.d.ts +43 -0
- package/dist/core/modules/sync/core-sync-mutation.store.js +88 -0
- package/dist/core/modules/sync/core-sync-mutation.store.js.map +1 -0
- package/dist/core/modules/sync/core-sync-state.store.d.ts +18 -0
- package/dist/core/modules/sync/core-sync-state.store.js +64 -0
- package/dist/core/modules/sync/core-sync-state.store.js.map +1 -0
- package/dist/core/modules/sync/core-sync.constants.d.ts +28 -0
- package/dist/core/modules/sync/core-sync.constants.js +23 -0
- package/dist/core/modules/sync/core-sync.constants.js.map +1 -0
- package/dist/core/modules/sync/core-sync.controller.d.ts +8 -0
- package/dist/core/modules/sync/core-sync.controller.js +79 -0
- package/dist/core/modules/sync/core-sync.controller.js.map +1 -0
- package/dist/core/modules/sync/core-sync.decorators.d.ts +12 -0
- package/dist/core/modules/sync/core-sync.decorators.js +28 -0
- package/dist/core/modules/sync/core-sync.decorators.js.map +1 -0
- package/dist/core/modules/sync/core-sync.module.d.ts +16 -0
- package/dist/core/modules/sync/core-sync.module.js +50 -0
- package/dist/core/modules/sync/core-sync.module.js.map +1 -0
- package/dist/core/modules/sync/core-sync.resolver.d.ts +9 -0
- package/dist/core/modules/sync/core-sync.resolver.js +46 -0
- package/dist/core/modules/sync/core-sync.resolver.js.map +1 -0
- package/dist/core/modules/sync/core-sync.service.d.ts +142 -0
- package/dist/core/modules/sync/core-sync.service.js +1208 -0
- package/dist/core/modules/sync/core-sync.service.js.map +1 -0
- package/dist/core/modules/sync/interfaces/core-sync.interfaces.d.ts +56 -0
- package/dist/core/modules/sync/interfaces/core-sync.interfaces.js +2 -0
- package/dist/core/modules/sync/interfaces/core-sync.interfaces.js.map +1 -0
- package/dist/core/modules/sync/models/core-sync-hint.model.d.ts +4 -0
- package/dist/core/modules/sync/models/core-sync-hint.model.js +30 -0
- package/dist/core/modules/sync/models/core-sync-hint.model.js.map +1 -0
- package/dist/core/modules/tenant/core-tenant.guard.js +8 -3
- package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
- package/dist/core.module.js +14 -0
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +16 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -1
- package/dist/server/modules/error-code/error-codes.d.ts +6 -0
- package/dist/server/modules/sync-note/inputs/sync-note-create.input.d.ts +4 -0
- package/dist/server/modules/sync-note/inputs/sync-note-create.input.js +27 -0
- package/dist/server/modules/sync-note/inputs/sync-note-create.input.js.map +1 -0
- package/dist/server/modules/sync-note/inputs/sync-note.input.d.ts +6 -0
- package/dist/server/modules/sync-note/inputs/sync-note.input.js +37 -0
- package/dist/server/modules/sync-note/inputs/sync-note.input.js.map +1 -0
- package/dist/server/modules/sync-note/sync-note.model.d.ts +10 -0
- package/dist/server/modules/sync-note/sync-note.model.js +73 -0
- package/dist/server/modules/sync-note/sync-note.model.js.map +1 -0
- package/dist/server/modules/sync-note/sync-note.module.d.ts +2 -0
- package/dist/server/modules/sync-note/sync-note.module.js +21 -0
- package/dist/server/modules/sync-note/sync-note.module.js.map +1 -0
- package/dist/server/modules/sync-note/sync-note.service.d.ts +10 -0
- package/dist/server/modules/sync-note/sync-note.service.js +35 -0
- package/dist/server/modules/sync-note/sync-note.service.js.map +1 -0
- package/docs/REQUEST-LIFECYCLE.md +3 -2
- package/docs/choosing-a-database.md +7 -4
- package/docs/offline-sync-protocol.md +410 -0
- package/docs/security-overrides.md +14 -0
- package/migration-guides/12.0.x-to-12.1.x.md +9 -4
- package/migration-guides/12.1.0-to-12.1.1.md +125 -0
- package/migration-guides/12.1.x-to-12.2.x.md +154 -0
- package/package.json +10 -8
- package/src/core/common/helpers/file.helper.ts +7 -5
- package/src/core/common/helpers/graphql-ws-connection.helper.ts +3 -2
- package/src/core/common/interfaces/cron-job-config.interface.ts +7 -2
- package/src/core/common/interfaces/server-options.interface.ts +149 -0
- package/src/core/common/interfaces/service-options.interface.ts +15 -0
- package/src/core/common/persistence/core-persistence.module.ts +21 -2
- package/src/core/common/persistence/data-source.runtime.ts +22 -23
- package/src/core/common/persistence/data-store.interface.ts +65 -12
- package/src/core/common/persistence/id-format.ts +26 -0
- package/src/core/common/persistence/model-descriptor.interface.ts +12 -0
- package/src/core/common/persistence/model-metadata.registry.ts +31 -2
- package/src/core/common/persistence/mongo/sync-schema.plugin.ts +508 -0
- package/src/core/common/persistence/mongoose-data-store.ts +171 -35
- package/src/core/common/persistence/persisted-model.decorator.ts +26 -0
- package/src/core/common/persistence/persistence-runtime.registry.ts +16 -5
- package/src/core/common/persistence/policies/sync.policy.ts +121 -0
- package/src/core/common/persistence/sql/mysql/mysql-data-store.ts +108 -30
- package/src/core/common/persistence/sql/mysql/mysql-schema.compiler.ts +107 -4
- package/src/core/common/persistence/sql/mysql/mysql-schema.migrator.ts +194 -3
- package/src/core/common/persistence/sql/postgres/postgres-schema.compiler.ts +74 -2
- package/src/core/common/persistence/sql/postgres/postgres-schema.migrator.ts +139 -7
- package/src/core/common/persistence/sql/sql-data-store.ts +325 -44
- package/src/core/common/persistence/sql/sql-dialect.ts +38 -1
- package/src/core/common/persistence/sql/sql-errors.ts +5 -1
- package/src/core/common/persistence/sql/sql-executor.interface.ts +4 -1
- package/src/core/common/persistence/sync-access.registry.ts +50 -0
- package/src/core/common/persistence/sync-model.ts +270 -0
- package/src/core/common/services/core-cron-jobs.service.ts +441 -27
- package/src/core/common/services/core-redis-pubsub.ts +8 -6
- package/src/core/common/services/core-redis.service.ts +99 -0
- package/src/core/common/services/crud.service.ts +257 -19
- package/src/core/modules/better-auth/README.md +25 -1
- package/src/core/modules/better-auth/better-auth-sql.helper.ts +56 -24
- package/src/core/modules/better-auth/better-auth.config.ts +4 -3
- package/src/core/modules/better-auth/core-better-auth-sql.store.ts +28 -21
- package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +122 -6
- package/src/core/modules/better-auth/core-better-auth.module.ts +2 -2
- package/src/core/modules/error-code/error-codes.ts +59 -0
- package/src/core/modules/hub/README.md +5 -2
- package/src/core/modules/hub/hub-buffer.ts +13 -7
- package/src/core/modules/migrate/README.md +20 -11
- package/src/core/modules/migrate/index.ts +1 -0
- package/src/core/modules/migrate/migration-runner.ts +68 -3
- package/src/core/modules/migrate/mongo-state-store.ts +7 -30
- package/src/core/modules/migrate/sql-migration.helper.ts +141 -7
- package/src/core/modules/sync/INTEGRATION-CHECKLIST.md +95 -0
- package/src/core/modules/sync/README.md +188 -0
- package/src/core/modules/sync/SECURITY.md +65 -0
- package/src/core/modules/sync/core-sync-base.controller.ts +43 -0
- package/src/core/modules/sync/core-sync-cursor.ts +117 -0
- package/src/core/modules/sync/core-sync-hints.controller.ts +52 -0
- package/src/core/modules/sync/core-sync-hints.service.ts +178 -0
- package/src/core/modules/sync/core-sync-infrastructure.models.ts +40 -0
- package/src/core/modules/sync/core-sync-mutation.store.ts +146 -0
- package/src/core/modules/sync/core-sync-state.store.ts +89 -0
- package/src/core/modules/sync/core-sync.constants.ts +51 -0
- package/src/core/modules/sync/core-sync.controller.ts +68 -0
- package/src/core/modules/sync/core-sync.decorators.ts +84 -0
- package/src/core/modules/sync/core-sync.module.ts +75 -0
- package/src/core/modules/sync/core-sync.resolver.ts +35 -0
- package/src/core/modules/sync/core-sync.service.ts +1728 -0
- package/src/core/modules/sync/interfaces/core-sync.interfaces.ts +85 -0
- package/src/core/modules/sync/models/core-sync-hint.model.ts +18 -0
- package/src/core/modules/tenant/README.md +1 -0
- package/src/core/modules/tenant/core-tenant.guard.ts +16 -3
- package/src/core.module.ts +25 -0
- package/src/index.ts +21 -0
- package/src/server/modules/sync-note/inputs/sync-note-create.input.ts +14 -0
- package/src/server/modules/sync-note/inputs/sync-note.input.ts +23 -0
- package/src/server/modules/sync-note/sync-note.model.ts +77 -0
- package/src/server/modules/sync-note/sync-note.module.ts +16 -0
- package/src/server/modules/sync-note/sync-note.service.ts +25 -0
|
@@ -3,7 +3,7 @@ import * as path from 'path';
|
|
|
3
3
|
|
|
4
4
|
import { _endMigration, _startMigration } from './migration.helper.js';
|
|
5
5
|
import type { MigrationStateStore } from './migration-state-store.interface.js';
|
|
6
|
-
import { withMigrationLock } from './mongo-state-store.js';
|
|
6
|
+
import { type MigrationOptions, MongoStateStore, withMigrationLock } from './mongo-state-store.js';
|
|
7
7
|
import { createRequire } from 'node:module';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -94,7 +94,7 @@ export function parseStrictEnv(value: string | undefined = process.env.NSC__MIGR
|
|
|
94
94
|
* Migration runner configuration
|
|
95
95
|
*/
|
|
96
96
|
export interface MigrationRunnerOptions {
|
|
97
|
-
/** Directory containing migration files */
|
|
97
|
+
/** Directory containing migration files, absolute or relative to the working directory */
|
|
98
98
|
migrationsDirectory: string;
|
|
99
99
|
/** Pattern to match migration files (default: {@link DEFAULT_MIGRATION_FILE_PATTERN}) */
|
|
100
100
|
pattern?: RegExp;
|
|
@@ -148,7 +148,13 @@ export class MigrationRunner {
|
|
|
148
148
|
constructor(options: MigrationRunnerOptions) {
|
|
149
149
|
// Resolve the strict default from the environment so NSC__MIGRATE__STRICT works
|
|
150
150
|
// identically for programmatic runners and the CLI (which parses it itself).
|
|
151
|
-
|
|
151
|
+
// A relative directory is resolved against the working directory, as by the CLI: the files are
|
|
152
|
+
// loaded with require(), which reads `migrations/<file>` as a package name (DEV-3897).
|
|
153
|
+
this.options = {
|
|
154
|
+
...options,
|
|
155
|
+
migrationsDirectory: path.resolve(options.migrationsDirectory),
|
|
156
|
+
strict: options.strict ?? parseStrictEnv(),
|
|
157
|
+
};
|
|
152
158
|
this.pattern = options.pattern || DEFAULT_MIGRATION_FILE_PATTERN;
|
|
153
159
|
}
|
|
154
160
|
|
|
@@ -413,3 +419,62 @@ export const down = async () => {
|
|
|
413
419
|
return filePath;
|
|
414
420
|
}
|
|
415
421
|
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Options of {@link synchronizedUp}
|
|
425
|
+
*/
|
|
426
|
+
export interface SynchronizedUpOptions extends MigrationOptions {
|
|
427
|
+
/** Directory containing migration files (default: `migrations` in the working directory, as for the `migrate` CLI) */
|
|
428
|
+
migrationsDirectory?: string;
|
|
429
|
+
/** Pattern to match migration files (default: {@link DEFAULT_MIGRATION_FILE_PATTERN}) */
|
|
430
|
+
pattern?: RegExp;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Executes all pending migrations in a synchronized manner (for clustered environments)
|
|
435
|
+
*
|
|
436
|
+
* Runs a {@link MigrationRunner} under the state store's lock. Unlike `MigrationRunner.up()`, it refuses a store that
|
|
437
|
+
* cannot be locked — a `MongoStateStore` without `lockCollectionName` — instead of running unsynchronized. Until
|
|
438
|
+
* 12.1.0 it called `up` on the loaded migration state, which has none, and threw on every call (DEV-3897).
|
|
439
|
+
*
|
|
440
|
+
* @param opts - State store, plus the migrations directory and file pattern of the runner
|
|
441
|
+
* @throws Error if the state store cannot be locked
|
|
442
|
+
*
|
|
443
|
+
* @example
|
|
444
|
+
* ```typescript
|
|
445
|
+
* await synchronizedUp({
|
|
446
|
+
* migrationsDirectory: './migrations',
|
|
447
|
+
* stateStore: new MongoStateStore({
|
|
448
|
+
* uri: 'mongodb://localhost/db',
|
|
449
|
+
* lockCollectionName: 'migrationlock'
|
|
450
|
+
* })
|
|
451
|
+
* });
|
|
452
|
+
* ```
|
|
453
|
+
*/
|
|
454
|
+
export async function synchronizedUp(opts: SynchronizedUpOptions): Promise<void> {
|
|
455
|
+
assertLockableStore(opts?.stateStore);
|
|
456
|
+
await new MigrationRunner({
|
|
457
|
+
migrationsDirectory: opts.migrationsDirectory ?? 'migrations',
|
|
458
|
+
pattern: opts.pattern,
|
|
459
|
+
stateStore: opts.stateStore,
|
|
460
|
+
}).up();
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* The checks of `synchronizedMigration()`: a store that brings its own lock, or a `MongoStateStore` with a lock
|
|
465
|
+
* collection
|
|
466
|
+
*/
|
|
467
|
+
function assertLockableStore(stateStore: MigrationStateStore | undefined): void {
|
|
468
|
+
if (!stateStore) {
|
|
469
|
+
throw new Error('No `stateStore` in migration options');
|
|
470
|
+
}
|
|
471
|
+
if (!(stateStore instanceof MongoStateStore)) {
|
|
472
|
+
if (typeof stateStore.withLock !== 'function') {
|
|
473
|
+
throw new Error('Given `stateStore` is not `MongoStateStore`');
|
|
474
|
+
}
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
if (typeof stateStore.lockCollectionName !== 'string') {
|
|
478
|
+
throw new Error('`lockCollectionName` in MongoStateStore is not set');
|
|
479
|
+
}
|
|
480
|
+
}
|
|
@@ -30,9 +30,8 @@ export interface MongoStateStoreOptions {
|
|
|
30
30
|
/**
|
|
31
31
|
* Optionally specify a collection to use for locking. This is intended for
|
|
32
32
|
* clusters with multiple nodes to ensure that not more than one migration
|
|
33
|
-
* can run at any given time.
|
|
34
|
-
* `synchronizedUp`
|
|
35
|
-
* `migrate` directly.
|
|
33
|
+
* can run at any given time. The `migrate` CLI, `MigrationRunner`,
|
|
34
|
+
* `synchronizedUp()` and `synchronizedMigration()` all hold this lock.
|
|
36
35
|
*/
|
|
37
36
|
lockCollectionName?: string;
|
|
38
37
|
/** MongoDB connection URI */
|
|
@@ -158,8 +157,11 @@ export class MongoStateStore implements MigrationStateStore {
|
|
|
158
157
|
* lockCollectionName: 'migrationlock'
|
|
159
158
|
* })
|
|
160
159
|
* }, async (migrationSet) => {
|
|
161
|
-
* // Only one instance at a time will execute this
|
|
162
|
-
*
|
|
160
|
+
* // Only one instance at a time will execute this. `migrationSet` is the loaded state
|
|
161
|
+
* // (`lastRun`, `migrations`); to run the pending migrations use `synchronizedUp()`.
|
|
162
|
+
* if (!migrationSet.migrations?.some((m) => m.title === 'seed-defaults')) {
|
|
163
|
+
* await seedDefaults();
|
|
164
|
+
* }
|
|
163
165
|
* });
|
|
164
166
|
* ```
|
|
165
167
|
*/
|
|
@@ -206,31 +208,6 @@ export async function synchronizedMigration(
|
|
|
206
208
|
}
|
|
207
209
|
}
|
|
208
210
|
|
|
209
|
-
/**
|
|
210
|
-
* Executes all pending migrations in a synchronized manner (for clustered environments)
|
|
211
|
-
*
|
|
212
|
-
* This is a convenience function that wraps `synchronizedMigration` and automatically
|
|
213
|
-
* calls the `up` method on the migration set.
|
|
214
|
-
*
|
|
215
|
-
* @param opts - Migration options including state store
|
|
216
|
-
* @throws Error if state store is not configured correctly
|
|
217
|
-
*
|
|
218
|
-
* @example
|
|
219
|
-
* ```typescript
|
|
220
|
-
* await synchronizedUp({
|
|
221
|
-
* stateStore: new MongoStateStore({
|
|
222
|
-
* uri: 'mongodb://localhost/db',
|
|
223
|
-
* lockCollectionName: 'migrationlock'
|
|
224
|
-
* })
|
|
225
|
-
* });
|
|
226
|
-
* ```
|
|
227
|
-
*/
|
|
228
|
-
export async function synchronizedUp(opts: MigrationOptions): Promise<void> {
|
|
229
|
-
await synchronizedMigration(opts, async (loadedSet) => {
|
|
230
|
-
await promisify(loadedSet.up).call(loadedSet);
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
|
|
234
211
|
/**
|
|
235
212
|
* Runs `fn` while holding the migration lock of the given state store
|
|
236
213
|
*
|
|
@@ -1,13 +1,44 @@
|
|
|
1
1
|
import type { DatabaseSqlEngine } from '../../common/interfaces/server-options.interface.js';
|
|
2
2
|
import { withMysqlSchemaLock } from '../../common/persistence/sql/mysql/mysql-schema.migrator.js';
|
|
3
|
+
import { MYSQL_SYNC_COUNTERS } from '../../common/persistence/sql/mysql/mysql-schema.compiler.js';
|
|
4
|
+
import { syncSequenceName } from '../../common/persistence/sql/postgres/postgres-schema.compiler.js';
|
|
3
5
|
import { SCHEMA_LOCK_SQL } from '../../common/persistence/sql/postgres/postgres-schema.migrator.js';
|
|
4
6
|
import { createSqlExecutor } from '../../common/persistence/sql/sql-executor.factory.js';
|
|
7
|
+
import { quoteIdentifier, quoteMysqlIdentifier } from '../../common/persistence/sql/sql-naming.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A data migration's multi-row write on the table of a synchronized model, numbered the way the store numbers it (plan
|
|
11
|
+
* §3.4, C1d): the rows are locked first (`SELECT … FOR UPDATE`), then the change numbers taken, then the rows written
|
|
12
|
+
* with their numbers set and their `version` incremented. "Rows first, counter last" is what keeps the migration from
|
|
13
|
+
* deadlocking with a running application's writes on MySQL and MariaDB, whose row locks also lock index gaps; the
|
|
14
|
+
* incremented version turns the change into a conflict for a client that edited the old one, never a silent overwrite.
|
|
15
|
+
* Clients receive the rows at their next pull, like any change.
|
|
16
|
+
*
|
|
17
|
+
* `set` and `where` are SQL, reviewed like every statement of the migration — never built from request data.
|
|
18
|
+
*/
|
|
19
|
+
export interface SqlSyncUpdate {
|
|
20
|
+
syncUpdate: {
|
|
21
|
+
/** Assignments without `SET`, e.g. `"status" = 'archived'` (never `version` or `sync_seq`, both set here) */
|
|
22
|
+
set: string;
|
|
23
|
+
/** The table of the synchronized model, e.g. `sync_notes` */
|
|
24
|
+
table: string;
|
|
25
|
+
/** The rows to write, a condition without `WHERE` */
|
|
26
|
+
where: string;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** How a migration statement runs: on the migration's connection, inside its transaction where there is one */
|
|
31
|
+
export type SqlMigrationRun = (statement: { params: unknown[]; text: string }) => Promise<{ rows: any[] }>;
|
|
32
|
+
|
|
33
|
+
/** Rows written per statement */
|
|
34
|
+
const SYNC_UPDATE_CHUNK = 500;
|
|
5
35
|
|
|
6
36
|
/**
|
|
7
37
|
* Run the reviewed statements of a SQL migration (`migrate create <name> --sql`) as the table OWNER, under the lock the
|
|
8
38
|
* boot's schema migration takes, so a replica booting meanwhile waits and then sees the result. On PostgreSQL in one
|
|
9
39
|
* transaction: either every statement applies or none does. MySQL and MariaDB commit every DDL statement on its own, so
|
|
10
|
-
* there a failure leaves the statements before it applied — write such a migration so it can run again.
|
|
40
|
+
* there a failure leaves the statements before it applied — write such a migration so it can run again. A `syncUpdate`
|
|
41
|
+
* runs in a transaction of its own there, because a DDL statement before it has ended the migration's.
|
|
11
42
|
*
|
|
12
43
|
* The statements are the ones a refused boot suggested (`SchemaMigrationRequiredError`) — after review: a narrowed
|
|
13
44
|
* type, a new unique index or a rename collision can reject or rewrite stored rows, which is why the framework never
|
|
@@ -15,7 +46,7 @@ import { createSqlExecutor } from '../../common/persistence/sql/sql-executor.fac
|
|
|
15
46
|
*/
|
|
16
47
|
export async function runSqlMigration(
|
|
17
48
|
ownerUrl: string,
|
|
18
|
-
statements: readonly string[],
|
|
49
|
+
statements: readonly (SqlSyncUpdate | string)[],
|
|
19
50
|
options: { engine?: DatabaseSqlEngine } = {},
|
|
20
51
|
): Promise<void> {
|
|
21
52
|
if (!ownerUrl) {
|
|
@@ -30,19 +61,122 @@ export async function runSqlMigration(
|
|
|
30
61
|
try {
|
|
31
62
|
if (/^(mysql|mariadb):/i.test(ownerUrl)) {
|
|
32
63
|
await withMysqlSchemaLock(executor, async (run) => {
|
|
33
|
-
for (const
|
|
34
|
-
await
|
|
64
|
+
for (const statement of statements) {
|
|
65
|
+
await (typeof statement === 'string'
|
|
66
|
+
? run({ params: [], text: statement })
|
|
67
|
+
: applySqlSyncUpdate(run, 'mysql', statement.syncUpdate));
|
|
35
68
|
}
|
|
36
69
|
});
|
|
37
70
|
return;
|
|
38
71
|
}
|
|
39
72
|
await executor.transaction(async (tx) => {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
73
|
+
const run: SqlMigrationRun = (statement) => tx.run(statement, { kind: 'system' });
|
|
74
|
+
await run({ params: [], text: SCHEMA_LOCK_SQL });
|
|
75
|
+
for (const statement of statements) {
|
|
76
|
+
await (typeof statement === 'string'
|
|
77
|
+
? run({ params: [], text: statement })
|
|
78
|
+
: applySqlSyncUpdate(run, 'postgres', statement.syncUpdate));
|
|
43
79
|
}
|
|
44
80
|
});
|
|
45
81
|
} finally {
|
|
46
82
|
await executor.close();
|
|
47
83
|
}
|
|
48
84
|
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* One `syncUpdate` of a migration: rows locked, numbers taken, rows written, in one transaction — the migration's on
|
|
88
|
+
* PostgreSQL. On MySQL / MariaDB in a transaction of its own: a DDL statement earlier in the migration committed the
|
|
89
|
+
* migration's transaction implicitly, and in autocommit every statement would release its locks at once — a running
|
|
90
|
+
* application could then commit a higher number before these rows (a client's cursor passes them for good) or read the
|
|
91
|
+
* counter between the increment and the read here (one number twice). Answers the number of rows written.
|
|
92
|
+
*/
|
|
93
|
+
export async function applySqlSyncUpdate(
|
|
94
|
+
run: SqlMigrationRun,
|
|
95
|
+
dialect: 'mysql' | 'postgres',
|
|
96
|
+
update: SqlSyncUpdate['syncUpdate'],
|
|
97
|
+
): Promise<number> {
|
|
98
|
+
if (dialect === 'postgres') {
|
|
99
|
+
return writeSyncUpdate(run, dialect, update);
|
|
100
|
+
}
|
|
101
|
+
await run({ params: [], text: 'START TRANSACTION' });
|
|
102
|
+
try {
|
|
103
|
+
const written = await writeSyncUpdate(run, dialect, update);
|
|
104
|
+
await run({ params: [], text: 'COMMIT' });
|
|
105
|
+
return written;
|
|
106
|
+
} catch (error) {
|
|
107
|
+
await run({ params: [], text: 'ROLLBACK' }).catch(() => undefined);
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function writeSyncUpdate(
|
|
113
|
+
run: SqlMigrationRun,
|
|
114
|
+
dialect: 'mysql' | 'postgres',
|
|
115
|
+
update: SqlSyncUpdate['syncUpdate'],
|
|
116
|
+
): Promise<number> {
|
|
117
|
+
const quote = dialect === 'mysql' ? quoteMysqlIdentifier : quoteIdentifier;
|
|
118
|
+
const table = quote(update.table);
|
|
119
|
+
const id = quote('id');
|
|
120
|
+
const { rows } = await run({
|
|
121
|
+
params: [],
|
|
122
|
+
text: `SELECT ${id} AS id FROM ${table} WHERE ${update.where} ORDER BY ${id} FOR UPDATE`,
|
|
123
|
+
});
|
|
124
|
+
const ids = rows.map((row) => String(row.id));
|
|
125
|
+
if (!ids.length) {
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
const numbers =
|
|
129
|
+
dialect === 'mysql'
|
|
130
|
+
? await mysqlNumbers(run, update.table, ids.length)
|
|
131
|
+
: await postgresNumbers(run, update.table, ids.length);
|
|
132
|
+
const bigint = dialect === 'mysql' ? '' : '::bigint';
|
|
133
|
+
for (let start = 0; start < ids.length; start += SYNC_UPDATE_CHUNK) {
|
|
134
|
+
const chunk = ids.slice(start, start + SYNC_UPDATE_CHUNK);
|
|
135
|
+
const params: unknown[] = [];
|
|
136
|
+
const param = (value: unknown) => {
|
|
137
|
+
params.push(value);
|
|
138
|
+
return `$${params.length}`;
|
|
139
|
+
};
|
|
140
|
+
const cases = chunk
|
|
141
|
+
.map((row, index) => `WHEN ${param(row)} THEN ${param(numbers[start + index])}${bigint}`)
|
|
142
|
+
.join(' ');
|
|
143
|
+
const list = chunk.map((row) => param(row)).join(', ');
|
|
144
|
+
await run({
|
|
145
|
+
params,
|
|
146
|
+
text:
|
|
147
|
+
`UPDATE ${table} SET ${update.set}, ${quote('version')} = ${quote('version')} + 1, ` +
|
|
148
|
+
`${quote('sync_seq')} = CASE ${id} ${cases} END WHERE ${id} IN (${list})`,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
return ids.length;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The next change numbers of a table on PostgreSQL, as the store takes them (advisory lock, then the sequence) */
|
|
155
|
+
async function postgresNumbers(run: SqlMigrationRun, table: string, count: number): Promise<string[]> {
|
|
156
|
+
await run({
|
|
157
|
+
params: [table],
|
|
158
|
+
text: `SELECT pg_advisory_xact_lock(hashtext('lenne.tech:sync:' || current_schema() || '.' || $1))`,
|
|
159
|
+
});
|
|
160
|
+
const { rows } = await run({
|
|
161
|
+
params: [syncSequenceName(table), count],
|
|
162
|
+
text: `SELECT nextval(format('%I.%I', current_schema(), $1::text)::regclass)::text AS n FROM generate_series(1, $2::int)`,
|
|
163
|
+
});
|
|
164
|
+
return rows.map((row) => String(row.n)).sort((a, b) => (BigInt(a) < BigInt(b) ? -1 : 1));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The next change numbers of a table on MySQL / MariaDB, as the store takes them (the counter row, last) */
|
|
168
|
+
async function mysqlNumbers(run: SqlMigrationRun, table: string, count: number): Promise<string[]> {
|
|
169
|
+
await run({
|
|
170
|
+
params: [count, table],
|
|
171
|
+
text: `UPDATE ${quoteMysqlIdentifier(MYSQL_SYNC_COUNTERS)} SET \`seq\` = \`seq\` + $1 WHERE \`model\` = $2`,
|
|
172
|
+
});
|
|
173
|
+
const { rows } = await run({
|
|
174
|
+
params: [table],
|
|
175
|
+
text: `SELECT \`seq\` FROM ${quoteMysqlIdentifier(MYSQL_SYNC_COUNTERS)} WHERE \`model\` = $1`,
|
|
176
|
+
});
|
|
177
|
+
if (!rows.length) {
|
|
178
|
+
throw new Error(`runSqlMigration(): ${table} is not the table of a synchronized model (no change counter)`);
|
|
179
|
+
}
|
|
180
|
+
const last = BigInt(rows[0].seq);
|
|
181
|
+
return Array.from({ length: count }, (_, index) => (last - BigInt(count - 1 - index)).toString());
|
|
182
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Sync Integration Checklist
|
|
2
|
+
|
|
3
|
+
Offer a model to offline clients (`docs/offline-sync-protocol.md`). Background: [`README.md`](./README.md).
|
|
4
|
+
|
|
5
|
+
## Reference Implementation
|
|
6
|
+
|
|
7
|
+
- Local: `node_modules/@lenne.tech/nest-server/src/server/modules/sync-note/`
|
|
8
|
+
- GitHub: https://github.com/lenneTech/nest-server/tree/develop/src/server/modules/sync-note
|
|
9
|
+
|
|
10
|
+
The reference is not part of the reference server (`ServerModule` does not import it); the sync contract suite runs on
|
|
11
|
+
exactly these files.
|
|
12
|
+
|
|
13
|
+
## Required Files (Create in Order)
|
|
14
|
+
|
|
15
|
+
### 1. Enable the module
|
|
16
|
+
|
|
17
|
+
**Edit:** `src/config.env.ts`
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
sync: { cursorSecret: process.env.SYNC_CURSOR_SECRET },
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
WHY: the cursors are signed with it. Without `sync.cursorSecret` (or `SECRETS_ENCRYPTION_KEY`) the boot fails in
|
|
24
|
+
`production` / `staging`.
|
|
25
|
+
|
|
26
|
+
### 2. The model
|
|
27
|
+
|
|
28
|
+
**Create:** `src/server/modules/<module>/<module>.model.ts`
|
|
29
|
+
**Copy from:** `sync-note.model.ts`
|
|
30
|
+
|
|
31
|
+
- `@PersistedModel({ sync: { roles: { pull, create, update, delete }, strategy } })` — declare all four roles.
|
|
32
|
+
WHY: the roles on your controllers do not reach `/sync`; an operation without roles here is open to admins only.
|
|
33
|
+
- Do **not** declare `version`, `deletedAt`, `syncAt`, `syncSeq` — the store adds them (a declared one is refused).
|
|
34
|
+
- Declare `createdBy` when an operation uses `S_CREATOR` or `securityCheck()` decides by the creator.
|
|
35
|
+
- `securityCheck()` decides who sees a record — a pull and every push lookup run through it.
|
|
36
|
+
- **MySQL / MariaDB:** the owner account creates the change-order triggers at boot. WHY: with binary logging on (the
|
|
37
|
+
MySQL 8.4 default) that needs `SUPER` or `log_bin_trust_function_creators=1` on the server — without it the boot stops
|
|
38
|
+
with error 1419. The application account needs neither.
|
|
39
|
+
|
|
40
|
+
### 3. The inputs
|
|
41
|
+
|
|
42
|
+
**Create:** `inputs/<module>-create.input.ts`, `inputs/<module>.input.ts`
|
|
43
|
+
**Copy from:** `inputs/sync-note-create.input.ts`, `inputs/sync-note.input.ts`
|
|
44
|
+
|
|
45
|
+
WHY: a push's `data` is validated and whitelisted against them exactly like a request body — only what they declare
|
|
46
|
+
can be set.
|
|
47
|
+
|
|
48
|
+
### 4. The service
|
|
49
|
+
|
|
50
|
+
**Create / edit:** `<module>.service.ts`
|
|
51
|
+
**Copy from:** `sync-note.service.ts`
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
@SyncService({ createInput: NoteCreateInput, model: Note, updateInput: NoteInput })
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
For `strategy: 'custom'` implement `resolveSyncConflict(context)` (`SyncConflictResolver`); the boot fails without it.
|
|
58
|
+
|
|
59
|
+
### 5. The module
|
|
60
|
+
|
|
61
|
+
**Edit:** `<module>.module.ts` — register the model with `CorePersistenceModule.forFeature([{ model, name, schema }])`
|
|
62
|
+
**Copy from:** `sync-note.module.ts`
|
|
63
|
+
|
|
64
|
+
WHY: only a model registered this way can be synchronized (its store maintains the system fields).
|
|
65
|
+
|
|
66
|
+
### 6. An EXISTING model with data
|
|
67
|
+
|
|
68
|
+
Making an existing model synchronized is a migration on every database: the boot refuses with the statements to apply
|
|
69
|
+
(SQL: the `deleted_at` column, the live-only unique index, `DROP` of the full one; MongoDB:
|
|
70
|
+
`SyncMigrationRequiredError`). See `.claude/rules/persistence.md` → "Synchronized models".
|
|
71
|
+
|
|
72
|
+
## Verification Checklist
|
|
73
|
+
|
|
74
|
+
- [ ] The boot logs `Offline sync for <Model>` and no "declares no sync roles" warning
|
|
75
|
+
- [ ] `GET /sync/<Model>` answers `{ items, cursor, hasMore }` for a signed-in user with the pull roles, 403 without
|
|
76
|
+
- [ ] A push of `{ mutationId, op: 'upsert', id, data }` answers `applied` with `version: 1`; the same push again too
|
|
77
|
+
- [ ] A user of another tenant pulls none of the records and gets `not_found` / `ID_UNAVAILABLE` for their ids
|
|
78
|
+
- [ ] `GET /sync/hints` (EventSource) sends `event: change` after a write in the user's scope, and nothing for another
|
|
79
|
+
tenant's; the client pulls on every hint and once after every reconnect
|
|
80
|
+
- [ ] Writes past the CrudService (data store, native API, migration) call `CoreSyncService.notifyChange()`, and
|
|
81
|
+
multi-row data migrations on a synchronized SQL table use `runSqlMigration()` with `syncUpdate`
|
|
82
|
+
- [ ] The client deletes every local record, cursor and unsent change on logout and on an account switch (the device
|
|
83
|
+
holds personal data — see [SECURITY.md](./SECURITY.md))
|
|
84
|
+
|
|
85
|
+
## Common Mistakes
|
|
86
|
+
|
|
87
|
+
| Mistake | Symptom | Fix |
|
|
88
|
+
| ----------------------------------------------------- | ------------------------------------------------------------------------ | ----------------------------------------------------------- |
|
|
89
|
+
| No `sync.roles` | Every push of a user is `rejected` / `FORBIDDEN`, pull 403; boot warning | Declare all four operations |
|
|
90
|
+
| `@SyncService()` missing | `404` for the model | Decorate the CrudService |
|
|
91
|
+
| Model registered with `MongooseModule.forFeature()` | Boot error "not registered with CorePersistenceModule.forFeature()" | Use `CorePersistenceModule.forFeature()` |
|
|
92
|
+
| A system field declared on the model | Boot error "reserved on a synchronized model" | Remove it — the store maintains it |
|
|
93
|
+
| Writes to a tenant-scoped model without `X-Tenant-Id` | Rejected by the tenant policy | Send the header on writes; pulls may span all memberships |
|
|
94
|
+
| Records moved by a direct store / native write | Previous owners keep their copies | Call `CoreSyncService.bumpAccessEpoch()` after such a write |
|
|
95
|
+
| A driver's default `new ObjectId()` on the client | Ids predictable from one observed id | Random tail per protocol §3, or uuidv7 |
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# Sync (offline sync)
|
|
2
|
+
|
|
3
|
+
Clients read and write while offline and reconcile with the server afterwards: they **pull** what changed since their
|
|
4
|
+
cursor, **push** what they changed locally, and receive **tombstones** for deletions. The client contract is the
|
|
5
|
+
protocol in [`docs/offline-sync-protocol.md`](../../../../docs/offline-sync-protocol.md) — a client needs `fetch` and
|
|
6
|
+
nothing from this package. This module is the server side, on every database the framework supports (MongoDB
|
|
7
|
+
standalone and replica set, PostgreSQL with TypeORM, Kysely or Drizzle, MySQL, MariaDB), with the same observable
|
|
8
|
+
behaviour.
|
|
9
|
+
|
|
10
|
+
Integration steps: [`INTEGRATION-CHECKLIST.md`](./INTEGRATION-CHECKLIST.md). Reference implementation:
|
|
11
|
+
[`src/server/modules/sync-note/`](../../../server/modules/sync-note/).
|
|
12
|
+
|
|
13
|
+
## What it adds
|
|
14
|
+
|
|
15
|
+
| Route | Protocol | |
|
|
16
|
+
| ------------------------------------ | -------- | ---------------------------------------------------------- |
|
|
17
|
+
| `GET /sync/{model}?cursor=…&limit=…` | §5 | One page of changes after the cursor, tombstones included |
|
|
18
|
+
| `POST /sync/{model}` | §6 | Apply `{ items: [...] }` item by item, one result per item |
|
|
19
|
+
| `GET /sync/hints?models=…` | §9 | SSE: `event: change` with `{ model, at }` — pull now |
|
|
20
|
+
| `subscription { syncHint(models) }` | §9 | The same hints over GraphQL (where GraphQL is enabled) |
|
|
21
|
+
|
|
22
|
+
Nothing without the `sync` configuration: no route, no infrastructure model, no listener on the write paths.
|
|
23
|
+
|
|
24
|
+
## Configuration (`sync`, presence implies enabled)
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
sync: {
|
|
28
|
+
cursorSecret: process.env.SYNC_CURSOR_SECRET, // else SECRETS_ENCRYPTION_KEY; REQUIRED in production / staging
|
|
29
|
+
path: 'sync',
|
|
30
|
+
pull: { defaultLimit: 200, maxLimit: 1000, maxBytes: 1_048_576, windowSeconds: undefined /* MongoDB, derived */ },
|
|
31
|
+
push: { maxItems: 100 },
|
|
32
|
+
hints: { debounceMs: 250, sse: true, graphql: true }, // false: both channels off
|
|
33
|
+
retention: { mutationsDays: 30, tombstonesDays: 90 }, // tombstonesDays: false keeps them for ever
|
|
34
|
+
rateLimit: { pull: { max: 120, windowSeconds: 60 }, push: { max: 60, windowSeconds: 60 } }, // false: off
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`true` or `{}` enables it with these defaults. The full reference: `ISync` in
|
|
39
|
+
`common/interfaces/server-options.interface.ts`.
|
|
40
|
+
|
|
41
|
+
## Offering a model
|
|
42
|
+
|
|
43
|
+
Two declarations, both explicit — a model is never offered by accident:
|
|
44
|
+
|
|
45
|
+
1. **The model** — `@PersistedModel({ sync: { roles, strategy, scope, idFormat } })`. This makes it a synchronized
|
|
46
|
+
model in the data store (version, tombstones, live-only unique indexes, change order — see
|
|
47
|
+
`.claude/rules/persistence.md` → "Synchronized models") and carries what the sync routes need:
|
|
48
|
+
- `roles` per operation (`pull`, `create`, `update`, `delete`). The roles a project puts on its own routes do **not**
|
|
49
|
+
reach `/sync`; an operation without roles is open to `ADMIN` only, and the boot warns until they are declared. They
|
|
50
|
+
are passed as `serviceOptions.roles`, so `S_CREATOR` / `S_SELF` are decided against the stored record.
|
|
51
|
+
- `strategy`: `reject` (default), `lww`, `merge` (field by field; `@SyncField('reject')` marks a field that still
|
|
52
|
+
conflicts), `custom` (the service's `resolveSyncConflict()`).
|
|
53
|
+
- `scope`: the user-id fields a tombstone keeps (e.g. `['ownerId']`), so a deletion reaches exactly its users.
|
|
54
|
+
2. **The service** — `@SyncService({ model, createInput, updateInput })` on the model's `CrudService`. Every pull and
|
|
55
|
+
push runs through that service; `data` is validated and whitelisted against the inputs like a request body.
|
|
56
|
+
|
|
57
|
+
The model must be registered with `CorePersistenceModule.forFeature()`.
|
|
58
|
+
|
|
59
|
+
## Security model
|
|
60
|
+
|
|
61
|
+
| Rule | How |
|
|
62
|
+
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
63
|
+
| The full pipeline, no lean path | Pull reads through the service's `find()` (`process()`, output `@Restricted`, tenant policy, RLS) and runs every record through `securityCheck()`; push writes through `create()` / `update()` / `delete()` |
|
|
64
|
+
| Operation rights | The model's `sync.roles`, deny by default (ADMIN only) |
|
|
65
|
+
| Hidden fields | No answer depends on a value the caller may not read: a repeated create is always `conflict` with the record as the caller sees it, never compared with `data` |
|
|
66
|
+
| Foreign ids | Change / delete: `not_found`, exactly like a missing id. Create: `ID_UNAVAILABLE` — the same answer for every reason an id cannot be used |
|
|
67
|
+
| No hard delete | Push `delete` goes through `CrudService.delete()`, which tombstones a synchronized model on every path |
|
|
68
|
+
| Tombstones | Carry id, version, `deletedAt`, `updatedAt`, `tenantId` and the scope fields the caller may see — no content |
|
|
69
|
+
| Cursor | Opaque, HMAC-signed, bound to model and user; another user's, another model's or a tampered cursor is `410 invalid` |
|
|
70
|
+
| Access loss | A fingerprint of the caller's access (user, tenant scope, roles, membership role, verification) and access epochs travel in the cursor; a change answers `410 access`, the client resyncs in full; a caller who may not pull at all, or names a left tenant in `X-Tenant-Id`, gets `403` and drops its copies the same way |
|
|
71
|
+
| Cookie push | `Content-Type: application/json`; while the server uses cookies, `Sec-Fetch-Site: cross-site` and an untrusted `Origin` answer 403 |
|
|
72
|
+
| API tokens | Refused like on every route without `@ApiTokenScopes()` (see "Extending") |
|
|
73
|
+
| Session expired | 401 for the whole request before any item; the client resends the same items, mutation ids recognise them |
|
|
74
|
+
|
|
75
|
+
A pull or push without `X-Tenant-Id` spans every tenant the caller belongs to (the tenant guard's membership logic);
|
|
76
|
+
writes to a tenant-scoped model need the header, as everywhere — a create without it is `rejected` / `FORBIDDEN` on
|
|
77
|
+
every database, because nothing could tell which of the caller's tenants the record belongs to. A pull without it reads
|
|
78
|
+
each of the caller's tenants on its own and merges them in change order, so the tenant-led change index serves every
|
|
79
|
+
page.
|
|
80
|
+
|
|
81
|
+
What a client must do on its side — delete its local data on logout and on an account switch, keep credentials out of
|
|
82
|
+
reach of injected scripts, cache no API responses — is in [SECURITY.md](./SECURITY.md).
|
|
83
|
+
|
|
84
|
+
## Clients
|
|
85
|
+
|
|
86
|
+
The protocol needs `fetch` and nothing from the server's code (`docs/offline-sync-protocol.md`). Two test clients in
|
|
87
|
+
the framework repository prove it end to end against the reference server, with one shared protocol implementation
|
|
88
|
+
(`tests/clients/sync-client.mjs`, not part of the package):
|
|
89
|
+
|
|
90
|
+
| Client | Storage | Suite |
|
|
91
|
+
| -------------------------------------------------------------------------------------------- | ---------------------- | ------------------------------------ |
|
|
92
|
+
| PWA in Chrome, served by the test server, service worker for offline loading, session cookie | IndexedDB | `tests/sync-pwa-client.e2e-spec.ts` |
|
|
93
|
+
| Node, as a desktop or React Native app would be, bearer session token | SQLite (`node:sqlite`) | `tests/sync-node-client.e2e-spec.ts` |
|
|
94
|
+
|
|
95
|
+
Both pass the same scenarios (`tests/helpers/sync-client-scenarios.ts`): create, change and delete offline, then online;
|
|
96
|
+
a conflict; two tabs pushing at once; a session that expired while offline; cleared storage. Two server processes with
|
|
97
|
+
clocks 10 s apart lose no change under parallel writers (`tests/sync-clock-skew.e2e-spec.ts`). A Nuxt composable for
|
|
98
|
+
projects follows in `@lenne.tech/nuxt-extensions`.
|
|
99
|
+
|
|
100
|
+
## Idempotency and repeats
|
|
101
|
+
|
|
102
|
+
Every item carries a `mutationId`. The module **claims** it before the write (model, user, record, mutation id —
|
|
103
|
+
hashed, unique), records the outcome afterwards and answers a repeat with that outcome for `retention.mutationsDays`.
|
|
104
|
+
A repeat that finds a claim still being written answers `retry` — that is how two tabs sending the same push end in one
|
|
105
|
+
write and no false conflict. A claim older than 30 s belongs to a request that died and is taken over.
|
|
106
|
+
|
|
107
|
+
## Change order and windows
|
|
108
|
+
|
|
109
|
+
The store decides how changes are ordered (`capabilities.changeOrder`): on SQL a commit-ordered sequence (`syncSeq`) —
|
|
110
|
+
no repeats; on MongoDB the server clock (`syncAt`) with a window W below each run's start — records changed within W
|
|
111
|
+
are delivered again, clients keep the higher `version`. W is derived: replica set or sharded cluster — the server's
|
|
112
|
+
`transactionLifetimeLimitSeconds` (60 when unreadable) + 30 s; standalone — 30 s. `sync.pull.windowSeconds` overrides
|
|
113
|
+
it; it must cover the longest time a write can take from its stamp until it is visible.
|
|
114
|
+
|
|
115
|
+
On MySQL / MariaDB the change numbers come from triggers the owner account (`database.ownerUrl`) creates at boot. With
|
|
116
|
+
binary logging on — the MySQL 8.4 default — that needs `SUPER` or `log_bin_trust_function_creators=1` on the server
|
|
117
|
+
(the parameter group on managed MySQL), otherwise the boot stops with error 1419. The application account needs
|
|
118
|
+
neither.
|
|
119
|
+
|
|
120
|
+
## Hints
|
|
121
|
+
|
|
122
|
+
A hint tells a connected client that pulling is worthwhile; sync works without them (protocol §9).
|
|
123
|
+
|
|
124
|
+
- **Source:** every successful `create()` / `update()` / `delete()` of the model's `CrudService` — on every database,
|
|
125
|
+
no change feed. A write past it (the data store, the native API, a migration) calls
|
|
126
|
+
`CoreSyncService.notifyChange(model, tenantIds)`, or clients learn of it at their next pull.
|
|
127
|
+
- **Content:** `{ model, at }` only. **Recipients:** callers with the model's pull roles and, on a tenant-scoped model,
|
|
128
|
+
only for changes in their own tenants (the validated `X-Tenant-Id`, without it every membership). `models` narrows a
|
|
129
|
+
channel; a name that is not offered never matches and reveals nothing.
|
|
130
|
+
- **Bursts:** one hint per model and tenant per `hints.debounceMs`, already at the sender. **Replicas:** with `redis`
|
|
131
|
+
every replica receives every hint through one channel and delivers it to its own subscribers; without Redis a hint
|
|
132
|
+
stays on its replica.
|
|
133
|
+
- **Long-lived channels are re-checked:** the GraphQL subscription runs on the WebSocket `CoreModule` re-checks; an SSE
|
|
134
|
+
stream is registered in the same registry and ends at once on an invalidation naming the caller or their tenant, and
|
|
135
|
+
otherwise before the first hint after `graphQl.subscriptionRevalidationMs` — the EventSource reconnects (`retry`) and
|
|
136
|
+
the new request passes the guards. A client pulls once after every (re)connect.
|
|
137
|
+
|
|
138
|
+
## Tombstone purge
|
|
139
|
+
|
|
140
|
+
Every hour, on one replica (a lease: Redis, else the SQL lease table, else `cron-locks` in MongoDB), each model's
|
|
141
|
+
horizon moves to `retention.tombstonesDays` ago **first**, then the older tombstones are deleted for good. A client
|
|
142
|
+
whose cursor is older than the horizon answers its next pull with `410 horizon` and resyncs; nothing is skipped.
|
|
143
|
+
The tombstones go in batches of 1000, read by id and deleted by id: one statement over the whole table would lock
|
|
144
|
+
every row it scans on MySQL / MariaDB and hold up every write of the model.
|
|
145
|
+
`CoreSyncService.purgeTombstones({ before?, model? })` runs it on demand.
|
|
146
|
+
|
|
147
|
+
## Data migrations on a synchronized SQL table
|
|
148
|
+
|
|
149
|
+
A multi-row write in a migration goes through `runSqlMigration()` as a `syncUpdate`, never as a plain `UPDATE`:
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
await runSqlMigration(ownerUrl, [
|
|
153
|
+
{ syncUpdate: { table: 'sync_notes', set: "status = 'archived'", where: "created_at < '2026-01-01'" } },
|
|
154
|
+
]);
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
It locks the rows first, then takes the change numbers like the store, then writes them with `version + 1` — the order
|
|
158
|
+
that cannot deadlock with a running application on MySQL / MariaDB, and the version a client's stale edit then
|
|
159
|
+
conflicts with. On MySQL / MariaDB each `syncUpdate` runs in a transaction of its own, because a DDL statement before
|
|
160
|
+
it has already committed the migration's. `set` and `where` are reviewed SQL, like every statement of a migration.
|
|
161
|
+
|
|
162
|
+
## Infrastructure models
|
|
163
|
+
|
|
164
|
+
| Model | Collection / table | Holds |
|
|
165
|
+
| -------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
|
166
|
+
| `SyncMutation` | `syncMutations` / `sync_mutations` | Claims and outcomes of pushed mutations, `expiresAt` (TTL on MongoDB, expiry sweep on SQL; every reader checks it) |
|
|
167
|
+
| `SyncState` | `syncStates` / `sync_states` | Access epochs (`epoch:t:<model>:<tenant>`, `epoch:u:<model>:<tenant>:<user>`) and tombstone horizons (`horizon:<model>`) |
|
|
168
|
+
|
|
169
|
+
Both follow `database` like every other model.
|
|
170
|
+
|
|
171
|
+
## Extending
|
|
172
|
+
|
|
173
|
+
Override through `CoreModule.forRoot(env, { sync: { controller, hintsController, resolver, service } })`:
|
|
174
|
+
|
|
175
|
+
- **`CoreSyncService`** — every step is `protected`: `readChanges()`, `toSyncRecord()`, `accessState()`,
|
|
176
|
+
`resolveUpdateConflict()`, `writeFailure()`, …
|
|
177
|
+
- **`CoreSyncController`** — e.g. to release a scope to API tokens: extend it, re-declare `pull()` / `push()` with their
|
|
178
|
+
route decorators plus `@ApiTokenScopes('sync')`, and call `super`.
|
|
179
|
+
- **`CoreSyncHintsController`** — `GET /sync/hints`, a controller of its own that the module registers before
|
|
180
|
+
`CoreSyncController`: Nest registers a class's own routes before the inherited ones, so a re-declared `pull()`
|
|
181
|
+
(`@Get(':model')`) would otherwise read `hints` as a model name. Extend it the same way to release hints to API
|
|
182
|
+
tokens. `CoreSyncBaseController` holds what both share (`scopeTenants()`, `limit()`).
|
|
183
|
+
- **`CoreSyncResolver`** — the `syncHint` subscription.
|
|
184
|
+
- **`CoreSyncService` is global** while `sync` is configured: inject it in any project service (with `@Optional()` where
|
|
185
|
+
the project also runs without `sync`) to call `notifyChange()` / `bumpAccessEpoch()`.
|
|
186
|
+
- **Access that moves past `CrudService.update()`** (a direct store write, a migration, the native API) bumps no epoch:
|
|
187
|
+
call `CoreSyncService.bumpAccessEpoch(model, tenantId, userId?)` after such a write, or the clients concerned keep
|
|
188
|
+
their copies until their next full resync.
|