@fedify/mysql 2.5.0-dev.2766 → 2.5.0-dev.2816

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.
package/README.md CHANGED
@@ -1,5 +1,3 @@
1
- <!-- deno-fmt-ignore-file -->
2
-
3
1
  @fedify/mysql: MySQL/MariaDB drivers for Fedify
4
2
  ===============================================
5
3
 
@@ -46,3 +44,108 @@ yarn add @fedify/mysql mysql2 # Yarn
46
44
  bun add @fedify/mysql mysql2 # Bun
47
45
  deno add jsr:@fedify/mysql # Deno
48
46
  ~~~~
47
+
48
+
49
+ Atomic key-value operations
50
+ ---------------------------
51
+
52
+ Since Fedify 2.5.0, `MysqlKvStore` implements `AtomicKvStore`. Use `getMany()`
53
+ to read related keys from one snapshot, `setMany()` or `deleteMany()` to change
54
+ them together, and `casMany()` to commit only when every expectation matches.
55
+ Single-key `cas()` follows the same rules as `casMany()`. After a `false`
56
+ result, read again and re-evaluate the application rule before retrying.
57
+
58
+ ~~~~ typescript
59
+ const store = new MysqlKvStore(pool);
60
+ await store.setMany([
61
+ { key: ["cursor"], value: 0 },
62
+ { key: ["budget"], value: 10 },
63
+ ]);
64
+ const [cursor, budget] = await store.getMany<number>([["cursor"], ["budget"]]);
65
+ const committed = await store.casMany([
66
+ { key: ["cursor"], expectedValue: cursor, newValue: (cursor ?? 0) + 1 },
67
+ { key: ["budget"], expectedValue: budget, newValue: (budget ?? 0) - 1 },
68
+ ]);
69
+ ~~~~
70
+
71
+ ### Scope and configuration
72
+
73
+ All keys in the same primary database and table share an atomic scope across
74
+ independent pools and processes. Each operation runs in its own transaction on
75
+ one pooled connection, with explicit `REPEATABLE READ` isolation. `get()` uses
76
+ the same snapshot transaction as `getMany()`, so reads now require transaction
77
+ setup and commit round trips. Successive calls do not form one transaction. A
78
+ failed commit response can leave its outcome unknown; use a non-reused version
79
+ or an application receipt before repeating external effects. Crash durability
80
+ depends on the server and storage configuration.
81
+
82
+ Use a normal mysql2 pool with `autocommit` enabled, object rows and default type
83
+ casting. The `jsonStrings` option is supported. Do not supply connections
84
+ already in caller-owned transactions, share borrowed connections with raw SQL,
85
+ or route reads to replicas. All cooperating clients must use the same
86
+ fixed-offset or UTC session `time_zone`; `DATETIME` expiry values do not carry
87
+ a time zone. `NO_BACKSLASH_ESCAPES`, custom `typeCast`, and `rowsAsArray` are
88
+ unsupported. Keep server settings and the table schema stable while stores
89
+ are in use. `initialize()` and `drop()` must not overlap other operations.
90
+
91
+ Initialization requires an InnoDB base table with the adapter's schema: a
92
+ `VARCHAR(768)` key in `utf8mb4_bin`, a full-column primary `BTREE` index with
93
+ no other unique indexes, a non-null native JSON or `utf8mb4` `LONGTEXT` value,
94
+ and a nullable `DATETIME(6)` expiry. It rejects incompatible existing tables
95
+ instead of migrating them. `initialized: true` skips DDL, but still requires
96
+ metadata visibility for schema validation. Custom pool-like objects must
97
+ provide mysql2's connection `destroy()` method. The legacy
98
+ `innodb_locks_unsafe_for_binlog` setting must be disabled if present.
99
+
100
+ ### Values, TTLs and limits
101
+
102
+ Values use `JSON.stringify()` on write and `JSON.parse()` on every read path,
103
+ including `list()`. JSON primitives, arrays and objects round-trip; dates and
104
+ `toJSON()` values follow normal JSON conversion. Unsupported object members
105
+ are omitted, unsupported array members and non-finite numbers become `null`,
106
+ and cycles, `BigInt` and values without a root JSON representation reject.
107
+ `set(key, undefined)` now rejects; use `delete()` instead. CAS compares decoded
108
+ values with `isEqual()`, ignoring object member order and preserving array
109
+ order and type distinctions. Expectations are not JSON-normalized: use the ISO
110
+ string returned by `get()` as the expected value for a stored date, rather than
111
+ a `Date`. Do not mutate expected values while an operation is pending.
112
+
113
+ Each batch accepts at most 1,000 input entries, including repeated keys in a
114
+ read. Mutation keys must be distinct. A JSON-serialized key, including its
115
+ punctuation and escapes, has at most 768 Unicode code points. Server packet,
116
+ JSON nesting, transaction and runtime resource limits also apply. Operations
117
+ reject rather than split a batch to fit a limit.
118
+
119
+ A stored `null` is distinct from absence. Expired entries count as absent;
120
+ `expectedValue: undefined` checks absence and `newValue: undefined` deletes.
121
+ Deletion rejects a non-null TTL, even when an expectation would mismatch.
122
+ Each replacement has its own TTL; omitting it clears previous expiry. TTLs
123
+ are truncated to safe integer microseconds, approximately ±285 years; larger
124
+ or server-unrepresentable durations reject. Calendar units use the current
125
+ local date for conversion. Non-positive TTLs expire immediately. One
126
+ server cutoff applies to each attempt: CAS captures it after acquiring all
127
+ locks, and unconditional writes capture it before any write-side lock waits, so
128
+ a short TTL can already have elapsed at commit.
129
+
130
+ ### Backend verification
131
+
132
+ CI runs the ordinary and atomic key-value suites against MariaDB 11.8 on
133
+ Node.js, Bun, and Deno, alongside the full-package MySQL 8 jobs. The MariaDB
134
+ jobs run only the key-value suites because the message-queue suite has
135
+ pre-existing MariaDB compatibility failures.
136
+
137
+ ### Conflicts and cleanup
138
+
139
+ CAS locks physical rows and absent key ranges before comparing. Expired rows
140
+ remain locked, and all expectations match before the first mutation. Deadlocks
141
+ (`1213`) and MariaDB snapshot conflicts (`1020`) retry the whole transaction,
142
+ with fresh comparisons and cutoff, for at most five total attempts. Other
143
+ backend errors reject. Lock timeout `1205` rejects after rollback; disabling
144
+ `innodb_deadlock_detect` can turn contention into such timeouts. A comparison
145
+ mismatch alone returns `false` and preserves values and TTLs.
146
+
147
+ Expiry cleanup runs after commit and after releasing the transaction's
148
+ connection. It is awaited and may wait for the server's lock timeout, but its
149
+ failures are logged without changing the committed result. The existing
150
+ `expireCleanupRate` option controls this housekeeping cost; `0` disables it.
151
+ Logical expiry works regardless of physical cleanup.
package/dist/kv.cjs CHANGED
@@ -11,7 +11,27 @@ const logger = (0, _logtape_logtape.getLogger)([
11
11
  "kv"
12
12
  ]);
