@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
@@ -23,39 +23,39 @@ const token_codec_1 = require("./token-codec");
23
23
  const transaction_not_committed_error_1 = require("./transaction-not-committed.error");
24
24
  const transaction_not_open_error_1 = require("./transaction-not-open.error");
25
25
  /**
26
- * Маршрутизатор чтений «читаешь свои записи»: после записи — токен с
27
- * соединения, на котором прошёл COMMIT (`issueToken(client)` или
28
- * `commitAndIssueToken(client)`), чтение с токеном — `route(token)`. Реплика
29
- * выбирается, только если доказано, что она догнала позицию токена на той же
30
- * линии времени того же кластера; всё, что не удалось установить, — мастер. Без
31
- * токена — реплика с отставанием в потолке от позиции вставки мастера.
26
+ * A "read your writes" router: after a write, a token from the
27
+ * connection on which COMMIT went through (`issueToken(client)` or
28
+ * `commitAndIssueToken(client)`), a read with the token is `route(token)`. A replica
29
+ * is chosen only if it is proven that it has caught up with the token position on the same
30
+ * timeline of the same cluster; everything that could not be established goes to the primary. Without
31
+ * a token — a replica whose lag from the primary insert position is within the ceiling.
32
32
  *
33
- * Состояние узлов снимается своими соединениями зонда (по одному на узел) и
34
- * кэшируется на `stateTtlMs`; одновременные чтения ждут один зонд узла, а новый
35
- * зонд узла — не чаще `minProbeIntervalMs`. Каждое `route()` укладывается в
33
+ * The node state is taken by own probe connections (one per node) and
34
+ * cached for `stateTtlMs`; concurrent reads wait for one probe of a node, and a new
35
+ * probe of a node happens no more often than `minProbeIntervalMs`. Each `route()` fits into
36
36
  * `probeTimeoutMs + waitForCatchUpMs`.
37
37
  */
