@fedify/mysql 2.5.0-dev.2811 → 2.5.0-dev.2822

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/dist/kv.js CHANGED
@@ -8,7 +8,27 @@ const logger = getLogger([
8
8
  "kv"
9
9
  ]);
10
10
  /**
11
- * A key-value store that uses MySQL (or MariaDB) as the underlying storage.
11
+ * An atomic key-value store backed by an InnoDB table on MySQL or MariaDB.
12
+ *
13
+ * All keys in one primary database/table share an atomic scope. Batches have
14
+ * at most 1,000 entries and serialized keys at most 768 Unicode code points;
15
+ * server packet and resource limits also apply. Values use JSON serialization
16
+ * and decoded structural equality (`isEqual`); object member order is ignored.
17
+ * Do not mutate expected values while a CAS is pending.
18
+ *
19
+ * TTLs are truncated to safe integer microseconds (approximately ±285 years),
20
+ * evaluated using one server cutoff per attempt. Calendar units use the local
21
+ * current date for conversion. Omitted TTL clears the previous expiry.
22
+ *
23
+ * Use a normal mysql2 pool with autocommit enabled, object rows, default type
24
+ * casting, and the same fixed-offset or UTC session time zone on every client.
25
+ * Caller-owned transactions, replica routing, concurrent schema changes,
26
+ * `NO_BACKSLASH_ESCAPES`, and disabled InnoDB gap locking are unsupported.
27
+ * Initialization checks the schema even with `initialized: true`.
28
+ *
29
+ * Deadlocks and MariaDB snapshot conflicts retry up to five total attempts.
30
+ * Other failures reject; a failed commit response can leave its outcome
31
+ * unknown. Atomicity does not promise crash durability or external effects.
12
32
  *
13
33
  * @example
14
34
  * ```ts
@@ -31,6 +51,7 @@ var MysqlKvStore = class {
31
51
  #tableName;
32
52
  #expireCleanupRate;
33
53
  #initialized;
54
+ #initialization;
34
55
  /**
35
56
  * Creates a new MySQL key-value store.
36
57
  * @param pool The MySQL connection pool to use.
@@ -51,161 +72,277 @@ var MysqlKvStore = class {
51
72
  async #expire() {
52
73
  if (this.#expireCleanupRate <= 0) return;
53
74
  if (this.#expireCleanupRate < 1 && Math.random() >= this.#expireCleanupRate) return;
54
- await this.#pool.query(`DELETE FROM \`${this.#tableName}\`
55
- WHERE \`expires\` IS NOT NULL AND \`expires\` < NOW(6)`);
75
+ try {
76
+ await this.#pool.query(`DELETE FROM \`${this.#tableName}\`
77
+ WHERE \`expires\` IS NOT NULL AND \`expires\` < NOW(6)`);
78
+ } catch (error) {
79
+ logger.warn("Failed to clean up expired key-value entries: {error}", { error });
80
+ }
56
81
  }
57
82
  /**
58
- * {@inheritDoc KvStore.get}
83
+ * {@inheritDoc AtomicKvStore.get}
59
84
  * @since 2.1.0
60
85
  */
61
86
  async get(key) {
62
- await this.initialize();
63
- const serializedKey = JSON.stringify([...key]);
64
- const [rows] = await this.#pool.query(`SELECT \`value\` FROM \`${this.#tableName}\`
65
- WHERE \`key\` = ?
66
- AND (\`expires\` IS NULL OR \`expires\` > NOW(6))`, [serializedKey]);
67
- if (rows.length < 1) return void 0;
68
- return rows[0].value;
87
+ return (await this.getMany([key]))[0];
69
88
  }
70
89
  /**
71
- * {@inheritDoc KvStore.set}
90
+ * {@inheritDoc AtomicKvStore.set}
72
91
  * @since 2.1.0
73
92
  */