13
13
  /**
14
- * A key-value store that uses MySQL (or MariaDB) as the underlying storage.
14
+ * An atomic key-value store backed by an InnoDB table on MySQL or MariaDB.
15
+ *
16
+ * All keys in one primary database/table share an atomic scope. Batches have
17
+ * at most 1,000 entries and serialized keys at most 768 Unicode code points;
18
+ * server packet and resource limits also apply. Values use JSON serialization
19
+ * and decoded structural equality (`isEqual`); object member order is ignored.
20
+ * Do not mutate expected values while a CAS is pending.
21
+ *
22
+ * TTLs are truncated to safe integer microseconds (approximately ±285 years),
23
+ * evaluated using one server cutoff per attempt. Calendar units use the local
24
+ * current date for conversion. Omitted TTL clears the previous expiry.
25
+ *
26
+ * Use a normal mysql2 pool with autocommit enabled, object rows, default type
27
+ * casting, and the same fixed-offset or UTC session time zone on every client.
28
+ * Caller-owned transactions, replica routing, concurrent schema changes,
29
+ * `NO_BACKSLASH_ESCAPES`, and disabled InnoDB gap locking are unsupported.
30
+ * Initialization checks the schema even with `initialized: true`.
31
+ *
32
+ * Deadlocks and MariaDB snapshot conflicts retry up to five total attempts.
33
+ * Other failures reject; a failed commit response can leave its outcome
34
+ * unknown. Atomicity does not promise crash durability or external effects.
15
35
  *
16
36
  * @example
17
37
  * ```ts
@@ -34,6 +54,7 @@ var MysqlKvStore = class {
34
54
  #tableName;
35
55
  #expireCleanupRate;
36
56
  #initialized;
57
+ #initialization;
37
58
  /**
38
59
  * Creates a new MySQL key-value store.
39
60
  * @param pool The MySQL connection pool to use.
@@ -54,161 +75,277 @@ var MysqlKvStore = class {
54
75
  async #expire() {
55
76
  if (this.#expireCleanupRate <= 0) return;
56
77
  if (this.#expireCleanupRate < 1 && Math.random() >= this.#expireCleanupRate) return;
57
- await this.#pool.query(`DELETE FROM \`${this.#tableName}\`
58
- WHERE \`expires\` IS NOT NULL AND \`expires\` < NOW(6)`);
78
+ try {
79
+ await this.#pool.query(`DELETE FROM \`${this.#tableName}\`
80
+ WHERE \`expires\` IS NOT NULL AND \`expires\` < NOW(6)`);
81
+ } catch (error) {
82
+ logger.warn("Failed to clean up expired key-value entries: {error}", { error });
83
+ }
59
84
  }
60
85
  /**
61
- * {@inheritDoc KvStore.get}
86
+ * {@inheritDoc AtomicKvStore.get}
62
87
  * @since 2.1.0
63
88
  */
