@powersync/service-core 0.0.0-dev-20240718134716 → 0.0.0-dev-20240918082156

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 (352) hide show
  1. package/CHANGELOG.md +89 -6
  2. package/dist/api/RouteAPI.d.ts +68 -0
  3. package/dist/api/RouteAPI.js +2 -0
  4. package/dist/api/RouteAPI.js.map +1 -0
  5. package/dist/api/api-index.d.ts +1 -0
  6. package/dist/api/api-index.js +1 -0
  7. package/dist/api/api-index.js.map +1 -1
  8. package/dist/api/diagnostics.d.ts +4 -4
  9. package/dist/api/diagnostics.js +11 -65
  10. package/dist/api/diagnostics.js.map +1 -1
  11. package/dist/api/schema.d.ts +3 -5
  12. package/dist/api/schema.js +9 -79
  13. package/dist/api/schema.js.map +1 -1
  14. package/dist/auth/KeyStore.d.ts +7 -4
  15. package/dist/auth/KeyStore.js +1 -1
  16. package/dist/auth/KeyStore.js.map +1 -1
  17. package/dist/auth/auth-index.d.ts +0 -1
  18. package/dist/auth/auth-index.js +0 -1
  19. package/dist/auth/auth-index.js.map +1 -1
  20. package/dist/entry/cli-entry.js +4 -2
  21. package/dist/entry/cli-entry.js.map +1 -1
  22. package/dist/entry/commands/compact-action.d.ts +2 -0
  23. package/dist/entry/commands/compact-action.js +52 -0
  24. package/dist/entry/commands/compact-action.js.map +1 -0
  25. package/dist/entry/commands/migrate-action.js +4 -5
  26. package/dist/entry/commands/migrate-action.js.map +1 -1
  27. package/dist/entry/commands/teardown-action.js +2 -2
  28. package/dist/entry/commands/teardown-action.js.map +1 -1
  29. package/dist/entry/entry-index.d.ts +1 -0
  30. package/dist/entry/entry-index.js +1 -0
  31. package/dist/entry/entry-index.js.map +1 -1
  32. package/dist/index.d.ts +4 -2
  33. package/dist/index.js +4 -2
  34. package/dist/index.js.map +1 -1
  35. package/dist/metrics/Metrics.d.ts +6 -5
  36. package/dist/metrics/Metrics.js +53 -10
  37. package/dist/metrics/Metrics.js.map +1 -1
  38. package/dist/migrations/db/migrations/1684951997326-init.d.ts +2 -2
  39. package/dist/migrations/db/migrations/1684951997326-init.js +4 -2
  40. package/dist/migrations/db/migrations/1684951997326-init.js.map +1 -1
  41. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.d.ts +2 -2
  42. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.js +4 -2
  43. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.js.map +1 -1
  44. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.d.ts +2 -2
  45. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.js +4 -2
  46. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.js.map +1 -1
  47. package/dist/migrations/migrations.d.ts +8 -0
  48. package/dist/migrations/migrations.js +19 -7
  49. package/dist/migrations/migrations.js.map +1 -1
  50. package/dist/modules/AbstractModule.d.ts +26 -0
  51. package/dist/modules/AbstractModule.js +11 -0
  52. package/dist/modules/AbstractModule.js.map +1 -0
  53. package/dist/modules/ModuleManager.d.ts +11 -0
  54. package/dist/modules/ModuleManager.js +32 -0
  55. package/dist/modules/ModuleManager.js.map +1 -0
  56. package/dist/modules/modules-index.d.ts +2 -0
  57. package/dist/modules/modules-index.js +3 -0
  58. package/dist/modules/modules-index.js.map +1 -0
  59. package/dist/replication/AbstractReplicationJob.d.ts +38 -0
  60. package/dist/replication/AbstractReplicationJob.js +51 -0
  61. package/dist/replication/AbstractReplicationJob.js.map +1 -0
  62. package/dist/replication/AbstractReplicator.d.ts +53 -0
  63. package/dist/replication/AbstractReplicator.js +187 -0
  64. package/dist/replication/AbstractReplicator.js.map +1 -0
  65. package/dist/replication/ErrorRateLimiter.d.ts +0 -9
  66. package/dist/replication/ErrorRateLimiter.js +1 -42
  67. package/dist/replication/ErrorRateLimiter.js.map +1 -1
  68. package/dist/replication/ReplicationEngine.d.ts +18 -0
  69. package/dist/replication/ReplicationEngine.js +41 -0
  70. package/dist/replication/ReplicationEngine.js.map +1 -0
  71. package/dist/replication/ReplicationModule.d.ts +39 -0
  72. package/dist/replication/ReplicationModule.js +65 -0
  73. package/dist/replication/ReplicationModule.js.map +1 -0
  74. package/dist/replication/replication-index.d.ts +4 -6
  75. package/dist/replication/replication-index.js +4 -6
  76. package/dist/replication/replication-index.js.map +1 -1
  77. package/dist/routes/RouterEngine.d.ts +42 -0
  78. package/dist/routes/RouterEngine.js +80 -0
  79. package/dist/routes/RouterEngine.js.map +1 -0
  80. package/dist/routes/auth.d.ts +2 -2
  81. package/dist/routes/auth.js +11 -11
  82. package/dist/routes/auth.js.map +1 -1
  83. package/dist/routes/configure-fastify.d.ts +737 -0
  84. package/dist/routes/configure-fastify.js +57 -0
  85. package/dist/routes/configure-fastify.js.map +1 -0
  86. package/dist/routes/configure-rsocket.d.ts +13 -0
  87. package/dist/routes/configure-rsocket.js +47 -0
  88. package/dist/routes/configure-rsocket.js.map +1 -0
  89. package/dist/routes/endpoints/admin.d.ts +0 -34
  90. package/dist/routes/endpoints/admin.js +48 -89
  91. package/dist/routes/endpoints/admin.js.map +1 -1
  92. package/dist/routes/endpoints/checkpointing.d.ts +56 -16
  93. package/dist/routes/endpoints/checkpointing.js +33 -12
  94. package/dist/routes/endpoints/checkpointing.js.map +1 -1
  95. package/dist/routes/endpoints/route-endpoints-index.d.ts +0 -1
  96. package/dist/routes/endpoints/route-endpoints-index.js +0 -1
  97. package/dist/routes/endpoints/route-endpoints-index.js.map +1 -1
  98. package/dist/routes/endpoints/socket-route.js +46 -39
  99. package/dist/routes/endpoints/socket-route.js.map +1 -1
  100. package/dist/routes/endpoints/sync-rules.d.ts +1 -1
  101. package/dist/routes/endpoints/sync-rules.js +32 -23
  102. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  103. package/dist/routes/endpoints/sync-stream.d.ts +10 -0
  104. package/dist/routes/endpoints/sync-stream.js +17 -13
  105. package/dist/routes/endpoints/sync-stream.js.map +1 -1
  106. package/dist/routes/route-register.d.ts +1 -1
  107. package/dist/routes/route-register.js +1 -1
  108. package/dist/routes/route-register.js.map +1 -1
  109. package/dist/routes/router-socket.d.ts +5 -4
  110. package/dist/routes/router-socket.js +2 -1
  111. package/dist/routes/router-socket.js.map +1 -1
  112. package/dist/routes/router.d.ts +7 -2
  113. package/dist/routes/router.js.map +1 -1
  114. package/dist/routes/routes-index.d.ts +3 -0
  115. package/dist/routes/routes-index.js +3 -0
  116. package/dist/routes/routes-index.js.map +1 -1
  117. package/dist/runner/teardown.js +47 -76
  118. package/dist/runner/teardown.js.map +1 -1
  119. package/dist/storage/BucketStorage.d.ts +61 -20
  120. package/dist/storage/BucketStorage.js +0 -10
  121. package/dist/storage/BucketStorage.js.map +1 -1
  122. package/dist/storage/MongoBucketStorage.d.ts +4 -4
  123. package/dist/storage/MongoBucketStorage.js +19 -24
  124. package/dist/storage/MongoBucketStorage.js.map +1 -1
  125. package/dist/storage/SourceEntity.d.ts +20 -0
  126. package/dist/storage/SourceEntity.js +2 -0
  127. package/dist/storage/SourceEntity.js.map +1 -0
  128. package/dist/storage/SourceTable.d.ts +4 -5
  129. package/dist/storage/SourceTable.js +3 -4
  130. package/dist/storage/SourceTable.js.map +1 -1
  131. package/dist/storage/StorageEngine.d.ts +24 -0
  132. package/dist/storage/StorageEngine.js +43 -0
  133. package/dist/storage/StorageEngine.js.map +1 -0
  134. package/dist/storage/StorageProvider.d.ts +21 -0
  135. package/dist/storage/StorageProvider.js +2 -0
  136. package/dist/storage/StorageProvider.js.map +1 -0
  137. package/dist/storage/mongo/MongoBucketBatch.d.ts +1 -1
  138. package/dist/storage/mongo/MongoBucketBatch.js +6 -7
  139. package/dist/storage/mongo/MongoBucketBatch.js.map +1 -1
  140. package/dist/storage/mongo/MongoCompactor.d.ts +40 -0
  141. package/dist/storage/mongo/MongoCompactor.js +293 -0
  142. package/dist/storage/mongo/MongoCompactor.js.map +1 -0
  143. package/dist/storage/mongo/MongoPersistedSyncRulesContent.d.ts +2 -2
  144. package/dist/storage/mongo/MongoPersistedSyncRulesContent.js +2 -2
  145. package/dist/storage/mongo/MongoPersistedSyncRulesContent.js.map +1 -1
  146. package/dist/storage/mongo/MongoStorageProvider.d.ts +5 -0
  147. package/dist/storage/mongo/MongoStorageProvider.js +26 -0
  148. package/dist/storage/mongo/MongoStorageProvider.js.map +1 -0
  149. package/dist/storage/mongo/MongoSyncBucketStorage.d.ts +9 -7
  150. package/dist/storage/mongo/MongoSyncBucketStorage.js +43 -28
  151. package/dist/storage/mongo/MongoSyncBucketStorage.js.map +1 -1
  152. package/dist/storage/mongo/MongoSyncRulesLock.js +1 -1
  153. package/dist/storage/mongo/MongoSyncRulesLock.js.map +1 -1
  154. package/dist/storage/mongo/OperationBatch.d.ts +7 -3
  155. package/dist/storage/mongo/OperationBatch.js +16 -7
  156. package/dist/storage/mongo/OperationBatch.js.map +1 -1
  157. package/dist/storage/mongo/PersistedBatch.d.ts +3 -3
  158. package/dist/storage/mongo/PersistedBatch.js +2 -2
  159. package/dist/storage/mongo/PersistedBatch.js.map +1 -1
  160. package/dist/storage/mongo/models.d.ts +17 -7
  161. package/dist/storage/mongo/models.js.map +1 -1
  162. package/dist/storage/mongo/util.d.ts +14 -0
  163. package/dist/storage/mongo/util.js +70 -0
  164. package/dist/storage/mongo/util.js.map +1 -1
  165. package/dist/storage/storage-index.d.ts +5 -2
  166. package/dist/storage/storage-index.js +5 -2
  167. package/dist/storage/storage-index.js.map +1 -1
  168. package/dist/sync/RequestTracker.js +2 -3
  169. package/dist/sync/RequestTracker.js.map +1 -1
  170. package/dist/sync/sync-index.d.ts +1 -0
  171. package/dist/sync/sync-index.js +1 -0
  172. package/dist/sync/sync-index.js.map +1 -1
  173. package/dist/sync/sync.d.ts +2 -1
  174. package/dist/sync/sync.js +56 -17
  175. package/dist/sync/sync.js.map +1 -1
  176. package/dist/system/ServiceContext.d.ts +37 -0
  177. package/dist/system/ServiceContext.js +48 -0
  178. package/dist/system/ServiceContext.js.map +1 -0
  179. package/dist/system/system-index.d.ts +1 -1
  180. package/dist/system/system-index.js +1 -1
  181. package/dist/system/system-index.js.map +1 -1
  182. package/dist/util/config/collectors/config-collector.d.ts +12 -0
  183. package/dist/util/config/collectors/config-collector.js +43 -0
  184. package/dist/util/config/collectors/config-collector.js.map +1 -1
  185. package/dist/util/config/compound-config-collector.d.ts +10 -29
  186. package/dist/util/config/compound-config-collector.js +28 -84
  187. package/dist/util/config/compound-config-collector.js.map +1 -1
  188. package/dist/util/config/sync-rules/sync-rules-provider.d.ts +9 -0
  189. package/dist/util/config/sync-rules/sync-rules-provider.js +15 -0
  190. package/dist/util/config/sync-rules/sync-rules-provider.js.map +1 -0
  191. package/dist/util/config/types.d.ts +6 -4
  192. package/dist/util/config/types.js.map +1 -1
  193. package/dist/util/config.d.ts +3 -4
  194. package/dist/util/config.js +5 -20
  195. package/dist/util/config.js.map +1 -1
  196. package/dist/util/protocol-types.d.ts +4 -0
  197. package/dist/util/protocol-types.js +5 -1
  198. package/dist/util/protocol-types.js.map +1 -1
  199. package/dist/util/util-index.d.ts +3 -6
  200. package/dist/util/util-index.js +3 -6
  201. package/dist/util/util-index.js.map +1 -1
  202. package/dist/util/utils.d.ts +10 -6
  203. package/dist/util/utils.js +45 -25
  204. package/dist/util/utils.js.map +1 -1
  205. package/package.json +7 -7
  206. package/src/api/RouteAPI.ts +78 -0
  207. package/src/api/api-index.ts +1 -0
  208. package/src/api/diagnostics.ts +16 -71
  209. package/src/api/schema.ts +13 -89
  210. package/src/auth/KeyStore.ts +9 -6
  211. package/src/auth/auth-index.ts +0 -1
  212. package/src/entry/cli-entry.ts +4 -2
  213. package/src/entry/commands/compact-action.ts +57 -0
  214. package/src/entry/commands/migrate-action.ts +5 -8
  215. package/src/entry/commands/teardown-action.ts +2 -2
  216. package/src/entry/entry-index.ts +1 -0
  217. package/src/index.ts +5 -2
  218. package/src/metrics/Metrics.ts +70 -15
  219. package/src/migrations/db/migrations/1684951997326-init.ts +9 -4
  220. package/src/migrations/db/migrations/1702295701188-sync-rule-state.ts +7 -4
  221. package/src/migrations/db/migrations/1711543888062-write-checkpoint-index.ts +6 -4
  222. package/src/migrations/migrations.ts +24 -8
  223. package/src/modules/AbstractModule.ts +37 -0
  224. package/src/modules/ModuleManager.ts +34 -0
  225. package/src/modules/modules-index.ts +2 -0
  226. package/src/replication/AbstractReplicationJob.ts +79 -0
  227. package/src/replication/AbstractReplicator.ts +227 -0
  228. package/src/replication/ErrorRateLimiter.ts +0 -44
  229. package/src/replication/ReplicationEngine.ts +43 -0
  230. package/src/replication/ReplicationModule.ts +101 -0
  231. package/src/replication/replication-index.ts +4 -6
  232. package/src/routes/RouterEngine.ts +120 -0
  233. package/src/routes/auth.ts +21 -12
  234. package/src/routes/configure-fastify.ts +101 -0
  235. package/src/routes/configure-rsocket.ts +60 -0
  236. package/src/routes/endpoints/admin.ts +74 -100
  237. package/src/routes/endpoints/checkpointing.ts +46 -12
  238. package/src/routes/endpoints/route-endpoints-index.ts +0 -1
  239. package/src/routes/endpoints/socket-route.ts +50 -42
  240. package/src/routes/endpoints/sync-rules.ts +41 -25
  241. package/src/routes/endpoints/sync-stream.ts +17 -13
  242. package/src/routes/route-register.ts +2 -2
  243. package/src/routes/router-socket.ts +6 -5
  244. package/src/routes/router.ts +7 -2
  245. package/src/routes/routes-index.ts +3 -0
  246. package/src/runner/teardown.ts +50 -88
  247. package/src/storage/BucketStorage.ts +74 -26
  248. package/src/storage/MongoBucketStorage.ts +23 -26
  249. package/src/storage/SourceEntity.ts +22 -0
  250. package/src/storage/SourceTable.ts +4 -6
  251. package/src/storage/StorageEngine.ts +55 -0
  252. package/src/storage/StorageProvider.ts +27 -0
  253. package/src/storage/mongo/MongoBucketBatch.ts +8 -8
  254. package/src/storage/mongo/MongoCompactor.ts +372 -0
  255. package/src/storage/mongo/MongoPersistedSyncRulesContent.ts +3 -3
  256. package/src/storage/mongo/MongoStorageProvider.ts +31 -0
  257. package/src/storage/mongo/MongoSyncBucketStorage.ts +64 -34
  258. package/src/storage/mongo/MongoSyncRulesLock.ts +1 -1
  259. package/src/storage/mongo/OperationBatch.ts +18 -11
  260. package/src/storage/mongo/PersistedBatch.ts +6 -5
  261. package/src/storage/mongo/models.ts +17 -7
  262. package/src/storage/mongo/util.ts +71 -1
  263. package/src/storage/storage-index.ts +5 -2
  264. package/src/sync/RequestTracker.ts +3 -3
  265. package/src/sync/sync-index.ts +1 -0
  266. package/src/sync/sync.ts +66 -17
  267. package/src/system/ServiceContext.ts +68 -0
  268. package/src/system/system-index.ts +1 -1
  269. package/src/util/config/collectors/config-collector.ts +48 -0
  270. package/src/util/config/compound-config-collector.ts +45 -110
  271. package/src/util/config/sync-rules/sync-rules-provider.ts +18 -0
  272. package/src/util/config/types.ts +6 -5
  273. package/src/util/config.ts +6 -23
  274. package/src/util/protocol-types.ts +6 -1
  275. package/src/util/util-index.ts +3 -6
  276. package/src/util/utils.ts +55 -39
  277. package/test/src/__snapshots__/sync.test.ts.snap +90 -5
  278. package/test/src/auth.test.ts +7 -7
  279. package/test/src/broadcast_iterable.test.ts +1 -1
  280. package/test/src/bucket_validation.test.ts +142 -0
  281. package/test/src/bucket_validation.ts +116 -0
  282. package/test/src/checksum_cache.test.ts +3 -3
  283. package/test/src/compacting.test.ts +216 -0
  284. package/test/src/data_storage.test.ts +275 -204
  285. package/test/src/env.ts +1 -3
  286. package/test/src/merge_iterable.test.ts +1 -6
  287. package/test/src/setup.ts +1 -1
  288. package/test/src/stream_utils.ts +42 -0
  289. package/test/src/sync.test.ts +209 -48
  290. package/test/src/util.ts +110 -55
  291. package/test/tsconfig.json +1 -1
  292. package/tsconfig.tsbuildinfo +1 -1
  293. package/dist/auth/SupabaseKeyCollector.d.ts +0 -22
  294. package/dist/auth/SupabaseKeyCollector.js +0 -61
  295. package/dist/auth/SupabaseKeyCollector.js.map +0 -1
  296. package/dist/replication/PgRelation.d.ts +0 -16
  297. package/dist/replication/PgRelation.js +0 -26
  298. package/dist/replication/PgRelation.js.map +0 -1
  299. package/dist/replication/WalConnection.d.ts +0 -34
  300. package/dist/replication/WalConnection.js +0 -190
  301. package/dist/replication/WalConnection.js.map +0 -1
  302. package/dist/replication/WalStream.d.ts +0 -57
  303. package/dist/replication/WalStream.js +0 -517
  304. package/dist/replication/WalStream.js.map +0 -1
  305. package/dist/replication/WalStreamManager.d.ts +0 -30
  306. package/dist/replication/WalStreamManager.js +0 -198
  307. package/dist/replication/WalStreamManager.js.map +0 -1
  308. package/dist/replication/WalStreamRunner.d.ts +0 -38
  309. package/dist/replication/WalStreamRunner.js +0 -155
  310. package/dist/replication/WalStreamRunner.js.map +0 -1
  311. package/dist/replication/util.d.ts +0 -9
  312. package/dist/replication/util.js +0 -62
  313. package/dist/replication/util.js.map +0 -1
  314. package/dist/routes/endpoints/dev.d.ts +0 -312
  315. package/dist/routes/endpoints/dev.js +0 -172
  316. package/dist/routes/endpoints/dev.js.map +0 -1
  317. package/dist/system/CorePowerSyncSystem.d.ts +0 -23
  318. package/dist/system/CorePowerSyncSystem.js +0 -52
  319. package/dist/system/CorePowerSyncSystem.js.map +0 -1
  320. package/dist/util/PgManager.d.ts +0 -24
  321. package/dist/util/PgManager.js +0 -55
  322. package/dist/util/PgManager.js.map +0 -1
  323. package/dist/util/migration_lib.d.ts +0 -11
  324. package/dist/util/migration_lib.js +0 -64
  325. package/dist/util/migration_lib.js.map +0 -1
  326. package/dist/util/pgwire_utils.d.ts +0 -24
  327. package/dist/util/pgwire_utils.js +0 -117
  328. package/dist/util/pgwire_utils.js.map +0 -1
  329. package/dist/util/populate_test_data.d.ts +0 -8
  330. package/dist/util/populate_test_data.js +0 -65
  331. package/dist/util/populate_test_data.js.map +0 -1
  332. package/src/auth/SupabaseKeyCollector.ts +0 -67
  333. package/src/replication/PgRelation.ts +0 -42
  334. package/src/replication/WalConnection.ts +0 -227
  335. package/src/replication/WalStream.ts +0 -628
  336. package/src/replication/WalStreamManager.ts +0 -213
  337. package/src/replication/WalStreamRunner.ts +0 -180
  338. package/src/replication/util.ts +0 -76
  339. package/src/routes/endpoints/dev.ts +0 -199
  340. package/src/system/CorePowerSyncSystem.ts +0 -64
  341. package/src/util/PgManager.ts +0 -64
  342. package/src/util/migration_lib.ts +0 -79
  343. package/src/util/pgwire_utils.ts +0 -139
  344. package/src/util/populate_test_data.ts +0 -78
  345. package/test/src/__snapshots__/pg_test.test.ts.snap +0 -256
  346. package/test/src/large_batch.test.ts +0 -194
  347. package/test/src/pg_test.test.ts +0 -450
  348. package/test/src/schema_changes.test.ts +0 -545
  349. package/test/src/slow_tests.test.ts +0 -296
  350. package/test/src/validation.test.ts +0 -63
  351. package/test/src/wal_stream.test.ts +0 -314
  352. package/test/src/wal_stream_utils.ts +0 -147
