@hoshinotatsuya/pg-replica-sync 0.0.0-stage → 0.2.2

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 (315) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/LICENSE +21 -0
  3. package/README.md +313 -2
  4. package/README.ru.md +292 -0
  5. package/dist/compare-lsn.d.mts +6 -0
  6. package/dist/compare-lsn.d.ts +7 -0
  7. package/dist/compare-lsn.d.ts.map +1 -0
  8. package/dist/compare-lsn.js +18 -0
  9. package/dist/compare-lsn.js.map +1 -0
  10. package/dist/constants/exclusion-reason.constant.d.mts +26 -0
  11. package/dist/constants/exclusion-reason.constant.d.ts +27 -0
  12. package/dist/constants/exclusion-reason.constant.d.ts.map +1 -0
  13. package/dist/constants/exclusion-reason.constant.js +32 -0
  14. package/dist/constants/exclusion-reason.constant.js.map +1 -0
  15. package/dist/constants/node-role.constant.d.mts +5 -0
  16. package/dist/constants/node-role.constant.d.ts +6 -0
  17. package/dist/constants/node-role.constant.d.ts.map +1 -0
  18. package/dist/constants/node-role.constant.js +11 -0
  19. package/dist/constants/node-role.constant.js.map +1 -0
  20. package/dist/constants/probe-sql.constant.d.mts +31 -0
  21. package/dist/constants/probe-sql.constant.d.ts +32 -0
  22. package/dist/constants/probe-sql.constant.d.ts.map +1 -0
  23. package/dist/constants/probe-sql.constant.js +47 -0
  24. package/dist/constants/probe-sql.constant.js.map +1 -0
  25. package/dist/constants/replica-sync-defaults.constant.d.mts +51 -0
  26. package/dist/constants/replica-sync-defaults.constant.d.ts +52 -0
  27. package/dist/constants/replica-sync-defaults.constant.d.ts.map +1 -0
  28. package/dist/constants/replica-sync-defaults.constant.js +57 -0
  29. package/dist/constants/replica-sync-defaults.constant.js.map +1 -0
  30. package/dist/constants/route-reason.constant.d.mts +27 -0
  31. package/dist/constants/route-reason.constant.d.ts +28 -0
  32. package/dist/constants/route-reason.constant.d.ts.map +1 -0
  33. package/dist/constants/route-reason.constant.js +33 -0
  34. package/dist/constants/route-reason.constant.js.map +1 -0
  35. package/dist/constants/token-format.constant.d.mts +26 -0
  36. package/dist/constants/token-format.constant.d.ts +27 -0
  37. package/dist/constants/token-format.constant.d.ts.map +1 -0
  38. package/dist/constants/token-format.constant.js +32 -0
  39. package/dist/constants/token-format.constant.js.map +1 -0
  40. package/dist/constants/wal-format.constant.d.mts +15 -0
  41. package/dist/constants/wal-format.constant.d.ts +16 -0
  42. package/dist/constants/wal-format.constant.d.ts.map +1 -0
  43. package/dist/constants/wal-format.constant.js +21 -0
  44. package/dist/constants/wal-format.constant.js.map +1 -0
  45. package/dist/decode-canonical-base64url.d.mts +2 -0
  46. package/dist/decode-canonical-base64url.d.ts +3 -0
  47. package/dist/decode-canonical-base64url.d.ts.map +1 -0
  48. package/dist/decode-canonical-base64url.js +9 -0
  49. package/dist/decode-canonical-base64url.js.map +1 -0
  50. package/dist/deep-freeze.d.mts +10 -0
  51. package/dist/deep-freeze.d.ts +11 -0
  52. package/dist/deep-freeze.d.ts.map +1 -0
  53. package/dist/deep-freeze.js +29 -0
  54. package/dist/deep-freeze.js.map +1 -0
  55. package/dist/destroy-client.d.mts +7 -0
  56. package/dist/destroy-client.d.ts +8 -0
  57. package/dist/destroy-client.d.ts.map +1 -0
  58. package/dist/destroy-client.js +14 -0
  59. package/dist/destroy-client.js.map +1 -0
  60. package/dist/evaluate-replica.d.mts +9 -0
  61. package/dist/evaluate-replica.d.ts +10 -0
  62. package/dist/evaluate-replica.d.ts.map +1 -0
  63. package/dist/evaluate-replica.js +47 -0
  64. package/dist/evaluate-replica.js.map +1 -0
  65. package/dist/format-lsn.d.mts +2 -0
  66. package/dist/format-lsn.d.ts +3 -0
  67. package/dist/format-lsn.d.ts.map +1 -0
  68. package/dist/format-lsn.js +12 -0
  69. package/dist/format-lsn.js.map +1 -0
  70. package/dist/index.d.mts +36 -0
  71. package/dist/index.d.ts +37 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +38 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/invalid-lsn.error.d.mts +6 -0
  76. package/dist/invalid-lsn.error.d.ts +7 -0
  77. package/dist/invalid-lsn.error.d.ts.map +1 -0
  78. package/dist/invalid-lsn.error.js +14 -0
  79. package/dist/invalid-lsn.error.js.map +1 -0
  80. package/dist/invalid-replica-sync-options.error.d.mts +4 -0
  81. package/dist/invalid-replica-sync-options.error.d.ts +5 -0
  82. package/dist/invalid-replica-sync-options.error.d.ts.map +1 -0
  83. package/dist/invalid-replica-sync-options.error.js +9 -0
  84. package/dist/invalid-replica-sync-options.error.js.map +1 -0
  85. package/dist/lag-bytes.d.mts +6 -0
  86. package/dist/lag-bytes.d.ts +7 -0
  87. package/dist/lag-bytes.d.ts.map +1 -0
  88. package/dist/lag-bytes.js +13 -0
  89. package/dist/lag-bytes.js.map +1 -0
  90. package/dist/lsn-or-null.d.mts +2 -0
  91. package/dist/lsn-or-null.d.ts +3 -0
  92. package/dist/lsn-or-null.d.ts.map +1 -0
  93. package/dist/lsn-or-null.js +17 -0
  94. package/dist/lsn-or-null.js.map +1 -0
  95. package/dist/notify.d.mts +10 -0
  96. package/dist/notify.d.ts +11 -0
  97. package/dist/notify.d.ts.map +1 -0
  98. package/dist/notify.js +30 -0
  99. package/dist/notify.js.map +1 -0
  100. package/dist/parse-lsn.d.mts +6 -0
  101. package/dist/parse-lsn.d.ts +7 -0
  102. package/dist/parse-lsn.d.ts.map +1 -0
  103. package/dist/parse-lsn.js +19 -0
  104. package/dist/parse-lsn.js.map +1 -0
  105. package/dist/probe-connection-closed.error.d.mts +6 -0
  106. package/dist/probe-connection-closed.error.d.ts +7 -0
  107. package/dist/probe-connection-closed.error.d.ts.map +1 -0
  108. package/dist/probe-connection-closed.error.js +14 -0
  109. package/dist/probe-connection-closed.error.js.map +1 -0
  110. package/dist/probe-connection.d.mts +44 -0
  111. package/dist/probe-connection.d.ts +45 -0
  112. package/dist/probe-connection.d.ts.map +1 -0
  113. package/dist/probe-connection.js +149 -0
  114. package/dist/probe-connection.js.map +1 -0
  115. package/dist/probe-timeout.error.d.mts +7 -0
  116. package/dist/probe-timeout.error.d.ts +8 -0
  117. package/dist/probe-timeout.error.d.ts.map +1 -0
  118. package/dist/probe-timeout.error.js +16 -0
  119. package/dist/probe-timeout.error.js.map +1 -0
  120. package/dist/read-node-state.d.mts +7 -0
  121. package/dist/read-node-state.d.ts +8 -0
  122. package/dist/read-node-state.d.ts.map +1 -0
  123. package/dist/read-node-state.js +38 -0
  124. package/dist/read-node-state.js.map +1 -0
  125. package/dist/replica-router.d.mts +248 -0
  126. package/dist/replica-router.d.ts +249 -0
  127. package/dist/replica-router.d.ts.map +1 -0
  128. package/dist/replica-router.js +798 -0
  129. package/dist/replica-router.js.map +1 -0
  130. package/dist/require-integer.d.mts +2 -0
  131. package/dist/require-integer.d.ts +3 -0
  132. package/dist/require-integer.d.ts.map +1 -0
  133. package/dist/require-integer.js +13 -0
  134. package/dist/require-integer.js.map +1 -0
  135. package/dist/secret-weakness.d.mts +19 -0
  136. package/dist/secret-weakness.d.ts +20 -0
  137. package/dist/secret-weakness.d.ts.map +1 -0
  138. package/dist/secret-weakness.js +49 -0
  139. package/dist/secret-weakness.js.map +1 -0
  140. package/dist/smallest-period.d.mts +7 -0
  141. package/dist/smallest-period.d.ts +8 -0
  142. package/dist/smallest-period.d.ts.map +1 -0
  143. package/dist/smallest-period.js +28 -0
  144. package/dist/smallest-period.js.map +1 -0
  145. package/dist/sql-state-of.d.mts +9 -0
  146. package/dist/sql-state-of.d.ts +10 -0
  147. package/dist/sql-state-of.d.ts.map +1 -0
  148. package/dist/sql-state-of.js +29 -0
  149. package/dist/sql-state-of.js.map +1 -0
  150. package/dist/state-cache.d.mts +37 -0
  151. package/dist/state-cache.d.ts +38 -0
  152. package/dist/state-cache.d.ts.map +1 -0
  153. package/dist/state-cache.js +80 -0
  154. package/dist/state-cache.js.map +1 -0
  155. package/dist/timeline-of.d.mts +5 -0
  156. package/dist/timeline-of.d.ts +6 -0
  157. package/dist/timeline-of.d.ts.map +1 -0
  158. package/dist/timeline-of.js +18 -0
  159. package/dist/timeline-of.js.map +1 -0
  160. package/dist/to-error.d.mts +2 -0
  161. package/dist/to-error.d.ts +3 -0
  162. package/dist/to-error.d.ts.map +1 -0
  163. package/dist/to-error.js +9 -0
  164. package/dist/to-error.js.map +1 -0
  165. package/dist/token-codec.d.mts +27 -0
  166. package/dist/token-codec.d.ts +28 -0
  167. package/dist/token-codec.d.ts.map +1 -0
  168. package/dist/token-codec.js +147 -0
  169. package/dist/token-codec.js.map +1 -0
  170. package/dist/token-lsn.d.mts +19 -0
  171. package/dist/token-lsn.d.ts +20 -0
  172. package/dist/token-lsn.d.ts.map +1 -0
  173. package/dist/token-lsn.js +37 -0
  174. package/dist/token-lsn.js.map +1 -0
  175. package/dist/transaction-not-committed.error.d.mts +9 -0
  176. package/dist/transaction-not-committed.error.d.ts +10 -0
  177. package/dist/transaction-not-committed.error.d.ts.map +1 -0
  178. package/dist/transaction-not-committed.error.js +17 -0
  179. package/dist/transaction-not-committed.error.js.map +1 -0
  180. package/dist/transaction-not-open.error.d.mts +11 -0
  181. package/dist/transaction-not-open.error.d.ts +12 -0
  182. package/dist/transaction-not-open.error.d.ts.map +1 -0
  183. package/dist/transaction-not-open.error.js +18 -0
  184. package/dist/transaction-not-open.error.js.map +1 -0
  185. package/dist/types/cache-entry.type.d.mts +13 -0
  186. package/dist/types/cache-entry.type.d.ts +14 -0
  187. package/dist/types/cache-entry.type.d.ts.map +1 -0
  188. package/dist/types/cache-entry.type.js +3 -0
  189. package/dist/types/cache-entry.type.js.map +1 -0
  190. package/dist/types/clock.type.d.mts +6 -0
  191. package/dist/types/clock.type.d.ts +7 -0
  192. package/dist/types/clock.type.d.ts.map +1 -0
  193. package/dist/types/clock.type.js +3 -0
  194. package/dist/types/clock.type.js.map +1 -0
  195. package/dist/types/confirm-event.type.d.mts +13 -0
  196. package/dist/types/confirm-event.type.d.ts +14 -0
  197. package/dist/types/confirm-event.type.d.ts.map +1 -0
  198. package/dist/types/confirm-event.type.js +3 -0
  199. package/dist/types/confirm-event.type.js.map +1 -0
  200. package/dist/types/decoded-token.type.d.mts +16 -0
  201. package/dist/types/decoded-token.type.d.ts +17 -0
  202. package/dist/types/decoded-token.type.d.ts.map +1 -0
  203. package/dist/types/decoded-token.type.js +3 -0
  204. package/dist/types/decoded-token.type.js.map +1 -0
  205. package/dist/types/evaluated.type.d.mts +8 -0
  206. package/dist/types/evaluated.type.d.ts +9 -0
  207. package/dist/types/evaluated.type.d.ts.map +1 -0
  208. package/dist/types/evaluated.type.js +3 -0
  209. package/dist/types/evaluated.type.js.map +1 -0
  210. package/dist/types/exclusion-reason.type.d.mts +2 -0
  211. package/dist/types/exclusion-reason.type.d.ts +3 -0
  212. package/dist/types/exclusion-reason.type.d.ts.map +1 -0
  213. package/dist/types/exclusion-reason.type.js +3 -0
  214. package/dist/types/exclusion-reason.type.js.map +1 -0
  215. package/dist/types/exclusion.type.d.mts +6 -0
  216. package/dist/types/exclusion.type.d.ts +7 -0
  217. package/dist/types/exclusion.type.d.ts.map +1 -0
  218. package/dist/types/exclusion.type.js +3 -0
  219. package/dist/types/exclusion.type.js.map +1 -0
  220. package/dist/types/node-role.type.d.mts +2 -0
  221. package/dist/types/node-role.type.d.ts +3 -0
  222. package/dist/types/node-role.type.d.ts.map +1 -0
  223. package/dist/types/node-role.type.js +3 -0
  224. package/dist/types/node-role.type.js.map +1 -0
  225. package/dist/types/node-state.type.d.mts +31 -0
  226. package/dist/types/node-state.type.d.ts +32 -0
  227. package/dist/types/node-state.type.d.ts.map +1 -0
  228. package/dist/types/node-state.type.js +3 -0
  229. package/dist/types/node-state.type.js.map +1 -0
  230. package/dist/types/not-a-pool.type.d.mts +12 -0
  231. package/dist/types/not-a-pool.type.d.ts +13 -0
  232. package/dist/types/not-a-pool.type.d.ts.map +1 -0
  233. package/dist/types/not-a-pool.type.js +3 -0
  234. package/dist/types/not-a-pool.type.js.map +1 -0
  235. package/dist/types/probe-event.type.d.mts +7 -0
  236. package/dist/types/probe-event.type.d.ts +8 -0
  237. package/dist/types/probe-event.type.d.ts.map +1 -0
  238. package/dist/types/probe-event.type.js +3 -0
  239. package/dist/types/probe-event.type.js.map +1 -0
  240. package/dist/types/probe-outcome.type.d.mts +9 -0
  241. package/dist/types/probe-outcome.type.d.ts +10 -0
  242. package/dist/types/probe-outcome.type.d.ts.map +1 -0
  243. package/dist/types/probe-outcome.type.js +3 -0
  244. package/dist/types/probe-outcome.type.js.map +1 -0
  245. package/dist/types/probe-sample.type.d.mts +6 -0
  246. package/dist/types/probe-sample.type.d.ts +7 -0
  247. package/dist/types/probe-sample.type.d.ts.map +1 -0
  248. package/dist/types/probe-sample.type.js +3 -0
  249. package/dist/types/probe-sample.type.js.map +1 -0
  250. package/dist/types/replica-node.type.d.mts +19 -0
  251. package/dist/types/replica-node.type.d.ts +20 -0
  252. package/dist/types/replica-node.type.d.ts.map +1 -0
  253. package/dist/types/replica-node.type.js +3 -0
  254. package/dist/types/replica-node.type.js.map +1 -0
  255. package/dist/types/replica-requirement.type.d.mts +15 -0
  256. package/dist/types/replica-requirement.type.d.ts +16 -0
  257. package/dist/types/replica-requirement.type.d.ts.map +1 -0
  258. package/dist/types/replica-requirement.type.js +3 -0
  259. package/dist/types/replica-requirement.type.js.map +1 -0
  260. package/dist/types/replica-router-options.type.d.mts +57 -0
  261. package/dist/types/replica-router-options.type.d.ts +58 -0
  262. package/dist/types/replica-router-options.type.d.ts.map +1 -0
  263. package/dist/types/replica-router-options.type.js +3 -0
  264. package/dist/types/replica-router-options.type.js.map +1 -0
  265. package/dist/types/route-decision.type.d.mts +19 -0
  266. package/dist/types/route-decision.type.d.ts +20 -0
  267. package/dist/types/route-decision.type.d.ts.map +1 -0
  268. package/dist/types/route-decision.type.js +3 -0
  269. package/dist/types/route-decision.type.js.map +1 -0
  270. package/dist/types/route-reason.type.d.mts +2 -0
  271. package/dist/types/route-reason.type.d.ts +3 -0
  272. package/dist/types/route-reason.type.d.ts.map +1 -0
  273. package/dist/types/route-reason.type.js +3 -0
  274. package/dist/types/route-reason.type.js.map +1 -0
  275. package/dist/types/router-observer.type.d.mts +18 -0
  276. package/dist/types/router-observer.type.d.ts +19 -0
  277. package/dist/types/router-observer.type.d.ts.map +1 -0
  278. package/dist/types/router-observer.type.js +3 -0
  279. package/dist/types/router-observer.type.js.map +1 -0
  280. package/dist/types/router-stats.type.d.mts +33 -0
  281. package/dist/types/router-stats.type.d.ts +34 -0
  282. package/dist/types/router-stats.type.d.ts.map +1 -0
  283. package/dist/types/router-stats.type.js +3 -0
  284. package/dist/types/router-stats.type.js.map +1 -0
  285. package/dist/types/sql-command-executor.type.d.mts +12 -0
  286. package/dist/types/sql-command-executor.type.d.ts +13 -0
  287. package/dist/types/sql-command-executor.type.d.ts.map +1 -0
  288. package/dist/types/sql-command-executor.type.js +3 -0
  289. package/dist/types/sql-command-executor.type.js.map +1 -0
  290. package/dist/types/sql-query-executor.type.d.mts +10 -0
  291. package/dist/types/sql-query-executor.type.d.ts +11 -0
  292. package/dist/types/sql-query-executor.type.d.ts.map +1 -0
  293. package/dist/types/sql-query-executor.type.js +3 -0
  294. package/dist/types/sql-query-executor.type.js.map +1 -0
  295. package/dist/types/wal-layout.type.d.mts +6 -0
  296. package/dist/types/wal-layout.type.d.ts +7 -0
  297. package/dist/types/wal-layout.type.d.ts.map +1 -0
  298. package/dist/types/wal-layout.type.js +3 -0
  299. package/dist/types/wal-layout.type.js.map +1 -0
  300. package/dist/types/wal-position.type.d.mts +12 -0
  301. package/dist/types/wal-position.type.d.ts +13 -0
  302. package/dist/types/wal-position.type.d.ts.map +1 -0
  303. package/dist/types/wal-position.type.js +3 -0
  304. package/dist/types/wal-position.type.js.map +1 -0
  305. package/dist/value-text.d.mts +8 -0
  306. package/dist/value-text.d.ts +9 -0
  307. package/dist/value-text.d.ts.map +1 -0
  308. package/dist/value-text.js +25 -0
  309. package/dist/value-text.js.map +1 -0
  310. package/dist/wal-layout-of.d.mts +3 -0
  311. package/dist/wal-layout-of.d.ts +4 -0
  312. package/dist/wal-layout-of.d.ts.map +1 -0
  313. package/dist/wal-layout-of.js +19 -0
  314. package/dist/wal-layout-of.js.map +1 -0
  315. package/package.json +92 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,89 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package uses