64
89
  async get(key) {
65
- await this.initialize();
66
- const serializedKey = JSON.stringify([...key]);
67
- const [rows] = await this.#pool.query(`SELECT \`value\` FROM \`${this.#tableName}\`
68
- WHERE \`key\` = ?
69
- AND (\`expires\` IS NULL OR \`expires\` > NOW(6))`, [serializedKey]);
70
- if (rows.length < 1) return void 0;
71
- return rows[0].value;
90
+ return (await this.getMany([key]))[0];
72
91
  }
73
92
  /**
74
- * {@inheritDoc KvStore.set}
93
+ * {@inheritDoc AtomicKvStore.set}
75
94
  * @since 2.1.0
76
95
  */
77
96
  async set(key, value, options) {
78
- if (value === void 0) return;
79
- await this.initialize();
80
- const serializedKey = JSON.stringify([...key]);
81
- const jsonValue = JSON.stringify(value);
82
- if (options?.ttl != null) {
83
- const ttlSeconds = durationToSeconds(options.ttl);
84
- await this.#pool.query(`INSERT INTO \`${this.#tableName}\` (\`key\`, \`value\`, \`expires\`)
85
- VALUES (?, CAST(? AS JSON),
86
- DATE_ADD(NOW(6), INTERVAL ? SECOND))
87
- ON DUPLICATE KEY UPDATE
88
- \`value\` = VALUES(\`value\`),
89
- \`expires\` = VALUES(\`expires\`)`, [
90
- serializedKey,
91
- jsonValue,
92
- ttlSeconds
93
- ]);
94
- } else await this.#pool.query(`INSERT INTO \`${this.#tableName}\` (\`key\`, \`value\`, \`expires\`)
95
- VALUES (?, CAST(? AS JSON), NULL)
96
- ON DUPLICATE KEY UPDATE
97
- \`value\` = VALUES(\`value\`),
98
- \`expires\` = NULL`, [serializedKey, jsonValue]);
99
- await this.#expire();
97
+ await this.setMany([{
98
+ key,
99
+ value,
100
+ options
101
+ }]);
100
102
  }
101
103
  /**
102
- * {@inheritDoc KvStore.delete}
104
+ * {@inheritDoc AtomicKvStore.delete}
103
105
  * @since 2.1.0
104
106
  */
105
107
  async delete(key) {
106
- await this.initialize();
107
- const serializedKey = JSON.stringify([...key]);
108
- await this.#pool.query(`DELETE FROM \`${this.#tableName}\` WHERE \`key\` = ?`, [serializedKey]);
109
- await this.#expire();
108
+ await this.deleteMany([key]);
110
109
  }