74
93
  async set(key, value, options) {
75
- if (value === void 0) return;
76
- await this.initialize();
77
- const serializedKey = JSON.stringify([...key]);
78
- const jsonValue = JSON.stringify(value);
79
- if (options?.ttl != null) {
80
- const ttlSeconds = durationToSeconds(options.ttl);
81
- await this.#pool.query(`INSERT INTO \`${this.#tableName}\` (\`key\`, \`value\`, \`expires\`)
82
- VALUES (?, CAST(? AS JSON),
83
- DATE_ADD(NOW(6), INTERVAL ? SECOND))
84
- ON DUPLICATE KEY UPDATE
85
- \`value\` = VALUES(\`value\`),
86
- \`expires\` = VALUES(\`expires\`)`, [
87
- serializedKey,
88
- jsonValue,
89
- ttlSeconds
90
- ]);
91
- } else await this.#pool.query(`INSERT INTO \`${this.#tableName}\` (\`key\`, \`value\`, \`expires\`)
92
- VALUES (?, CAST(? AS JSON), NULL)
93
- ON DUPLICATE KEY UPDATE
94
- \`value\` = VALUES(\`value\`),
95
- \`expires\` = NULL`, [serializedKey, jsonValue]);
96
- await this.#expire();
94
+ await this.setMany([{
95
+ key,
96
+ value,
97
+ options
98
+ }]);
97
99
  }
98
100
  /**
99
- * {@inheritDoc KvStore.delete}
101
+ * {@inheritDoc AtomicKvStore.delete}
100
102
  * @since 2.1.0
101
103
  */
102
104
  async delete(key) {
103
- await this.initialize();
104
- const serializedKey = JSON.stringify([...key]);
105
- await this.#pool.query(`DELETE FROM \`${this.#tableName}\` WHERE \`key\` = ?`, [serializedKey]);
106
- await this.#expire();
105
+ await this.deleteMany([key]);
107
106
  }
108
107
  /**
109
- * {@inheritDoc KvStore.cas}
108
+ * {@inheritDoc AtomicKvStore.cas}
110
109
  * @since 2.1.0
111
110
  */
112
111
  async cas(key, expectedValue, newValue, options) {
112
+ return await this.casMany([{
113
+ key,
114
+ expectedValue,
115
+ newValue,
116
+ options
117
+ }]);
118
+ }
119
+ /**
120
+ * {@inheritDoc AtomicKvStore.getMany}
121
+ * @since 2.5.0
122
+ */
123
+ async getMany(keys) {
124
+ validateBatch(keys);
125
+ const serialized = Array.from(keys, serializeKey);
126
+ if (serialized.length === 0) return [];
113
127
  await this.initialize();
114
- const serializedKey = JSON.stringify([...key]);
115
- let conn;
116
- try {
117
- conn = await this.#pool.getConnection();
118
- await conn.beginTransaction();
119
- const [rows] = await conn.query(`SELECT
120
- \`value\`,
121
- (\`expires\` IS NOT NULL AND \`expires\` <= NOW(6)) AS \`is_expired\`
122
- FROM \`${this.#tableName}\`
123
- WHERE \`key\` = ?
124
- FOR UPDATE`, [serializedKey]);
125
- const row = rows[0];
126
- if (!isEqual(!row || row.is_expired ? void 0 : row.value, expectedValue)) {
127
- await conn.rollback();
128
- return false;
128
+ return await this.#transaction(async (conn) => {
129
+ const [rows] = await conn.query(`SELECT \`key\`, CAST(\`value\` AS CHAR CHARACTER SET utf8mb4) AS \`value\`
130
+ FROM \`${this.#tableName}\` WHERE \`key\` IN (?)
131
+ AND (\`expires\` IS NULL OR \`expires\` > NOW(6))`, [serialized]);
132
+ const values = new Map(rows.map((row) => [row.key, JSON.parse(row.value)]));
133
+ return serialized.map((key) => values.get(key));
134
+ });
135
+ }
136
+ /**
137
+ * {@inheritDoc AtomicKvStore.setMany}
138
+ * @since 2.5.0
139
+ */
140
+ async setMany(entries) {
141
+ validateBatch(entries);
142
+ const captured = Array.from(entries, (entry) => ({
143
+ key: serializeKey(entry.key),
144
+ value: serializeValue(entry.value),
145
+ ttl: encodeTtl(entry.options)
146
+ }));
147
+ validateDistinct(captured);
148
+ if (captured.length === 0) return;
149
+ await this.#mutate(captured, false);
150
+ }
151
+ /**
152
+ * {@inheritDoc AtomicKvStore.deleteMany}
153
+ * @since 2.5.0
154
+ */
155
+ async deleteMany(keys) {
156
+ validateBatch(keys);
157
+ const captured = Array.from(keys, (key) => ({
158
+ key: serializeKey(key),
159
+ value: void 0,
160
+ ttl: null
161
+ }));
162
+ validateDistinct(captured);
163
+ if (captured.length === 0) return;
164
+ await this.#mutate(captured, false);
165
+ }
166
+ /**
167
+ * {@inheritDoc AtomicKvStore.casMany}
168
+ * @since 2.5.0
169
+ */
170
+ async casMany(entries) {
171
+ validateBatch(entries);
172
+ const captured = Array.from(entries, (entry) => {
173
+ const value = entry.newValue;
174
+ const options = entry.options;
175
+ if (value === void 0 && options?.ttl != null) throw new TypeError("A CAS deletion must not specify a TTL.");
176
+ return {
177
+ key: serializeKey(entry.key),
178
+ expectedValue: entry.expectedValue,
179
+ value: value === void 0 ? void 0 : serializeValue(value),
180
+ ttl: encodeTtl(options)
181
+ };
182
+ });
183
+ validateDistinct(captured);
184
+ if (captured.length === 0) return true;
185
+ return await this.#mutate(captured, true);
186
+ }
187
+ async #mutate(entries, conditional) {
188
+ entries.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
189
+ await this.initialize();
190
+ const matched = await this.#transaction(async (conn) => {
191
+ const rows = /* @__PURE__ */ new Map();
192
+ if (conditional) for (const entry of entries) {
193
+ const [found] = await conn.query(`SELECT \`key\`, CAST(\`value\` AS CHAR CHARACTER SET utf8mb4) AS \`value\`,
194
+ DATE_FORMAT(\`expires\`, '%Y-%m-%d %H:%i:%s.%f') AS \`expires\`
195
+ FROM \`${this.#tableName}\` WHERE \`key\` = ? FOR UPDATE`, [entry.key]);
196
+ if (found.length > 0) rows.set(entry.key, found[0]);
197
+ }
198
+ const [clock] = await conn.query("SELECT DATE_FORMAT(NOW(6), '%Y-%m-%d %H:%i:%s.%f') AS cutoff");
199
+ const cutoff = clock[0].cutoff;
200
+ const durations = [...new Set(entries.flatMap((e) => e.ttl == null ? [] : [e.ttl]))];
201
+ const expiries = /* @__PURE__ */ new Map();
202
+ if (durations.length > 0) {
203
+ const expressions = durations.map((_, i) => `DATE_FORMAT(DATE_ADD(?, INTERVAL ? MICROSECOND), '%Y-%m-%d %H:%i:%s.%f') AS e${i}`);
204
+ const [computed] = await conn.query(`SELECT ${expressions.join(", ")}`, durations.flatMap((ttl) => [cutoff, ttl]));
205
+ for (let i = 0; i < durations.length; i++) {
206
+ const expiry = computed[0][`e${i}`];
207
+ if (expiry == null) throw new RangeError("TTL exceeds the server DATETIME range.");
208
+ expiries.set(durations[i], expiry);
209
+ }
129
210
  }
