@hoshinotatsuya/pg-replica-sync 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/compare-lsn.d.mts +3 -3
  4. package/dist/compare-lsn.d.ts +3 -3
  5. package/dist/compare-lsn.js +3 -3
  6. package/dist/constants/exclusion-reason.constant.d.mts +12 -12
  7. package/dist/constants/exclusion-reason.constant.d.ts +12 -12
  8. package/dist/constants/exclusion-reason.constant.d.ts.map +1 -1
  9. package/dist/constants/exclusion-reason.constant.js +12 -12
  10. package/dist/constants/exclusion-reason.constant.js.map +1 -1
  11. package/dist/constants/node-role.constant.d.mts +1 -1
  12. package/dist/constants/node-role.constant.d.ts +1 -1
  13. package/dist/constants/node-role.constant.d.ts.map +1 -1
  14. package/dist/constants/node-role.constant.js +1 -1
  15. package/dist/constants/node-role.constant.js.map +1 -1
  16. package/dist/constants/probe-sql.constant.d.mts +25 -25
  17. package/dist/constants/probe-sql.constant.d.ts +25 -25
  18. package/dist/constants/probe-sql.constant.js +25 -25
  19. package/dist/constants/replica-sync-defaults.constant.d.mts +26 -26
  20. package/dist/constants/replica-sync-defaults.constant.d.ts +26 -26
  21. package/dist/constants/replica-sync-defaults.constant.d.ts.map +1 -1
  22. package/dist/constants/replica-sync-defaults.constant.js +26 -26
  23. package/dist/constants/replica-sync-defaults.constant.js.map +1 -1
  24. package/dist/constants/route-reason.constant.d.mts +13 -13
  25. package/dist/constants/route-reason.constant.d.ts +13 -13
  26. package/dist/constants/route-reason.constant.d.ts.map +1 -1
  27. package/dist/constants/route-reason.constant.js +13 -13
  28. package/dist/constants/route-reason.constant.js.map +1 -1
  29. package/dist/constants/token-format.constant.d.mts +11 -11
  30. package/dist/constants/token-format.constant.d.ts +11 -11
  31. package/dist/constants/token-format.constant.d.ts.map +1 -1
  32. package/dist/constants/token-format.constant.js +11 -11
  33. package/dist/constants/token-format.constant.js.map +1 -1
  34. package/dist/constants/wal-format.constant.d.mts +6 -6
  35. package/dist/constants/wal-format.constant.d.ts +6 -6
  36. package/dist/constants/wal-format.constant.d.ts.map +1 -1
  37. package/dist/constants/wal-format.constant.js +6 -6
  38. package/dist/constants/wal-format.constant.js.map +1 -1
  39. package/dist/decode-canonical-base64url.d.mts +1 -1
  40. package/dist/decode-canonical-base64url.d.ts +1 -1
  41. package/dist/decode-canonical-base64url.d.ts.map +1 -1
  42. package/dist/decode-canonical-base64url.js +1 -1
  43. package/dist/decode-canonical-base64url.js.map +1 -1
  44. package/dist/deep-freeze.d.mts +7 -7
  45. package/dist/deep-freeze.d.ts +7 -7
  46. package/dist/deep-freeze.js +9 -9
  47. package/dist/deep-freeze.js.map +1 -1
  48. package/dist/destroy-client.d.mts +3 -3
  49. package/dist/destroy-client.d.ts +3 -3
  50. package/dist/destroy-client.js +3 -3
  51. package/dist/evaluate-replica.d.mts +3 -3
  52. package/dist/evaluate-replica.d.ts +3 -3
  53. package/dist/evaluate-replica.js +3 -3
  54. package/dist/format-lsn.d.mts +1 -1
  55. package/dist/format-lsn.d.ts +1 -1
  56. package/dist/format-lsn.d.ts.map +1 -1
  57. package/dist/format-lsn.js +2 -2
  58. package/dist/format-lsn.js.map +1 -1
  59. package/dist/invalid-lsn.error.d.mts +1 -1
  60. package/dist/invalid-lsn.error.d.ts +1 -1
  61. package/dist/invalid-lsn.error.d.ts.map +1 -1
  62. package/dist/invalid-lsn.error.js +2 -2
  63. package/dist/invalid-lsn.error.js.map +1 -1
  64. package/dist/invalid-replica-sync-options.error.d.mts +1 -1
  65. package/dist/invalid-replica-sync-options.error.d.ts +1 -1
  66. package/dist/invalid-replica-sync-options.error.d.ts.map +1 -1
  67. package/dist/invalid-replica-sync-options.error.js +1 -1
  68. package/dist/invalid-replica-sync-options.error.js.map +1 -1
  69. package/dist/lag-bytes.d.mts +3 -3
  70. package/dist/lag-bytes.d.ts +3 -3
  71. package/dist/lag-bytes.js +3 -3
  72. package/dist/lsn-or-null.d.mts +1 -1
  73. package/dist/lsn-or-null.d.ts +1 -1
  74. package/dist/lsn-or-null.d.ts.map +1 -1
  75. package/dist/lsn-or-null.js +1 -1
  76. package/dist/lsn-or-null.js.map +1 -1
  77. package/dist/notify.d.mts +7 -7
  78. package/dist/notify.d.ts +7 -7
  79. package/dist/notify.js +8 -8
  80. package/dist/notify.js.map +1 -1
  81. package/dist/parse-lsn.d.mts +3 -3
  82. package/dist/parse-lsn.d.ts +3 -3
  83. package/dist/parse-lsn.js +3 -3
  84. package/dist/probe-connection-closed.error.d.mts +1 -1
  85. package/dist/probe-connection-closed.error.d.ts +1 -1
  86. package/dist/probe-connection-closed.error.d.ts.map +1 -1
  87. package/dist/probe-connection-closed.error.js +2 -2
  88. package/dist/probe-connection-closed.error.js.map +1 -1
  89. package/dist/probe-connection.d.mts +20 -20
  90. package/dist/probe-connection.d.ts +20 -20
  91. package/dist/probe-connection.d.ts.map +1 -1
  92. package/dist/probe-connection.js +25 -25
  93. package/dist/probe-connection.js.map +1 -1
  94. package/dist/probe-timeout.error.d.mts +1 -1
  95. package/dist/probe-timeout.error.d.ts +1 -1
  96. package/dist/probe-timeout.error.d.ts.map +1 -1
  97. package/dist/probe-timeout.error.js +2 -2
  98. package/dist/probe-timeout.error.js.map +1 -1
  99. package/dist/read-node-state.d.mts +3 -3
  100. package/dist/read-node-state.d.ts +3 -3
  101. package/dist/read-node-state.js +4 -4
  102. package/dist/read-node-state.js.map +1 -1
  103. package/dist/replica-router.d.mts +133 -133
  104. package/dist/replica-router.d.ts +133 -133
  105. package/dist/replica-router.d.ts.map +1 -1
  106. package/dist/replica-router.js +162 -162
  107. package/dist/replica-router.js.map +1 -1
  108. package/dist/require-integer.d.mts +1 -1
  109. package/dist/require-integer.d.ts +1 -1
  110. package/dist/require-integer.d.ts.map +1 -1
  111. package/dist/require-integer.js +3 -3
  112. package/dist/require-integer.js.map +1 -1
  113. package/dist/secret-weakness.d.mts +13 -13
  114. package/dist/secret-weakness.d.ts +13 -13
  115. package/dist/secret-weakness.js +16 -16
  116. package/dist/secret-weakness.js.map +1 -1
  117. package/dist/smallest-period.d.mts +4 -4
  118. package/dist/smallest-period.d.ts +4 -4
  119. package/dist/smallest-period.js +4 -4
  120. package/dist/sql-state-of.d.mts +6 -6
  121. package/dist/sql-state-of.d.ts +6 -6
  122. package/dist/sql-state-of.js +6 -6
  123. package/dist/state-cache.d.mts +14 -14
  124. package/dist/state-cache.d.ts +14 -14
  125. package/dist/state-cache.d.ts.map +1 -1
  126. package/dist/state-cache.js +15 -15
  127. package/dist/state-cache.js.map +1 -1
  128. package/dist/timeline-of.d.mts +2 -2
  129. package/dist/timeline-of.d.ts +2 -2
  130. package/dist/timeline-of.js +2 -2
  131. package/dist/to-error.d.mts +1 -1
  132. package/dist/to-error.d.ts +1 -1
  133. package/dist/to-error.d.ts.map +1 -1
  134. package/dist/to-error.js +1 -1
  135. package/dist/to-error.js.map +1 -1
  136. package/dist/token-codec.d.mts +10 -10
  137. package/dist/token-codec.d.ts +10 -10
  138. package/dist/token-codec.js +31 -31
  139. package/dist/token-codec.js.map +1 -1
  140. package/dist/token-lsn.d.mts +13 -13
  141. package/dist/token-lsn.d.ts +13 -13
  142. package/dist/token-lsn.js +13 -13
  143. package/dist/transaction-not-committed.error.d.mts +2 -2
  144. package/dist/transaction-not-committed.error.d.ts +2 -2
  145. package/dist/transaction-not-committed.error.d.ts.map +1 -1
  146. package/dist/transaction-not-committed.error.js +3 -3
  147. package/dist/transaction-not-committed.error.js.map +1 -1
  148. package/dist/transaction-not-open.error.d.mts +5 -5
  149. package/dist/transaction-not-open.error.d.ts +5 -5
  150. package/dist/transaction-not-open.error.js +6 -6
  151. package/dist/transaction-not-open.error.js.map +1 -1
  152. package/dist/types/cache-entry.type.d.mts +4 -4
  153. package/dist/types/cache-entry.type.d.ts +4 -4
  154. package/dist/types/clock.type.d.mts +3 -3
  155. package/dist/types/clock.type.d.ts +3 -3
  156. package/dist/types/confirm-event.type.d.mts +3 -3
  157. package/dist/types/confirm-event.type.d.ts +3 -3
  158. package/dist/types/decoded-token.type.d.mts +2 -2
  159. package/dist/types/decoded-token.type.d.ts +2 -2
  160. package/dist/types/evaluated.type.d.mts +1 -1
  161. package/dist/types/evaluated.type.d.ts +1 -1
  162. package/dist/types/evaluated.type.d.ts.map +1 -1
  163. package/dist/types/exclusion.type.d.mts +1 -1
  164. package/dist/types/exclusion.type.d.ts +1 -1
  165. package/dist/types/exclusion.type.d.ts.map +1 -1
  166. package/dist/types/node-state.type.d.mts +13 -13
  167. package/dist/types/node-state.type.d.ts +13 -13
  168. package/dist/types/node-state.type.d.ts.map +1 -1
  169. package/dist/types/not-a-pool.type.d.mts +5 -5
  170. package/dist/types/not-a-pool.type.d.ts +5 -5
  171. package/dist/types/probe-event.type.d.mts +1 -1
  172. package/dist/types/probe-event.type.d.ts +1 -1
  173. package/dist/types/probe-event.type.d.ts.map +1 -1
  174. package/dist/types/probe-outcome.type.d.mts +1 -1
  175. package/dist/types/probe-outcome.type.d.ts +1 -1
  176. package/dist/types/probe-outcome.type.d.ts.map +1 -1
  177. package/dist/types/probe-sample.type.d.mts +1 -1
  178. package/dist/types/probe-sample.type.d.ts +1 -1
  179. package/dist/types/probe-sample.type.d.ts.map +1 -1
  180. package/dist/types/replica-node.type.d.mts +7 -7
  181. package/dist/types/replica-node.type.d.ts +7 -7
  182. package/dist/types/replica-requirement.type.d.mts +2 -2
  183. package/dist/types/replica-requirement.type.d.ts +2 -2
  184. package/dist/types/replica-router-options.type.d.mts +25 -25
  185. package/dist/types/replica-router-options.type.d.ts +25 -25
  186. package/dist/types/replica-router-options.type.d.ts.map +1 -1
  187. package/dist/types/route-decision.type.d.mts +5 -5
  188. package/dist/types/route-decision.type.d.ts +5 -5
  189. package/dist/types/route-decision.type.d.ts.map +1 -1
  190. package/dist/types/router-observer.type.d.mts +5 -5
  191. package/dist/types/router-observer.type.d.ts +5 -5
  192. package/dist/types/router-observer.type.d.ts.map +1 -1
  193. package/dist/types/router-stats.type.d.mts +8 -8
  194. package/dist/types/router-stats.type.d.ts +8 -8
  195. package/dist/types/router-stats.type.d.ts.map +1 -1
  196. package/dist/types/sql-command-executor.type.d.mts +4 -4
  197. package/dist/types/sql-command-executor.type.d.ts +4 -4
  198. package/dist/types/sql-query-executor.type.d.mts +3 -3
  199. package/dist/types/sql-query-executor.type.d.ts +3 -3
  200. package/dist/types/wal-layout.type.d.mts +1 -1
  201. package/dist/types/wal-layout.type.d.ts +1 -1
  202. package/dist/types/wal-layout.type.d.ts.map +1 -1
  203. package/dist/types/wal-position.type.d.mts +5 -5
  204. package/dist/types/wal-position.type.d.ts +5 -5
  205. package/dist/types/wal-position.type.d.ts.map +1 -1
  206. package/dist/value-text.d.mts +5 -5
  207. package/dist/value-text.d.ts +5 -5
  208. package/dist/value-text.js +6 -6
  209. package/dist/value-text.js.map +1 -1
  210. package/dist/wal-layout-of.d.mts +1 -1
  211. package/dist/wal-layout-of.d.ts +1 -1
  212. package/dist/wal-layout-of.d.ts.map +1 -1
  213. package/dist/wal-layout-of.js +1 -1
  214. package/dist/wal-layout-of.js.map +1 -1
  215. package/package.json +11 -9