111
110
  /**
112
- * {@inheritDoc KvStore.cas}
111
+ * {@inheritDoc AtomicKvStore.cas}
113
112
  * @since 2.1.0
114
113
  */
115
114
  async cas(key, expectedValue, newValue, options) {
115
+ return await this.casMany([{
116
+ key,
117
+ expectedValue,
118
+ newValue,
119
+ options
120
+ }]);
121
+ }
122
+ /**
123
+ * {@inheritDoc AtomicKvStore.getMany}
124
+ * @since 2.5.0
125
+ */
126
+ async getMany(keys) {
127
+ validateBatch(keys);
128
+ const serialized = Array.from(keys, serializeKey);
129
+ if (serialized.length === 0) return [];
116
130
  await this.initialize();
117
- const serializedKey = JSON.stringify([...key]);
118
- let conn;
119
- try {
120
- conn = await this.#pool.getConnection();
121
- await conn.beginTransaction();
122
- const [rows] = await conn.query(`SELECT
123
- \`value\`,
124
- (\`expires\` IS NOT NULL AND \`expires\` <= NOW(6)) AS \`is_expired\`
125
- FROM \`${this.#tableName}\`
126
- WHERE \`key\` = ?
127
- FOR UPDATE`, [serializedKey]);
128
- const row = rows[0];
129
- if (!(0, es_toolkit.isEqual)(!row || row.is_expired ? void 0 : row.value, expectedValue)) {
130
- await conn.rollback();
131
- return false;
131
+ return await this.#transaction(async (conn) => {
132
+ const [rows] = await conn.query(`SELECT \`key\`, CAST(\`value\` AS CHAR CHARACTER SET utf8mb4) AS \`value\`
133
+ FROM \`${this.#tableName}\` WHERE \`key\` IN (?)
134
+ AND (\`expires\` IS NULL OR \`expires\` > NOW(6))`, [serialized]);
135
+ const values = new Map(rows.map((row) => [row.key, JSON.parse(row.value)]));
136
+ return serialized.map((key) => values.get(key));
137
+ });
138
+ }
139
+ /**
140
+ * {@inheritDoc AtomicKvStore.setMany}
141
+ * @since 2.5.0
142
+ */
143
+ async setMany(entries) {
144
+ validateBatch(entries);
145
+ const captured = Array.from(entries, (entry) => ({
146
+ key: serializeKey(entry.key),
147
+ value: serializeValue(entry.value),
148
+ ttl: encodeTtl(entry.options)
149
+ }));
150
+ validateDistinct(captured);
151
+ if (captured.length === 0) return;
152
+ await this.#mutate(captured, false);
153
+ }
154
+ /**
155
+ * {@inheritDoc AtomicKvStore.deleteMany}
156
+ * @since 2.5.0
157
+ */
158
+ async deleteMany(keys) {
159
+ validateBatch(keys);
160
+ const captured = Array.from(keys, (key) => ({
161
+ key: serializeKey(key),
162
+ value: void 0,
163
+ ttl: null
164
+ }));
165
+ validateDistinct(captured);
166
+ if (captured.length === 0) return;
167
+ await this.#mutate(captured, false);
168
+ }
169
+ /**
170
+ * {@inheritDoc AtomicKvStore.casMany}
171
+ * @since 2.5.0
172
+ */
173
+ async casMany(entries) {
174
+ validateBatch(entries);
175
+ const captured = Array.from(entries, (entry) => {
176
+ const value = entry.newValue;
177
+ const options = entry.options;
178
+ if (value === void 0 && options?.ttl != null) throw new TypeError("A CAS deletion must not specify a TTL.");
179
+ return {
180
+ key: serializeKey(entry.key),
181
+ expectedValue: entry.expectedValue,
182
+ value: value === void 0 ? void 0 : serializeValue(value),
183
+ ttl: encodeTtl(options)
184
+ };
185
+ });
186
+ validateDistinct(captured);
187
+ if (captured.length === 0) return true;
188
+ return await this.#mutate(captured, true);
189
+ }
190
+ async #mutate(entries, conditional) {
191
+ entries.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
192
+ await this.initialize();
193
+ const matched = await this.#transaction(async (conn) => {
194
+ const rows = /* @__PURE__ */ new Map();
195
+ if (conditional) for (const entry of entries) {
196
+ const [found] = await conn.query(`SELECT \`key\`, CAST(\`value\` AS CHAR CHARACTER SET utf8mb4) AS \`value\`,
197
+ DATE_FORMAT(\`expires\`, '%Y-%m-%d %H:%i:%s.%f') AS \`expires\`
198
+ FROM \`${this.#tableName}\` WHERE \`key\` = ? FOR UPDATE`, [entry.key]);
199
+ if (found.length > 0) rows.set(entry.key, found[0]);
200
+ }
201
+ const [clock] = await conn.query("SELECT DATE_FORMAT(NOW(6), '%Y-%m-%d %H:%i:%s.%f') AS cutoff");
202
+ const cutoff = clock[0].cutoff;
203
+ const durations = [...new Set(entries.flatMap((e) => e.ttl == null ? [] : [e.ttl]))];
204
+ const expiries = /* @__PURE__ */ new Map();
205
+ if (durations.length > 0) {
206
+ const expressions = durations.map((_, i) => `DATE_FORMAT(DATE_ADD(?, INTERVAL ? MICROSECOND), '%Y-%m-%d %H:%i:%s.%f') AS e${i}`);
207
+ const [computed] = await conn.query(`SELECT ${expressions.join(", ")}`, durations.flatMap((ttl) => [cutoff, ttl]));
208
+ for (let i = 0; i < durations.length; i++) {
209
+ const expiry = computed[0][`e${i}`];
210
+ if (expiry == null) throw new RangeError("TTL exceeds the server DATETIME range.");
211
+ expiries.set(durations[i], expiry);
212
+ }
132
213
  }