5
+ [Semantic Versioning](https://semver.org/) (before 1.0 a breaking change bumps the minor version).
6
+
7
+ ## 0.2.2 — 2026-11-21
8
+
9
+ First public release as `@hoshinotatsuya/pg-replica-sync`, MIT; documentation in English and Russian; no
10
+ functional changes.
11
+
12
+ - README examples (English and Russian, the same blocks) are compiled by `readme-examples.spec.ts` under
13
+ `strict`, `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess`.
14
+ - CI moved to GitHub Actions (PostgreSQL 15–18 on a real replication stand); development dependencies bumped
15
+ (arch-gates 0.12.2, jest-groups 0.7.2, fault-kit 0.3.1).
16
+
17
+ ## 0.2.1 — 2026-11-21
18
+
19
+ ### Fixed
20
+
21
+ - Converting a rejection of a user executor to an `Error` no longer throws on a value without a prototype or with
22
+ a throwing `toString`: the token path that must not throw used to reject, and the observer got no error. Now it
23
+ is an `Error` with a text and the original value in `cause`.
24
+
25
+ ## 0.2.0 — 2026-11-17
26
+
27
+ Fixes found on a real replication stand (primary, streaming, cascading and archive-only replicas). Breaking
28
+ changes — see *Migration*.
29
+
30
+ ### Changed
31
+
32
+ - **A token only from the write connection.** `issueToken()` without an argument took the position on the probe
33
+ connection, which does not see the caller's transaction — inside an open transaction it issued a token without
34
+ the write. Now `issueToken(executor)` requires the connection, and `commitAndIssueToken(client)` sends COMMIT
35
+ and takes the position on the same connection, after checking that a transaction is open there (`SAVEPOINT`):
36
+ a pool, a wrapper around a pool or a connection without `BEGIN` → `TransactionNotOpenError` (COMMIT not sent); a
37
+ failed transaction → ROLLBACK and `TransactionNotCommittedError`.
38
+ - **Load-balanced nodes**: `ReplicaNode.balanced`, `RouteDecision.mustConfirm`, `router.confirm(decision,
39
+ readConnection)`, `stats().confirms`, hook `observer.confirmed`. Without it a balancer address gave 5 of 10
40
+ reads without the write.
41
+ - **Replica restart**: a probe connection dropped from outside evicts the node from the cache at once, and
42
+ `stateTtlMs` is capped at 1000 ms (the replay position rolls back on restart).
43
+ - A token right after a WAL page header is aligned to the page boundary, so an idle primary does not delay it.
44
+ - **Unavailable primary**: with the WAL receiver stopped, the timeline last reported by the same replica
45
+ instance is used, so reads with a token keep going to replicas.
46
+ - **Token lifetime** (`tokenTtlMs`, 60 s; the issue time is in the token, `wallClock`): a token of another
47
+ timeline, another cluster or ahead of the primary keeps reads on the primary at most that long, then reads as
48
+ without a token (`stats().expiredTokens`). Only a **proven** unsatisfiable token expires — by a primary probe
49
+ started after the process first met the token's position — so clock skew never expires a legitimate token.
50
+ - **Cost and ceilings**: `minProbeIntervalMs` (10 ms) per token position (LRU memory of 1024 positions, probe
51
+ sequence numbers instead of clocks): 203 probes/s instead of 2647/s with lagging replicas; `route()` stays within
52
+ `probeTimeoutMs + waitForCatchUpMs`; timers above 2³¹−1 ms are rejected; a probe query over `probeTimeoutMs` no
53
+ longer drops the connection before `connectTimeoutMs` (10 s, new option), so a slow but live replica is usable.
54
+ - **Connections and hooks**: a late failure of an old probe no longer closes the new connection; `close()`
55
+ interrupts running `route()` and no probe connection is reopened after it; failures of async hooks and throwing
56
+ hook getters are swallowed; clocks stepping back or returning non-numbers evict the cache; `stats()` is
57
+ JSON-serializable (lag is a number, not `bigint`).
58
+ - **Token format `v2`** (issue time in the payload, signing domain `pg-replica-sync/token/v2`); weak keys
59
+ (repeated chunks, few distinct bytes, near-repeats, non-string/non-bytes) are rejected; the key check is linear.
60
+
61
+ ### Migration
62
+
63
+ - `router.issueToken()` without an argument → `router.commitAndIssueToken(client)` instead of your own COMMIT, or
64
+ `router.issueToken(pool)` **after** the transaction returned.
65
+ - `v1` tokens read as `token-invalid` (primary) until the client's next write; old instances treat `v2` tokens the
66
+ same way during a rolling deploy — primary only, the guarantee holds.
67
+ - `stateTtlMs` above 1000, timers above 2³¹−1 ms, weak signing keys and clocks not returning finite numbers are
68
+ rejected with `InvalidReplicaSyncOptionsError`.
69
+ - `TokenCodec.encode(position, issuedAt)` — the second argument is required; `DecodedToken` has `issuedAt`.
70
+ - `RouterStats.lagBytes` is `number | null` instead of `bigint | null`.
71
+ - `commitAndIssueToken(pool)` is a type error (`NotAPool`); roll back in your `catch` on any exception.
72
+ - After `close()`: `issueToken`/`commitAndIssueToken` return a primary-only token (COMMIT is sent), `confirm` returns
73
+ `false`; `route()` still throws.
74
+ - Mark balancer addresses `balanced: true` and confirm their decisions.
75
+
76
+ ## 0.1.1 — 2026-11-16
77
+
78
+ ### Fixed
79
+
80
+ - Test flakiness: the specs waited for a target the replica could not reach after `pg_switch_wal` (the insert
81
+ position right after a new segment header); they now wait for a reachable target and with a time ceiling. The
82
+ router code did not change.
83
+
84
+ ## 0.1.0 — 2026-11-15
85
+
86
+ First release: a signed WAL position token (HMAC-SHA256, key rotation, primary-only token), a router excluding
87
+ replicas by pause, promotion, cluster, timeline and position, a lag ceiling without a token, a bounded state cache
88
+ with eviction, waiting for catch-up with a ceiling, a probe with its own connection and timeout, metrics and hooks;
89
+ `parseLsn`/`formatLsn`/`compareLsn`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hoshino Tatsuya
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,314 @@
1
- # Temporary Holding Version
1
+ # @hoshinotatsuya/pg-replica-sync
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@hoshinotatsuya/pg-replica-sync.svg)](https://www.npmjs.com/package/@hoshinotatsuya/pg-replica-sync)
4
+ [![CI](https://github.com/HoshinoTatsuya/pg-replica-sync/actions/workflows/ci.yml/badge.svg)](https://github.com/HoshinoTatsuya/pg-replica-sync/actions/workflows/ci.yml)
5
+
6
+ [Русская версия](README.ru.md) · [Changelog](CHANGELOG.md)
7
+
8
+ Reads from PostgreSQL replicas with a **read-your-writes** guarantee, by WAL position. After a write the client
9
+ gets a signed position token. A read carrying the token goes to a replica only when it is **proven** that the
10
+ replica has replayed that position on the same timeline of the same cluster; otherwise it goes to the primary.
11
+ Anything that cannot be established also sends the read to the primary, never to a replica.
12
+
13
+ **The problem it solves.** With asynchronous streaming replication a user saves a profile, reloads the page — and
14
+ the change is not there, because the read hit a lagging replica. The usual fixes are guesses ("all reads go to the
15
+ primary for N seconds after a write", which breaks when lag exceeds N) or giving up ("all reads to the primary",
16
+ so replicas offload nothing). This package routes each read by the actual replay position of each replica.
17
+
18
+ **When you do not need it:** without replicas; with synchronous replication and `synchronous_commit =
19
+ remote_apply` (every commit already waits for the replica); or when "not older than N" is enough for the read —
20
+ then reads without a token and the lag ceiling (`maxLagBytes`) suffice.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ pnpm add @hoshinotatsuya/pg-replica-sync pg
26
+ pnpm add -D @types/pg # optional, for TypeScript
27
+ ```
28
+
29
+ Peer dependencies: `pg` `^8.18.0`, `@types/pg` `>=8.15.0` (optional). No other runtime dependencies. CommonJS with
30
+ ESM type declarations; checked with `commonjs`, `node16`, `nodenext` and `bundler` resolution.
31
+
32
+ The **probe role** (the user in each node's `connection`) needs membership in `pg_monitor` or at least
33
+ `pg_read_all_stats`: without it the replica's timeline is invisible, every replica is excluded as
34
+ `no-stats-privilege` and all reads go to the primary (the reason is named so that "everything on the primary" does
35
+ not look like healthy operation).
36
+
37
+ ## Quick start
38
+
39
+ ```ts
40
+ import { ReplicaRouter } from '@hoshinotatsuya/pg-replica-sync';
41
+ import { Pool } from 'pg';
42
+
43
+ /** A required environment variable: missing means a startup failure, not `undefined` in the options. */
44
+ const required = (key: string): string => {
45
+ const value = process.env[key];
46
+ if (value === undefined || value === '') {
47
+ throw new Error(`${key} is not set`);
48
+ }
49
+ return value;
50
+ };
51
+
52
+ const primaryPool = new Pool({ connectionString: required('PRIMARY_URL') });
53
+ const replica1Pool = new Pool({ connectionString: required('REPLICA1_URL') });
54
+ const replica2Pool = new Pool({ connectionString: required('REPLICA2_URL') });
55
+
56
+ export const router = new ReplicaRouter<Pool>({
57
+ // `connection` is what the router's own probe connects to; `target` is what you read with.
58
+ primary: { name: 'primary', connection: required('PRIMARY_URL'), target: primaryPool },
59
+ replicas: [
60
+ { name: 'r1', connection: required('REPLICA1_URL'), target: replica1Pool },
61
+ { name: 'r2', connection: required('REPLICA2_URL'), target: replica2Pool },
62
+ ],
63
+ // >= 32 RANDOM bytes (openssl rand -base64 32); to rotate, put the new key first
64
+ secrets: [required('REPLICA_TOKEN_KEY')],
65
+ });
66
+
67
+ // Write: COMMIT and the token in one call, on the transaction's own connection.
68
+ export async function renameProfile(id: number, name: string): Promise<string> {
69
+ const client = await primaryPool.connect();
70
+ try {
71
+ await client.query('BEGIN');
72
+ await client.query('UPDATE profiles SET name = $1 WHERE id = $2', [name, id]);
73
+ return await router.commitAndIssueToken(client); // give it to the client: a cookie, a header
74
+ } catch (error) {
75
+ // An exception means "no write, or unknown": end the transaction HERE, otherwise the connection
76
+ // goes back to the pool with an open transaction and somebody else's COMMIT commits it.
77
+ await client.query('ROLLBACK').catch(() => undefined);
78
+ throw error;
79
+ } finally {
80
+ client.release();
81
+ }
82
+ }
83
+
84
+ // Read: with the token of the client's last write (undefined when there is none).
85
+ export async function loadProfile(id: number, token: string | undefined) {
86
+ const { target, role, reason } = await router.route(token);
87
+ const { rows } = await target.query('SELECT * FROM profiles WHERE id = $1', [id]);
88
+ return { rows, servedBy: role, reason }; // role: 'primary' | 'replica'
89
+ }
90
+ ```
91
+
92
+ Every `ts` block of this README (and of `README.ru.md`) is compiled by the spec `readme-examples.spec.ts` under
93
+ `strict`, `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess` against the package sources; objects of
94
+ your application that a block does not declare itself (pools, `router`, `token`, `work`, …) are declared by the
95
+ spec's prelude.
96
+
97
+ `target` is whatever you read a node with (a `pg` pool, drizzle, anything); the package never touches it. Node
98
+ state is probed by the router's **own** connections, one per node, so a probe can be cut off by its timeout
99
+ without touching your pool. `router.close()` (or `await using`) closes only those.
100
+
101
+ ## API
102
+
103
+ ### `new ReplicaRouter<TTarget>(options)`
104
+
105
+ | Option | Default | Meaning |
106
+ |---|---|---|
107
+ | `primary`, `replicas` | — | `{ name, connection, target, balanced? }`; `connection` — URL or `pg` `ClientConfig` for the probe; `balanced: true` — the address is a load balancer over several servers (see below) |
108
+ | `secrets` | — | signing keys, newest first (rotation): ≥ 32 random bytes; keys that are guessable by shape (repeated chunks, few distinct bytes, near-repeats) are rejected |
109
+ | `stateTtlMs` | 250 (≤ 1000) | lifetime of a cached node state |
110
+ | `probeTimeoutMs` | 1 000 | ceiling of one probe |
111
+ | `connectTimeoutMs` | 10 000 | a probe connection that stays silent this long is dropped and reopened |
112
+ | `unavailableRetryMs` | 2 000 | how long a failed probe is remembered |
113
+ | `maxLagBytes` | 1 048 576 | lag ceiling for reads **without** a token, in WAL bytes |
114
+ | `waitForCatchUpMs` | 0 | how long a read with a token may wait for a lagging replica |
115
+ | `catchUpPollMs` | 10 | poll interval while waiting |
116
+ | `minProbeIntervalMs` | 10 | a lagging replica is re-probed at most this often for the same token position |
117
+ | `tokenTtlMs` | 60 000 | lifetime of a token that is **proven** unsatisfiable (other timeline/cluster, ahead of the primary) |
118
+ | `observer` | — | hooks `routed`, `probed`, `tokenUnresolved`, `confirmed` (may be async; failures are swallowed) |
119
+ | `clock`, `wallClock` | `performance.now`, `Date.now` | for tests |
120
+
121
+ Invalid options throw `InvalidReplicaSyncOptionsError` at construction (timers above 2³¹−1 ms included).
122
+ Defaults are exported as `REPLICA_SYNC_DEFAULTS`.
123
+
124
+ ### Tokens after a write
125
+
126
+ The token must take the position **after** COMMIT, otherwise a replica could "catch up" with it without the write.
127
+
128
+ - **`commitAndIssueToken(client)`** → `Promise<string>` — sends COMMIT on the transaction's connection and takes
129
+ the position from it. Before COMMIT it verifies that a transaction is open **on this connection** (`SAVEPOINT`):
130
+ a pool, a wrapper around a pool or a connection without `BEGIN` → `TransactionNotOpenError`, and COMMIT is not
131
+ sent. A failed transaction is ended with ROLLBACK → `TransactionNotCommittedError`. A pool is also rejected by
132
+ the type (`NotAPool`). **Any exception means "no write or unknown"**: roll back in your `catch` (as in the quick
133
+ start). After COMMIT went through it never throws: a token with the position, or a primary-only token.
134
+ - **`issueToken(executor)`** → `Promise<string>` — when somebody else commits (an ORM, a transaction helper): call
135
+ it **after** COMMIT returned, with that connection or any primary connection (the insert position is monotonic).
136
+ An open transaction with writes on this connection → a primary-only token (`write_pending`). A transaction on
137
+ ANOTHER connection is invisible: prefer `commitAndIssueToken` when you can.
138
+
139
+ `issueToken` does not throw on node failures: when the position cannot be determined (node in recovery, timeout,
140
+ closed router) it returns a **primary-only** token — reads with it go to the primary (`token-unresolved`) until the
141
+ next write. The position is `pg_current_wal_insert_lsn()` (correct even with `synchronous_commit = off`), aligned
142
+ to a WAL page boundary when it sits right after a page header.
143
+
144
+ ### `route(token?)` → `Promise<RouteDecision>`
145
+
146
+ `{ role, node, target, reason, excluded, catchUpPolls, mustConfirm }`. Bounded in time by
147
+ `probeTimeoutMs + waitForCatchUpMs`. A malformed, truncated, foreign-key-signed, old-format or too long
148
+ (> 256 chars) token gives `token-invalid` and the primary — it never fails the request.
149
+
150
+ **With a token** a replica is eligible only if **every** condition holds; otherwise it is excluded with a reason
151
+ (`EXCLUSION_REASON`):
152
+
153
+ | Condition | How | Otherwise |
154
+ |---|---|---|
155
+ | the probe answered in time | own connection, `probeTimeoutMs` | `unavailable` |
156
+ | the node is a replica | `pg_is_in_recovery()` | `promoted` |
157
+ | replay is not paused | `pg_get_wal_replay_pause_state()` | `paused` |
158
+ | same cluster | `pg_control_system().system_identifier` | `other-cluster` / `state-unknown` |
159
+ | same timeline | `pg_stat_wal_receiver.received_tli` | `timeline-mismatch` / `timeline-unknown` / `no-stats-privilege` |
160
+ | caught up | `pg_last_wal_replay_lsn() >= token position` | `behind` |
161
+
162
+ Several eligible replicas are used round-robin. None → the primary, with the reason (`ROUTE_REASON`):
163
+ `token-other-timeline` (failover happened), `token-ahead-of-primary`, `token-foreign` (other cluster) or
164
+ `no-replica-eligible`.
165
+
166
+ **Without a token** a replica is eligible under the same conditions, but instead of "caught up" it must lag the
167
+ primary's insert position by at most `maxLagBytes` (`replica-within-lag`); if the primary's state is unknown, the
168
+ read goes to the primary (`primary-state-unknown`). Lag is measured in WAL bytes, not seconds — a replica with
169
+ `recovery_min_apply_delay` may be an hour behind within the byte ceiling, so such replicas are not suitable for
170
+ reads without a token.
171
+
172
+ ### Load-balanced nodes — `confirm(decision, readConnection)` → `Promise<boolean>`
173
+
174
+ A node address must lead to **one** server: the probe proves the state of the server it is connected to. If the
175
+ address is a balancer over several replicas (a Kubernetes read-only service, a proxy, a cloud reader endpoint),
176
+ mark it `balanced: true`; its decisions come with `mustConfirm: true` and are confirmed **on the read connection**:
177
+
178
+ ```ts
179
+ const decision = await router.route(token);
180
+ const client = await decision.target.connect();
181
+ try {
182
+ // `confirm` runs the same probe on THIS connection; `false` means read from the primary.
183
+ const reader = (await router.confirm(decision, client)) ? client : primaryPool;
184
+ await reader.query('SELECT 1');
185
+ } finally {
186
+ client.release();
187
+ }
188
+ ```
189
+
190
+ The read role then needs the same privileges as the probe role. A failure, a timeout or "cannot determine" is
191
+ `false`; a primary decision needs no confirmation (`true`). With a connection-level balancer (TCP, a Kubernetes
192
+ service, PgBouncer in session mode) the connection is pinned to the server; with a transaction pooler over several
193
+ servers call `confirm` as the **first statement inside the read transaction** and read in it. Statement-mode
194
+ pooling is not supported.
195
+
196
+ ### Other exports
197
+
198
+ - `stats()` → `RouterStats` — reads per role, `ROUTE_REASON` and `EXCLUSION_REASON` counters, probes ok/failed,
199
+ last measured lag per replica (number or `null`), expired tokens, confirm results; serializable with
200
+ `JSON.stringify`.
201
+ - `close()` / `[Symbol.asyncDispose]` — closes probe connections; later `route()` throws, `issueToken` and
202
+ `commitAndIssueToken` return primary-only tokens (COMMIT is still sent), `confirm` returns `false`.
203
+ - `parseLsn`, `formatLsn`, `compareLsn` — WAL positions as 64-bit numbers (`'10/0' > '9/0'`, unlike strings);
204
+ `InvalidLsnError`.
205
+ - `TokenCodec` — the token format on its own (`encode(position, issuedAt)`, `decode(token)`), `TOKEN_FORMAT`.
206
+ - `PROBE_SQL`, `NODE_ROLE`, `ROUTE_REASON`, `EXCLUSION_REASON`, `REPLICA_SYNC_DEFAULTS`.
207
+ - Errors: `InvalidReplicaSyncOptionsError`, `TransactionNotOpenError`, `TransactionNotCommittedError`,
208
+ `ProbeTimeoutError`, `ProbeConnectionClosedError`, `InvalidLsnError`.
209
+
210
+ ### Metrics and tuning
211
+
212
+ ```ts
213
+ import { ReplicaRouter } from '@hoshinotatsuya/pg-replica-sync';
214
+
215
+ const key = process.env.REPLICA_TOKEN_KEY;
216
+ if (key === undefined) {
217
+ throw new Error('REPLICA_TOKEN_KEY is not set');
218
+ }
219
+ const observed = new ReplicaRouter<Pool>({
220
+ primary: { name: 'primary', connection: 'postgres://app@primary/app', target: primaryPool },
221
+ replicas: [{ name: 'r1', connection: 'postgres://app@replica-1/app', target: replica1Pool }],
222
+ secrets: [key],
223
+ waitForCatchUpMs: 20, // wait up to 20 ms for a lagging replica before falling back to the primary
224
+ observer: {
225
+ routed: (decision) => console.log('route', decision.role, decision.reason, decision.excluded),
226
+ probed: (event) => console.log('probe', event.node, event.outcome, event.durationMs),
227
+ },
228
+ });
229
+ // Plain numbers, safe for JSON.stringify: reads per role, reasons, exclusions, probes, lag per replica.
230
+ setInterval(() => console.log(JSON.stringify(observed.stats())), 60_000);
231
+ ```
232
+
233
+ ### With a transaction helper
234
+
235
+ The router returns `target`; the caller opens the transaction (here `transactionKeepingFailure` from
236
+ `@hoshinotatsuya/pg-runtime`):
237
+
238
+ ```ts
239
+ // read: a read-only transaction on the chosen node
240
+ const { target } = await router.route(token);
241
+ await transactionKeepingFailure(target, work, { readOnly: true });
242
+
243
+ // write: on the primary; the token after the transaction returned (COMMIT is done), any primary connection
244
+ await transactionKeepingFailure(primaryDb, work);
245
+ const next = await router.issueToken(primaryPool);
246
+ ```
247
+
248
+ ## Guarantees and limits
249
+
250
+ - **Read-your-writes for the bearer of the token.** A read with a token sees everything committed before the
251
+ token was issued (within the token's cluster and timeline). Writes of others made later may be invisible: this
252
+ is not linearizability; for "the latest value" read from the primary.
253
+ - **Causality between clients only by passing the token** (in a message, a header). Without it the other client
254
+ gets only "lag ≤ `maxLagBytes`".
255
+ - **Monotonic reads relative to the token only**: two reads with one token may hit different replicas. For
256
+ monotonic reads advance the token (issue a new one after reading) or stick to one replica.
257
+ - **Cost**: node state is cached (`stateTtlMs`, evicted on every access; keys are only configured nodes), and
258
+ concurrent reads share one probe. The extra query per read appears only right after the client's own write
259
+ (fresh token ahead of the cache) — then all replicas are probed at once; lagging replicas are re-probed at most
260
+ every `minProbeIntervalMs` per token position (positions remembered: 1024, LRU). Measured on a laptop
261
+ (`bench/cost.cjs`, PostgreSQL 17, primary + 2 replicas): a probe p50 0.26 ms; the same token for 5000 reads —
262
+ 2 probes in total; write → read with a new token — 2 probes, and 999 of 1000 such reads went to a replica.
263
+ - Not detected: a token taken before COMMIT on **another** connection; a balancer without `balanced: true`; two
264
+ independent promotions to the same timeline number (split history — fencing is the orchestrator's job); a
265
+ replica that switched timelines from the archive while its WAL receiver was stopped.
266
+ - The cache ceiling is the window in which a node may change its role unnoticed when a dropped probe connection
267
+ has not reached the client: at most `stateTtlMs` ≤ 1 s. Safe for read-your-writes; `paused`, unavailability and
268
+ a restart (replay position rolls back) are noticed up to that late.
269
+
270
+ ## Failure behavior
271
+
272
+ Fails toward the primary:
273
+
274
+ - unknown state, timeout, missing privilege, unknown timeline, unknown primary state → the primary, with a named
275
+ reason;
276
+ - an invalid or foreign token → `token-invalid`, the primary; it never fails the request;
277
+ - a token that no replica can ever satisfy (failover, other cluster, ahead of the primary) keeps reads on the
278
+ primary for `tokenTtlMs`, then is treated as no token; only a **proven** unsatisfiable token expires, so clock
279
+ skew between processes never expires a legitimate token;
280
+ - **after failover** the replica that became primary is excluded as `promoted`; tokens of the old timeline go to
281
+ the primary (`token-other-timeline`); updating the primary address in the options is the caller's job;
282
+ - when the primary is down, reads with a token still go to a replica that replayed it on the timeline this
283
+ replica instance last reported; reads without a token go to the primary (`primary-state-unknown`);
284
+ - a throwing or rejecting observer hook never breaks routing or the process.
285
+
286
+ ## Compatibility
287
+
288
+ - Node.js ≥ 24.
289
+ - PostgreSQL 15, 16, 17, 18 (the full suite runs on each, `PG_TEST_IMAGE`). Older versions are not supported.
290
+ - Load balancing checked with PgBouncer 1.26 in transaction mode over two replicas.
291
+ - `pg` 8.18+.
292
+
293
+ ## Testing and development
294
+
295
+ ```sh
296
+ pnpm install
297
+ pnpm typecheck
298
+ pnpm lint
299
+ pnpm test # needs Docker: a real streaming-replication stand (see below)
300
+ pnpm test:consumers # packs the build into throwaway commonjs/node16/nodenext/ESM projects
301
+ pnpm build
302
+ ```
303
+
304
+ `pnpm test` starts **real streaming replication** (`scripts/with-replication.sh`): a primary with a WAL archive,
305
+ three replicas of `postgres:17-alpine` (`PG_TEST_IMAGE` for another; 15, 16 and 18 are tested) via
306
+ `pg_basebackup -R` with physical slots, a cascading replica, an archive-only replica and PgBouncer in transaction
307
+ mode over the first two (`PG_BOUNCER_IMAGE`, pinned by digest). The application role `app` (`pg_monitor`, no
308
+ superuser) routes and reads; pause, apply delay, stopping the WAL receiver and promotion are done as superuser.
309
+ Specs change the shared topology, so groups run in one worker (`JEST_GROUP_WORKERS=1`) through `jest-groups`
310
+ (at most 300 tests per group, groups one after another). Containers and the network are removed on exit.
311
+
312
+ ## License
313
+
314
+ [MIT](LICENSE) © 2026 Hoshino Tatsuya