130
- if (newValue === void 0) await conn.query(`DELETE FROM \`${this.#tableName}\` WHERE \`key\` = ?`, [serializedKey]);
211
+ if (conditional) for (const entry of entries) {
212
+ const row = rows.get(entry.key);
213
+ if (!isEqual(row == null || row.expires != null && row.expires <= cutoff ? void 0 : JSON.parse(row.value), entry.expectedValue)) return false;
214
+ }
215
+ for (const entry of entries) if (entry.value === void 0) await conn.query(`DELETE FROM \`${this.#tableName}\` WHERE \`key\` = ?`, [entry.key]);
131
216
  else {
132
- const jsonValue = JSON.stringify(newValue);
133
- if (options?.ttl != null) {
134
- const ttlSeconds = durationToSeconds(options.ttl);
135
- await conn.query(`INSERT INTO \`${this.#tableName}\`
136
- (\`key\`, \`value\`, \`expires\`)
137
- VALUES (?, CAST(? AS JSON),
138
- DATE_ADD(NOW(6), INTERVAL ? SECOND))
139
- ON DUPLICATE KEY UPDATE
140
- \`value\` = VALUES(\`value\`),
141
- \`expires\` = VALUES(\`expires\`)`, [
142
- serializedKey,
143
- jsonValue,
144
- ttlSeconds
145
- ]);
146
- } else await conn.query(`INSERT INTO \`${this.#tableName}\`
147
- (\`key\`, \`value\`, \`expires\`)
148
- VALUES (?, CAST(? AS JSON), NULL)
149
- ON DUPLICATE KEY UPDATE
150
- \`value\` = VALUES(\`value\`),
151
- \`expires\` = NULL`, [serializedKey, jsonValue]);
217
+ const expiry = entry.ttl == null ? null : expiries.get(entry.ttl);
218
+ await conn.query(`INSERT INTO \`${this.#tableName}\` (\`key\`, \`value\`, \`expires\`)
219
+ VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE \`value\` = ?, \`expires\` = ?`, [
220
+ entry.key,
221
+ entry.value,
222
+ expiry,
223
+ entry.value,
224
+ expiry
225
+ ]);
152
226
  }