133
- if (newValue === void 0) await conn.query(`DELETE FROM \`${this.#tableName}\` WHERE \`key\` = ?`, [serializedKey]);
214
+ if (conditional) for (const entry of entries) {
215
+ const row = rows.get(entry.key);
216
+ if (!(0, es_toolkit.isEqual)(row == null || row.expires != null && row.expires <= cutoff ? void 0 : JSON.parse(row.value), entry.expectedValue)) return false;
217
+ }
218
+ for (const entry of entries) if (entry.value === void 0) await conn.query(`DELETE FROM \`${this.#tableName}\` WHERE \`key\` = ?`, [entry.key]);
134
219
  else {
135
- const jsonValue = JSON.stringify(newValue);
136
- if (options?.ttl != null) {
137
- const ttlSeconds = durationToSeconds(options.ttl);
138
- await conn.query(`INSERT INTO \`${this.#tableName}\`
139
- (\`key\`, \`value\`, \`expires\`)
140
- VALUES (?, CAST(? AS JSON),
141
- DATE_ADD(NOW(6), INTERVAL ? SECOND))
142
- ON DUPLICATE KEY UPDATE
143
- \`value\` = VALUES(\`value\`),
144
- \`expires\` = VALUES(\`expires\`)`, [
145
- serializedKey,
146
- jsonValue,
147
- ttlSeconds
148
- ]);
149
- } else await conn.query(`INSERT INTO \`${this.#tableName}\`
150
- (\`key\`, \`value\`, \`expires\`)
151
- VALUES (?, CAST(? AS JSON), NULL)
152
- ON DUPLICATE KEY UPDATE
153
- \`value\` = VALUES(\`value\`),
154
- \`expires\` = NULL`, [serializedKey, jsonValue]);
220
+ const expiry = entry.ttl == null ? null : expiries.get(entry.ttl);
221
+ await conn.query(`INSERT INTO \`${this.#tableName}\` (\`key\`, \`value\`, \`expires\`)
222
+ VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE \`value\` = ?, \`expires\` = ?`, [
223
+ entry.key,
224
+ entry.value,
225
+ expiry,
226
+ entry.value,
227
+ expiry
228
+ ]);
155
229
  }
156
- await conn.commit();
157
- await this.#expire();
158
230
  return true;