@@ -5,35 +5,35 @@ import type { RouterStats } from './types/router-stats.type.mjs';
5
5
  import type { SqlCommandExecutor } from './types/sql-command-executor.type.mjs';
6
6
  import type { SqlQueryExecutor } from './types/sql-query-executor.type.mjs';
7
7
  /**
8
- * Маршрутизатор чтений «читаешь свои записи»: после записи — токен с
9
- * соединения, на котором прошёл COMMIT (`issueToken(client)` или
10
- * `commitAndIssueToken(client)`), чтение с токеном — `route(token)`. Реплика
11
- * выбирается, только если доказано, что она догнала позицию токена на той же
12
- * линии времени того же кластера; всё, что не удалось установить, — мастер. Без
13
- * токена — реплика с отставанием в потолке от позиции вставки мастера.
8
+ * A "read your writes" router: after a write, a token from the
9
+ * connection on which COMMIT went through (`issueToken(client)` or
10
+ * `commitAndIssueToken(client)`), a read with the token is `route(token)`. A replica
11
+ * is chosen only if it is proven that it has caught up with the token position on the same
12
+ * timeline of the same cluster; everything that could not be established goes to the primary. Without
13
+ * a token — a replica whose lag from the primary insert position is within the ceiling.
14
14
  *
15
- * Состояние узлов снимается своими соединениями зонда (по одному на узел) и
16
- * кэшируется на `stateTtlMs`; одновременные чтения ждут один зонд узла, а новый
17
- * зонд узла — не чаще `minProbeIntervalMs`. Каждое `route()` укладывается в
15
+ * The node state is taken by own probe connections (one per node) and
16
+ * cached for `stateTtlMs`; concurrent reads wait for one probe of a node, and a new
17
+ * probe of a node happens no more often than `minProbeIntervalMs`. Each `route()` fits into
18
18
  * `probeTimeoutMs + waitForCatchUpMs`.
19
19
  */
