@stacksjs/cache 0.75.378 → 0.75.379

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.
@@ -134,9 +134,13 @@ export declare class StacksCache implements CacheDriver {
134
134
  * the named tag(s) so `flush()` can invalidate cascade-style without the
135
135
  * caller having to track keys themselves.
136
136
  *
137
- * The tag index is stored as `string[]` on disk (so it survives the
138
- * Redis driver's serializer), but operated on in memory as a `Set` so
139
- * each write is `O(1)` instead of `O(N)` over the existing index.
137
+ * Each tagged key gets an index entry of its own, under the tag's scope
138
+ * (`__stacks_tag__:<digest>:<key>`), and `flush()` lists the scope. The index
139
+ * used to be one `string[]` per tag, updated by read, add, write: two
140
+ * processes writing to one tag both read it, and the second write dropped the
141
+ * first one's key, so a flush left it cached (stacksjs/stacks#3073). An entry
142
+ * per key has nothing to read first, so there is nothing for another process
143
+ * to lose, and it expires with its key instead of growing for ever.
140
144
  *
141
145
  * `flush()` uses a per-tag in-process mutex so concurrent flushes don't
142
146
  * 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 I,overridesReady as K}from"@stacksjs/config";import{createCache as v}from"@stacksjs/ts-cache";import{EventEmitter as L}from"events";var{SQL:_}=globalThis.Bun;function c(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function P(e){return c(e).replace(/\*/g,"%")}function O(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:s="root",password:i="",database:o="stacks",table:u="stacks_cache",ssl:m=!1}=e;this.table=u,this.qualified=O(u),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0;let d=i?`${s}:${encodeURIComponent(i)}`:s,y=m?"?ssl=true":"";this.sql=new _(`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 q}from"bun:sqlite";import{EventEmitter as A}from"events";import{mkdirSync as M}from"fs";import{dirname as D}from"path";function F(e){return`"${e.replace(/"/g,'""')}"`}function N(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 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(D(t),{recursive:!0});if(this.db=new q(t,{create:!0}),this.db.run("PRAGMA busy_timeout = 5000"),t!==":memory:")N(this.db,5000);this.qualified=F(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?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()),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 fe,MemoryDriver as pe,RedisDriver as Te}from"@stacksjs/ts-cache";import{CacheAsidePattern as be,MultiLevelPattern as ve,RefreshAheadPattern as we,WriteThroughPattern as Pe,BatchOperations as xe,CacheInvalidation as Ee,CacheLock as Se,CircuitBreaker as Ce,memoize as ke,RateLimiter as Re}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,R)=>{d=setTimeout(()=>{R(Error(`[cache] getOrSet('${e}') timed out after ${m}ms`))},m)}),g=Promise.race([u,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")}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 U(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 h(t)}function x(e={}){let t=v({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 E(e={}){let t=new p(e);return new h(t)}function S(e={}){return new h(new T(e))}function ce(e,t){if(e==="redis")return x(t);if(e==="singlestore")return E(t);if(e==="sqlite")return S(t);return U(t)}var W=v({driver:"memory",stdTTL:0,checkPeriod:600,maxKeys:-1,useClones:!0}),C=new h(W);function H(e=I.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 l=null,b=!1;Promise.resolve(K).then(()=>{b=!0},()=>{b=!0});function ue(){l=null}function n(){if(l)return l;if(!b)return C;return l=H(),l}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 he=new k;function Le(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{xe as BatchOperations,be as CacheAsidePattern,Ee as CacheInvalidation,Se as CacheLock,fe as CacheManager,Ce as CircuitBreaker,pe as MemoryDriver,ve as MultiLevelPattern,Re as RateLimiter,Te as RedisDriver,we as RefreshAheadPattern,p as SingleStoreCacheStore,T as SqliteCacheStore,h as StacksCache,a as TaggedCache,Pe as WriteThroughPattern,he as cache,H as cacheFromConfig,Le as cacheKey,ce as createCache,U as createMemoryCache,x as createRedisCache,E as createSingleStoreCache,S as createSqliteCache,ke as memoize,C as memory,ue 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.378",
4
+ "version": "0.75.379",
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.378",
63
- "@stacksjs/ts-cache": "^0.1.7"
62
+ "@stacksjs/config": "0.75.379",
63
+ "@stacksjs/ts-cache": "^0.1.8"
64
64
  }
65
65
  }