|
| 1 | +import { createCancelablePromise, MaybeCancelablePromise } from '@cubejs-backend/shared'; |
| 2 | +import { CacheDriverInterface } from '@cubejs-backend/base-driver'; |
| 3 | + |
| 4 | +import { CubeStoreDriver } from './CubeStoreDriver'; |
| 5 | + |
| 6 | +export class CubeStoreCacheDriver implements CacheDriverInterface { |
| 7 | + public constructor( |
| 8 | + protected readonly connection: CubeStoreDriver |
| 9 | + ) {} |
| 10 | + |
| 11 | + public withLock = ( |
| 12 | + key: string, |
| 13 | + cb: () => MaybeCancelablePromise<any>, |
| 14 | + expiration: number = 60, |
| 15 | + freeAfter: boolean = true, |
| 16 | + ) => createCancelablePromise(async (tkn) => { |
| 17 | + if (tkn.isCanceled()) { |
| 18 | + return false; |
| 19 | + } |
| 20 | + |
| 21 | + const rows = await this.connection.query('CACHE SET NX TTL ? ? ?', [expiration, key, '1']); |
| 22 | + if (rows && rows.length === 1 && rows[0]?.success === 'true') { |
| 23 | + if (tkn.isCanceled()) { |
| 24 | + if (freeAfter) { |
| 25 | + await this.connection.query('CACHE REMOVE ?', [ |
| 26 | + key |
| 27 | + ]); |
| 28 | + } |
| 29 | + |
| 30 | + return false; |
| 31 | + } |
| 32 | + |
| 33 | + try { |
| 34 | + await tkn.with(cb()); |
| 35 | + } finally { |
| 36 | + if (freeAfter) { |
| 37 | + await this.connection.query('CACHE REMOVE ?', [ |
| 38 | + key |
| 39 | + ]); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return true; |
| 44 | + } |
| 45 | + |
| 46 | + return false; |
| 47 | + }); |
| 48 | + |
| 49 | + public async get(key: string) { |
| 50 | + const rows = await this.connection.query('CACHE GET ?', [ |
| 51 | + key |
| 52 | + ]); |
| 53 | + if (rows && rows.length === 1) { |
| 54 | + return JSON.parse(rows[0].value); |
| 55 | + } |
| 56 | + |
| 57 | + return null; |
| 58 | + } |
| 59 | + |
| 60 | + public async set(key: string, value, expiration) { |
| 61 | + const strValue = JSON.stringify(value); |
| 62 | + await this.connection.query('CACHE SET TTL ? ? ?', [expiration, key, strValue]); |
| 63 | + |
| 64 | + return { |
| 65 | + key, |
| 66 | + bytes: Buffer.byteLength(strValue), |
| 67 | + }; |
| 68 | + } |
| 69 | + |
| 70 | + public async remove(key: string) { |
| 71 | + await this.connection.query('CACHE REMOVE ?', [ |
| 72 | + key |
| 73 | + ]); |
| 74 | + } |
| 75 | + |
| 76 | + public async keysStartingWith(prefix: string) { |
| 77 | + const rows = await this.connection.query('CACHE KEYS ?', [ |
| 78 | + prefix |
| 79 | + ]); |
| 80 | + return rows.map((row) => row.key); |
| 81 | + } |
| 82 | + |
| 83 | + public async cleanup(): Promise<void> { |
| 84 | + // |
| 85 | + } |
| 86 | + |
| 87 | + public async testConnection(): Promise<void> { |
| 88 | + return this.connection.testConnection(); |
| 89 | + } |
| 90 | +} |
0 commit comments