@stacksjs/cache 0.75.378 → 0.75.382
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/drivers/index.d.ts +31 -6
- package/dist/index.js +1 -1
- package/package.json +3 -3
package/dist/drivers/index.d.ts
CHANGED
|
@@ -35,14 +35,30 @@ export declare function createCache(driver: 'memory', options?: MemoryOptions):
|
|
|
35
35
|
export declare function createCache(driver: 'redis', options?: RedisOptions): CacheDriver;
|
|
36
36
|
export declare function createCache(driver: 'singlestore', options?: SingleStoreCacheOptions): CacheDriver;
|
|
37
37
|
export declare function createCache(driver: 'sqlite', options?: SqliteCacheOptions): CacheDriver;
|
|
38
|
+
/**
|
|
39
|
+
* The other Redis namespaces the framework writes - the queue, failed jobs,
|
|
40
|
+
* batches and realtime - that lie inside the cache's prefix.
|
|
41
|
+
*
|
|
42
|
+
* The Redis cache lists its keys as `<prefix>:*`, so `flush()` deletes, and
|
|
43
|
+
* `keys()` and `getStats()` report, everything below any of these when they
|
|
44
|
+
* share a server. The shipped `stacks` prefix held all four: clearing the
|
|
45
|
+
* cache emptied the job queue (stacksjs/stacks#3075). No prefix at all means
|
|
46
|
+
* the whole database.
|
|
47
|
+
*/
|
|
48
|
+
export declare function redisNamespacesInside(cachePrefix: string | undefined, settings?: RedisNamespaceSettings): string[];
|
|
38
49
|
/**
|
|
39
50
|
* The driver `config/cache.ts` selects, built from its options. Memory is
|
|
40
51
|
* the `memory` instance itself, so an app on the default changes nothing;
|
|
41
52
|
* the others get the configured `prefix` and `ttl` as their key prefix and
|
|
42
|
-
* default TTL.
|
|
53
|
+
* default TTL. `namespaces` is where the other Redis prefixes are read from,
|
|
54
|
+
* the app's config unless given.
|
|
55
|
+
*/
|
|
56
|
+
export declare function cacheFromConfig(settings?: CacheSettings | undefined, namespaces?: RedisNamespaceSettings): CacheDriver;
|
|
57
|
+
/**
|
|
58
|
+
* Forget the resolved driver (tests, or after changing the cache config), and
|
|
59
|
+
* whether the namespace warning was given, so a changed config is warned about
|
|
60
|
+
* again.
|
|
43
61
|
*/
|
|
44
|
-
export declare function cacheFromConfig(settings?: CacheSettings | undefined): CacheDriver;
|
|
45
|
-
/** Forget the resolved driver (tests, or after changing the cache config). */
|
|
46
62
|
export declare function resetConfiguredCache(): void;
|
|
47
63
|
/**
|
|
48
64
|
* Default memory cache instance
|
|
@@ -84,6 +100,11 @@ export declare interface CacheSettings {
|
|
|
84
100
|
sqlite?: SqliteCacheOptions
|
|
85
101
|
}
|
|
86
102
|
}
|
|
103
|
+
/** The parts of the app's config that name the other Redis namespaces. */
|
|
104
|
+
declare interface RedisNamespaceSettings {
|
|
105
|
+
queue?: { connections?: { redis?: { prefix?: string } }, failed?: { prefix?: string }, batching?: { prefix?: string } }
|
|
106
|
+
realtime?: { server?: { redis?: { prefix?: string } } }
|
|
107
|
+
}
|
|
87
108
|
/**
|
|
88
109
|
* Stacks Cache Wrapper
|
|
89
110
|
*
|
|
@@ -134,9 +155,13 @@ export declare class StacksCache implements CacheDriver {
|
|
|
134
155
|
* the named tag(s) so `flush()` can invalidate cascade-style without the
|
|
135
156
|
* caller having to track keys themselves.
|
|
136
157
|
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
158
|
+
* Each tagged key gets an index entry of its own, under the tag's scope
|
|
159
|
+
* (`__stacks_tag__:<digest>:<key>`), and `flush()` lists the scope. The index
|
|
160
|
+
* used to be one `string[]` per tag, updated by read, add, write: two
|
|
161
|
+
* processes writing to one tag both read it, and the second write dropped the
|
|
162
|
+
* first one's key, so a flush left it cached (stacksjs/stacks#3073). An entry
|
|
163
|
+
* per key has nothing to read first, so there is nothing for another process
|
|
164
|
+
* to lose, and it expires with its key instead of growing for ever.
|
|
140
165
|
*
|
|
141
166
|
* `flush()` uses a per-tag in-process mutex so concurrent flushes don't
|
|
142
167
|
* race-and-lose keys: without it, two parallel flushes could both read
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{config as N,overridesReady as I}from"@stacksjs/config";import{createCache as v}from"@stacksjs/ts-cache";import{EventEmitter as L}from"events";var{SQL:O}=globalThis.Bun;function o(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function P(e){return o(e).replace(/\*/g,"%")}function _(e){return`\`${e.replace(/`/g,"``")}\``}class p extends L{sql;table;qualified;prefix;stdTTL;ready=null;hits=0;misses=0;constructor(e={}){super();let{host:t="127.0.0.1",port:r=3306,username:i="root",password:s="",database:h="stacks",table:l="stacks_cache",ssl:m=!1}=e;this.table=l,this.qualified=_(l),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0;let d=s?`${i}:${encodeURIComponent(s)}`:i,y=m?"?ssl=true":"";this.sql=new O(`mysql://${d}@${t}:${r}/${h}${y}`)}async ensureReady(){if(!this.ready)this.ready=this.sql.unsafe(`CREATE ROWSTORE TABLE IF NOT EXISTS ${this.qualified} ( cache_key VARCHAR(255) NOT NULL, value LONGTEXT NOT NULL, expires_at BIGINT NULL, PRIMARY KEY (cache_key) )`).then(()=>{return});await this.ready}k(e){return this.prefix?`${this.prefix}:${e}`:e}nowMs(){return Date.now()}expiryFor(e){let t=e??this.stdTTL;if(!t||t<=0)return null;return this.nowMs()+t*1000}async get(e){await this.ensureReady();let r=(await this.sql.unsafe(`SELECT value, expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!r){this.misses++;return}if(r.expires_at!=null&&r.expires_at<=this.nowMs()){await this.del(e),this.misses++;return}return this.hits++,JSON.parse(r.value)}async mget(e){let t={};for(let r of e){let i=await this.get(r);if(i!==void 0)t[r]=i}return t}async set(e,t,r){await this.ensureReady();let i=this.expiryFor(r);return await this.sql.unsafe(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value), expires_at = VALUES(expires_at)`,[this.k(e),JSON.stringify(t),i]),!0}async mset(e){for(let t of e)await this.set(t.key,t.value,t.ttl);return!0}async fetch(e,t,r){let i=await this.get(e);if(i!==void 0)return i;let s=await t();return await this.set(e,s,r),s}async del(e){await this.ensureReady();let t=Array.isArray(e)?e:[e];if(t.length===0)return 0;let r=t.map(()=>"?").join(", "),s=(await this.sql.unsafe(`DELETE FROM ${this.qualified} WHERE cache_key IN (${r})`,t.map((h)=>this.k(h)))).affectedRows;return typeof s==="number"?s:t.length}async has(e){return await this.get(e)!==void 0}async flush(){if(await this.ensureReady(),this.prefix)await this.sql.unsafe(`DELETE FROM ${this.qualified} WHERE cache_key LIKE ?`,[`${o(this.prefix)}:%`]);else await this.sql.unsafe(`TRUNCATE TABLE ${this.qualified}`)}async keys(e){await this.ensureReady();let t=`${this.prefix?`${o(this.prefix)}:`:""}${e?e.replace(/\*/g,"%"):"%"}`,r=await this.sql.unsafe(`SELECT cache_key FROM ${this.qualified} WHERE cache_key LIKE ? AND (expires_at IS NULL OR expires_at > ?)`,[t,this.nowMs()]),i=this.prefix?this.prefix.length+1:0;return r.map((s)=>i?s.cache_key.slice(i):s.cache_key)}async getTtl(e){await this.ensureReady();let r=(await this.sql.unsafe(`SELECT expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!r)return;return r.expires_at==null?0:r.expires_at}async ttl(e,t){await this.ensureReady();let r=this.expiryFor(t);if(((await this.sql.unsafe(`UPDATE ${this.qualified} SET expires_at = ? WHERE cache_key = ?`,[r,this.k(e)])).affectedRows??0)>0)return!0;let s=await this.sql.unsafe(`SELECT 1 FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]);return Array.isArray(s)&&s.length>0}async take(e){let t=await this.get(e);if(t!==void 0)await this.del(e);return t}async getStats(){await this.ensureReady();let e=await this.sql.unsafe(`SELECT COUNT(*) AS n FROM ${this.qualified} WHERE expires_at IS NULL OR expires_at > ?`,[this.nowMs()]);return{hits:this.hits,misses:this.misses,keys:Number(e[0]?.n??0),ksize:0,vsize:0}}async close(){await this.sql.end()}}import{Database as q}from"bun:sqlite";import{EventEmitter as A}from"events";import{mkdirSync as M}from"fs";import{dirname as F}from"path";function D(e){return`"${e.replace(/"/g,'""')}"`}class T extends A{db;qualified;prefix;stdTTL;hits=0;misses=0;constructor(e={}){super();let t=e.path??"storage/framework/cache/cache.sqlite";if(t!==":memory:"&&!t.startsWith("file:"))M(F(t),{recursive:!0});if(this.db=new q(t,{create:!0}),this.db.run("PRAGMA busy_timeout = 5000"),t!==":memory:")this.db.run("PRAGMA journal_mode = WAL");this.qualified=D(e.table??"stacks_cache"),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0,this.db.run(`CREATE TABLE IF NOT EXISTS ${this.qualified} (cache_key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER NULL)`)}k(e){return this.prefix?`${this.prefix}:${e}`:e}expiryFor(e){let t=e??this.stdTTL;if(!t||t<=0)return null;return Date.now()+t*1000}async get(e){let t=this.db.query(`SELECT value, expires_at FROM ${this.qualified} WHERE cache_key = ?`).get(this.k(e));if(!t){this.misses++;return}if(t.expires_at!=null&&t.expires_at<=Date.now()){this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key = ?`).run(this.k(e)),this.misses++;return}return this.hits++,JSON.parse(t.value)}async mget(e){let t={};for(let r of e){let i=await this.get(r);if(i!==void 0)t[r]=i}return t}async set(e,t,r){return this.db.query(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON CONFLICT(cache_key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`).run(this.k(e),JSON.stringify(t),this.expiryFor(r)),!0}async mset(e){return this.db.transaction(()=>{for(let t of e)this.db.query(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON CONFLICT(cache_key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`).run(this.k(t.key),JSON.stringify(t.value),this.expiryFor(t.ttl))})(),!0}async fetch(e,t,r){let i=await this.get(e);if(i!==void 0)return i;let s=await t();return await this.set(e,s,r),s}async del(e){let t=Array.isArray(e)?e:[e];if(t.length===0)return 0;let r=t.map(()=>"?").join(", ");return this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key IN (${r})`).run(...t.map((i)=>this.k(i))).changes}async has(e){return await this.get(e)!==void 0}async flush(){if(this.prefix)this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key LIKE ? ESCAPE '\\'`).run(`${o(this.prefix)}:%`);else this.db.run(`DELETE FROM ${this.qualified}`)}async keys(e){let t=`${this.prefix?`${o(this.prefix)}:`:""}${e?P(e):"%"}`,r=this.db.query(`SELECT cache_key FROM ${this.qualified} WHERE cache_key LIKE ? ESCAPE '\\' AND (expires_at IS NULL OR expires_at > ?)`).all(t,Date.now()),i=this.prefix?this.prefix.length+1:0;return r.map((s)=>i?s.cache_key.slice(i):s.cache_key)}async getTtl(e){let t=this.db.query(`SELECT expires_at FROM ${this.qualified} WHERE cache_key = ?`).get(this.k(e));if(!t)return;return t.expires_at==null?0:t.expires_at}async ttl(e,t){return this.db.query(`UPDATE ${this.qualified} SET expires_at = ? WHERE cache_key = ?`).run(this.expiryFor(t),this.k(e)).changes>0}async take(e){let t=await this.get(e);if(t!==void 0)await this.del(e);return t}async getStats(){let e=this.db.query(`SELECT COUNT(*) AS n FROM ${this.qualified} WHERE expires_at IS NULL OR expires_at > ?`).get(Date.now());return{hits:this.hits,misses:this.misses,keys:Number(e?.n??0),ksize:0,vsize:0}}async close(){this.db.close()}}import{CacheManager as ge,MemoryDriver as fe,RedisDriver as pe}from"@stacksjs/ts-cache";import{CacheAsidePattern as ye,MultiLevelPattern as be,RefreshAheadPattern as ve,WriteThroughPattern as we,BatchOperations as Pe,CacheInvalidation as xe,CacheLock as Ee,CircuitBreaker as Se,memoize as Ce,RateLimiter as ke}from"@stacksjs/ts-cache";class c{manager;inflight=new Map;inflightTimeoutMs;constructor(e,t={}){this.manager=e,this.inflightTimeoutMs=t.inflightTimeoutMs??30000}async get(e){return await this.manager.get(e)}async mget(e){return await this.manager.mget(e)}async set(e,t,r){return await this.manager.set(e,t,r)}async mset(e){return await this.manager.mset(e)}async setForever(e,t){return await this.manager.set(e,t,0)}async getOrSet(e,t,r){let i=await this.manager.get(e);if(i!==void 0)return i;let s=this.inflight.get(e);if(s)return await s;let l=(async()=>{let f=await t();return await this.manager.set(e,f,r),this.manager.emit("fetch",e,f,r),f})(),m=this.inflightTimeoutMs,d,y=new Promise((f,R)=>{d=setTimeout(()=>{R(Error(`[cache] getOrSet('${e}') timed out after ${m}ms`))},m)}),g=Promise.race([l,y]),w=()=>{if(clearTimeout(d),this.inflight.get(e)===g)this.inflight.delete(e)};return g.then(w,w),this.inflight.set(e,g),await g}async remember(e,t,r){return await this.getOrSet(e,r,t)}async rememberForever(e,t){return this.getOrSet(e,t,0)}async del(e){return await this.manager.del(e)}async has(e){return await this.manager.has(e)}async missing(e){return!await this.manager.has(e)}async remove(e){await this.manager.del(e)}async deleteMany(e){return await this.manager.del(e)}async clear(){await this.manager.flush()}async flush(){await this.manager.flush()}async keys(e){return await this.manager.keys(e)}async getTtl(e){return await this.manager.getTtl(e)}async ttl(e,t){return await this.manager.ttl(e,t)}async take(e){return await this.manager.take(e)}async getStats(){let e=await this.manager.getStats(),t=e.hits+e.misses;return{hits:e.hits,misses:e.misses,keys:e.keys,size:e.ksize+e.vsize,hitRate:t>0?e.hits/t:0}}async close(){await this.manager.close()}async disconnect(){await this.manager.close()}get cacheManager(){return this.manager}tags(e){return new a(this,e)}}class a{cache;tags;static TAG_PREFIX="__stacks_tag__:";static flushLocks=new Map;constructor(e,t){this.cache=e;this.tags=t;if(!t||t.length===0)throw Error("cache.tags(...) requires at least one tag")}tagKey(e){return`${a.TAG_PREFIX}${e}`}serialize(e){let t=this.tags.map((s)=>this.tagKey(s)),r=t.map((s)=>a.flushLocks.get(s)).filter((s)=>s!==void 0),i=Promise.all(r.map((s)=>s.catch(()=>0))).then(e);for(let s of t)a.flushLocks.set(s,i);return i.finally(()=>{for(let s of t)if(a.flushLocks.get(s)===i)a.flushLocks.delete(s)})}async indexKey(e){for(let t of this.tags){let r=this.tagKey(t),i=await this.cache.get(r)??[],s=new Set(i);if(!s.has(e))s.add(e),await this.cache.setForever(r,[...s])}}async put(e,t,r){return this.serialize(async()=>{let i=await this.cache.set(e,t,r);if(i)await this.indexKey(e);return i})}async set(e,t,r){return this.put(e,t,r)}async setForever(e,t){return this.serialize(async()=>{let r=await this.cache.setForever(e,t);if(r)await this.indexKey(e);return r})}async remember(e,t,r){let i=await this.cache.remember(e,t,r);return await this.serialize(()=>this.indexKey(e)),i}async rememberForever(e,t){let r=await this.cache.rememberForever(e,t);return await this.serialize(()=>this.indexKey(e)),r}async get(e){return this.cache.get(e)}async has(e){return this.cache.has(e)}async flush(){let e=0;for(let t of this.tags){let r=this.tagKey(t),i=a.flushLocks.get(r),s=i?i.catch(()=>0).then(()=>this.doFlushOne(r)):this.doFlushOne(r);a.flushLocks.set(r,s);try{e+=await s}finally{if(a.flushLocks.get(r)===s)a.flushLocks.delete(r)}}return e}async doFlushOne(e){let t=await this.cache.get(e)??[],r=0;if(t.length>0)r=await this.cache.del(t);return await this.cache.del(e),r}}function K(e={}){let t=v({driver:"memory",stdTTL:e.stdTTL??0,checkPeriod:e.checkPeriod??600,maxKeys:e.maxKeys??-1,useClones:e.useClones??!0,prefix:e.prefix});return new c(t)}function x(e={}){let t=v({driver:"redis",url:e.url,host:e.host??"localhost",port:e.port??6379,password:e.password,database:e.database??0,tls:e.tls??!1,stdTTL:e.stdTTL??0,prefix:e.prefix});return new c(t)}function E(e={}){let t=new p(e);return new c(t)}function S(e={}){return new c(new T(e))}function oe(e,t){if(e==="redis")return x(t);if(e==="singlestore")return E(t);if(e==="sqlite")return S(t);return K(t)}var U=v({driver:"memory",stdTTL:0,checkPeriod:600,maxKeys:-1,useClones:!0}),C=new c(U);function W(e=N.cache){let t={prefix:e?.prefix,stdTTL:e?.ttl};switch(e?.driver){case"redis":return x({...e.drivers?.redis,...t});case"singlestore":return E({...e.drivers?.singlestore,...t});case"sqlite":return S({...e.drivers?.sqlite,...t});default:return C}}var u=null,b=!1;Promise.resolve(I).then(()=>{b=!0},()=>{b=!0});function ce(){u=null}function n(){if(u)return u;if(!b)return C;return u=W(),u}class k{get(e){return n().get(e)}mget(e){return n().mget(e)}set(e,t,r){return n().set(e,t,r)}mset(e){return n().mset(e)}setForever(e,t){return n().setForever(e,t)}getOrSet(e,t,r){return n().getOrSet(e,t,r)}del(e){return n().del(e)}has(e){return n().has(e)}missing(e){return n().missing(e)}remove(e){return n().remove(e)}deleteMany(e){return n().deleteMany(e)}clear(){return n().clear()}flush(){return n().flush()}keys(e){return n().keys(e)}getTtl(e){return n().getTtl(e)}ttl(e,t){return n().ttl(e,t)}take(e){return n().take(e)}remember(e,t,r){return n().remember(e,t,r)}rememberForever(e,t){return n().rememberForever(e,t)}getStats(){return n().getStats()}close(){return n().close()}disconnect(){return n().disconnect()}tags(e){return n().tags(e)}}var ue=new k;function Re(e,t){let r=Object.keys(t).sort().map((i)=>{let s=t[i];if(typeof s==="number"&&!Number.isFinite(s))throw RangeError("Cache key numbers must be finite");if(s!==void 0&&s!==null&&!["string","number","boolean"].includes(typeof s))throw TypeError("Invalid cache key value");return[i,s===void 0?["undefined"]:s]});return JSON.stringify([e,r])}export{Pe as BatchOperations,ye as CacheAsidePattern,xe as CacheInvalidation,Ee as CacheLock,ge as CacheManager,Se as CircuitBreaker,fe as MemoryDriver,be as MultiLevelPattern,ke as RateLimiter,pe as RedisDriver,ve as RefreshAheadPattern,p as SingleStoreCacheStore,T as SqliteCacheStore,c as StacksCache,a as TaggedCache,we as WriteThroughPattern,ue as cache,W as cacheFromConfig,Re as cacheKey,oe as createCache,K as createMemoryCache,x as createRedisCache,E as createSingleStoreCache,S as createSqliteCache,Ce as memoize,C as memory,ce as resetConfiguredCache};
|
|
2
|
+
import{config as b,overridesReady as U}from"@stacksjs/config";import{createCache as x}from"@stacksjs/ts-cache";import{EventEmitter as _}from"events";var{SQL:q}=globalThis.Bun;function c(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function S(e){return c(e).replace(/\*/g,"%")}function A(e){return`\`${e.replace(/`/g,"``")}\``}class p extends _{sql;table;qualified;prefix;stdTTL;ready=null;hits=0;misses=0;constructor(e={}){super();let{host:t="127.0.0.1",port:r=3306,username:s="root",password:i="",database:o="stacks",table:u="stacks_cache",ssl:m=!1}=e;this.table=u,this.qualified=A(u),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0;let d=i?`${s}:${encodeURIComponent(i)}`:s,y=m?"?ssl=true":"";this.sql=new q(`mysql://${d}@${t}:${r}/${o}${y}`)}async ensureReady(){if(!this.ready)this.ready=this.sql.unsafe(`CREATE ROWSTORE TABLE IF NOT EXISTS ${this.qualified} ( cache_key VARCHAR(255) NOT NULL, value LONGTEXT NOT NULL, expires_at BIGINT NULL, PRIMARY KEY (cache_key) )`).then(()=>{return});await this.ready}k(e){return this.prefix?`${this.prefix}:${e}`:e}nowMs(){return Date.now()}expiryFor(e){let t=e??this.stdTTL;if(!t||t<=0)return null;return this.nowMs()+t*1000}async get(e){await this.ensureReady();let r=(await this.sql.unsafe(`SELECT value, expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!r){this.misses++;return}if(r.expires_at!=null&&r.expires_at<=this.nowMs()){await this.del(e),this.misses++;return}return this.hits++,JSON.parse(r.value)}async mget(e){let t={};for(let r of e){let s=await this.get(r);if(s!==void 0)t[r]=s}return t}async set(e,t,r){await this.ensureReady();let s=this.expiryFor(r);return await this.sql.unsafe(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value), expires_at = VALUES(expires_at)`,[this.k(e),JSON.stringify(t),s]),!0}async mset(e){for(let t of e)await this.set(t.key,t.value,t.ttl);return!0}async fetch(e,t,r){let s=await this.get(e);if(s!==void 0)return s;let i=await t();return await this.set(e,i,r),i}async del(e){await this.ensureReady();let t=Array.isArray(e)?e:[e];if(t.length===0)return 0;let r=t.map(()=>"?").join(", "),i=(await this.sql.unsafe(`DELETE FROM ${this.qualified} WHERE cache_key IN (${r})`,t.map((o)=>this.k(o)))).affectedRows;return typeof i==="number"?i:t.length}async has(e){return await this.get(e)!==void 0}async flush(){if(await this.ensureReady(),this.prefix)await this.sql.unsafe(`DELETE FROM ${this.qualified} WHERE cache_key LIKE ?`,[`${c(this.prefix)}:%`]);else await this.sql.unsafe(`TRUNCATE TABLE ${this.qualified}`)}async keys(e){await this.ensureReady();let t=`${this.prefix?`${c(this.prefix)}:`:""}${e?e.replace(/\*/g,"%"):"%"}`,r=await this.sql.unsafe(`SELECT cache_key FROM ${this.qualified} WHERE cache_key LIKE ? AND (expires_at IS NULL OR expires_at > ?)`,[t,this.nowMs()]),s=this.prefix?this.prefix.length+1:0;return r.map((i)=>s?i.cache_key.slice(s):i.cache_key)}async getTtl(e){await this.ensureReady();let r=(await this.sql.unsafe(`SELECT expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!r)return;return r.expires_at==null?0:r.expires_at}async ttl(e,t){await this.ensureReady();let r=this.expiryFor(t);if(((await this.sql.unsafe(`UPDATE ${this.qualified} SET expires_at = ? WHERE cache_key = ?`,[r,this.k(e)])).affectedRows??0)>0)return!0;let i=await this.sql.unsafe(`SELECT 1 FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]);return Array.isArray(i)&&i.length>0}async take(e){let t=await this.get(e);if(t!==void 0)await this.del(e);return t}async getStats(){await this.ensureReady();let e=await this.sql.unsafe(`SELECT COUNT(*) AS n FROM ${this.qualified} WHERE expires_at IS NULL OR expires_at > ?`,[this.nowMs()]);return{hits:this.hits,misses:this.misses,keys:Number(e[0]?.n??0),ksize:0,vsize:0}}async close(){await this.sql.end()}}import{Database as M}from"bun:sqlite";import{EventEmitter as N}from"events";import{mkdirSync as D}from"fs";import{dirname as F}from"path";function I(e){return`"${e.replace(/"/g,'""')}"`}function K(e,t){let r=Date.now()+t;for(;;)try{let{journal_mode:s}=e.query("PRAGMA journal_mode").get();if(s!=="wal")e.run("PRAGMA journal_mode = WAL");return}catch(s){if(s.code!=="SQLITE_BUSY"||Date.now()>=r)throw s;Bun.sleepSync(10)}}class T extends N{db;qualified;prefix;stdTTL;hits=0;misses=0;constructor(e={}){super();let t=e.path??"storage/framework/cache/cache.sqlite";if(t!==":memory:"&&!t.startsWith("file:"))D(F(t),{recursive:!0});if(this.db=new M(t,{create:!0}),this.db.run("PRAGMA busy_timeout = 5000"),t!==":memory:")K(this.db,5000);this.qualified=I(e.table??"stacks_cache"),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0,this.db.run(`CREATE TABLE IF NOT EXISTS ${this.qualified} (cache_key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER NULL)`)}k(e){return this.prefix?`${this.prefix}:${e}`:e}expiryFor(e){let t=e??this.stdTTL;if(!t||t<=0)return null;return Date.now()+t*1000}async get(e){let t=this.db.query(`SELECT value, expires_at FROM ${this.qualified} WHERE cache_key = ?`).get(this.k(e));if(!t){this.misses++;return}if(t.expires_at!=null&&t.expires_at<=Date.now()){this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key = ?`).run(this.k(e)),this.misses++;return}return this.hits++,JSON.parse(t.value)}async mget(e){let t={};for(let r of e){let s=await this.get(r);if(s!==void 0)t[r]=s}return t}async set(e,t,r){return this.db.query(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON CONFLICT(cache_key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`).run(this.k(e),JSON.stringify(t),this.expiryFor(r)),!0}async mset(e){return this.db.transaction(()=>{for(let t of e)this.db.query(`INSERT INTO ${this.qualified} (cache_key, value, expires_at) VALUES (?, ?, ?) ON CONFLICT(cache_key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`).run(this.k(t.key),JSON.stringify(t.value),this.expiryFor(t.ttl))})(),!0}async fetch(e,t,r){let s=await this.get(e);if(s!==void 0)return s;let i=await t();return await this.set(e,i,r),i}async del(e){let t=Array.isArray(e)?e:[e];if(t.length===0)return 0;let r=t.map(()=>"?").join(", ");return this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key IN (${r})`).run(...t.map((s)=>this.k(s))).changes}async has(e){return await this.get(e)!==void 0}async flush(){if(this.prefix)this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key LIKE ? ESCAPE '\\'`).run(`${c(this.prefix)}:%`);else this.db.run(`DELETE FROM ${this.qualified}`)}async keys(e){let t=`${this.prefix?`${c(this.prefix)}:`:""}${e?S(e):"%"}`,r=this.db.query(`SELECT cache_key FROM ${this.qualified} WHERE cache_key LIKE ? ESCAPE '\\' AND (expires_at IS NULL OR expires_at > ?)`).all(t,Date.now()),s=this.prefix?this.prefix.length+1:0;return r.map((i)=>s?i.cache_key.slice(s):i.cache_key)}async getTtl(e){let t=this.db.query(`SELECT expires_at FROM ${this.qualified} WHERE cache_key = ?`).get(this.k(e));if(!t)return;return t.expires_at==null?0:t.expires_at}async ttl(e,t){return this.db.query(`UPDATE ${this.qualified} SET expires_at = ? WHERE cache_key = ?`).run(this.expiryFor(t),this.k(e)).changes>0}async take(e){let t=await this.get(e);if(t!==void 0)await this.del(e);return t}async getStats(){let e=this.db.query(`SELECT COUNT(*) AS n FROM ${this.qualified} WHERE expires_at IS NULL OR expires_at > ?`).get(Date.now());return{hits:this.hits,misses:this.misses,keys:Number(e?.n??0),ksize:0,vsize:0}}async close(){this.db.close()}}import{CacheManager as Te,MemoryDriver as ye,RedisDriver as be}from"@stacksjs/ts-cache";import{CacheAsidePattern as we,MultiLevelPattern as xe,RefreshAheadPattern as Pe,WriteThroughPattern as Se,BatchOperations as Ee,CacheInvalidation as Re,CacheLock as Ce,CircuitBreaker as ke,memoize as Le,RateLimiter as Oe}from"@stacksjs/ts-cache";class h{manager;inflight=new Map;inflightTimeoutMs;constructor(e,t={}){this.manager=e,this.inflightTimeoutMs=t.inflightTimeoutMs??30000}async get(e){return await this.manager.get(e)}async mget(e){return await this.manager.mget(e)}async set(e,t,r){return await this.manager.set(e,t,r)}async mset(e){return await this.manager.mset(e)}async setForever(e,t){return await this.manager.set(e,t,0)}async getOrSet(e,t,r){let s=await this.manager.get(e);if(s!==void 0)return s;let i=this.inflight.get(e);if(i)return await i;let u=(async()=>{let f=await t();return await this.manager.set(e,f,r),this.manager.emit("fetch",e,f,r),f})(),m=this.inflightTimeoutMs,d,y=new Promise((f,O)=>{d=setTimeout(()=>{O(Error(`[cache] getOrSet('${e}') timed out after ${m}ms`))},m)}),g=Promise.race([u,y]),P=()=>{if(clearTimeout(d),this.inflight.get(e)===g)this.inflight.delete(e)};return g.then(P,P),this.inflight.set(e,g),await g}async remember(e,t,r){return await this.getOrSet(e,r,t)}async rememberForever(e,t){return this.getOrSet(e,t,0)}async del(e){return await this.manager.del(e)}async has(e){return await this.manager.has(e)}async missing(e){return!await this.manager.has(e)}async remove(e){await this.manager.del(e)}async deleteMany(e){return await this.manager.del(e)}async clear(){await this.manager.flush()}async flush(){await this.manager.flush()}async keys(e){return await this.manager.keys(e)}async getTtl(e){return await this.manager.getTtl(e)}async ttl(e,t){return await this.manager.ttl(e,t)}async take(e){return await this.manager.take(e)}async getStats(){let e=await this.manager.getStats(),t=e.hits+e.misses;return{hits:e.hits,misses:e.misses,keys:e.keys,size:e.ksize+e.vsize,hitRate:t>0?e.hits/t:0}}async close(){await this.manager.close()}async disconnect(){await this.manager.close()}get cacheManager(){return this.manager}tags(e){return new a(this,e)}}class a{cache;tags;static TAG_PREFIX="__stacks_tag__:";static flushLocks=new Map;constructor(e,t){this.cache=e;this.tags=t;if(!t||t.length===0)throw Error("cache.tags(...) requires at least one tag")}tagScope(e){return`${a.TAG_PREFIX}${new Bun.CryptoHasher("sha256").update(e).digest("hex").slice(0,32)}:`}legacyTagKey(e){return`${a.TAG_PREFIX}${e}`}serialize(e){let t=this.tags.map((i)=>this.tagScope(i)),r=t.map((i)=>a.flushLocks.get(i)).filter((i)=>i!==void 0),s=Promise.all(r.map((i)=>i.catch(()=>0))).then(e);for(let i of t)a.flushLocks.set(i,s);return s.finally(()=>{for(let i of t)if(a.flushLocks.get(i)===s)a.flushLocks.delete(i)})}async indexKey(e,t){for(let r of this.tags)await this.cache.set(`${this.tagScope(r)}${e}`,e,t)}async put(e,t,r){return this.serialize(async()=>{let s=await this.cache.set(e,t,r);if(s)await this.indexKey(e,r);return s})}async set(e,t,r){return this.put(e,t,r)}async setForever(e,t){return this.serialize(async()=>{let r=await this.cache.setForever(e,t);if(r)await this.indexKey(e,0);return r})}async remember(e,t,r){let s=await this.cache.remember(e,t,r);return await this.serialize(()=>this.indexKey(e,t)),s}async rememberForever(e,t){let r=await this.cache.rememberForever(e,t);return await this.serialize(()=>this.indexKey(e,0)),r}async get(e){return this.cache.get(e)}async has(e){return this.cache.has(e)}async flush(){let e=0;for(let t of this.tags){let r=this.tagScope(t),s=a.flushLocks.get(r),i=s?s.catch(()=>0).then(()=>this.doFlushOne(t)):this.doFlushOne(t);a.flushLocks.set(r,i);try{e+=await i}finally{if(a.flushLocks.get(r)===i)a.flushLocks.delete(r)}}return e}async doFlushOne(e){let t=this.tagScope(e),r=await this.cache.keys(`${t}*`),s=await this.cache.get(this.legacyTagKey(e))??[],i=[...new Set([...r.map((u)=>u.slice(t.length)),...s])],o=0;if(i.length>0)o=await this.cache.del(i);return await this.cache.del([...r,this.legacyTagKey(e)]),o}}function W(e={}){let t=x({driver:"memory",stdTTL:e.stdTTL??0,checkPeriod:e.checkPeriod??600,maxKeys:e.maxKeys??-1,useClones:e.useClones??!0,prefix:e.prefix});return new h(t)}function E(e={}){let t=x({driver:"redis",url:e.url,host:e.host??"localhost",port:e.port??6379,username:e.username,password:e.password,database:e.database??0,tls:e.tls??!1,stdTTL:e.stdTTL??0,prefix:e.prefix});return new h(t)}function R(e={}){let t=new p(e);return new h(t)}function C(e={}){return new h(new T(e))}function he(e,t){if(e==="redis")return E(t);if(e==="singlestore")return R(t);if(e==="sqlite")return C(t);return W(t)}var H=x({driver:"memory",stdTTL:0,checkPeriod:600,maxKeys:-1,useClones:!0}),k=new h(H);function z(e,t=b){let r=[t.queue?.connections?.redis?.prefix,t.queue?.failed?.prefix,t.queue?.batching?.prefix,t.realtime?.server?.redis?.prefix].filter((s)=>typeof s==="string"&&s!=="");if(!e)return r;return r.filter((s)=>s===e||s.startsWith(`${e}:`))}var v=!1;function B(e=b.cache,t=b){let r={prefix:e?.prefix,stdTTL:e?.ttl};switch(e?.driver){case"redis":{let s=z(e.prefix,t);if(s.length>0&&!v)v=!0,console.warn(`[cache] The Redis cache prefix '${e.prefix??""}' contains ${s.join(", ")}. On a shared Redis, cache.flush() deletes those keys too. Set a prefix of its own in config/cache.ts, such as 'stacks:cache'.`);return E({...e.drivers?.redis,...r})}case"singlestore":return R({...e.drivers?.singlestore,...r});case"sqlite":return C({...e.drivers?.sqlite,...r});default:return k}}var l=null,w=!1;Promise.resolve(U).then(()=>{w=!0},()=>{w=!0});function le(){l=null,v=!1}function n(){if(l)return l;if(!w)return k;return l=B(),l}class L{get(e){return n().get(e)}mget(e){return n().mget(e)}set(e,t,r){return n().set(e,t,r)}mset(e){return n().mset(e)}setForever(e,t){return n().setForever(e,t)}getOrSet(e,t,r){return n().getOrSet(e,t,r)}del(e){return n().del(e)}has(e){return n().has(e)}missing(e){return n().missing(e)}remove(e){return n().remove(e)}deleteMany(e){return n().deleteMany(e)}clear(){return n().clear()}flush(){return n().flush()}keys(e){return n().keys(e)}getTtl(e){return n().getTtl(e)}ttl(e,t){return n().ttl(e,t)}take(e){return n().take(e)}remember(e,t,r){return n().remember(e,t,r)}rememberForever(e,t){return n().rememberForever(e,t)}getStats(){return n().getStats()}close(){return n().close()}disconnect(){return n().disconnect()}tags(e){return n().tags(e)}}var me=new L;function _e(e,t){let r=Object.keys(t).sort().map((s)=>{let i=t[s];if(typeof i==="number"&&!Number.isFinite(i))throw RangeError("Cache key numbers must be finite");if(i!==void 0&&i!==null&&!["string","number","boolean"].includes(typeof i))throw TypeError("Invalid cache key value");return[s,i===void 0?["undefined"]:i]});return JSON.stringify([e,r])}export{Ee as BatchOperations,we as CacheAsidePattern,Re as CacheInvalidation,Ce as CacheLock,Te as CacheManager,ke as CircuitBreaker,ye as MemoryDriver,xe as MultiLevelPattern,Oe as RateLimiter,be as RedisDriver,Pe as RefreshAheadPattern,p as SingleStoreCacheStore,T as SqliteCacheStore,h as StacksCache,a as TaggedCache,Se as WriteThroughPattern,me as cache,B as cacheFromConfig,_e as cacheKey,he as createCache,W as createMemoryCache,E as createRedisCache,R as createSingleStoreCache,C as createSqliteCache,Le as memoize,k as memory,z as redisNamespacesInside,le as resetConfiguredCache};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/cache",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.75.
|
|
4
|
+
"version": "0.75.382",
|
|
5
5
|
"description": "Caching the Stacks way.",
|
|
6
6
|
"author": "Chris Breuer",
|
|
7
7
|
"contributors": [
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"prepublishOnly": "bun run build"
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"@stacksjs/config": "0.75.
|
|
63
|
-
"@stacksjs/ts-cache": "^0.1.
|
|
62
|
+
"@stacksjs/config": "0.75.382",
|
|
63
|
+
"@stacksjs/ts-cache": "^0.1.9"
|
|
64
64
|
}
|
|
65
65
|
}
|