@@ -0,0 +1,79 @@
1
+ import * as storage from '../storage/storage-index.js';
2
+ import { ErrorRateLimiter } from './ErrorRateLimiter.js';
3
+ import { container, logger } from '@powersync/lib-services-framework';
4
+ import winston from 'winston';
5
+
6
+ export interface AbstractReplicationJobOptions {
7
+ id: string;
8
+ storage: storage.SyncRulesBucketStorage;
9
+ lock: storage.ReplicationLock;
10
+ rateLimiter: ErrorRateLimiter;
11
+ }
12
+
13
+ export abstract class AbstractReplicationJob {
14
+ protected logger: winston.Logger;
15
+ protected abortController = new AbortController();
16
+ protected isReplicatingPromise: Promise<void> | null = null;
17
+
18
+ protected constructor(protected options: AbstractReplicationJobOptions) {
19
+ this.logger = logger.child({ name: `ReplicationJob: ${options.id}` });
20
+ }
21
+
22
+ /**
23
+ * Copy the initial data set from the data source if required and then keep it in sync.
24
+ */
25
+ abstract replicate(): Promise<void>;
26
+
27
+ /**
28
+ * Ensure the connection to the data source remains active
29
+ */
30
+ abstract keepAlive(): Promise<void>;
31
+
32
+ /**
33
+ * Start the replication process
34
+ */
35
+ public async start(): Promise<void> {
36
+ this.isReplicatingPromise = this.replicate()
37
+ .catch((ex) => {
38
+ container.reporter.captureException(ex, {
39
+ metadata: {
40
+ replicator: this.id
41
+ }
42
+ });
43
+ this.logger.error(`Replication failed.`, ex);
44
+ })
45
+ .finally(async () => {
46
+ this.abortController.abort();
47
+ await this.options.lock.release();
48
+ });
49
+ }
50
+
51
+ /**
52
+ * Safely stop the replication process
53
+ */
54
+ public async stop(): Promise<void> {
55
+ this.logger.info(`Stopping ${this.id} replication job for sync rule iteration: ${this.storage.group_id}`);
56
+ this.abortController.abort();
57
+ await this.isReplicatingPromise;
58
+ }
59
+
60
+ public get id() {
61
+ return this.options.id;
62
+ }
63
+
64
+ public get storage() {
65
+ return this.options.storage;
66
+ }
67
+
68
+ protected get lock() {
69
+ return this.options.lock;
70
+ }
71
+
72
+ protected get rateLimiter() {
73
+ return this.options.rateLimiter;
74
+ }
75
+
76
+ public get isStopped(): boolean {
77
+ return this.abortController.signal.aborted;
78
+ }
79
+ }
@@ -0,0 +1,227 @@
1
+ import { hrtime } from 'node:process';
2
+ import * as storage from '../storage/storage-index.js';
3
+ import { container, logger } from '@powersync/lib-services-framework';
4
+ import { SyncRulesProvider } from '../util/config/sync-rules/sync-rules-provider.js';
5
+ import winston from 'winston';
6
+ import { AbstractReplicationJob } from './AbstractReplicationJob.js';
7
+ import { StorageEngine } from '../storage/storage-index.js';
8
+ import { ErrorRateLimiter } from './ErrorRateLimiter.js';
9
+
10
+ // 5 minutes
11
+ const PING_INTERVAL = 1_000_000_000n * 300n;
12
+
13
+ export interface CreateJobOptions {
14
+ lock: storage.ReplicationLock;
15
+ storage: storage.SyncRulesBucketStorage;
16
+ }
17
+
18
+ export interface AbstractReplicatorOptions {
19
+ id: string;
20
+ storageEngine: StorageEngine;
21
+ syncRuleProvider: SyncRulesProvider;
22
+ /**
23
+ * This limits the effect of retries when there is a persistent issue.
24
+ */
25
+ rateLimiter: ErrorRateLimiter;
26
+ }
27
+
28
+ /**
29
+ * A replicator manages the mechanics for replicating data from a data source to a storage bucket.
30
+ * This includes copying across the original data set and then keeping it in sync with the data source using Replication Jobs.
31
+ * It also handles any changes to the sync rules.
32
+ */
33
+ export abstract class AbstractReplicator<T extends AbstractReplicationJob = AbstractReplicationJob> {
34
+ protected logger: winston.Logger;
35
+ /**
36
+ * Map of replication jobs by sync rule id. Usually there is only one running job, but there could be two when
37
+ * transitioning to a new set of sync rules.
38
+ * @private
39
+ */
40
+ private replicationJobs = new Map<number, T>();
41
+ private stopped = false;
42
+
43
+ // First ping is only after 5 minutes, not when starting
44
+ private lastPing = hrtime.bigint();
45
+
46
+ protected constructor(private options: AbstractReplicatorOptions) {
47
+ this.logger = logger.child({ name: `Replicator:${options.id}` });
48
+ }
49
+
50
+ abstract createJob(options: CreateJobOptions): T;
51
+
52
+ /**
53
+ * Clean up any configuration or state for the specified sync rule on the datasource.
54
+ * Should be a no-op if the configuration has already been cleared
55
+ */
56
+ abstract cleanUp(syncRuleStorage: storage.SyncRulesBucketStorage): Promise<void>;
57
+
58
+ public get id() {
59
+ return this.options.id;
60
+ }
61
+
62
+ protected get storage() {
63
+ return this.options.storageEngine.activeBucketStorage;
64
+ }
65
+
66
+ protected get syncRuleProvider() {
67
+ return this.options.syncRuleProvider;
68
+ }
69
+
70
+ protected get rateLimiter() {
71
+ return this.options.rateLimiter;
72
+ }
73
+
74
+ public async start(): Promise<void> {
75
+ this.runLoop().catch((e) => {
76
+ this.logger.error('Data source fatal replication error', e);
77
+ container.reporter.captureException(e);
78
+ setTimeout(() => {
79
+ process.exit(1);
80
+ }, 1000);
81
+ });
82
+ }
83
+
84
+ public async stop(): Promise<void> {
85
+ this.stopped = true;
86
+ let promises: Promise<void>[] = [];
87
+ for (const job of this.replicationJobs.values()) {
88
+ promises.push(job.stop());
89
+ }
90
+ await Promise.all(promises);
91
+ }
92
+
93
+ private async runLoop() {
94
+ const syncRules = await this.syncRuleProvider.get();
95
+ let configuredLock: storage.ReplicationLock | undefined = undefined;
96
+ if (syncRules != null) {
97
+ this.logger.info('Loaded sync rules');
98
+ try {
99
+ // Configure new sync rules, if they have changed.
100
+ // In that case, also immediately take out a lock, so that another process doesn't start replication on it.
101
+ const { lock } = await this.storage.configureSyncRules(syncRules, {
102
+ lock: true
103
+ });
104
+ if (lock) {
105
+ configuredLock = lock;
106
+ }
107
+ } catch (e) {
108
+ // Log, but continue with previous sync rules
109
+ this.logger.error(`Failed to update sync rules from configuration`, e);
110
+ }
111
+ } else {
112
+ this.logger.info('No sync rules configured - configure via API');
113
+ }
114
+ while (!this.stopped) {
115
+ await container.probes.touch();
116
+ try {
117
+ await this.refresh({ configured_lock: configuredLock });
118
+ // The lock is only valid on the first refresh.
119
+ configuredLock = undefined;
120
+
121
+ // Ensure that the replication jobs' connections are kept alive.
122
+ // We don't ping while in error retry back-off, to avoid having too failures.
123
+ if (this.rateLimiter.mayPing()) {
124
+ const now = hrtime.bigint();
125
+ if (now - this.lastPing >= PING_INTERVAL) {
126
+ for (const activeJob of this.replicationJobs.values()) {
127
+ await activeJob.keepAlive();
128
+ }
129
+
130
+ this.lastPing = now;
131
+ }
132
+ }
133
+ } catch (e) {
134
+ this.logger.error('Failed to refresh replication jobs', e);
135
+ }
136
+ await new Promise((resolve) => setTimeout(resolve, 5000));
137
+ }
138
+ }
139
+
140
+ private async refresh(options?: { configured_lock?: storage.ReplicationLock }) {
141
+ if (this.stopped) {
142
+ return;
143
+ }
144
+
145
+ let configuredLock = options?.configured_lock;
146
+
147
+ const existingJobs = new Map<number, T>(this.replicationJobs.entries());
148
+ const replicatingSyncRules = await this.storage.getReplicatingSyncRules();
149
+ const newJobs = new Map<number, T>();
150
+ for (let syncRules of replicatingSyncRules) {
151
+ const existingJob = existingJobs.get(syncRules.id);
152
+ if (existingJob && !existingJob.isStopped) {
153
+ // No change
154
+ existingJobs.delete(syncRules.id);
155
+ newJobs.set(syncRules.id, existingJob);
156
+ } else if (existingJob && existingJob.isStopped) {
157
+ // Stopped (e.g. fatal error).
158
+ // Remove from the list. Next refresh call will restart the job.
159
+ existingJobs.delete(syncRules.id);
160
+ } else {
161
+ // New sync rules were found (or resume after restart)
162
+ try {
163
+ let lock: storage.ReplicationLock;
164
+ if (configuredLock?.sync_rules_id == syncRules.id) {
165
+ lock = configuredLock;
166
+ } else {
167
+ lock = await syncRules.lock();
168
+ }
169
+ const storage = this.storage.getInstance(syncRules);
170
+ const newJob = this.createJob({
171
+ lock: lock,
172
+ storage: storage
173
+ });
174
+
175
+ newJobs.set(syncRules.id, newJob);
176
+ newJob.start();
177
+ } catch (e) {
178
+ // Could be a sync rules parse error,
179
+ // for example from stricter validation that was added.
180
+ // This will be retried every couple of seconds.
181
+ // When new (valid) sync rules are deployed and processed, this one be disabled.
182
+ this.logger.error('Failed to start replication for new sync rules', e);
183
+ }
184
+ }
185
+ }
186
+
187
+ this.replicationJobs = newJobs;
188
+
189
+ // Terminate any orphaned jobs that no longer have sync rules
190
+ for (let job of existingJobs.values()) {
191
+ // Old - stop and clean up
192
+ try {
193
+ await job.stop();
194
+ await this.terminateSyncRules(job.storage);
195
+ } catch (e) {
196
+ // This will be retried
197
+ this.logger.warn('Failed to terminate old replication job}', e);
198
+ }
199
+ }
200
+
201
+ // Sync rules stopped previously or by a different process.
202
+ const stopped = await this.storage.getStoppedSyncRules();
203
+ for (let syncRules of stopped) {
204
+ try {
205
+ const syncRuleStorage = this.storage.getInstance(syncRules);
206
+ await this.terminateSyncRules(syncRuleStorage);
207
+ } catch (e) {
208
+ this.logger.warn(`Failed clean up replication config for sync rule: ${syncRules.id}`, e);
209
+ }
210
+ }
211
+ }
212
+
213
+ protected createJobId(syncRuleId: number) {
214
+ return `${this.id}-${syncRuleId}`;
215
+ }
216
+
217
+ protected async terminateSyncRules(syncRuleStorage: storage.SyncRulesBucketStorage) {
218
+ this.logger.info(`Terminating sync rules: ${syncRuleStorage.group_id}...`);
219
+ try {
220
+ await this.cleanUp(syncRuleStorage);
221
+ await syncRuleStorage.terminate();
222
+ this.logger.info(`Successfully terminated sync rules: ${syncRuleStorage.group_id}`);
223
+ } catch (e) {
224
+ this.logger.warn(`Failed clean up replication config for sync rules: ${syncRuleStorage.group_id}`, e);
225
+ }
226
+ }
227
+ }
@@ -1,50 +1,6 @@
1
- import { setTimeout } from 'timers/promises';
2
-
3
1
  export interface ErrorRateLimiter {
4
2
  waitUntilAllowed(options?: { signal?: AbortSignal }): Promise<void>;
5
3
  reportError(e: any): void;
6
4
 
7
5
  mayPing(): boolean;
8
6
  }
