@syncular/server 0.0.1-100

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 (225) hide show
  1. package/dist/blobs/adapters/database.d.ts +83 -0
  2. package/dist/blobs/adapters/database.d.ts.map +1 -0
  3. package/dist/blobs/adapters/database.js +202 -0
  4. package/dist/blobs/adapters/database.js.map +1 -0
  5. package/dist/blobs/adapters/s3.d.ts +82 -0
  6. package/dist/blobs/adapters/s3.d.ts.map +1 -0
  7. package/dist/blobs/adapters/s3.js +170 -0
  8. package/dist/blobs/adapters/s3.js.map +1 -0
  9. package/dist/blobs/index.d.ts +9 -0
  10. package/dist/blobs/index.d.ts.map +1 -0
  11. package/dist/blobs/index.js +9 -0
  12. package/dist/blobs/index.js.map +1 -0
  13. package/dist/blobs/manager.d.ts +195 -0
  14. package/dist/blobs/manager.d.ts.map +1 -0
  15. package/dist/blobs/manager.js +440 -0
  16. package/dist/blobs/manager.js.map +1 -0
  17. package/dist/blobs/migrate.d.ts +27 -0
  18. package/dist/blobs/migrate.d.ts.map +1 -0
  19. package/dist/blobs/migrate.js +119 -0
  20. package/dist/blobs/migrate.js.map +1 -0
  21. package/dist/blobs/types.d.ts +54 -0
  22. package/dist/blobs/types.d.ts.map +1 -0
  23. package/dist/blobs/types.js +5 -0
  24. package/dist/blobs/types.js.map +1 -0
  25. package/dist/clients.d.ts +14 -0
  26. package/dist/clients.d.ts.map +1 -0
  27. package/dist/clients.js +7 -0
  28. package/dist/clients.js.map +1 -0
  29. package/dist/compaction.d.ts +27 -0
  30. package/dist/compaction.d.ts.map +1 -0
  31. package/dist/compaction.js +49 -0
  32. package/dist/compaction.js.map +1 -0
  33. package/dist/dialect/base.d.ts +83 -0
  34. package/dist/dialect/base.d.ts.map +1 -0
  35. package/dist/dialect/base.js +144 -0
  36. package/dist/dialect/base.js.map +1 -0
  37. package/dist/dialect/helpers.d.ts +10 -0
  38. package/dist/dialect/helpers.d.ts.map +1 -0
  39. package/dist/dialect/helpers.js +59 -0
  40. package/dist/dialect/helpers.js.map +1 -0
  41. package/dist/dialect/index.d.ts +7 -0
  42. package/dist/dialect/index.d.ts.map +1 -0
  43. package/dist/dialect/index.js +7 -0
  44. package/dist/dialect/index.js.map +1 -0
  45. package/dist/dialect/types.d.ts +149 -0
  46. package/dist/dialect/types.d.ts.map +1 -0
  47. package/dist/dialect/types.js +8 -0
  48. package/dist/dialect/types.js.map +1 -0
  49. package/dist/helpers/conflict.d.ts +52 -0
  50. package/dist/helpers/conflict.d.ts.map +1 -0
  51. package/dist/helpers/conflict.js +49 -0
  52. package/dist/helpers/conflict.js.map +1 -0
  53. package/dist/helpers/emitted-change.d.ts +56 -0
  54. package/dist/helpers/emitted-change.d.ts.map +1 -0
  55. package/dist/helpers/emitted-change.js +46 -0
  56. package/dist/helpers/emitted-change.js.map +1 -0
  57. package/dist/helpers/index.d.ts +10 -0
  58. package/dist/helpers/index.d.ts.map +1 -0
  59. package/dist/helpers/index.js +10 -0
  60. package/dist/helpers/index.js.map +1 -0
  61. package/dist/helpers/paginate.d.ts +49 -0
  62. package/dist/helpers/paginate.d.ts.map +1 -0
  63. package/dist/helpers/paginate.js +54 -0
  64. package/dist/helpers/paginate.js.map +1 -0
  65. package/dist/helpers/scope-strings.d.ts +74 -0
  66. package/dist/helpers/scope-strings.d.ts.map +1 -0
  67. package/dist/helpers/scope-strings.js +82 -0
  68. package/dist/helpers/scope-strings.js.map +1 -0
  69. package/dist/index.d.ts +28 -0
  70. package/dist/index.d.ts.map +1 -0
  71. package/dist/index.js +27 -0
  72. package/dist/index.js.map +1 -0
  73. package/dist/migrate.d.ts +14 -0
  74. package/dist/migrate.d.ts.map +1 -0
  75. package/dist/migrate.js +13 -0
  76. package/dist/migrate.js.map +1 -0
  77. package/dist/proxy/handler.d.ts +42 -0
  78. package/dist/proxy/handler.d.ts.map +1 -0
  79. package/dist/proxy/handler.js +102 -0
  80. package/dist/proxy/handler.js.map +1 -0
  81. package/dist/proxy/index.d.ts +9 -0
  82. package/dist/proxy/index.d.ts.map +1 -0
  83. package/dist/proxy/index.js +14 -0
  84. package/dist/proxy/index.js.map +1 -0
  85. package/dist/proxy/mutation-detector.d.ts +35 -0
  86. package/dist/proxy/mutation-detector.d.ts.map +1 -0
  87. package/dist/proxy/mutation-detector.js +246 -0
  88. package/dist/proxy/mutation-detector.js.map +1 -0
  89. package/dist/proxy/oplog.d.ts +30 -0
  90. package/dist/proxy/oplog.d.ts.map +1 -0
  91. package/dist/proxy/oplog.js +110 -0
  92. package/dist/proxy/oplog.js.map +1 -0
  93. package/dist/proxy/registry.d.ts +35 -0
  94. package/dist/proxy/registry.d.ts.map +1 -0
  95. package/dist/proxy/registry.js +49 -0
  96. package/dist/proxy/registry.js.map +1 -0
  97. package/dist/proxy/types.d.ts +44 -0
  98. package/dist/proxy/types.d.ts.map +1 -0
  99. package/dist/proxy/types.js +7 -0
  100. package/dist/proxy/types.js.map +1 -0
  101. package/dist/prune.d.ts +37 -0
  102. package/dist/prune.d.ts.map +1 -0
  103. package/dist/prune.js +112 -0
  104. package/dist/prune.js.map +1 -0
  105. package/dist/pull.d.ts +31 -0
  106. package/dist/pull.d.ts.map +1 -0
  107. package/dist/pull.js +608 -0
  108. package/dist/pull.js.map +1 -0
  109. package/dist/push.d.ts +33 -0
  110. package/dist/push.d.ts.map +1 -0
  111. package/dist/push.js +412 -0
  112. package/dist/push.js.map +1 -0
  113. package/dist/realtime/in-memory.d.ts +13 -0
  114. package/dist/realtime/in-memory.d.ts.map +1 -0
  115. package/dist/realtime/in-memory.js +28 -0
  116. package/dist/realtime/in-memory.js.map +1 -0
  117. package/dist/realtime/index.d.ts +3 -0
  118. package/dist/realtime/index.d.ts.map +1 -0
  119. package/dist/realtime/index.js +2 -0
  120. package/dist/realtime/index.js.map +1 -0
  121. package/dist/realtime/types.d.ts +50 -0
  122. package/dist/realtime/types.d.ts.map +1 -0
  123. package/dist/realtime/types.js +7 -0
  124. package/dist/realtime/types.js.map +1 -0
  125. package/dist/schema.d.ts +164 -0
  126. package/dist/schema.d.ts.map +1 -0
  127. package/dist/schema.js +10 -0
  128. package/dist/schema.js.map +1 -0
  129. package/dist/shapes/create-handler.d.ts +119 -0
  130. package/dist/shapes/create-handler.d.ts.map +1 -0
  131. package/dist/shapes/create-handler.js +327 -0
  132. package/dist/shapes/create-handler.js.map +1 -0
  133. package/dist/shapes/index.d.ts +4 -0
  134. package/dist/shapes/index.d.ts.map +1 -0
  135. package/dist/shapes/index.js +4 -0
  136. package/dist/shapes/index.js.map +1 -0
  137. package/dist/shapes/registry.d.ts +20 -0
  138. package/dist/shapes/registry.d.ts.map +1 -0
  139. package/dist/shapes/registry.js +88 -0
  140. package/dist/shapes/registry.js.map +1 -0
  141. package/dist/shapes/types.d.ts +204 -0
  142. package/dist/shapes/types.d.ts.map +1 -0
  143. package/dist/shapes/types.js +2 -0
  144. package/dist/shapes/types.js.map +1 -0
  145. package/dist/snapshot-chunks/adapters/s3.d.ts +74 -0
  146. package/dist/snapshot-chunks/adapters/s3.d.ts.map +1 -0
  147. package/dist/snapshot-chunks/adapters/s3.js +50 -0
  148. package/dist/snapshot-chunks/adapters/s3.js.map +1 -0
  149. package/dist/snapshot-chunks/db-metadata.d.ts +38 -0
  150. package/dist/snapshot-chunks/db-metadata.d.ts.map +1 -0
  151. package/dist/snapshot-chunks/db-metadata.js +324 -0
  152. package/dist/snapshot-chunks/db-metadata.js.map +1 -0
  153. package/dist/snapshot-chunks/index.d.ts +9 -0
  154. package/dist/snapshot-chunks/index.d.ts.map +1 -0
  155. package/dist/snapshot-chunks/index.js +9 -0
  156. package/dist/snapshot-chunks/index.js.map +1 -0
  157. package/dist/snapshot-chunks/types.d.ts +78 -0
  158. package/dist/snapshot-chunks/types.d.ts.map +1 -0
  159. package/dist/snapshot-chunks/types.js +8 -0
  160. package/dist/snapshot-chunks/types.js.map +1 -0
  161. package/dist/snapshot-chunks.d.ts +60 -0
  162. package/dist/snapshot-chunks.d.ts.map +1 -0
  163. package/dist/snapshot-chunks.js +223 -0
  164. package/dist/snapshot-chunks.js.map +1 -0
  165. package/dist/stats.d.ts +19 -0
  166. package/dist/stats.d.ts.map +1 -0
  167. package/dist/stats.js +57 -0
  168. package/dist/stats.js.map +1 -0
  169. package/dist/subscriptions/index.d.ts +2 -0
  170. package/dist/subscriptions/index.d.ts.map +1 -0
  171. package/dist/subscriptions/index.js +2 -0
  172. package/dist/subscriptions/index.js.map +1 -0
  173. package/dist/subscriptions/resolve.d.ts +35 -0
  174. package/dist/subscriptions/resolve.d.ts.map +1 -0
  175. package/dist/subscriptions/resolve.js +134 -0
  176. package/dist/subscriptions/resolve.js.map +1 -0
  177. package/package.json +80 -0
  178. package/src/blobs/adapters/database.test.ts +67 -0
  179. package/src/blobs/adapters/database.ts +315 -0
  180. package/src/blobs/adapters/s3.ts +271 -0
  181. package/src/blobs/index.ts +9 -0
  182. package/src/blobs/manager.ts +600 -0
  183. package/src/blobs/migrate.ts +150 -0
  184. package/src/blobs/types.ts +70 -0
  185. package/src/clients.ts +21 -0
  186. package/src/compaction.ts +77 -0
  187. package/src/dialect/base.ts +292 -0
  188. package/src/dialect/helpers.ts +61 -0
  189. package/src/dialect/index.ts +7 -0
  190. package/src/dialect/types.ts +197 -0
  191. package/src/helpers/conflict.ts +64 -0
  192. package/src/helpers/emitted-change.ts +69 -0
  193. package/src/helpers/index.ts +10 -0
  194. package/src/helpers/paginate.ts +82 -0
  195. package/src/helpers/scope-strings.ts +101 -0
  196. package/src/index.ts +28 -0
  197. package/src/migrate.ts +20 -0
  198. package/src/proxy/handler.test.ts +120 -0
  199. package/src/proxy/handler.ts +159 -0
  200. package/src/proxy/index.ts +18 -0
  201. package/src/proxy/mutation-detector.test.ts +71 -0
  202. package/src/proxy/mutation-detector.ts +281 -0
  203. package/src/proxy/oplog.ts +146 -0
  204. package/src/proxy/registry.ts +56 -0
  205. package/src/proxy/types.ts +46 -0
  206. package/src/prune.ts +200 -0
  207. package/src/pull.ts +858 -0
  208. package/src/push.ts +583 -0
  209. package/src/realtime/in-memory.ts +33 -0
  210. package/src/realtime/index.ts +5 -0
  211. package/src/realtime/types.ts +55 -0
  212. package/src/schema.ts +172 -0
  213. package/src/shapes/create-handler.ts +590 -0
  214. package/src/shapes/index.ts +3 -0
  215. package/src/shapes/registry.ts +109 -0
  216. package/src/shapes/types.ts +267 -0
  217. package/src/snapshot-chunks/adapters/s3.ts +68 -0
  218. package/src/snapshot-chunks/db-metadata.test.ts +100 -0
  219. package/src/snapshot-chunks/db-metadata.ts +466 -0
  220. package/src/snapshot-chunks/index.ts +9 -0
  221. package/src/snapshot-chunks/types.ts +103 -0
  222. package/src/snapshot-chunks.ts +329 -0
  223. package/src/stats.ts +104 -0
  224. package/src/subscriptions/index.ts +1 -0
  225. package/src/subscriptions/resolve.ts +185 -0