38
38
  class ReplicaRouter {
39
39
  /**
40
- * Причины «мастер», которые после failover или подмены кластера не снимет ни
41
- * одна реплика: такой токен держит мастер `tokenTtlMs`, затем — как без токена.
42
- * Истечение — только если причина ДОКАЗАНА состоянием мастера из зонда, начатого
43
- * после первой встречи процесса с позицией токена (или исключением каждой
44
- * реплики как чужого кластера). Состояние, снятое раньше, о токене ничего не
45
- * говорит: свежий законный токен впереди него законно, и истечение по нему
46
- * отправило бы чтение на реплику без записи. Токен «без позиции» сюда НЕ
47
- * входит: его позиция неизвестна, и «как без токена» могло бы отправить чтение
48
- * на реплику без этой записи (с задержкой применения она в потолке отставания) —
49
- * он держит мастер, пока клиент не получит новый токен.
40
+ * "Primary" reasons that after a failover or a cluster substitution no
41
+ * replica will lift: such a token holds the primary for `tokenTtlMs`, then it is handled as without a token.
42
+ * Expiry happens only if the reason is PROVEN by the primary state from a probe started
43
+ * after the process first met the token position (or by excluding each
44
+ * replica as another cluster). A state taken earlier says nothing about the token:
45
+ * a fresh legitimate token is legitimately ahead of it, and expiry based on it would
46
+ * send the read to a replica without the write. A token "without a position" does NOT
47
+ * belong here: its position is unknown, and "as without a token" could send the read
48
+ * to a replica without this write (with an apply delay it is within the lag ceiling) —
49
+ * it holds the primary until the client gets a new token.
50
50
  */
51
51
  static UNSATISFIABLE = new Set([
52
52
  route_reason_constant_1.ROUTE_REASON.tokenOtherTimeline,
53
53
  route_reason_constant_1.ROUTE_REASON.tokenForeign,
54
54
  route_reason_constant_1.ROUTE_REASON.tokenAheadOfPrimary,
55
55
  ]);
56
- /** SQLSTATE: команда транзакционного блока вне транзакции. */
56
+ /** SQLSTATE: a transaction block command outside a transaction. */
57
57
  static NO_ACTIVE_TRANSACTION = '25P01';
58
- /** SQLSTATE: транзакция в ошибке, команды до её конца отвергаются. */
58
+ /** SQLSTATE: the transaction is in error, commands until its end are rejected. */
59
59
  static IN_FAILED_TRANSACTION = '25P02';
60
60
  codec;
61
61
  primary;
@@ -64,12 +64,12 @@ class ReplicaRouter {
64
64
  inflight = new Map();
65
65
  inflightSeq = new Map();
66
66
  /**
67
- * Позиция токена → номер зонда при первой встрече с ней (потолок частоты
68
- * зондов и доказательство невыполнимости), не больше `POSITION_MEMORY`
69
- * записей, вытесняется давно не встречавшаяся (LRU).
67
+ * Token position → the probe number at the first encounter with it (the probe frequency
68
+ * ceiling and the proof of unsatisfiability), no more than `POSITION_MEMORY`
69
+ * entries, the one not seen for the longest time is evicted (LRU).
70
70
  */
71
71
  seenPositions = new Map();
72
- /** Последняя линия времени, которую приёмник WAL показал у экземпляра реплики. */
72
+ /** The last timeline that the WAL receiver showed on the replica instance. */
73
73
  lastTimeline = new Map();
74
74
  requirements = new WeakMap();
75
75
  cache;
@@ -107,11 +107,11 @@ class ReplicaRouter {
107
107
  const names = [this.primary, ...this.replicas].map((node) => node.name);
108
108
  for (const name of names) {
109
109
  if (typeof name !== 'string' || name.length === 0) {
110
- throw new invalid_replica_sync_options_error_1.InvalidReplicaSyncOptionsError('имя узла пусто');
110
+ throw new invalid_replica_sync_options_error_1.InvalidReplicaSyncOptionsError('a node name is empty');
111
111
  }
112
112
  }
113
113
  if (new Set(names).size !== names.length) {
114
- throw new invalid_replica_sync_options_error_1.InvalidReplicaSyncOptionsError(`имена узлов повторяются: ${names.join(', ')}`);
114
+ throw new invalid_replica_sync_options_error_1.InvalidReplicaSyncOptionsError(`node names repeat: ${names.join(', ')}`);
115
115
  }
116
116
  const D = replica_sync_defaults_constant_1.REPLICA_SYNC_DEFAULTS;
117
117
  const stateTtlMs = (0, require_integer_1.requireInteger)('stateTtlMs', options.stateTtlMs ?? D.STATE_TTL_MS, 1, D.MAX_STATE_TTL_MS);
@@ -136,43 +136,43 @@ class ReplicaRouter {
136
136
  this.counters.lag.delete(this.primary.name);
137
137
  }
138
138
  /**
139
- * Токен позиции после записи — с `executor`, на котором прошёл COMMIT (или с
140
- * любым соединением мастера ПОСЛЕ того, как COMMIT вернулся: позиция вставки
141
- * монотонна). Аргумент обязателен: соединение зонда или пул не видят
142
- * незакоммиченную транзакцию ДРУГОГО соединения, и токен, взятый ими до
143
- * COMMIT, оказался бы меньше позиции коммита — реплика «догнала» бы его без
144
- * этой записи. Позицию определить не смогли (узел в recovery, транзакция с
145
- * записью на этом соединении не закоммичена, отказ, потолок времени) — токен
146
- * «только мастер», а не исключение: клиент с ним читает с мастера.
147
- * Так же после `close()`: запись уже прошла, и исключение выглядело бы её
148
- * отказом и толкало бы к повтору.
139
+ * The position token after a write — from the `executor` on which COMMIT went through (or from
140
+ * any primary connection AFTER COMMIT returned: the insert position
141
+ * is monotonic). The argument is required: a probe connection or a pool does not see
142
+ * an uncommitted transaction of ANOTHER connection, and a token taken by them before
143
+ * COMMIT would be smaller than the commit position — a replica would "catch up" with it without
144
+ * this write. If the position could not be determined (the node is in recovery, a transaction with
145
+ * a write on this connection is not committed, a refusal, the time ceiling), the token is
146
+ * "primary only", not an exception: a client with it reads from the primary.
147
+ * The same after `close()`: the write has already gone through, and an exception would look like its
148
+ * refusal and push towards a retry.
149
149
  */
150
150
  async issueToken(executor) {
151
151
  ReplicaRouter.requireExecutor('issueToken', executor);
152
152
  return this.tokenAfterCommit(executor);
153
153
  }
154
154
  /**
155
- * COMMIT на соединении транзакции записи и токен с него же — порядок «сначала
156
- * COMMIT, потом позиция» держит пакет, а не вызывающий.
155
+ * COMMIT on the connection of the write transaction and the token from it — the order "first
156
+ * COMMIT, then the position" is held by the package, not by the caller.
157
157
  *
158
- * До COMMIT проверяется ИНВАРИАНТ, а не форма объекта: на этом соединении
159
- * открыта транзакция. Проверка — `SAVEPOINT`: вне транзакции Postgres отвечает
160
- * отказом 25P01, внутри — создаёт точку сохранения, которую COMMIT закоммитит
161
- * вместе со всем. Пул или обёртка над пулом отправили бы запрос на другое
162
- * соединение без транзакции — `TransactionNotOpenError`, и COMMIT не
163
- * отправляется вовсе (транзакция вызывающего остаётся открытой, а не
164
- * «закоммиченной» предупреждением на чужом соединении). Транзакция в ошибке
165
- * (25P02) завершается ROLLBACK — `TransactionNotCommittedError`; отказ самого
166
- * COMMIT — его исключение. SQLSTATE ищется и в цепочке `cause` (обёртки).
158
+ * Before COMMIT the INVARIANT is checked, not the shape of the object: a transaction is open
159
+ * on this connection. The check is `SAVEPOINT`: outside a transaction Postgres answers
160
+ * with the refusal 25P01, inside one it creates a savepoint that COMMIT commits
161
+ * together with everything. A pool or a wrapper over a pool would send the query to another
162
+ * connection without a transaction — `TransactionNotOpenError`, and COMMIT is not
163
+ * sent at all (the caller's transaction stays open rather than
164
+ * "committed" with a warning on someone else's connection). A transaction in error
165
+ * (25P02) is finished with ROLLBACK — `TransactionNotCommittedError`; a refusal of the
166
+ * COMMIT itself is its exception. The SQLSTATE is also looked for in the `cause` chain (wrappers).
167
167
  *
168
- * Исключение значит «записи нет или неизвестно, что с ней»: транзакцию
169
- * вызывающий обязан завершить (`catch → ROLLBACK`), иначе соединение уйдёт в
170
- * пул с открытой транзакцией. Закрытый маршрутизатор COMMIT не отменяет:
171
- * исключение до COMMIT на штатном выключении оставляло бы транзакцию открытой, а
172
- * её запись закоммитил бы чужой COMMIT из пула. После `close()` — COMMIT как
173
- * обычно и токен «только мастер». Транзакция, которую SAVEPOINT застал
174
- * исправной, после COMMIT без исключения закоммичена — и драйвер без тега
175
- * ответа (`command`) не получает «откачена» (повтор записал бы дубль).
168
+ * An exception means "there is no write or it is unknown what happened to it": the caller
169
+ * must finish the transaction (`catch → ROLLBACK`), otherwise the connection goes to the
170
+ * pool with an open transaction. A closed router does not cancel COMMIT:
171
+ * an exception before COMMIT on a regular shutdown would leave the transaction open, and
172
+ * its write would be committed by someone else's COMMIT from the pool. After `close()` — COMMIT as
173
+ * usual and a "primary only" token. A transaction that SAVEPOINT found
174
+ * healthy is committed after a COMMIT without an exception — and a driver without the response
175
+ * tag (`command`) does not get "rolled back" (a retry would write a duplicate).
176
176
  */
177
177
  async commitAndIssueToken(client) {
178
178
  ReplicaRouter.requireExecutor('commitAndIssueToken', client);
@@ -191,7 +191,7 @@ class ReplicaRouter {
191
191
  failedTransaction = true;
192
192
  }
193
193
  if (failedTransaction) {
194
- // COMMIT Postgres выполнил бы как ROLLBACK; завершаем явно — соединение без транзакции.
194
+ // Postgres would execute COMMIT as ROLLBACK; we finish explicitly — the connection is left without a transaction.
195
195
  await client.query('ROLLBACK');
196
196
  throw new transaction_not_committed_error_1.TransactionNotCommittedError('ROLLBACK');
197
197
  }
@@ -202,10 +202,10 @@ class ReplicaRouter {
202
202
  return this.tokenAfterCommit(client);
203
203
  }
204
204
  /**
205
- * Куда читать. Токен отсутствует (`undefined`, `null`, пустая строка) —
206
- * реплика с отставанием в потолке. Токен есть — только догнавшая его реплика;
207
- * токен не разобрался — мастер. Не бросает на отказах узлов: отказ — это
208
- * исключение реплики и, в конце концов, мастер. Длится не дольше
205
+ * Where to read. No token (`undefined`, `null`, an empty string) —
206
+ * a replica with the lag within the ceiling. With a token — only a replica that has caught up with it;
207
+ * a token that did not parse — the primary. Does not throw on node refusals: a refusal is an
208
+ * exclusion of the replica and, in the end, the primary. Lasts no longer than
209
209
  * `probeTimeoutMs + waitForCatchUpMs`.
210
210
  */
211
211
  async route(token) {
@@ -214,12 +214,12 @@ class ReplicaRouter {
214
214
  return this.decide(await this.resolve(token, deadline));
215
215
  }
216
216
  /**
217
- * Подтвердить решение «реплика» на соединении, которым будет чтение: тот же
218
- * зонд и те же условия, но на сервере чтения. Нужен узлам-балансировщикам
219
- * (`balanced: true`, `decision.mustConfirm`): зонд маршрутизатора видел один
220
- * сервер, а соединение чтения могло попасть на другой. Решение «мастер» —
221
- * `true`. Отказ, потолок времени, «не смогли определить», закрытый
222
- * маршрутизатор — `false`: читать с мастера.
217
+ * Confirm the "replica" decision on the connection that the read will use: the same
218
+ * probe and the same conditions, but on the read server. Needed for balancer nodes
219
+ * (`balanced: true`, `decision.mustConfirm`): the router probe saw one
220
+ * server, while the read connection could get to another. A "primary" decision is
221
+ * `true`. A refusal, the time ceiling, "could not determine", a closed
222
+ * router — `false`: read from the primary.
223
223
  */
224
224
  async confirm(decision, executor) {
225
225
  if (decision.role !== node_role_constant_1.NODE_ROLE.replica) {
@@ -227,15 +227,15 @@ class ReplicaRouter {
227
227
  }
228
228
  const requirement = this.requirements.get(decision);
229
229
  if (requirement === undefined) {
230
- throw new TypeError('confirm: решение выдано не этим маршрутизатором');
230
+ throw new TypeError('confirm: the decision was not issued by this router');
231
231
  }
232
232
  ReplicaRouter.requireExecutor('confirm', executor);
233
233
  let reason;
234
234
  let failure;
235
235
  try {
236
236
  if (this.closed) {
237
- // Решение получено до close(): чтение не роняется, а уходит на мастер.
238
- throw new Error('ReplicaRouter закрыт: подтверждения нет');
237
+ // The decision was obtained before close(): the read does not fail but goes to the primary.
238
+ throw new Error('ReplicaRouter is closed: no confirmation');
239
239
  }
240
240
  const rows = await this.queryWithin(executor);
241
241
  const state = this.withLastTimeline(decision.node, (0, read_node_state_1.readNodeState)(rows[0]), false);
@@ -261,7 +261,7 @@ class ReplicaRouter {
261
261
  });
262
262
  return confirmed;
263
263
  }
264
- /** Счётчики; результат сериализуется `JSON.stringify` (отставание — число, не `bigint`). */
264
+ /** Counters; the result is serialized by `JSON.stringify` (the lag is a number, not a `bigint`). */
265
265
  stats() {
266
266
  return {
267
267
  reads: { replica: this.counters.replica, primary: this.counters.primary },
@@ -281,9 +281,9 @@ class ReplicaRouter {
281
281
  };
282
282
  }
283
283
  /**
284
- * Закрыть соединения зондов; они больше не открываются. Идущие `route()`
285
- * перестают ждать и зондировать и решают «мастер» по тому, что уже знают.
286
- * Соединения `target` принадлежат вызывающему.
284
+ * Close the probe connections; they are not opened again. Ongoing `route()` calls
285
+ * stop waiting and probing and decide "primary" by what they already know.
286
+ * The `target` connections belong to the caller.
287
287
  */
288
288
  async close() {
289
289
  this.closed = true;
@@ -297,35 +297,35 @@ class ReplicaRouter {
297
297
  if (typeof executor !== 'object' ||
298
298
  executor === null ||
299
299
  typeof executor.query !== 'function') {
300
- throw new TypeError(`${method}: нужен executor — соединение мастера, на котором прошёл COMMIT (pg.Client, pg.PoolClient), или пул после возврата COMMIT`);
300
+ throw new TypeError(`${method}: an executor is required — the primary connection on which COMMIT went through (pg.Client, pg.PoolClient), or a pool after COMMIT returned`);
301
301
  }
302
302
  }
303
303
  /**
304
- * Часы обязаны давать конечное число уже при создании: часы кэша, вернувшие
305
- * не-число, сделали бы кэш вечным (или отключили бы его), часы выдачи — токены
306
- * без срока. Ошибка настройки видна на старте, а не молчанием потолков.
304
+ * The clocks must give a finite number already at creation: a cache clock that returned
305
+ * a non-number would make the cache eternal (or turn it off), an issue clock would give tokens
306
+ * without an expiry. A configuration error is visible at startup, not as silence of the ceilings.
307
307
  */
308
308
  static requireClock(name, clock) {
309
309
  if (typeof clock !== 'function') {
310
- throw new invalid_replica_sync_options_error_1.InvalidReplicaSyncOptionsError(`${name}: ожидается функция, получено ${typeof clock}`);
310
+ throw new invalid_replica_sync_options_error_1.InvalidReplicaSyncOptionsError(`${name}: a function is expected, got ${typeof clock}`);
311
311
  }
312
312
  const value = clock();
313
313
  if (typeof value !== 'number' || !Number.isFinite(value)) {
314
- throw new invalid_replica_sync_options_error_1.InvalidReplicaSyncOptionsError(`${name}: часы вернули не конечное число (${String(value)})`);
314
+ throw new invalid_replica_sync_options_error_1.InvalidReplicaSyncOptionsError(`${name}: the clock returned a non-finite number (${String(value)})`);
315
315
  }
316
316
  }
317
317
  /**
318
- * Номер зонда в момент, когда процесс впервые увидел ПОЗИЦИЮ токена. Зонд с
319
- * большим номером начат после этого — значит, после выдачи токена с этой
320
- * позицией: позиция вставки мастера к его началу не меньше позиции токена
321
- * (если мастер не сменился), а «реплика отстаёт» в нём — не по снимку до
322
- * записи. Ключ — позиция, а не строка токена: токены одной позиции (разные
323
- * моменты выдачи) делят одну запись, и это верно — к выдаче любого из них
324
- * позиция вставки уже дошла до этой. Память ограничена (`POSITION_MEMORY`):
325
- * ключи приходят от клиентов. Вытесняется давно не встречавшаяся позиция (LRU),
326
- * а не первая вставленная: горячая позиция не уходит из-за потока новых.
327
- * Вытесненная при новой встрече считается новой — один лишний зонд и
328
- * консервативный ответ, а не ошибка.
318
+ * The probe number at the moment the process first saw the token POSITION. A probe with
319
+ * a greater number is started after that — that is, after the token with this
320
+ * position was issued: the primary insert position by its start is not smaller than the token position
321
+ * (if the primary did not change), and "the replica lags" in it is not by a snapshot before the
322
+ * write. The key is the position, not the token string: tokens of one position (different
323
+ * issue moments) share one entry, and that is correct — by the issue of any of them
324
+ * the insert position had already reached this one. The memory is bounded (`POSITION_MEMORY`):
325
+ * the keys come from clients. The position not seen for the longest time is evicted (LRU),
326
+ * not the first inserted one: a hot position does not go away because of a stream of new ones.
327
+ * An evicted one is considered new at the next encounter — one extra probe and
328
+ * a conservative answer, not an error.
329
329
  */
330
330
  firstSeen(position) {
331
331
  const key = `${position.systemId}/${position.timeline}/${position.lsn.toString(16)}`;
@@ -345,19 +345,19 @@ class ReplicaRouter {
345
345
  return this.seq;
346
346
  }
347
347
  /**
348
- * Момент выдачи по `wallClock`. Часы, начавшие отдавать не то (не число,
349
- * отрицательное), не роняют выдачу токена ПОСЛЕ записи: момент — 0, то есть
350
- * «давно», а истечение всё равно требует доказанной невыполнимости.
348
+ * The issue moment by `wallClock`. A clock that started returning something wrong (not a number,
349
+ * a negative one) does not fail the issue of a token AFTER a write: the moment is 0, that is
350
+ * "long ago", and expiry still requires a proven unsatisfiability.
351
351
  */
352
352
  issuedAt() {
353
353
  const value = Math.floor(this.wallClock());
354
354
  return Number.isSafeInteger(value) && value >= 0 ? value : 0;
355
355
  }
356
- /** Токен после COMMIT: позиция с соединения записи, а при отказе или после `close()` — «только мастер». */
356
+ /** The token after COMMIT: the position from the write connection, and on a refusal or after `close()` — "primary only". */
357
357
  async tokenAfterCommit(executor) {
358
358
  try {
359
359
  if (this.closed) {
360
- throw new Error('ReplicaRouter закрыт: токен «только мастер»');
360
+ throw new Error('ReplicaRouter is closed: a "primary only" token');
361
361
  }
362
362
  const rows = await this.queryWithin(executor);
363
363
  return this.codec.encode(this.positionAfterCommit(rows[0]), this.issuedAt());
@@ -376,15 +376,15 @@ class ReplicaRouter {
376
376
  }
377
377
  const decoded = typeof token === 'string'
378
378
  ? this.codec.decode(token)
379
- : { kind: 'invalid', detail: 'не строка' };
379
+ : { kind: 'invalid', detail: 'not a string' };
380
380
  if (decoded.kind === 'invalid') {
381
381
  return this.toPrimary(route_reason_constant_1.ROUTE_REASON.tokenInvalid, [], 0);
382
382
  }
383
383
  if (decoded.kind === 'unresolved') {
384
384
  return this.toPrimary(route_reason_constant_1.ROUTE_REASON.tokenUnresolved, [], 0);
385
385
  }
386
- // Возраст по часам выдавшего и читающего: их расхождение сдвигает срок, но
387
- // само по себе ничего не решает — истекает только ДОКАЗАННО невыполнимый токен.
386
+ // The age by the clocks of the issuer and the reader: their divergence shifts the expiry, but
387
+ // decides nothing by itself — only a PROVEN unsatisfiable token expires.
388
388
  const expired = this.issuedAt() - decoded.issuedAt > this.tokenTtlMs;
389
389
  const routed = await this.routeWithPosition(decoded.position, deadline, expired);
390
390
  if (expired && routed.unsatisfiable) {
@@ -392,23 +392,23 @@ class ReplicaRouter {
392
392
  }
393
393
  return routed.decision;
394
394
  }
395
- /** Токен старше `tokenTtlMs`, который после failover ни одна реплика выполнить не может: чтение как без токена. */
395
+ /** A token older than `tokenTtlMs` that after a failover no replica can satisfy: the read goes as without a token. */
396
396
  routeExpired(deadline) {
397
397
  this.counters.expiredTokens += 1;
398
398
  return this.routeWithoutToken(deadline, true);
399
399
  }
400
400
  /**
401
- * Решение по позиции токена и признак «невыполнимость доказана» (для
402
- * истечения). `expired` — токен старше срока: тогда причина ухода на мастер
403
- * устанавливается по зонду мастера, начатому после первой встречи с позицией,
404
- * даже если в кэше есть более раннее состояние.
401
+ * The decision by the token position and the flag "unsatisfiability is proven" (for
402
+ * expiry). `expired` means the token is older than the expiry: then the reason for going to the primary
403
+ * is established by a primary probe started after the first encounter with the position,
404
+ * even if the cache has an earlier state.
405
405
  */
406
406
  async routeWithPosition(position, deadline, expired) {
407
407
  const requirement = { kind: 'position', position };
408
408
  const seenSince = this.firstSeen(position);
409
- // Сначала — только кэш: догнавшая по кэшу реплика не требует зонда. Кэш живёт
410
- // не дольше `stateTtlMs` и теряет узел, соединение зонда которого оборвалось
411
- // (перезапуск реплики откатывает позицию воспроизведения).
409
+ // First only the cache: a replica that caught up by the cache needs no probe. The cache lives
410
+ // no longer than `stateTtlMs` and loses a node whose probe connection broke
411
+ // (a replica restart rolls back the replay position).
412
412
  const cached = this.evaluateAll(requirement, (node) => this.cache.get(node.name)?.outcome);
413
413
  const fromCache = this.pick(cached);
414
414
  if (fromCache !== null) {
@@ -417,16 +417,16 @@ class ReplicaRouter {
417
417
  unsatisfiable: false,
418
418
  };
419
419
  }
420
- // Нет в кэше или отстаёт — свежий зонд; прочие исключения кэша живут до своего потолка.
421
- // Первые зонды ограничены своим потолком (`probeTimeoutMs`): гонка с потолком
422
- // чтения оборвала бы их ровно на нём же, раньше их собственного итога.
420
+ // Not in the cache or lagging — a fresh probe; other cache exclusions live until their ceiling.
421
+ // The first probes are bounded by their own ceiling (`probeTimeoutMs`): a race with the
422
+ // read ceiling would cut them exactly at it, earlier than their own outcome.
423
423
  let evaluated = await this.evaluateFresh(requirement, Number.POSITIVE_INFINITY, (outcome) => (0, evaluate_replica_1.evaluateReplica)(outcome, requirement) === exclusion_reason_constant_1.EXCLUSION_REASON.behind, [], seenSince);
424
424
  let polls = 0;
425
425
  let chosen = this.pick(evaluated);
426
426
  if (chosen === null && this.waitForCatchUpMs > 0 && this.anyBehind(evaluated)) {
427
427
  const waitUntil = Math.min(node_perf_hooks_1.performance.now() + this.waitForCatchUpMs, deadline);
428
428
  while (chosen === null && this.anyBehind(evaluated)) {
429
- // Пауза прерывается close(): ожидание не тянется до своего потолка после закрытия.
429
+ // The pause is interrupted by close(): the wait does not drag on to its ceiling after closing.
430
430
  const pause = (0, promises_1.setTimeout)(this.catchUpPollMs, undefined, { signal: this.closing.signal }).catch(() => undefined);
431
431
  if ((await this.within(pause, waitUntil)) === null || this.closing.signal.aborted) {
432
432
  break;
@@ -450,8 +450,8 @@ class ReplicaRouter {
450
450
  };
451
451
  }
452
452
  /**
453
- * Без токена: состояние мастера (зонд ограничен своим потолком, а после
454
- * просроченного токена — остатком потолка чтения), затем реплики — к потолку чтения.
453
+ * Without a token: the primary state (the probe is bounded by its own ceiling, and after
454
+ * an expired token by the rest of the read ceiling), then the replicas — up to the read ceiling.
455
455
  */
456
456
  async routeWithoutToken(deadline, primaryWithinDeadline) {
457
457
  const sample = await this.within(this.state(this.primary), primaryWithinDeadline ? deadline : Number.POSITIVE_INFINITY);
@@ -479,17 +479,17 @@ class ReplicaRouter {
479
479
  return this.toPrimary(route_reason_constant_1.ROUTE_REASON.noReplicaEligible, this.exclusionsOf(evaluated), 0);
480
480
  }
481
481
  /**
482
- * Почему мастер: по исключениям и (если удаётся) по состоянию мастера.
483
- * «Токен впереди мастера» называется только по состоянию из зонда, начатого
484
- * ПОСЛЕ первой встречи процесса с позицией токена: токен выдан до этого, и
485
- * мастер, снятый раньше, законно позади него. Свежего состояния нет (потолок
486
- * чтения, отказ) — `no-replica-eligible`, а не ложная тревога.
482
+ * Why the primary: by the exclusions and (if possible) by the primary state.
483
+ * "The token is ahead of the primary" is named only by a state from a probe started
484
+ * AFTER the process first met the token position: the token was issued before that, and
485
+ * a primary snapshot taken earlier is legitimately behind it. No fresh state (the read
486
+ * ceiling, a refusal) — `no-replica-eligible`, not a false alarm.
487
487
  *
488
- * `proven` — причина установлена таким состоянием (или каждая реплика —
489
- * другой кластер): только тогда просроченный токен истекает. Кэш мастера,
490
- * снятый до первой встречи с позицией, ничего не доказывает, сколько бы ему ни
491
- * было и как бы ни расходились часы процессов. `requireFresh` (просроченный
492
- * токен) — такое состояние добывается зондом, даже если кэш говорит «позади».
488
+ * `proven` means the reason is established by such a state (or each replica is
489
+ * another cluster): only then does an expired token expire. A primary cache
490
+ * taken before the first encounter with the position proves nothing, however old it
491
+ * is and however the process clocks diverge. `requireFresh` (an expired
492
+ * token) — such a state is obtained by a probe even if the cache says "behind".
493
493
  */
494
494
  async fallbackReason(position, evaluated, deadline, seenSince, requireFresh) {
495
495
  if (evaluated.length > 0 && evaluated.every((entry) => entry.reason === exclusion_reason_constant_1.EXCLUSION_REASON.otherCluster)) {
@@ -518,7 +518,7 @@ class ReplicaRouter {
518
518
  }
519
519
  return { reason: route_reason_constant_1.ROUTE_REASON.noReplicaEligible, proven: false };
520
520
  }
521
- /** Байты отставания числом: JSON-сериализуемо; больше 2⁵³ (8 ПиБ WAL) — потолок, а не потеря точности молча. */
521
+ /** 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. */
522
522
  static toSafeNumber(value) {
523
523
  return value > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(value);
524
524
  }
@@ -537,12 +537,12 @@ class ReplicaRouter {
537
537
  });
538
538
  }
539
539
  /**
540
- * Состояние каждой реплики, параллельно: из кэша, или свежим зондом, если в
541
- * кэше нет или `needsProbe` (с потолком частоты). Отказ, ещё живущий в кэше,
542
- * не опрашивается заново до своего потолка. Зонд, не успевший к `deadline`,
543
- * — прежняя оценка узла из `previous` (опрос во время ожидания), а без неё —
544
- * `unavailable` для этого чтения; сам зонд доживает до своего потолка и
545
- * попадает в кэш.
540
+ * The state of each replica, in parallel: from the cache, or by a fresh probe if it is
541
+ * not in the cache or `needsProbe` (with the frequency ceiling). A refusal still living in the cache
542
+ * is not polled again until its ceiling. A probe that did not make it by the `deadline`
543
+ * gives the previous estimate of the node from `previous` (a poll during the wait), and without it
544
+ * `unavailable` for this read; the probe itself lives until its ceiling and
545
+ * gets into the cache.
546
546
  */
547
547
  async evaluateFresh(requirement, deadline, needsProbe, previous = [], tokenSeenSince) {
548
548
  const outcomes = await Promise.all(this.replicas.map(async (node) => {
@@ -582,16 +582,16 @@ class ReplicaRouter {
582
582
  });
583
583
  }
584
584
  /**
585
- * Состояние узла: из кэша или зонд. Одновременные вызовы по одному узлу ждут
586
- * ОДИН зонд. `maxAgeMs` — кэш годится, только если его зонд начат не раньше
587
- * стольких мс назад (потолок частоты: моложе — повторного зонда нет), а с
588
- * `startedAfterSeq` — ещё и только если зонд начат ПОСЛЕ того, как этот
589
- * процесс впервые увидел токен: зонд, снятый раньше, о записи токена ничего не
590
- * говорит, и чтение сразу после своей записи получает свежий зонд, а не
591
- * «отстаёт» по чужому. То же — для идущего зонда: начатый раньше не годится,
592
- * его дожидаются и зондируют снова. Часы не участвуют: расхождение часов
593
- * процессов не снимает потолок и не отдаёт чужой зонд.
594
- * Отказ из кэша годится всегда — до своего потолка.
585
+ * The state of a node: from the cache or a probe. Concurrent calls for one node wait for
586
+ * ONE probe. `maxAgeMs`: the cache is usable only if its probe was started not earlier than
587
+ * that many ms ago (the frequency ceiling: a younger one gets no repeated probe), and with
588
+ * `startedAfterSeq` also only if the probe was started AFTER this
589
+ * process first saw the token: a probe taken earlier says nothing about the token's write,
590
+ * and a read right after its own write gets a fresh probe rather than
591
+ * "lags" by someone else's. The same for an ongoing probe: one started earlier is not usable,
592
+ * it is waited for and the node is probed again. The clocks do not take part: a divergence of the
593
+ * process clocks does not remove the ceiling and does not hand out someone else's probe.
594
+ * A refusal from the cache is always usable — until its ceiling.
595
595
  */
596
596
  state(node, freshness = {}) {
597
597
  const entry = this.cache.get(node.name);
@@ -608,9 +608,9 @@ class ReplicaRouter {
608
608
  if (freshness.startedAfterSeq === undefined || runningSeq > freshness.startedAfterSeq) {
609
609
  return running;
610
610
  }
611
- // Идущий зонд начат до первой встречи с позицией: о её записи он ничего не
612
- // говорит. Дождаться его (один зонд узла за раз) и решить заново: следующий
613
- // начнётся после — или к нему присоединится.
611
+ // The ongoing probe was started before the first encounter with the position: it says nothing
612
+ // about its write. Wait for it (one probe of a node at a time) and decide again: the next one
613
+ // starts after it — or this call joins it.
614
614
  return running.then(() => this.state(node, freshness));
615
615
  }
616
616
  this.seq += 1;
@@ -648,13 +648,13 @@ class ReplicaRouter {
648
648
  return { outcome, seq };
649
649
  }
650
650
  /**
651
- * Линия времени реплики, у которой не работает приёмник WAL (мастер лежит или
652
- * недоступен): та, что приёмник показывал у ЭТОГО ЖЕ экземпляра сервера
653
- * (перезапуск — другой экземпляр, и прежнее знание не переносится). Сменить
654
- * линию времени реплика может, только последовав за новым мастером, — то есть
655
- * после failover, где запись, потерянная при нём, не видна и на новом мастере.
656
- * Подстановка не зависит от права на `pg_stat_wal_receiver`: без него линия
657
- * времени не видна никогда, и подставлять нечего — остаётся «нет прав».
651
+ * The timeline of a replica whose WAL receiver does not work (the primary is down or
652
+ * unreachable): the one the receiver showed on THE SAME server instance
653
+ * (a restart is another instance, and the previous knowledge does not carry over). A replica can
654
+ * change its timeline only by following a new primary — that is,
655
+ * after a failover, where a write lost in it is not visible on the new primary either.
656
+ * The substitution does not depend on the privilege on `pg_stat_wal_receiver`: without it the
657
+ * timeline is never visible, and there is nothing to substitute — "no privileges" stays.
658
658
  */
659
659
  withLastTimeline(node, state, remember) {
660
660
  if (!state.inRecovery || state.instance === null) {
@@ -671,24 +671,24 @@ class ReplicaRouter {
671
671
  ? { ...state, timeline: known.timeline }
672
672
  : state;
673
673
  }
674
- /** Позиция после COMMIT на соединении записи: всё «не смогли определить» — исключение. */
674
+ /** The position after COMMIT on the write connection: every "could not determine" is an exception. */
675
675
  positionAfterCommit(row) {
676
676
  const state = (0, read_node_state_1.readNodeState)(row);
677
677
  if (state.inRecovery) {
678
- throw new Error(`узел ${this.primary.name} в recovery: это не мастер`);
678
+ throw new Error(`the node ${this.primary.name} is in recovery: it is not the primary`);
679
679
  }
680
680
  if (state.writePending) {
681
- throw new Error('транзакция с записью ещё не закоммичена: позиция её коммита неизвестна');
681
+ throw new Error('a transaction with a write is not committed yet: the position of its commit is unknown');
682
682
  }
683
683
  if (state.tokenLsn === null || state.timeline === null || state.systemId === null) {
684
- throw new Error('позиция, линия времени или идентификатор кластера не определились');
684
+ throw new Error('the position, the timeline or the cluster identifier was not determined');
685
685
  }
686
686
  return { systemId: state.systemId, timeline: state.timeline, lsn: state.tokenLsn };
687
687
  }
688
688
  async queryWithin(executor) {
689
689
  let timer;
690
690
  const deadline = new Promise((_, reject) => {
691
- timer = setTimeout(() => reject(new Error(`состояние узла не определилось за ${this.probeTimeoutMs} мс`)), this.probeTimeoutMs);
691
+ timer = setTimeout(() => reject(new Error(`the node state was not determined within ${this.probeTimeoutMs} ms`)), this.probeTimeoutMs);
692
692
  });
693
693
  try {
694
694
  return (await Promise.race([executor.query(probe_sql_constant_1.PROBE_SQL.STATE), deadline])).rows;
@@ -698,9 +698,9 @@ class ReplicaRouter {
698
698
  }
699
699
  }
700
700
  /**
701
- * `work` или `null`, если не успело к `deadline` (монотонные часы) или
702
- * маршрутизатор закрыт. Уже готовое значение успевает и при исчерпанном потолке;
703
- * бесконечный `deadline` — без таймера (`setTimeout(Infinity)` сработал бы через 1 мс).
701
+ * `work` or `null` if it did not make it by the `deadline` (the monotonic clock) or
702
+ * the router is closed. An already ready value makes it even with an exhausted ceiling;
703
+ * an infinite `deadline` means no timer (`setTimeout(Infinity)` would fire after 1 ms).
704
704
  */
705
705
  async within(work, deadline) {
706
706
  if (this.closing.signal.aborted) {
@@ -729,14 +729,14 @@ class ReplicaRouter {
729
729
  connectionOf(name) {
730
730
  const connection = this.connections.get(name);
731
731
  if (connection === undefined) {
732
- throw new Error(`нет соединения зонда для узла ${name}`);
732
+ throw new Error(`no probe connection for the node ${name}`);
733
733
  }
734
734
  return connection;
735
735
  }
736
736
  anyBehind(evaluated) {
737
737
  return evaluated.some((entry) => entry.reason === exclusion_reason_constant_1.EXCLUSION_REASON.behind);
738
738
  }
739
- /** Подходящие — по кругу: нагрузка делится между догнавшими репликами. */
739
+ /** The eligible ones in turn: the load is shared between the replicas that caught up. */
740
740
  pick(evaluated) {
741
741
  const eligible = evaluated.filter((entry) => entry.reason === null);
742
742
  if (eligible.length === 0) {
@@ -773,7 +773,7 @@ class ReplicaRouter {
773
773
  mustConfirm: false,
774
774
  };
775
775
  }
776
- /** Единственная точка учёта решения: счётчики и хук — ровно по одному разу на `route()`. */
776
+ /** The single point of accounting a decision: counters and the hook — exactly once per `route()`. */
777
777
  decide(decision) {
778
778
  if (decision.role === node_role_constant_1.NODE_ROLE.replica) {
779
779
  this.counters.replica += 1;
@@ -790,7 +790,7 @@ class ReplicaRouter {
790
790
  }
791
791
  assertOpen() {
792
792
  if (this.closed) {
793
- throw new Error('ReplicaRouter закрыт');
793
+ throw new Error('ReplicaRouter is closed');
794
794
  }
795
795
  }
796
796
  }