9
-
10
- export class DefaultErrorRateLimiter implements ErrorRateLimiter {
11
- nextAllowed: number = Date.now();
12
-
13
- async waitUntilAllowed(options?: { signal?: AbortSignal | undefined } | undefined): Promise<void> {
14
- const delay = Math.max(0, this.nextAllowed - Date.now());
15
- // Minimum delay between connections, even without errors
16
- this.setDelay(500);
17
- await setTimeout(delay, undefined, { signal: options?.signal });
18
- }
19
-
20
- mayPing(): boolean {
21
- return Date.now() >= this.nextAllowed;
22
- }
23
-
24
- reportError(e: any): void {
25
- const message = (e.message as string) ?? '';
26
- if (message.includes('password authentication failed')) {
27
- // Wait 15 minutes, to avoid triggering Supabase's fail2ban
28
- this.setDelay(900_000);
29
- } else if (message.includes('ENOTFOUND')) {
30
- // DNS lookup issue - incorrect URI or deleted instance
31
- this.setDelay(120_000);
32
- } else if (message.includes('ECONNREFUSED')) {
33
- // Could be fail2ban or similar
34
- this.setDelay(120_000);
35
- } else if (
36
- message.includes('Unable to do postgres query on ended pool') ||
37
- message.includes('Postgres unexpectedly closed connection')
38
- ) {
39
- // Connection timed out - ignore / immediately retry
40
- // We don't explicitly set the delay to 0, since there could have been another error that
41
- // we need to respect.
42
- } else {
43
- this.setDelay(30_000);
44
- }
45
- }
46
-
47
- private setDelay(delay: number) {
48
- this.nextAllowed = Math.max(this.nextAllowed, Date.now() + delay);
49
- }
50
- }
@@ -0,0 +1,43 @@
1
+ import { AbstractReplicator } from './AbstractReplicator.js';
2
+ import { logger } from '@powersync/lib-services-framework';
3
+
4
+ export class ReplicationEngine {
5
+ private readonly replicators: Map<string, AbstractReplicator> = new Map();
6
+
7
+ /**
8
+ * Register a Replicator with the engine
9
+ *
10
+ * @param replicator
11
+ */
12
+ public register(replicator: AbstractReplicator) {
13
+ if (this.replicators.has(replicator.id)) {
14
+ throw new Error(`Replicator with id: ${replicator.id} already registered`);
15
+ }
16
+ logger.info(`Successfully registered Replicator ${replicator.id} with ReplicationEngine`);
17
+ this.replicators.set(replicator.id, replicator);
18
+ }
19
+
20
+ /**
21
+ * Start replication on all managed Replicators
22
+ */
23
+ public start(): void {
24
+ logger.info('Starting Replication Engine...');
25
+ for (const replicator of this.replicators.values()) {
26
+ logger.info(`Starting Replicator: ${replicator.id}`);
27
+ replicator.start();
28
+ }
29
+ logger.info('Successfully started Replication Engine.');
30
+ }
31
+
32
+ /**
33
+ * Stop replication on all managed Replicators
34
+ */
35
+ public async shutDown(): Promise<void> {
36
+ logger.info('Shutting down Replication Engine...');
37
+ for (const replicator of this.replicators.values()) {
38
+ logger.info(`Stopping Replicator: ${replicator.id}`);
39
+ await replicator.stop();
40
+ }
41
+ logger.info('Successfully shut down Replication Engine.');
42
+ }
43
+ }
@@ -0,0 +1,101 @@
1
+ import { DataSourceConfig } from '@powersync/service-types/dist/config/PowerSyncConfig.js';
2
+ import * as t from 'ts-codec';
3
+
4
+ import * as types from '@powersync/service-types';
5
+ import * as api from '../api/api-index.js';
6
+ import * as modules from '../modules/modules-index.js';
7
+ import * as system from '../system/system-index.js';
8
+ import { schema } from '@powersync/lib-services-framework';
9
+ import { AbstractReplicator } from './AbstractReplicator.js';
10
+
11
+ export interface ReplicationModuleOptions extends modules.AbstractModuleOptions {
12
+ type: string;
13
+ configSchema: t.AnyCodec;
14
+ }
15
+
16
+ /**
17
+ * A replication module describes all the functionality that PowerSync requires to
18
+ * replicate data from a DataSource. Whenever a new data source is added to powersync this class should be extended.
19
+ */
20
+ export abstract class ReplicationModule<TConfig extends DataSourceConfig> extends modules.AbstractModule {
21
+ protected type: string;
22
+ protected configSchema: t.AnyCodec;
23
+ protected decodedConfig: TConfig | undefined;
24
+
25
+ /**
26
+ * @protected
27
+ * @param options
28
+ */
29
+ protected constructor(options: ReplicationModuleOptions) {
30
+ super(options);
31
+ this.type = options.type;
32
+ this.configSchema = options.configSchema;
33
+ }
34
+
35
+ /**
36
+ * Create the RouteAPI adapter for the DataSource required to service the sync API
37
+ * endpoints.
38
+ */
39
+ protected abstract createRouteAPIAdapter(): api.RouteAPI;
40
+
41
+ /**
42
+ * Create the Replicator to be used by the ReplicationEngine.
43
+ */
44
+ protected abstract createReplicator(context: system.ServiceContext): AbstractReplicator;
45
+
46
+ /**
47
+ * Register this module's Replicators and RouteAPI adapters if the required configuration is present.
48
+ */
49
+ public async initialize(context: system.ServiceContext): Promise<void> {
50
+ if (!context.configuration.connections) {
51
+ // No data source configuration found in the config skip for now
52
+ return;
53
+ }
54
+
55
+ const matchingConfig = context.configuration.connections.filter((dataSource) => dataSource.type === this.type);
56
+ if (!matchingConfig.length) {
57
+ // This module is needed given the config
58
+ return;
59
+ }
60
+
61
+ if (matchingConfig.length > 1) {
62
+ this.logger.warning(
63
+ `Multiple data sources of type ${this.type} found in the configuration. Only the first will be used.`
64
+ );
65
+ }
66
+
67
+ try {
68
+ const baseMatchingConfig = matchingConfig[0] as TConfig;
69
+ // If validation fails, log the error and continue, no replication will happen for this data source
70
+ this.validateConfig(baseMatchingConfig);
71
+ this.decodedConfig = this.configSchema.decode(baseMatchingConfig);
72
+
73
+ context.replicationEngine?.register(this.createReplicator(context));
74
+ context.routerEngine?.registerAPI(this.createRouteAPIAdapter());
75
+ } catch (e) {
76
+ this.logger.error('Failed to initialize.', e);
77
+ }
78
+ }
79
+
80
+ private validateConfig(config: TConfig): void {
81
+ const validator = schema
82
+ .parseJSONSchema(
83
+ // This generates a schema for the encoded form of the codec
84
+ t.generateJSONSchema(this.configSchema, {
85
+ allowAdditional: true,
86
+ parsers: [types.configFile.portParser]
87
+ })
88
+ )
89
+ .validator();
90
+
91
+ const valid = validator.validate(config);
92
+
93
+ if (!valid.valid) {
94
+ throw new Error(`Failed to validate Module ${this.name} configuration: ${valid.errors.join(', ')}`);
95
+ }
96
+ }
97
+
98
+ protected getDefaultId(dataSourceName: string): string {
99
+ return `${this.type}-${dataSourceName}`;
100
+ }
101
+ }
@@ -1,7 +1,5 @@
1
1
  export * from './ErrorRateLimiter.js';