153
- await conn.commit();
154
- await this.#expire();
155
227
  return true;
156
- } catch (e) {
157
- if (conn) await conn.rollback();
158
- throw e;
159
- } finally {
160
- if (conn) conn.release();
228
+ });
229
+ if (matched) await this.#expire();
230
+ return matched;
231
+ }
232
+ async #transaction(run) {
233
+ for (let attempt = 0;; attempt++) {
234
+ const conn = await this.#pool.getConnection();
235
+ let phase = "setup";
236
+ let reusable = false;
237
+ try {
238
+ await conn.query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");
239
+ await conn.beginTransaction();
240
+ phase = "active";
241
+ const result = await run(conn);
242
+ if (result === false) {
243
+ phase = "rollback";
244
+ await conn.rollback();
245
+ } else {
246
+ phase = "commit";
247
+ await conn.commit();
248
+ }
249
+ reusable = true;
250
+ return result;
251
+ } catch (error) {
252
+ if (phase !== "active") throw error;
253
+ try {
254
+ await conn.rollback();
255
+ reusable = true;
256
+ } catch (rollbackError) {
257
+ throw new AggregateError([error, rollbackError], "MySQL transaction and rollback failed.");
258
+ }
259
+ if (attempt >= 4 || !retryable(error)) throw error;
260
+ } finally {
261
+ if (reusable) conn.release();
262
+ else conn.destroy();
263
+ }
264
+ await new Promise((resolve) => setTimeout(resolve, 5 + Math.random() * Math.min(45, 5 * 2 ** attempt)));
161
265
  }
162
266
  }
163
267
  /**
164
- * {@inheritDoc KvStore.list}
268
+ * {@inheritDoc AtomicKvStore.list}
165
269
  * @since 2.1.0
166
270
  */
167
271
  async *list(prefix) {
168
272
  await this.initialize();
169
- let rows;
170
- if (prefix == null || prefix.length === 0) [rows] = await this.#pool.query(`SELECT \`key\`, \`value\` FROM \`${this.#tableName}\`
171
- WHERE \`expires\` IS NULL OR \`expires\` > NOW(6)
172
- ORDER BY \`key\``);
173
- else {
174
- const serializedPrefix = JSON.stringify([...prefix]);
175
- const likePrefix = serializedPrefix.slice(0, -1).replace(/[%_\\]/g, "\\$&") + ",%";
176
- [rows] = await this.#pool.query(`SELECT \`key\`, \`value\` FROM \`${this.#tableName}\`
177
- WHERE (\`key\` = ? OR \`key\` LIKE ? ESCAPE '\\\\')
178
- AND (\`expires\` IS NULL OR \`expires\` > NOW(6))
179
- ORDER BY \`key\``, [serializedPrefix, likePrefix]);
180
- }
273
+ const rows = await this.#transaction(async (conn) => {
274
+ let rows;
275
+ if (prefix == null || prefix.length === 0) [rows] = await conn.query(`SELECT \`key\`, CAST(\`value\` AS CHAR CHARACTER SET utf8mb4) AS \`value\` FROM \`${this.#tableName}\`
276
+ WHERE \`expires\` IS NULL OR \`expires\` > NOW(6)
277
+ ORDER BY \`key\``);
278
+ else {
279
+ const serializedPrefix = JSON.stringify([...prefix]);
280
+ const likePrefix = serializedPrefix.slice(0, -1).replace(/[%_\\]/g, "\\$&") + ",%";
281
+ [rows] = await conn.query(`SELECT \`key\`, CAST(\`value\` AS CHAR CHARACTER SET utf8mb4) AS \`value\` FROM \`${this.#tableName}\`
282
+ WHERE (\`key\` = ? OR \`key\` LIKE ? ESCAPE '\\\\')
283
+ AND (\`expires\` IS NULL OR \`expires\` > NOW(6))
284
+ ORDER BY \`key\``, [serializedPrefix, likePrefix]);
285
+ }
286
+ return rows;
287
+ });
181
288
  for (const row of rows) yield {
182
289
  key: JSON.parse(row.key),
183
- value: row.value
290
+ value: JSON.parse(row.value)
184
291
  };