159
- } catch (e) {
160
- if (conn) await conn.rollback();
161
- throw e;
162
- } finally {
163
- if (conn) conn.release();
231
+ });
232
+ if (matched) await this.#expire();
233
+ return matched;
234
+ }
235
+ async #transaction(run) {
236
+ for (let attempt = 0;; attempt++) {
237
+ const conn = await this.#pool.getConnection();
238
+ let phase = "setup";
239
+ let reusable = false;
240
+ try {
241
+ await conn.query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");
242
+ await conn.beginTransaction();
243
+ phase = "active";
244
+ const result = await run(conn);
245
+ if (result === false) {
246
+ phase = "rollback";
247
+ await conn.rollback();
248
+ } else {
249
+ phase = "commit";
250
+ await conn.commit();
251
+ }
252
+ reusable = true;
253
+ return result;
254
+ } catch (error) {
255
+ if (phase !== "active") throw error;
256
+ try {
257
+ await conn.rollback();
258
+ reusable = true;
259
+ } catch (rollbackError) {
260
+ throw new AggregateError([error, rollbackError], "MySQL transaction and rollback failed.");
261
+ }
262
+ if (attempt >= 4 || !retryable(error)) throw error;
263
+ } finally {
264
+ if (reusable) conn.release();
265
+ else conn.destroy();
266
+ }
267
+ await new Promise((resolve) => setTimeout(resolve, 5 + Math.random() * Math.min(45, 5 * 2 ** attempt)));
164
268
  }
165
269
  }
166
270
  /**
167
- * {@inheritDoc KvStore.list}
271
+ * {@inheritDoc AtomicKvStore.list}
168
272
  * @since 2.1.0
169
273
  */
170
274
  async *list(prefix) {
171
275
  await this.initialize();
172
- let rows;
173
- if (prefix == null || prefix.length === 0) [rows] = await this.#pool.query(`SELECT \`key\`, \`value\` FROM \`${this.#tableName}\`
174
- WHERE \`expires\` IS NULL OR \`expires\` > NOW(6)
175
- ORDER BY \`key\``);
176
- else {
177
- const serializedPrefix = JSON.stringify([...prefix]);
178
- const likePrefix = serializedPrefix.slice(0, -1).replace(/[%_\\]/g, "\\$&") + ",%";
179
- [rows] = await this.#pool.query(`SELECT \`key\`, \`value\` FROM \`${this.#tableName}\`
180
- WHERE (\`key\` = ? OR \`key\` LIKE ? ESCAPE '\\\\')
181
- AND (\`expires\` IS NULL OR \`expires\` > NOW(6))
182
- ORDER BY \`key\``, [serializedPrefix, likePrefix]);
183
- }
276
+ const rows = await this.#transaction(async (conn) => {
277
+ let rows;
278
+ if (prefix == null || prefix.length === 0) [rows] = await conn.query(`SELECT \`key\`, CAST(\`value\` AS CHAR CHARACTER SET utf8mb4) AS \`value\` FROM \`${this.#tableName}\`
279
+ WHERE \`expires\` IS NULL OR \`expires\` > NOW(6)
280
+ ORDER BY \`key\``);
281
+ else {
282
+ const serializedPrefix = JSON.stringify([...prefix]);
283
+ const likePrefix = serializedPrefix.slice(0, -1).replace(/[%_\\]/g, "\\$&") + ",%";
284
+ [rows] = await conn.query(`SELECT \`key\`, CAST(\`value\` AS CHAR CHARACTER SET utf8mb4) AS \`value\` FROM \`${this.#tableName}\`
285
+ WHERE (\`key\` = ? OR \`key\` LIKE ? ESCAPE '\\\\')
286
+ AND (\`expires\` IS NULL OR \`expires\` > NOW(6))
287
+ ORDER BY \`key\``, [serializedPrefix, likePrefix]);
288
+ }
289
+ return rows;
290
+ });
184
291
  for (const row of rows) yield {
185
292
  key: JSON.parse(row.key),
186
- value: row.value
293
+ value: JSON.parse(row.value)
187
294
  };
188
295
  }