2
- export * from './PgRelation.js';
3
- export * from './util.js';
4
- export * from './WalConnection.js';
5
- export * from './WalStream.js';
6
- export * from './WalStreamManager.js';
7
- export * from './WalStreamRunner.js';
2
+ export * from './AbstractReplicationJob.js';
3
+ export * from './AbstractReplicator.js';
4
+ export * from './ReplicationEngine.js';
5
+ export * from './ReplicationModule.js';
@@ -0,0 +1,120 @@
1
+ import { logger } from '@powersync/lib-services-framework';
2
+
3
+ import * as api from '../api/api-index.js';
4
+
5
+ import { ADMIN_ROUTES } from './endpoints/admin.js';
6
+ import { CHECKPOINT_ROUTES } from './endpoints/checkpointing.js';
7
+ import { syncStreamReactive } from './endpoints/socket-route.js';
8
+ import { SYNC_RULES_ROUTES } from './endpoints/sync-rules.js';
9
+ import { SYNC_STREAM_ROUTES } from './endpoints/sync-stream.js';
10
+ import { SocketRouteGenerator } from './router-socket.js';
11
+ import { RouteDefinition } from './router.js';
12
+
13
+ export type RouterSetupResponse = {
14
+ onShutdown: () => Promise<void>;
15
+ };
16
+
17
+ export type RouterEngineRoutes = {
18
+ api_routes: RouteDefinition[];
19
+ stream_routes: RouteDefinition[];
20
+ socket_routes: SocketRouteGenerator[];
21
+ };
22
+
23
+ export type RouterSetup = (routes: RouterEngineRoutes) => Promise<RouterSetupResponse>;
24
+
25
+ /**
26
+ * Serves as a registry from which SyncAPIs can be retrieved based on Replication DataSource type
27
+ * Initially only one SyncAPI per DataSource type is supported
28
+ */
29
+ export class RouterEngine {
30
+ closed: boolean;
31
+ routes: RouterEngineRoutes;
32
+
33
+ protected stopHandlers: Set<() => void>;
34
+
35
+ /**
36
+ * A final cleanup handler to be executed after all stopHandlers
37
+ */
38
+ protected cleanupHandler: (() => Promise<void>) | null;
39
+
40
+ private api: api.RouteAPI | null;
41
+
42
+ constructor() {
43
+ this.api = null;
44
+ this.stopHandlers = new Set();
45
+ this.cleanupHandler = null;
46
+ this.closed = false;
47
+
48
+ // Default routes
49
+ this.routes = {
50
+ api_routes: [...ADMIN_ROUTES, ...CHECKPOINT_ROUTES, ...SYNC_RULES_ROUTES],
51
+ stream_routes: [...SYNC_STREAM_ROUTES],
52
+ socket_routes: [syncStreamReactive]
53
+ };
54
+ }
55
+
56
+ public registerAPI(api: api.RouteAPI) {
57
+ if (this.api) {
58
+ logger.warn('A RouteAPI has already been registered. Overriding existing implementation');
59
+ }
60
+
61
+ this.api = api;
62
+ }
63
+
64
+ public getAPI(): api.RouteAPI {
65
+ if (!this.api) {
66
+ throw new Error('No RouteAPI adapter has been registered yet.');
67
+ }
68
+ return this.api;
69
+ }
70
+
71
+ /**
72
+ * Starts the router given the configuration provided
73
+ */
74
+ async start(setup: RouterSetup) {
75
+ logger.info('Starting Router Engine...');
76
+ const { onShutdown } = await setup(this.routes);
77
+ this.cleanupHandler = onShutdown;
78
+ logger.info('Successfully started Router Engine.');
79
+ }
80
+
81
+ /**
82
+ * Runs all stop handlers then final cleanup.
83
+ */
84
+ async shutDown() {
85
+ logger.info('Shutting down Router Engine...');
86
+ // Close open streams, so that they don't block the server from closing.
87
+ // Note: This does not work well when streaming requests are queued. In that case, the server still doesn't
88
+ // close in the 30-second timeout.
89
+ this.closed = true;
90
+
91
+ logger.info(`Closing ${this.stopHandlers.size} streams.`);
92
+ for (let handler of this.stopHandlers) {
93
+ handler();
94
+ }
95
+
96
+ logger.info(`Running cleanup.`);
97
+
98
+ // Typically closes the server
99
+ await this.cleanupHandler?.();
100
+
101
+ // Close the api handlers
102
+ await this.api?.shutdown();
103
+ logger.info('Successfully shut down Router Engine.');
104
+ }
105
+
106
+ /**
107
+ * Add a stop handler callback to be executed when the router engine is being
108
+ * shutdown.
109
+ */
110
+ addStopHandler(handler: () => void): () => void {
111
+ if (this.closed) {
112
+ handler();
113
+ return () => {};
114
+ }
115
+ this.stopHandlers.add(handler);
116
+ return () => {
117
+ this.stopHandlers.delete(handler);
118
+ };
119
+ }
120
+ }