185
292
  }
186
293
  /**
187
294
  * Creates the table used by the key-value store if it does not already exist.
188
- * Does nothing if the table already exists.
295
+ * Validates the existing schema, including when `initialized: true` was
296
+ * supplied. Successful initialization is cached until {@link MysqlKvStore.drop}.
297
+ * Initialization and dropping must not overlap store operations.
189
298
  *
190
299
  * @since 2.1.0
191
300
  */
192
301
  async initialize() {
193
- if (this.#initialized) return;
194
- logger.debug("Initializing the key-value store table {tableName}...", { tableName: this.#tableName });
195
- await this.#pool.query(`CREATE TABLE IF NOT EXISTS \`${this.#tableName}\` (
196
- \`key\` VARCHAR(768) NOT NULL,
197
- \`value\` JSON NOT NULL,
198
- \`expires\` DATETIME(6) NULL DEFAULT NULL,
199
- PRIMARY KEY (\`key\`)
200
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin`);
201
- try {
302
+ if (this.#initialization == null) {
303
+ const pending = this.#initialize();
304
+ this.#initialization = pending;
305
+ pending.catch(() => {
306
+ if (this.#initialization === pending) this.#initialization = void 0;
307
+ });
308
+ }
309
+ await this.#initialization;
310
+ }
311
+ async #initialize() {
312
+ if (!this.#initialized) await this.#pool.query(`CREATE TABLE IF NOT EXISTS \`${this.#tableName}\` (
313
+ \`key\` VARCHAR(768) NOT NULL,
314
+ \`value\` JSON NOT NULL,
315
+ \`expires\` DATETIME(6) NULL DEFAULT NULL,
316
+ PRIMARY KEY (\`key\`)
317
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin`);
318
+ const predicate = `TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?
319
+ AND (@@lower_case_table_names <> 0 OR
320
+ (CAST(TABLE_SCHEMA AS BINARY) = CAST(DATABASE() AS BINARY)
321
+ AND CAST(TABLE_NAME AS BINARY) = CAST(? AS BINARY)))`;
322
+ const params = [this.#tableName, this.#tableName];
323
+ const [tables] = await this.#pool.query(`SELECT ENGINE AS \`engine\`, TABLE_TYPE AS \`table_type\`
324
+ FROM information_schema.TABLES WHERE ${predicate}`, params);
325
+ 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.");
326
+ const [columns] = await this.#pool.query(`SELECT COLUMN_NAME AS \`name\`, DATA_TYPE AS \`type\`, IS_NULLABLE AS \`nullable\`,
327
+ CHARACTER_MAXIMUM_LENGTH AS \`length\`, CHARACTER_SET_NAME AS \`charset\`,
328
+ COLLATION_NAME AS \`collation\`, DATETIME_PRECISION AS \`precision\`
329
+ FROM information_schema.COLUMNS WHERE ${predicate}`, params);
330
+ const key = columns.find((c) => c.name === "key");
331
+ const value = columns.find((c) => c.name === "value");
332
+ const expires = columns.find((c) => c.name === "expires");
333
+ 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.");
334
+ const [indexes] = await this.#pool.query(`SELECT INDEX_NAME AS \`name\`, COLUMN_NAME AS \`column_name\`,
335
+ SEQ_IN_INDEX AS \`position\`, SUB_PART AS \`prefix\`, INDEX_TYPE AS \`type\`
336
+ FROM information_schema.STATISTICS WHERE ${predicate} AND NON_UNIQUE = 0`, params);
337
+ 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.");
338
+ const [unsafe] = await this.#pool.query("SHOW VARIABLES WHERE Variable_name = 'innodb_locks_unsafe_for_binlog'");
339
+ if (unsafe.some((row) => !["off", "0"].includes(String(row.Value).toLowerCase()))) throw new TypeError("MysqlKvStore requires InnoDB gap locking to be enabled.");
340
+ if (!this.#initialized) try {
202
341
  await this.#pool.query(`CREATE INDEX \`idx_${this.#tableName}_expires\`
203
- ON \`${this.#tableName}\` (\`expires\`)`);
204
- } catch (e) {
205
- if (e.code !== "ER_DUP_KEYNAME") throw e;
342
+ ON \`${this.#tableName}\` (\`expires\`)`);
343
+ } catch (error) {
344
+ if (error.code !== "ER_DUP_KEYNAME") throw error;
206
345
  }
207
- this.#initialized = true;
208
- logger.debug("Initialized the key-value store table {tableName}.", { tableName: this.#tableName });
209
346
  }
210
347
  /**
211
348
  * Drops the table used by the key-value store. Does nothing if the table
@@ -215,15 +352,46 @@ var MysqlKvStore = class {
215
352
  * @since 2.1.0
216
353
  */
217
354
  async drop() {
218
- await this.#pool.query(`DROP TABLE IF EXISTS \`${this.#tableName}\``);
219
- this.#initialized = false;
355
+ try {
356
+ await this.#pool.query(`DROP TABLE IF EXISTS \`${this.#tableName}\``);
357
+ } finally {
358
+ this.#initialization = void 0;
359
+ this.#initialized = false;
360
+ }
220
361
  }
221
362
  };
222
- function durationToSeconds(duration) {
223
- return duration.total({
224
- unit: "second",
363
+ function validateBatch(entries) {
364
+ if (!Array.isArray(entries)) throw new TypeError("An atomic batch must be an array.");
365
+ if (entries.length > 1e3) throw new RangeError("An atomic batch has at most 1,000 entries.");
366
+ for (let i = 0; i < entries.length; i++) if (!Object.hasOwn(entries, i)) throw new TypeError("Atomic batches must not be sparse.");
367
+ }
368
+ function serializeKey(key) {
369
+ if (!Array.isArray(key) || key.length === 0) throw new TypeError("A key must be a nonempty array of strings.");
370
+ 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.");
371
+ const encoded = JSON.stringify([...key]);
372
+ if ([...encoded].length > 768) throw new RangeError("A serialized key has at most 768 Unicode code points.");
373
+ return encoded;
374
+ }
375
+ function serializeValue(value) {
376
+ const encoded = JSON.stringify(value);
377
+ if (encoded === void 0) throw new TypeError("The value must have a JSON representation; undefined cannot be stored.");
378
+ return encoded;
379
+ }
380
+ function encodeTtl(options) {
381
+ if (options?.ttl == null) return null;
382
+ const micros = Math.trunc(options.ttl.total({
383
+ unit: "microsecond",
225
384
  relativeTo: Temporal.Now.plainDateTimeISO()
226
- });
385
+ }));
386
+ if (!Number.isSafeInteger(micros)) throw new RangeError("TTL must fit in safe integer microseconds.");
387
+ return micros;
388
+ }
389
+ function validateDistinct(entries) {
390
+ if (new Set(entries.map((entry) => entry.key)).size !== entries.length) throw new TypeError("Duplicate keys in an atomic mutation.");
391
+ }
392
+ function retryable(error) {
393
+ const e = error;
394
+ return e?.errno === 1213 || e?.errno === 1020 || e?.code === "ER_LOCK_DEADLOCK" || e?.code === "ER_CHECKREAD";
227
395
  }
228
396
  //#endregion
229
397
  export { MysqlKvStore };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/mysql",
3
- "version": "2.5.0-dev.2811+71b5c016",
3
+ "version": "2.5.0-dev.2822+facaae33",
4
4
  "description": "MySQL/MariaDB drivers for Fedify",
5
5
  "keywords": [
6
6
  "fedify",
@@ -85,14 +85,14 @@
85
85
  },
86
86
  "peerDependencies": {
87
87
  "mysql2": "^3.22.3",
88
- "@fedify/fedify": "^2.5.0-dev.2811+71b5c016"
88
+ "@fedify/fedify": "^2.5.0-dev.2822+facaae33"
89
89
  },
90
90
  "devDependencies": {
91
91
  "@js-temporal/polyfill": "^0.5.1",
92
92
  "tsdown": "^0.22.0",
93
93
  "typescript": "^6.0.3",
94
94
  "@fedify/fixture": "^2.0.0",
95
- "@fedify/testing": "^2.5.0-dev.2811+71b5c016"
95
+ "@fedify/testing": "^2.5.0-dev.2822+facaae33"
96
96
  },
97
97
  "scripts": {
98
98
  "build:self": "tsdown",