189
296
  /**
190
297
  * Creates the table used by the key-value store if it does not already exist.
191
- * Does nothing if the table already exists.
298
+ * Validates the existing schema, including when `initialized: true` was
299
+ * supplied. Successful initialization is cached until {@link MysqlKvStore.drop}.
300
+ * Initialization and dropping must not overlap store operations.
192
301
  *
193
302
  * @since 2.1.0
194
303
  */
195
304
  async initialize() {
196
- if (this.#initialized) return;
197
- logger.debug("Initializing the key-value store table {tableName}...", { tableName: this.#tableName });
198
- await this.#pool.query(`CREATE TABLE IF NOT EXISTS \`${this.#tableName}\` (
199
- \`key\` VARCHAR(768) NOT NULL,
200
- \`value\` JSON NOT NULL,
201
- \`expires\` DATETIME(6) NULL DEFAULT NULL,
202
- PRIMARY KEY (\`key\`)
203
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin`);
204
- try {
305
+ if (this.#initialization == null) {
306
+ const pending = this.#initialize();
307
+ this.#initialization = pending;
308
+ pending.catch(() => {
309
+ if (this.#initialization === pending) this.#initialization = void 0;
310
+ });
311
+ }
312
+ await this.#initialization;
313
+ }
314
+ async #initialize() {
315
+ if (!this.#initialized) await this.#pool.query(`CREATE TABLE IF NOT EXISTS \`${this.#tableName}\` (
316
+ \`key\` VARCHAR(768) NOT NULL,
317
+ \`value\` JSON NOT NULL,
318
+ \`expires\` DATETIME(6) NULL DEFAULT NULL,
319
+ PRIMARY KEY (\`key\`)
320
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin`);
321
+ const predicate = `TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?
322
+ AND (@@lower_case_table_names <> 0 OR
323
+ (CAST(TABLE_SCHEMA AS BINARY) = CAST(DATABASE() AS BINARY)
324
+ AND CAST(TABLE_NAME AS BINARY) = CAST(? AS BINARY)))`;
325
+ const params = [this.#tableName, this.#tableName];
326
+ const [tables] = await this.#pool.query(`SELECT ENGINE AS \`engine\`, TABLE_TYPE AS \`table_type\`
327
+ FROM information_schema.TABLES WHERE ${predicate}`, params);
328
+ if (tables.length !== 1 || tables[0].engine?.toLowerCase() !== "innodb" || tables[0].table_type !== "BASE TABLE") throw new TypeError("MysqlKvStore requires an InnoDB base table in the pool's default database.");
329
+ const [columns] = await this.#pool.query(`SELECT COLUMN_NAME AS \`name\`, DATA_TYPE AS \`type\`, IS_NULLABLE AS \`nullable\`,
330
+ CHARACTER_MAXIMUM_LENGTH AS \`length\`, CHARACTER_SET_NAME AS \`charset\`,
331
+ COLLATION_NAME AS \`collation\`, DATETIME_PRECISION AS \`precision\`
332
+ FROM information_schema.COLUMNS WHERE ${predicate}`, params);
333
+ const key = columns.find((c) => c.name === "key");
334
+ const value = columns.find((c) => c.name === "value");
335
+ const expires = columns.find((c) => c.name === "expires");
336
+ if (key?.type !== "varchar" || Number(key.length) !== 768 || key.charset !== "utf8mb4" || key.collation !== "utf8mb4_bin" || key.nullable !== "NO" || value?.nullable !== "NO" || !(value.type === "json" || value.type === "longtext" && value.charset === "utf8mb4") || expires?.type !== "datetime" || Number(expires.precision) !== 6 || expires.nullable !== "YES") throw new TypeError("Incompatible MysqlKvStore key, JSON value, or nullable DATETIME(6) expiry columns.");
337
+ const [indexes] = await this.#pool.query(`SELECT INDEX_NAME AS \`name\`, COLUMN_NAME AS \`column_name\`,
338
+ SEQ_IN_INDEX AS \`position\`, SUB_PART AS \`prefix\`, INDEX_TYPE AS \`type\`
339
+ FROM information_schema.STATISTICS WHERE ${predicate} AND NON_UNIQUE = 0`, params);
340
+ if (indexes.length !== 1 || indexes[0].name !== "PRIMARY" || indexes[0].column_name !== "key" || Number(indexes[0].position) !== 1 || indexes[0].prefix != null || indexes[0].type !== "BTREE") throw new TypeError("MysqlKvStore requires a full key BTREE primary index and no other unique indexes.");
341
+ const [unsafe] = await this.#pool.query("SHOW VARIABLES WHERE Variable_name = 'innodb_locks_unsafe_for_binlog'");
342
+ if (unsafe.some((row) => !["off", "0"].includes(String(row.Value).toLowerCase()))) throw new TypeError("MysqlKvStore requires InnoDB gap locking to be enabled.");
343
+ if (!this.#initialized) try {
205
344
  await this.#pool.query(`CREATE INDEX \`idx_${this.#tableName}_expires\`
206
- ON \`${this.#tableName}\` (\`expires\`)`);
207
- } catch (e) {
208
- if (e.code !== "ER_DUP_KEYNAME") throw e;
345
+ ON \`${this.#tableName}\` (\`expires\`)`);
346
+ } catch (error) {
347
+ if (error.code !== "ER_DUP_KEYNAME") throw error;
209
348
  }
210
- this.#initialized = true;
211
- logger.debug("Initialized the key-value store table {tableName}.", { tableName: this.#tableName });
212
349
  }
213
350
  /**
214
351
  * Drops the table used by the key-value store. Does nothing if the table
@@ -218,15 +355,46 @@ var MysqlKvStore = class {
218
355
  * @since 2.1.0
219
356
  */
220
357
  async drop() {
221
- await this.#pool.query(`DROP TABLE IF EXISTS \`${this.#tableName}\``);
222
- this.#initialized = false;
358
+ try {
359
+ await this.#pool.query(`DROP TABLE IF EXISTS \`${this.#tableName}\``);
360
+ } finally {
361
+ this.#initialization = void 0;
362
+ this.#initialized = false;
363
+ }
223
364
  }
224
365
  };
225
- function durationToSeconds(duration) {
226
- return duration.total({
227
- unit: "second",
366
+ function validateBatch(entries) {
367
+ if (!Array.isArray(entries)) throw new TypeError("An atomic batch must be an array.");
368
+ if (entries.length > 1e3) throw new RangeError("An atomic batch has at most 1,000 entries.");
369
+ for (let i = 0; i < entries.length; i++) if (!Object.hasOwn(entries, i)) throw new TypeError("Atomic batches must not be sparse.");
370
+ }
371
+ function serializeKey(key) {
372
+ if (!Array.isArray(key) || key.length === 0) throw new TypeError("A key must be a nonempty array of strings.");
373
+ for (let i = 0; i < key.length; i++) if (!Object.hasOwn(key, i) || typeof key[i] !== "string") throw new TypeError("Key parts must be strings.");
374
+ const encoded = JSON.stringify([...key]);
375
+ if ([...encoded].length > 768) throw new RangeError("A serialized key has at most 768 Unicode code points.");
376
+ return encoded;
377
+ }
378
+ function serializeValue(value) {
379
+ const encoded = JSON.stringify(value);
380
+ if (encoded === void 0) throw new TypeError("The value must have a JSON representation; undefined cannot be stored.");
381
+ return encoded;
382
+ }
383
+ function encodeTtl(options) {
384
+ if (options?.ttl == null) return null;
385
+ const micros = Math.trunc(options.ttl.total({
386
+ unit: "microsecond",
228
387
  relativeTo: Temporal.Now.plainDateTimeISO()
229
- });
388
+ }));
389
+ if (!Number.isSafeInteger(micros)) throw new RangeError("TTL must fit in safe integer microseconds.");
390
+ return micros;
391
+ }
392
+ function validateDistinct(entries) {
393
+ if (new Set(entries.map((entry) => entry.key)).size !== entries.length) throw new TypeError("Duplicate keys in an atomic mutation.");
394
+ }
395
+ function retryable(error) {
396
+ const e = error;
397
+ return e?.errno === 1213 || e?.errno === 1020 || e?.code === "ER_LOCK_DEADLOCK" || e?.code === "ER_CHECKREAD";
230
398
  }
231
399
  //#endregion
232
400
  exports.MysqlKvStore = MysqlKvStore;