UNPKG

@daiso-tech/core

Version:

The library offers flexible, framework-agnostic solutions for modern web applications, built on adaptable components that integrate seamlessly with popular frameworks like Next Js.

286 lines 9.45 kB
/** * @module Lock */ import { MysqlAdapter, Transaction } from "kysely"; import {} from "../../../../execution-context/contracts/_module.js"; import {} from "../../../../lock/contracts/_module.js"; import {} from "../../../../time-span/contracts/_module.js"; import { TimeSpan } from "../../../../time-span/implementations/_module.js"; import {} from "../../../../utilities/_module.js"; async function find(kysely, key) { const row = await kysely .selectFrom("lock") .where("lock.key", "=", key) .select(["lock.owner", "lock.expiration"]) .executeTakeFirst(); if (row === undefined) { return null; } if (row.expiration === null) { return { owner: row.owner, expiration: null, }; } return { owner: row.owner, expiration: new Date(Number(row.expiration)), }; } /** * @internal */ class DatabaseLockTransaction { kysely; isMysql; constructor(kysely) { this.kysely = kysely; this.isMysql = this.kysely.getExecutor().adapter instanceof MysqlAdapter; } async find(_context, key) { return await find(this.kysely, key); } async upsert(_context, key, lockId, expiration) { const expirationAsMs = expiration?.getTime() ?? null; await this.kysely .insertInto("lock") .values({ key, owner: lockId, expiration: expirationAsMs, }) .$if(!this.isMysql, (eb) => eb.onConflict((eb_) => eb_.column("key").doUpdateSet({ key, owner: lockId, expiration: expirationAsMs, }))) .$if(this.isMysql, (eb) => eb.onDuplicateKeyUpdate({ key, owner: lockId, expiration: expirationAsMs, })) .execute(); } } /** * To utilize the `KyselyLockAdapter`, you must install the [`"kysely"`](https://www.npmjs.com/package/kysely) package and configure a `Kysely` class instance. * * Note in order to use `KyselyLockAdapter` correctly, ensure you use a single, consistent database across all server instances and use a database that has support for transactions. * The adapter have been tested with `sqlite`, `postgres` and `mysql` databases. * * IMPORT_PATH: `"@daiso-tech/core/lock/kysely-lock-adapter"` * @group Adapters */ export class KyselyLockAdapter { kysely; expiredKeysRemovalInterval; shouldRemoveExpiredKeys; intervalId = null; isMysql; enableTransactions; /** * @example * ```ts * import { KyselyLockAdapter } from "@daiso-tech/core/lock/kysely-lock-adapter"; * import Sqlite from "better-sqlite3"; * import { Kysely, SqliteDialect } from "kysely"; * * const lockAdapter = new KyselyLockAdapter({ * kysely: new Kysely({ * dialect: new SqliteDialect({ * database: new Sqlite("local.db"), * }), * }), * }); * // You need initialize the adapter once before using it. * await lockAdapter.init(); * ``` */ constructor(settings) { const { kysely, expiredKeysRemovalInterval = TimeSpan.fromMinutes(1), shouldRemoveExpiredKeys = true, enableTransactions = !(settings.kysely instanceof Transaction), } = settings; this.expiredKeysRemovalInterval = TimeSpan.fromTimeSpan(expiredKeysRemovalInterval); this.shouldRemoveExpiredKeys = shouldRemoveExpiredKeys; this.kysely = kysely; this.isMysql = this.kysely.getExecutor().adapter instanceof MysqlAdapter; this.enableTransactions = enableTransactions; } _transaction(trxFn) { if (this.enableTransactions) { return this.kysely .transaction() .setIsolationLevel("serializable") .execute(async (trx) => { return await trxFn(trx); }); } return trxFn(this.kysely); } /** * Removes all related lock tables and their rows. * Note all lock data will be removed. */ async deInit() { if (this.shouldRemoveExpiredKeys && this.intervalId !== null) { clearInterval(this.intervalId); } // Should throw if the index does not exists thats why the try catch is used. try { await this.kysely.schema .dropIndex("lock_expiration") .on("lock") .execute(); } catch { /* EMPTY */ } // Should throw if the table does not exists thats why the try catch is used. try { await this.kysely.schema.dropTable("lock").execute(); } catch { /* EMPTY */ } } /** * Creates all related tables and indexes. * Note the `init` method needs to be called once before using the adapter. */ async init() { // Should throw if the table already exists thats why the try catch is used. try { await this.kysely.schema .createTable("lock") .addColumn("key", "varchar(255)", (col) => col.primaryKey().notNull()) .addColumn("owner", "varchar(255)", (col) => col.notNull()) .addColumn("expiration", "bigint") .execute(); } catch { /* EMPTY */ } // Should throw if the index already exists thats why the try catch is used. try { await this.kysely.schema .createIndex("lock_expiration") .on("lock") .column("expiration") .execute(); } catch { /* EMPTY */ } if (this.shouldRemoveExpiredKeys) { this.intervalId = setInterval(() => { void this.removeAllExpired(); }, this.expiredKeysRemovalInterval.toMilliseconds()); } } async removeAllExpired() { await this.kysely .deleteFrom("lock") .where("lock.expiration", "<=", Date.now()) .execute(); } async transaction(_context, fn) { return await this._transaction(async (trx) => { return await fn(new DatabaseLockTransaction(trx)); }); } async remove(_context, key) { let result; if (this.isMysql) { result = await this._transaction(async (trx) => { const row = await trx .selectFrom("lock") .where("lock.key", "=", key) .select("lock.expiration") .executeTakeFirst(); await trx .deleteFrom("lock") .where("lock.key", "=", key) .executeTakeFirst(); return row; }); } else { result = await this.kysely .deleteFrom("lock") .where("lock.key", "=", key) .returning(["lock.expiration"]) .executeTakeFirst(); } if (result === undefined) { return null; } if (result.expiration === null) { return { expiration: null, }; } return { expiration: new Date(Number(result.expiration)), }; } async removeIfOwner(_context, key, lockId) { let row; if (this.isMysql) { row = await this._transaction(async (trx) => { const row_ = await trx .selectFrom("lock") .where("lock.key", "=", key) .where("lock.owner", "=", lockId) .select(["lock.expiration", "lock.owner"]) .executeTakeFirst(); await trx .deleteFrom("lock") .where("lock.key", "=", key) .where("lock.owner", "=", lockId) .execute(); return row_; }); } else { row = await this.kysely .deleteFrom("lock") .where("lock.key", "=", key) .where("lock.owner", "=", lockId) .returning(["lock.expiration", "lock.owner"]) .executeTakeFirst(); } if (row === undefined) { return null; } const { expiration } = row; if (expiration === null) { return { owner: row.owner, expiration: null, }; } return { owner: row.owner, expiration: new Date(Number(expiration)), }; } async updateExpiration(_context, key, lockId, expiration) { const result = await this.kysely .updateTable("lock") .where("lock.key", "=", key) .where("lock.owner", "=", lockId) .where((eb) => eb.and([ eb("lock.expiration", "is not", null), eb("lock.expiration", ">", Date.now()), ])) .set({ expiration: expiration.getTime(), }) .executeTakeFirst(); return Number(result.numUpdatedRows); } async find(_context, key) { return await find(this.kysely, key); } } //# sourceMappingURL=kysely-lock-adapter.js.map