@@ -0,0 +1,150 @@
1
+ /**
2
+ * @syncular/server - Blob storage migrations
3
+ *
4
+ * These migrations are separate from core sync migrations because
5
+ * blob storage is optional and may use external storage (S3/R2).
6
+ */
7
+
8
+ import type { Kysely } from 'kysely';
9
+ import { sql } from 'kysely';
10
+ import type { SyncBlobDb, SyncBlobUploadsDb } from './types';
11
+
12
+ /**
13
+ * Ensures the blob uploads tracking schema exists.
14
+ * This table is required for the blob manager regardless of storage backend.
15
+ *
16
+ * For PostgreSQL.
17
+ */
18
+ async function ensureBlobUploadsSchemaPostgres<DB extends SyncBlobUploadsDb>(
19
+ db: Kysely<DB>
20
+ ): Promise<void> {
21
+ await db.schema
22
+ .createTable('sync_blob_uploads')
23
+ .ifNotExists()
24
+ .addColumn('hash', 'text', (col) => col.primaryKey())
25
+ .addColumn('size', 'bigint', (col) => col.notNull())
26
+ .addColumn('mime_type', 'text', (col) => col.notNull())
27
+ .addColumn('status', 'text', (col) => col.notNull())
28
+ .addColumn('actor_id', 'text', (col) => col.notNull())
29
+ .addColumn('created_at', 'timestamptz', (col) =>
30
+ col.notNull().defaultTo(sql`now()`)
31
+ )
32
+ .addColumn('expires_at', 'timestamptz', (col) => col.notNull())
33
+ .addColumn('completed_at', 'timestamptz')
34
+ .execute();
35
+
36
+ await db.schema
37
+ .createIndex('idx_sync_blob_uploads_status')
38
+ .ifNotExists()
39
+ .on('sync_blob_uploads')
40
+ .columns(['status'])
41
+ .execute();
42
+
43
+ await db.schema
44
+ .createIndex('idx_sync_blob_uploads_expires_at')
45
+ .ifNotExists()
46
+ .on('sync_blob_uploads')
47
+ .columns(['expires_at'])
48
+ .execute();
49
+ }
50
+
51
+ /**
52
+ * Ensures the blob uploads tracking schema exists.
53
+ * This table is required for the blob manager regardless of storage backend.
54
+ *
55
+ * For SQLite.
56
+ */
57
+ async function ensureBlobUploadsSchemasSqlite<DB extends SyncBlobUploadsDb>(
58
+ db: Kysely<DB>
59
+ ): Promise<void> {
60
+ await db.schema
61
+ .createTable('sync_blob_uploads')
62
+ .ifNotExists()
63
+ .addColumn('hash', 'text', (col) => col.primaryKey())
64
+ .addColumn('size', 'integer', (col) => col.notNull())
65
+ .addColumn('mime_type', 'text', (col) => col.notNull())
66
+ .addColumn('status', 'text', (col) => col.notNull())
67
+ .addColumn('actor_id', 'text', (col) => col.notNull())
68
+ .addColumn('created_at', 'text', (col) =>
69
+ col.notNull().defaultTo(sql`(datetime('now'))`)
70
+ )
71
+ .addColumn('expires_at', 'text', (col) => col.notNull())
72
+ .addColumn('completed_at', 'text')
73
+ .execute();
74
+
75
+ await db.schema
76
+ .createIndex('idx_sync_blob_uploads_status')
77
+ .ifNotExists()
78
+ .on('sync_blob_uploads')
79
+ .columns(['status'])
80
+ .execute();
81
+
82
+ await db.schema
83
+ .createIndex('idx_sync_blob_uploads_expires_at')
84
+ .ifNotExists()
85
+ .on('sync_blob_uploads')
86
+ .columns(['expires_at'])
87
+ .execute();
88
+ }
89
+
90
+ /**
91
+ * Ensures the blob storage schema exists (for database adapter).
92
+ * Only needed if using the database blob storage adapter.
93
+ *
94
+ * For PostgreSQL.
95
+ */
96
+ export async function ensureBlobStorageSchemaPostgres<DB extends SyncBlobDb>(
97
+ db: Kysely<DB>
98
+ ): Promise<void> {
99
+ // First ensure uploads table
100
+ await ensureBlobUploadsSchemaPostgres(db);
101
+
102
+ // Then create blobs table
103
+ await db.schema
104
+ .createTable('sync_blobs')
105
+ .ifNotExists()
106
+ .addColumn('hash', 'text', (col) => col.primaryKey())
107
+ .addColumn('size', 'bigint', (col) => col.notNull())
108
+ .addColumn('mime_type', 'text', (col) => col.notNull())
109
+ .addColumn('body', 'bytea', (col) => col.notNull())
110
+ .addColumn('created_at', 'timestamptz', (col) =>
111
+ col.notNull().defaultTo(sql`now()`)
112
+ )
113
+ .execute();
114
+ }
115
+
116
+ /**
117
+ * Ensures the blob storage schema exists (for database adapter).
118
+ * Only needed if using the database blob storage adapter.
119
+ *
120
+ * For SQLite.
121
+ */
122
+ export async function ensureBlobStorageSchemaSqlite<DB extends SyncBlobDb>(
123
+ db: Kysely<DB>
124
+ ): Promise<void> {
125
+ // First ensure uploads table
126
+ await ensureBlobUploadsSchemasSqlite(db);
127
+
128
+ // Then create blobs table
129
+ await db.schema
130
+ .createTable('sync_blobs')
131
+ .ifNotExists()
132
+ .addColumn('hash', 'text', (col) => col.primaryKey())
133
+ .addColumn('size', 'integer', (col) => col.notNull())
134
+ .addColumn('mime_type', 'text', (col) => col.notNull())
135
+ .addColumn('body', 'blob', (col) => col.notNull())
136
+ .addColumn('created_at', 'text', (col) =>
137
+ col.notNull().defaultTo(sql`(datetime('now'))`)
138
+ )
139
+ .execute();
140
+ }
141
+
142
+ /**
143
+ * Drops the blob schema from the database.
144
+ */
145
+ export async function dropBlobSchema<DB extends SyncBlobDb>(
146
+ db: Kysely<DB>
147
+ ): Promise<void> {
148
+ await db.schema.dropTable('sync_blobs').ifExists().execute();
149
+ await db.schema.dropTable('sync_blob_uploads').ifExists().execute();
150
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @syncular/server - Blob storage types
3
+ */
4
+
5
+ import type { Generated } from 'kysely';
6
+
7
+ // ============================================================================
8
+ // Blob Upload Tracking
9
+ // ============================================================================
10
+
11
+ /**
12
+ * Blob uploads tracking table.
13
+ * Tracks initiated uploads and their completion status.
14
+ */
15
+ export interface SyncBlobUploadsTable {
16
+ /** SHA-256 hash with prefix: "sha256:<hex>" */
17
+ hash: string;
18
+ /** Expected size in bytes */
19
+ size: number;
20
+ /** MIME type */
21
+ mime_type: string;
22
+ /** Upload status */
23
+ status: 'pending' | 'complete';
24
+ /** Actor who initiated the upload */
25
+ actor_id: string;
26
+ /** When the upload was initiated */
27
+ created_at: Generated<string>;
28
+ /** When the upload expires (for cleanup of incomplete uploads) */
29
+ expires_at: string;
30
+ /** When the upload was completed */
31
+ completed_at: string | null;
32
+ }
33
+
34
+ export interface SyncBlobUploadsDb {
35
+ sync_blob_uploads: SyncBlobUploadsTable;
36
+ }
37
+
38
+ // ============================================================================
39
+ // Blob Storage (Database Adapter)
40
+ // ============================================================================
41
+
42
+ /**
43
+ * Blob storage table (for database adapter).
44
+ * Stores blob content directly in the database.
45
+ */
46
+ export interface SyncBlobsTable {
47
+ /** SHA-256 hash with prefix: "sha256:<hex>" */
48
+ hash: string;
49
+ /** Size in bytes */
50
+ size: number;
51
+ /** MIME type */
52
+ mime_type: string;
53
+ /** Blob content */
54
+ body: Uint8Array;
55
+ /** When the blob was created */
56
+ created_at: Generated<string>;
57
+ }
58
+
59
+ export interface SyncBlobsDb {
60
+ sync_blobs: SyncBlobsTable;
61
+ }
62
+
63
+ // ============================================================================
64
+ // Combined DB Interface
65
+ // ============================================================================
66
+
67
+ /**
68
+ * Full database interface for blob storage.
69
+ */
70
+ export interface SyncBlobDb extends SyncBlobUploadsDb, SyncBlobsDb {}
package/src/clients.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @syncular/server - Client cursor tracking
3
+ */
4
+
5
+ import type { ScopeValues } from '@syncular/core';
6
+ import type { DbExecutor, ServerSyncDialect } from './dialect/types';
7
+ import type { SyncCoreDb } from './schema';
8
+
9
+ export async function recordClientCursor<DB extends SyncCoreDb>(
10
+ db: DbExecutor<DB>,
11
+ dialect: ServerSyncDialect,
12
+ args: {
13
+ partitionId?: string;
14
+ clientId: string;
15
+ actorId: string;
16
+ cursor: number;
17
+ effectiveScopes: ScopeValues;
18
+ }
19
+ ): Promise<void> {
20
+ await dialect.recordClientCursor(db, args);
21
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @syncular/server - Change-log compaction utilities
3
+ *
4
+ * Compaction reduces storage by deleting intermediate history while preserving
5
+ * the newest change per (shape, table_name, row_id, scope_key) for older data.
6
+ *
7
+ * Dialect-specific implementation lives in `ServerSyncDialect.compactChanges`.
8
+ */
9
+
10
+ import type { DbExecutor, ServerSyncDialect } from './dialect/types';
11
+ import type { SyncCoreDb } from './schema';
12
+
13
+ export interface CompactOptions {
14
+ /**
15
+ * Keep full (non-compacted) history for the most recent N hours.
16
+ * Older history may be compacted depending on dialect strategy.
17
+ */
18
+ fullHistoryHours: number;
19
+ }
20
+
21
+ export async function compactChanges<DB extends SyncCoreDb>(
22
+ db: DbExecutor<DB>,
23
+ args: { dialect: ServerSyncDialect; options: CompactOptions }
24
+ ): Promise<number> {
25
+ const fullHistoryHours = Math.max(0, args.options.fullHistoryHours);
26
+ if (fullHistoryHours <= 0) return 0;
27
+ return args.dialect.compactChanges(db, { fullHistoryHours });
28
+ }
29
+
30
+ interface CompactState {
31
+ lastCompactAtMs: number;
32
+ compactInFlight: Promise<number> | null;
33
+ }
34
+
35
+ const compactStateByDb = new WeakMap<object, CompactState>();
36
+
37
+ function getCompactState(db: object): CompactState {
38
+ const existing = compactStateByDb.get(db);
39
+ if (existing) return existing;
40
+
41
+ const created: CompactState = {
42
+ lastCompactAtMs: 0,
43
+ compactInFlight: null,
44
+ };
45
+ compactStateByDb.set(db, created);
46
+ return created;
47
+ }
48
+
49
+ export async function maybeCompactChanges<DB extends SyncCoreDb>(
50
+ db: DbExecutor<DB>,
51
+ args: {
52
+ dialect: ServerSyncDialect;
53
+ minIntervalMs: number;
54
+ options: CompactOptions;
55
+ }
56
+ ): Promise<number> {
57
+ const state = getCompactState(db);
58
+ const now = Date.now();
59
+ if (now - state.lastCompactAtMs < args.minIntervalMs) return 0;
60
+
61
+ if (state.compactInFlight) return state.compactInFlight;
62
+
63
+ state.compactInFlight = (async () => {
64
+ try {
65
+ const deleted = await compactChanges(db, {
66
+ dialect: args.dialect,
67
+ options: args.options,
68
+ });
69
+ state.lastCompactAtMs = Date.now();
70
+ return deleted;
71
+ } finally {
72
+ state.compactInFlight = null;
73
+ }
74
+ })();
75
+
76
+ return state.compactInFlight;
77
+ }
@@ -0,0 +1,292 @@
1
+ /**
2
+ * @syncular/server - Base Server Sync Dialect
3
+ *
4
+ * Abstract base class that implements shared query methods for all
5
+ * database-specific sync dialect implementations.
6
+ */
7
+
8
+ import type { ScopeValues, StoredScopes } from '@syncular/core';
9
+ import type { Kysely, RawBuilder, Transaction } from 'kysely';
10
+ import { sql } from 'kysely';
11
+ import type { SyncChangeRow, SyncCommitRow, SyncCoreDb } from '../schema';
12
+ import { coerceIsoString, coerceNumber, parseScopes } from './helpers';
13
+ import type {
14
+ DbExecutor,
15
+ IncrementalPullRow,
16
+ IncrementalPullRowsArgs,
17
+ ServerSyncDialect,
18
+ } from './types';
19
+
20
+ /**
21
+ * Abstract base class for server sync dialects.
22
+ *
23
+ * Implements methods that are identical across dialects (pure SQL with no
24
+ * dialect-specific syntax) and methods that differ only in trivial SQL
25
+ * fragments (IN vs ANY, jsonb casts). Dialect-specific fragments are
26
+ * provided via small abstract hook methods.
27
+ *
28
+ * Genuinely different methods (DDL, transaction control, scope filtering,
29
+ * compaction) remain abstract for each dialect to implement.
30
+ */
31
+ export abstract class BaseServerSyncDialect implements ServerSyncDialect {
32
+ abstract readonly name: string;
33
+ abstract readonly supportsForUpdate: boolean;
34
+ abstract readonly supportsSavepoints: boolean;
35
+
36
+ // ===========================================================================
37
+ // Abstract SQL fragment hooks
38
+ // ===========================================================================
39
+
40
+ /**
41
+ * Build a SQL fragment for "column IN/= list of numbers".
42
+ * SQLite: `IN (1, 2, 3)` via sql.join
43
+ * Postgres: `= ANY(ARRAY[1,2,3]::bigint[])`
44
+ */
45
+ protected abstract buildNumberListFilter(
46
+ values: number[]
47
+ ): RawBuilder<unknown>;
48
+
49
+ /**
50
+ * Build a SQL fragment for "column IN/= list of strings".
51
+ * SQLite: `IN ('a', 'b')` via sql.join
52
+ * Postgres: `= ANY(ARRAY['a','b']::text[])`
53
+ */
54
+ protected abstract buildStringListFilter(
55
+ values: string[]
56
+ ): RawBuilder<unknown>;
57
+
58
+ // ===========================================================================
59
+ // Abstract methods (genuinely different implementations)
60
+ // ===========================================================================
61
+
62
+ abstract ensureSyncSchema<DB extends SyncCoreDb>(
63
+ db: Kysely<DB>
64
+ ): Promise<void>;
65
+
66
+ abstract ensureConsoleSchema?<DB extends SyncCoreDb>(
67
+ db: Kysely<DB>
68
+ ): Promise<void>;
69
+
70
+ abstract executeInTransaction<DB extends SyncCoreDb, T>(
71
+ db: Kysely<DB>,
72
+ fn: (executor: DbExecutor<DB>) => Promise<T>
73
+ ): Promise<T>;
74
+
75
+ abstract setRepeatableRead<DB extends SyncCoreDb>(
76
+ trx: DbExecutor<DB>
77
+ ): Promise<void>;
78
+
79
+ abstract readChangesForCommits<DB extends SyncCoreDb>(
80
+ db: DbExecutor<DB>,
81
+ args: {
82
+ commitSeqs: number[];
83
+ table: string;
84
+ scopes: ScopeValues;
85
+ partitionId?: string;
86
+ }
87
+ ): Promise<SyncChangeRow[]>;
88
+
89
+ protected abstract readIncrementalPullRowsBatch<DB extends SyncCoreDb>(
90
+ db: DbExecutor<DB>,
91
+ args: Omit<IncrementalPullRowsArgs, 'batchSize'>
92
+ ): Promise<IncrementalPullRow[]>;
93
+
94
+ abstract compactChanges<DB extends SyncCoreDb>(
95
+ db: DbExecutor<DB>,
96
+ args: { fullHistoryHours: number }
97
+ ): Promise<number>;
98
+
99
+ abstract scopesToDb(scopes: StoredScopes): unknown;
100
+ abstract dbToArray(value: unknown): string[];
101
+ abstract arrayToDb(values: string[]): unknown;
102
+
103
+ // ===========================================================================
104
+ // Concrete methods (identical SQL across dialects)
105
+ // ===========================================================================
106
+
107
+ async readMaxCommitSeq<DB extends SyncCoreDb>(
108
+ db: Kysely<DB> | Transaction<DB>,
109
+ options?: { partitionId?: string }
110
+ ): Promise<number> {
111
+ const partitionId = options?.partitionId ?? 'default';
112
+ const res = await sql<{ max_seq: unknown }>`
113
+ SELECT max(commit_seq) as max_seq
114
+ FROM sync_commits
115
+ WHERE partition_id = ${partitionId}
116
+ `.execute(db);
117
+
118
+ return coerceNumber(res.rows[0]?.max_seq) ?? 0;
119
+ }
120
+
121
+ async readMinCommitSeq<DB extends SyncCoreDb>(
122
+ db: Kysely<DB> | Transaction<DB>,
123
+ options?: { partitionId?: string }
124
+ ): Promise<number> {
125
+ const partitionId = options?.partitionId ?? 'default';
126
+ const res = await sql<{ min_seq: unknown }>`
127
+ SELECT min(commit_seq) as min_seq
128
+ FROM sync_commits
129
+ WHERE partition_id = ${partitionId}
130
+ `.execute(db);
131
+
132
+ return coerceNumber(res.rows[0]?.min_seq) ?? 0;
133
+ }
134
+
135
+ async readAffectedTablesFromChanges<DB extends SyncCoreDb>(
136
+ db: Kysely<DB> | Transaction<DB>,
137
+ commitSeq: number,
138
+ options?: { partitionId?: string }
139
+ ): Promise<string[]> {
140
+ const partitionId = options?.partitionId ?? 'default';
141
+ const res = await sql<{ table: string }>`
142
+ SELECT DISTINCT "table"
143
+ FROM sync_changes
144
+ WHERE commit_seq = ${commitSeq}
145
+ AND partition_id = ${partitionId}
146
+ `.execute(db);
147
+
148
+ return res.rows
149
+ .map((r) => r.table)
150
+ .filter((t): t is string => typeof t === 'string' && t.length > 0);
151
+ }
152
+
153
+ dbToScopes(value: unknown): StoredScopes {
154
+ return parseScopes(value);
155
+ }
156
+
157
+ // ===========================================================================
158
+ // Concrete methods using hooks (trivial dialect diffs)
159
+ // ===========================================================================
160
+
161
+ async readCommitSeqsForPull<DB extends SyncCoreDb>(
162
+ db: Kysely<DB> | Transaction<DB>,
163
+ args: {
164
+ cursor: number;
165
+ limitCommits: number;
166
+ tables: string[];
167
+ partitionId?: string;
168
+ }
169
+ ): Promise<number[]> {
170
+ const partitionId = args.partitionId ?? 'default';
171
+ if (args.tables.length === 0) return [];
172
+
173
+ const tablesFilter = this.buildStringListFilter(args.tables);
174
+
175
+ const res = await sql<{ commit_seq: unknown }>`
176
+ SELECT DISTINCT commit_seq
177
+ FROM sync_table_commits
178
+ WHERE partition_id = ${partitionId}
179
+ AND "table" ${tablesFilter}
180
+ AND commit_seq > ${args.cursor}
181
+ ORDER BY commit_seq ASC
182
+ LIMIT ${args.limitCommits}
183
+ `.execute(db);
184
+
185
+ return res.rows
186
+ .map((r) => coerceNumber(r.commit_seq))
187
+ .filter(
188
+ (n): n is number =>
189
+ typeof n === 'number' && Number.isFinite(n) && n > args.cursor
190
+ );
191
+ }
192
+
193
+ async readCommits<DB extends SyncCoreDb>(
194
+ db: Kysely<DB> | Transaction<DB>,
195
+ commitSeqs: number[],
196
+ options?: { partitionId?: string }
197
+ ): Promise<SyncCommitRow[]> {
198
+ const partitionId = options?.partitionId ?? 'default';
199
+ if (commitSeqs.length === 0) return [];
200
+
201
+ const seqsFilter = this.buildNumberListFilter(commitSeqs);
202
+
203
+ const res = await sql<{
204
+ commit_seq: unknown;
205
+ actor_id: string;
206
+ created_at: unknown;
207
+ result_json: unknown | null;
208
+ }>`
209
+ SELECT commit_seq, actor_id, created_at, result_json
210
+ FROM sync_commits
211
+ WHERE commit_seq ${seqsFilter}
212
+ AND partition_id = ${partitionId}
213
+ ORDER BY commit_seq ASC
214
+ `.execute(db);
215
+
216
+ return res.rows.map((row) => ({
217
+ commit_seq: coerceNumber(row.commit_seq) ?? 0,
218
+ actor_id: row.actor_id,
219
+ created_at: coerceIsoString(row.created_at),
220
+ result_json: row.result_json ?? null,
221
+ }));
222
+ }
223
+
224
+ async recordClientCursor<DB extends SyncCoreDb>(
225
+ db: Kysely<DB> | Transaction<DB>,
226
+ args: {
227
+ partitionId?: string;
228
+ clientId: string;
229
+ actorId: string;
230
+ cursor: number;
231
+ effectiveScopes: ScopeValues;
232
+ }
233
+ ): Promise<void> {
234
+ const partitionId = args.partitionId ?? 'default';
235
+ const now = new Date().toISOString();
236
+ const scopesJson = JSON.stringify(args.effectiveScopes);
237
+
238
+ await sql`
239
+ INSERT INTO sync_client_cursors (partition_id, client_id, actor_id, cursor, effective_scopes, updated_at)
240
+ VALUES (${partitionId}, ${args.clientId}, ${args.actorId}, ${args.cursor}, ${scopesJson}, ${now})
241
+ ON CONFLICT(partition_id, client_id) DO UPDATE SET
242
+ actor_id = ${args.actorId},
243
+ cursor = ${args.cursor},
244
+ effective_scopes = ${scopesJson},
245
+ updated_at = ${now}
246
+ `.execute(db);
247
+ }
248
+
249
+ async *iterateIncrementalPullRows<DB extends SyncCoreDb>(
250
+ db: DbExecutor<DB>,
251
+ args: IncrementalPullRowsArgs
252
+ ): AsyncGenerator<IncrementalPullRow> {
253
+ const limitCommits = Math.max(1, Math.min(500, args.limitCommits));
254
+ const batchSize = Math.max(
255
+ 1,
256
+ Math.min(limitCommits, args.batchSize ?? 100, 500)
257
+ );
258
+
259
+ let processedCommits = 0;
260
+ let cursor = args.cursor;
261
+
262
+ while (processedCommits < limitCommits) {
263
+ const remainingCommits = limitCommits - processedCommits;
264
+ const commitLimit = Math.min(batchSize, remainingCommits);
265
+ const rows = await this.readIncrementalPullRowsBatch(db, {
266
+ table: args.table,
267
+ scopes: args.scopes,
268
+ cursor,
269
+ limitCommits: commitLimit,
270
+ partitionId: args.partitionId,
271
+ });
272
+
273
+ if (rows.length === 0) break;
274
+
275
+ let maxCommitSeq = cursor;
276
+ const commitSeqs = new Set<number>();
277
+
278
+ for (const row of rows) {
279
+ maxCommitSeq = Math.max(maxCommitSeq, row.commit_seq);
280
+ commitSeqs.add(row.commit_seq);
281
+ yield row;
282
+ }
283
+
284
+ if (maxCommitSeq <= cursor) break;
285
+
286
+ processedCommits += commitSeqs.size;
287
+ cursor = maxCommitSeq;
288
+
289
+ if (commitSeqs.size < commitLimit) break;
290
+ }
291
+ }
292
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @syncular/server - Shared dialect helpers
3
+ *
4
+ * Pure helper functions used by all server sync dialect implementations.
5
+ */
6
+
7
+ import type { StoredScopes } from '@syncular/core';
8
+
9
+ export function coerceNumber(value: unknown): number | null {
10
+ if (value === null || value === undefined) return null;
11
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
12
+ if (typeof value === 'bigint')
13
+ return Number.isFinite(Number(value)) ? Number(value) : null;
14
+ if (typeof value === 'string') {
15
+ const n = Number(value);
16
+ return Number.isFinite(n) ? n : null;
17
+ }
18
+ return null;
19
+ }
20
+
21
+ export function coerceIsoString(value: unknown): string {
22
+ if (typeof value === 'string') return value;
23
+ if (value instanceof Date) return value.toISOString();
24
+ return String(value);
25
+ }
26
+
27
+ export function parseScopes(value: unknown): StoredScopes {
28
+ if (value === null || value === undefined) return {};
29
+ if (typeof value === 'object' && !Array.isArray(value)) {
30
+ const result: StoredScopes = {};
31
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
32
+ if (typeof v === 'string') {
33
+ result[k] = v;
34
+ }
35
+ }
36
+ return result;
37
+ }
38
+ if (typeof value === 'string') {
39
+ try {
40
+ const parsed = JSON.parse(value);
41
+ if (
42
+ typeof parsed === 'object' &&
43
+ parsed !== null &&
44
+ !Array.isArray(parsed)
45
+ ) {
46
+ const result: StoredScopes = {};
47
+ for (const [k, v] of Object.entries(
48
+ parsed as Record<string, unknown>
49
+ )) {
50
+ if (typeof v === 'string') {
51
+ result[k] = v;
52
+ }
53
+ }
54
+ return result;
55
+ }
56
+ } catch {
57
+ // ignore
58
+ }
59
+ }
60
+ return {};
61
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @syncular/server - Dialect exports
3
+ */
4
+
5
+ export * from './base';
6
+ export * from './helpers';
7
+ export * from './types';