20
20
  export declare class ReplicaRouter<TTarget> {
21
21
  /**
22
- * Причины «мастер», которые после failover или подмены кластера не снимет ни
23
- * одна реплика: такой токен держит мастер `tokenTtlMs`, затем — как без токена.
24
- * Истечение — только если причина ДОКАЗАНА состоянием мастера из зонда, начатого
25
- * после первой встречи процесса с позицией токена (или исключением каждой
26
- * реплики как чужого кластера). Состояние, снятое раньше, о токене ничего не
27
- * говорит: свежий законный токен впереди него законно, и истечение по нему
28
- * отправило бы чтение на реплику без записи. Токен «без позиции» сюда НЕ
29
- * входит: его позиция неизвестна, и «как без токена» могло бы отправить чтение
30
- * на реплику без этой записи (с задержкой применения она в потолке отставания) —
31
- * он держит мастер, пока клиент не получит новый токен.
22
+ * "Primary" reasons that after a failover or a cluster substitution no
23
+ * replica will lift: such a token holds the primary for `tokenTtlMs`, then it is handled as without a token.
24
+ * Expiry happens only if the reason is PROVEN by the primary state from a probe started
25
+ * after the process first met the token position (or by excluding each
26
+ * replica as another cluster). A state taken earlier says nothing about the token:
27
+ * a fresh legitimate token is legitimately ahead of it, and expiry based on it would
28
+ * send the read to a replica without the write. A token "without a position" does NOT
29
+ * belong here: its position is unknown, and "as without a token" could send the read
30
+ * to a replica without this write (with an apply delay it is within the lag ceiling) —
31
+ * it holds the primary until the client gets a new token.
32
32
  */
33
33
  private static readonly UNSATISFIABLE;
34
- /** SQLSTATE: команда транзакционного блока вне транзакции. */
34
+ /** SQLSTATE: a transaction block command outside a transaction. */
35
35
  private static readonly NO_ACTIVE_TRANSACTION;
36
- /** SQLSTATE: транзакция в ошибке, команды до её конца отвергаются. */
36
+ /** SQLSTATE: the transaction is in error, commands until its end are rejected. */
37
37
  private static readonly IN_FAILED_TRANSACTION;
38
38
  private readonly codec;
39
39
  private readonly primary;
@@ -42,12 +42,12 @@ export declare class ReplicaRouter<TTarget> {
42
42
  private readonly inflight;
43
43
  private readonly inflightSeq;
44
44
  /**
45
- * Позиция токена → номер зонда при первой встрече с ней (потолок частоты
46
- * зондов и доказательство невыполнимости), не больше `POSITION_MEMORY`
47
- * записей, вытесняется давно не встречавшаяся (LRU).
45
+ * Token position → the probe number at the first encounter with it (the probe frequency
46
+ * ceiling and the proof of unsatisfiability), no more than `POSITION_MEMORY`
47
+ * entries, the one not seen for the longest time is evicted (LRU).
48
48
  */
49
49
  private readonly seenPositions;
50
- /** Последняя линия времени, которую приёмник WAL показал у экземпляра реплики. */
50
+ /** The last timeline that the WAL receiver showed on the replica instance. */
51
51
  private readonly lastTimeline;
52
52
  private readonly requirements;
53
53
  private readonly cache;
@@ -68,181 +68,181 @@ export declare class ReplicaRouter<TTarget> {
68
68
  private readonly counters;
69
69
  constructor(options: ReplicaRouterOptions<TTarget>);
70
70
  /**
71
- * Токен позиции после записи — с `executor`, на котором прошёл COMMIT (или с
72
- * любым соединением мастера ПОСЛЕ того, как COMMIT вернулся: позиция вставки
73
- * монотонна). Аргумент обязателен: соединение зонда или пул не видят
74
- * незакоммиченную транзакцию ДРУГОГО соединения, и токен, взятый ими до
75
- * COMMIT, оказался бы меньше позиции коммита — реплика «догнала» бы его без
76
- * этой записи. Позицию определить не смогли (узел в recovery, транзакция с
77
- * записью на этом соединении не закоммичена, отказ, потолок времени) — токен
78
- * «только мастер», а не исключение: клиент с ним читает с мастера.
79
- * Так же после `close()`: запись уже прошла, и исключение выглядело бы её
80
- * отказом и толкало бы к повтору.
71
+ * The position token after a write — from the `executor` on which COMMIT went through (or from
72
+ * any primary connection AFTER COMMIT returned: the insert position
73
+ * is monotonic). The argument is required: a probe connection or a pool does not see
74
+ * an uncommitted transaction of ANOTHER connection, and a token taken by them before
75
+ * COMMIT would be smaller than the commit position — a replica would "catch up" with it without
76
+ * this write. If the position could not be determined (the node is in recovery, a transaction with
77
+ * a write on this connection is not committed, a refusal, the time ceiling), the token is
78
+ * "primary only", not an exception: a client with it reads from the primary.
79
+ * The same after `close()`: the write has already gone through, and an exception would look like its
80
+ * refusal and push towards a retry.
81
81
  */
82
82
  issueToken(executor: SqlQueryExecutor): Promise<string>;
83
83
  /**
84
- * COMMIT на соединении транзакции записи и токен с него же — порядок «сначала
85
- * COMMIT, потом позиция» держит пакет, а не вызывающий.
84
+ * COMMIT on the connection of the write transaction and the token from it — the order "first
85
+ * COMMIT, then the position" is held by the package, not by the caller.
86
86
  *
87
- * До COMMIT проверяется ИНВАРИАНТ, а не форма объекта: на этом соединении
88
- * открыта транзакция. Проверка — `SAVEPOINT`: вне транзакции Postgres отвечает
89
- * отказом 25P01, внутри — создаёт точку сохранения, которую COMMIT закоммитит
90
- * вместе со всем. Пул или обёртка над пулом отправили бы запрос на другое
91
- * соединение без транзакции — `TransactionNotOpenError`, и COMMIT не
92
- * отправляется вовсе (транзакция вызывающего остаётся открытой, а не
93
- * «закоммиченной» предупреждением на чужом соединении). Транзакция в ошибке
94
- * (25P02) завершается ROLLBACK — `TransactionNotCommittedError`; отказ самого
95
- * COMMIT — его исключение. SQLSTATE ищется и в цепочке `cause` (обёртки).
87
+ * Before COMMIT the INVARIANT is checked, not the shape of the object: a transaction is open
88
+ * on this connection. The check is `SAVEPOINT`: outside a transaction Postgres answers
89
+ * with the refusal 25P01, inside one it creates a savepoint that COMMIT commits
90
+ * together with everything. A pool or a wrapper over a pool would send the query to another
91
+ * connection without a transaction — `TransactionNotOpenError`, and COMMIT is not
92
+ * sent at all (the caller's transaction stays open rather than
93
+ * "committed" with a warning on someone else's connection). A transaction in error
94
+ * (25P02) is finished with ROLLBACK — `TransactionNotCommittedError`; a refusal of the
95
+ * COMMIT itself is its exception. The SQLSTATE is also looked for in the `cause` chain (wrappers).
96
96
  *
97
- * Исключение значит «записи нет или неизвестно, что с ней»: транзакцию
98
- * вызывающий обязан завершить (`catch → ROLLBACK`), иначе соединение уйдёт в
99
- * пул с открытой транзакцией. Закрытый маршрутизатор COMMIT не отменяет:
100
- * исключение до COMMIT на штатном выключении оставляло бы транзакцию открытой, а
101
- * её запись закоммитил бы чужой COMMIT из пула. После `close()` — COMMIT как
102
- * обычно и токен «только мастер». Транзакция, которую SAVEPOINT застал
103
- * исправной, после COMMIT без исключения закоммичена — и драйвер без тега
104
- * ответа (`command`) не получает «откачена» (повтор записал бы дубль).
97
+ * An exception means "there is no write or it is unknown what happened to it": the caller
98
+ * must finish the transaction (`catch → ROLLBACK`), otherwise the connection goes to the
99
+ * pool with an open transaction. A closed router does not cancel COMMIT:
100
+ * an exception before COMMIT on a regular shutdown would leave the transaction open, and
101
+ * its write would be committed by someone else's COMMIT from the pool. After `close()` — COMMIT as
102
+ * usual and a "primary only" token. A transaction that SAVEPOINT found
103
+ * healthy is committed after a COMMIT without an exception — and a driver without the response
104
+ * tag (`command`) does not get "rolled back" (a retry would write a duplicate).
105
105
  */
106
106
  commitAndIssueToken(client: SqlCommandExecutor & NotAPool): Promise<string>;
107
107
  /**
108
- * Куда читать. Токен отсутствует (`undefined`, `null`, пустая строка) —
109
- * реплика с отставанием в потолке. Токен есть — только догнавшая его реплика;
110
- * токен не разобрался — мастер. Не бросает на отказах узлов: отказ — это
111
- * исключение реплики и, в конце концов, мастер. Длится не дольше
108
+ * Where to read. No token (`undefined`, `null`, an empty string) —
109
+ * a replica with the lag within the ceiling. With a token — only a replica that has caught up with it;
110
+ * a token that did not parse — the primary. Does not throw on node refusals: a refusal is an
111
+ * exclusion of the replica and, in the end, the primary. Lasts no longer than
112
112
  * `probeTimeoutMs + waitForCatchUpMs`.
113
113
  */
114
114
  route(token?: string | null): Promise<RouteDecision<TTarget>>;
115
115
  /**
116
- * Подтвердить решение «реплика» на соединении, которым будет чтение: тот же
117
- * зонд и те же условия, но на сервере чтения. Нужен узлам-балансировщикам
118
- * (`balanced: true`, `decision.mustConfirm`): зонд маршрутизатора видел один
119
- * сервер, а соединение чтения могло попасть на другой. Решение «мастер» —
120
- * `true`. Отказ, потолок времени, «не смогли определить», закрытый
121
- * маршрутизатор — `false`: читать с мастера.
116
+ * Confirm the "replica" decision on the connection that the read will use: the same
117
+ * probe and the same conditions, but on the read server. Needed for balancer nodes
118
+ * (`balanced: true`, `decision.mustConfirm`): the router probe saw one
119
+ * server, while the read connection could get to another. A "primary" decision is
120
+ * `true`. A refusal, the time ceiling, "could not determine", a closed
121
+ * router — `false`: read from the primary.
122
122
  */
123
123
  confirm(decision: RouteDecision<TTarget>, executor: SqlQueryExecutor): Promise<boolean>;
124
- /** Счётчики; результат сериализуется `JSON.stringify` (отставание — число, не `bigint`). */
124
+ /** Counters; the result is serialized by `JSON.stringify` (the lag is a number, not a `bigint`). */
125
125
  stats(): RouterStats;
126
126
  /**
127
- * Закрыть соединения зондов; они больше не открываются. Идущие `route()`
128
- * перестают ждать и зондировать и решают «мастер» по тому, что уже знают.
129
- * Соединения `target` принадлежат вызывающему.
127
+ * Close the probe connections; they are not opened again. Ongoing `route()` calls
128
+ * stop waiting and probing and decide "primary" by what they already know.
129
+ * The `target` connections belong to the caller.
130
130
  */
131
131
  close(): Promise<void>;
132
132
  [Symbol.asyncDispose](): Promise<void>;
133
133
  private static requireExecutor;
134
134
  /**
135
- * Часы обязаны давать конечное число уже при создании: часы кэша, вернувшие
136
- * не-число, сделали бы кэш вечным (или отключили бы его), часы выдачи — токены
137
- * без срока. Ошибка настройки видна на старте, а не молчанием потолков.
135
+ * The clocks must give a finite number already at creation: a cache clock that returned
136
+ * a non-number would make the cache eternal (or turn it off), an issue clock would give tokens
137
+ * without an expiry. A configuration error is visible at startup, not as silence of the ceilings.
138
138
  */
139
139
  private static requireClock;
140
140
  /**
141
- * Номер зонда в момент, когда процесс впервые увидел ПОЗИЦИЮ токена. Зонд с
142
- * большим номером начат после этого — значит, после выдачи токена с этой
143
- * позицией: позиция вставки мастера к его началу не меньше позиции токена
144
- * (если мастер не сменился), а «реплика отстаёт» в нём — не по снимку до
145
- * записи. Ключ — позиция, а не строка токена: токены одной позиции (разные
146
- * моменты выдачи) делят одну запись, и это верно — к выдаче любого из них
147
- * позиция вставки уже дошла до этой. Память ограничена (`POSITION_MEMORY`):
148
- * ключи приходят от клиентов. Вытесняется давно не встречавшаяся позиция (LRU),
149
- * а не первая вставленная: горячая позиция не уходит из-за потока новых.
150
- * Вытесненная при новой встрече считается новой — один лишний зонд и
151
- * консервативный ответ, а не ошибка.
141
+ * The probe number at the moment the process first saw the token POSITION. A probe with
142
+ * a greater number is started after that — that is, after the token with this
143
+ * position was issued: the primary insert position by its start is not smaller than the token position
144
+ * (if the primary did not change), and "the replica lags" in it is not by a snapshot before the
145
+ * write. The key is the position, not the token string: tokens of one position (different
146
+ * issue moments) share one entry, and that is correct — by the issue of any of them
147
+ * the insert position had already reached this one. The memory is bounded (`POSITION_MEMORY`):
148
+ * the keys come from clients. The position not seen for the longest time is evicted (LRU),
149
+ * not the first inserted one: a hot position does not go away because of a stream of new ones.
150
+ * An evicted one is considered new at the next encounter — one extra probe and
151
+ * a conservative answer, not an error.
152
152
  */
153
153
  private firstSeen;
154
154
  /**
155
- * Момент выдачи по `wallClock`. Часы, начавшие отдавать не то (не число,
156
- * отрицательное), не роняют выдачу токена ПОСЛЕ записи: момент — 0, то есть
157
- * «давно», а истечение всё равно требует доказанной невыполнимости.
155
+ * The issue moment by `wallClock`. A clock that started returning something wrong (not a number,
156
+ * a negative one) does not fail the issue of a token AFTER a write: the moment is 0, that is
157
+ * "long ago", and expiry still requires a proven unsatisfiability.
158
158
  */
159
159
  private issuedAt;
160
- /** Токен после COMMIT: позиция с соединения записи, а при отказе или после `close()` — «только мастер». */
160
+ /** The token after COMMIT: the position from the write connection, and on a refusal or after `close()` — "primary only". */
161
161
  private tokenAfterCommit;
162
162
  private resolve;
163
- /** Токен старше `tokenTtlMs`, который после failover ни одна реплика выполнить не может: чтение как без токена. */
163
+ /** A token older than `tokenTtlMs` that after a failover no replica can satisfy: the read goes as without a token. */
164
164
  private routeExpired;
165
165
  /**
166
- * Решение по позиции токена и признак «невыполнимость доказана» (для
167
- * истечения). `expired` — токен старше срока: тогда причина ухода на мастер
168
- * устанавливается по зонду мастера, начатому после первой встречи с позицией,
169
- * даже если в кэше есть более раннее состояние.
166
+ * The decision by the token position and the flag "unsatisfiability is proven" (for
167
+ * expiry). `expired` means the token is older than the expiry: then the reason for going to the primary
168
+ * is established by a primary probe started after the first encounter with the position,
169
+ * even if the cache has an earlier state.
170
170
  */
171
171
  private routeWithPosition;
172
172
  /**
173
- * Без токена: состояние мастера (зонд ограничен своим потолком, а после
174
- * просроченного токена — остатком потолка чтения), затем реплики — к потолку чтения.
173
+ * Without a token: the primary state (the probe is bounded by its own ceiling, and after
174
+ * an expired token by the rest of the read ceiling), then the replicas — up to the read ceiling.
175
175
  */
176
176
  private routeWithoutToken;
177
177
  /**
178
- * Почему мастер: по исключениям и (если удаётся) по состоянию мастера.
179
- * «Токен впереди мастера» называется только по состоянию из зонда, начатого
180
- * ПОСЛЕ первой встречи процесса с позицией токена: токен выдан до этого, и
181
- * мастер, снятый раньше, законно позади него. Свежего состояния нет (потолок
182
- * чтения, отказ) — `no-replica-eligible`, а не ложная тревога.
178
+ * Why the primary: by the exclusions and (if possible) by the primary state.
179
+ * "The token is ahead of the primary" is named only by a state from a probe started
180
+ * AFTER the process first met the token position: the token was issued before that, and
181
+ * a primary snapshot taken earlier is legitimately behind it. No fresh state (the read
182
+ * ceiling, a refusal) — `no-replica-eligible`, not a false alarm.
183
183
  *
184
- * `proven` — причина установлена таким состоянием (или каждая реплика —
185
- * другой кластер): только тогда просроченный токен истекает. Кэш мастера,
186
- * снятый до первой встречи с позицией, ничего не доказывает, сколько бы ему ни
187
- * было и как бы ни расходились часы процессов. `requireFresh` (просроченный
188
- * токен) — такое состояние добывается зондом, даже если кэш говорит «позади».
184
+ * `proven` means the reason is established by such a state (or each replica is
185
+ * another cluster): only then does an expired token expire. A primary cache
186
+ * taken before the first encounter with the position proves nothing, however old it
187
+ * is and however the process clocks diverge. `requireFresh` (an expired
188
+ * token) — such a state is obtained by a probe even if the cache says "behind".
189
189
  */
190
190
  private fallbackReason;
191
- /** Байты отставания числом: JSON-сериализуемо; больше 2⁵³ (8 ПиБ WAL) — потолок, а не потеря точности молча. */
191
+ /** The lag in bytes as a number: JSON-serializable; above 2⁵³ (8 PiB of WAL) it is a ceiling, not a silent loss of precision. */
192
192
  private static toSafeNumber;
193
193
  private static ahead;
194
194
  private evaluateAll;
195
195
  /**
196
- * Состояние каждой реплики, параллельно: из кэша, или свежим зондом, если в
197
- * кэше нет или `needsProbe` (с потолком частоты). Отказ, ещё живущий в кэше,
198
- * не опрашивается заново до своего потолка. Зонд, не успевший к `deadline`,
199
- * — прежняя оценка узла из `previous` (опрос во время ожидания), а без неё —
200
- * `unavailable` для этого чтения; сам зонд доживает до своего потолка и
201
- * попадает в кэш.
196
+ * The state of each replica, in parallel: from the cache, or by a fresh probe if it is
197
+ * not in the cache or `needsProbe` (with the frequency ceiling). A refusal still living in the cache
198
+ * is not polled again until its ceiling. A probe that did not make it by the `deadline`
199
+ * gives the previous estimate of the node from `previous` (a poll during the wait), and without it
200
+ * `unavailable` for this read; the probe itself lives until its ceiling and
201
+ * gets into the cache.
202
202
  */
203
203
  private evaluateFresh;
204
204
  private recordLag;
205
205
  /**
206
- * Состояние узла: из кэша или зонд. Одновременные вызовы по одному узлу ждут
207
- * ОДИН зонд. `maxAgeMs` — кэш годится, только если его зонд начат не раньше
208
- * стольких мс назад (потолок частоты: моложе — повторного зонда нет), а с
209
- * `startedAfterSeq` — ещё и только если зонд начат ПОСЛЕ того, как этот
210
- * процесс впервые увидел токен: зонд, снятый раньше, о записи токена ничего не
211
- * говорит, и чтение сразу после своей записи получает свежий зонд, а не
212
- * «отстаёт» по чужому. То же — для идущего зонда: начатый раньше не годится,
213
- * его дожидаются и зондируют снова. Часы не участвуют: расхождение часов
214
- * процессов не снимает потолок и не отдаёт чужой зонд.
215
- * Отказ из кэша годится всегда — до своего потолка.
206
+ * The state of a node: from the cache or a probe. Concurrent calls for one node wait for
207
+ * ONE probe. `maxAgeMs`: the cache is usable only if its probe was started not earlier than
208
+ * that many ms ago (the frequency ceiling: a younger one gets no repeated probe), and with
209
+ * `startedAfterSeq` also only if the probe was started AFTER this
210
+ * process first saw the token: a probe taken earlier says nothing about the token's write,
211
+ * and a read right after its own write gets a fresh probe rather than
212
+ * "lags" by someone else's. The same for an ongoing probe: one started earlier is not usable,
213
+ * it is waited for and the node is probed again. The clocks do not take part: a divergence of the
214
+ * process clocks does not remove the ceiling and does not hand out someone else's probe.
215
+ * A refusal from the cache is always usable — until its ceiling.
216
216
  */
217
217
  private state;
218
218
  private probe;
219
219
  /**
220
- * Линия времени реплики, у которой не работает приёмник WAL (мастер лежит или
221
- * недоступен): та, что приёмник показывал у ЭТОГО ЖЕ экземпляра сервера
222
- * (перезапуск — другой экземпляр, и прежнее знание не переносится). Сменить
223
- * линию времени реплика может, только последовав за новым мастером, — то есть
224
- * после failover, где запись, потерянная при нём, не видна и на новом мастере.
225
- * Подстановка не зависит от права на `pg_stat_wal_receiver`: без него линия
226
- * времени не видна никогда, и подставлять нечего — остаётся «нет прав».
220
+ * The timeline of a replica whose WAL receiver does not work (the primary is down or
221
+ * unreachable): the one the receiver showed on THE SAME server instance
222
+ * (a restart is another instance, and the previous knowledge does not carry over). A replica can
223
+ * change its timeline only by following a new primary — that is,
224
+ * after a failover, where a write lost in it is not visible on the new primary either.
225
+ * The substitution does not depend on the privilege on `pg_stat_wal_receiver`: without it the
226
+ * timeline is never visible, and there is nothing to substitute — "no privileges" stays.
227
227
  */
228
228
  private withLastTimeline;
229
- /** Позиция после COMMIT на соединении записи: всё «не смогли определить» — исключение. */
229
+ /** The position after COMMIT on the write connection: every "could not determine" is an exception. */
230
230
  private positionAfterCommit;
231
231
  private queryWithin;
232
232
  /**
233
- * `work` или `null`, если не успело к `deadline` (монотонные часы) или
234
- * маршрутизатор закрыт. Уже готовое значение успевает и при исчерпанном потолке;
235
- * бесконечный `deadline` — без таймера (`setTimeout(Infinity)` сработал бы через 1 мс).
233
+ * `work` or `null` if it did not make it by the `deadline` (the monotonic clock) or
234
+ * the router is closed. An already ready value makes it even with an exhausted ceiling;
235
+ * an infinite `deadline` means no timer (`setTimeout(Infinity)` would fire after 1 ms).
236
236
  */
237
237
  private within;
238
238
  private connectionOf;
239
239
  private anyBehind;
240
- /** Подходящие — по кругу: нагрузка делится между догнавшими репликами. */
240
+ /** The eligible ones in turn: the load is shared between the replicas that caught up. */
241
241
  private pick;
242
242
  private exclusionsOf;
243
243
  private toReplica;
244
244
  private toPrimary;
245
- /** Единственная точка учёта решения: счётчики и хук — ровно по одному разу на `route()`. */
245
+ /** The single point of accounting a decision: counters and the hook — exactly once per `route()`. */
246
246
  private decide;
247
247
  private assertOpen;
248
248
  }