@stacksjs/cache 0.75.408 → 0.75.417
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/README.md +10 -0
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Stacks Cache
|
|
2
2
|
|
|
3
|
+
`getOrSet` and `remember` share concurrent misses within one cache instance.
|
|
4
|
+
The fetcher deadline rejects every joined caller and discards late results.
|
|
5
|
+
Once a result starts being stored, callers remain joined until publication
|
|
6
|
+
finishes; backend I/O relies on the selected driver's own connection deadlines.
|
|
7
|
+
This prevents a timed-out attempt from overwriting a successful retry.
|
|
8
|
+
|
|
9
|
+
Tagged `remember` hits retain the stored value's expiry in their tag index.
|
|
10
|
+
Finite index entries include a short grace period for drivers that round TTLs
|
|
11
|
+
to whole seconds, so the index cannot expire before the value is invalidated.
|
|
12
|
+
|
|
3
13
|
wip
|
|
4
14
|
|
|
5
15
|
## ☘️ Features
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{config as b,overridesReady as W}from"@stacksjs/config";import{createCache as P}from"@stacksjs/ts-cache";import{EventEmitter as q}from"events";var{SQL:A}=globalThis.Bun;function c(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function E(e){return c(e).replace(/\*/g,"%")}function M(e){return`\`${e.replace(/`/g,"``")}\``}class p extends q{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=M(u),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0;let d=i?`${s}:${encodeURIComponent(i)}`:s,T=m?"?ssl=true":"";this.sql=new A(`mysql://${d}@${t}:${r}/${o}${T}`)}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 N}from"bun:sqlite";import{EventEmitter as D}from"events";import{mkdirSync as F}from"fs";import{dirname as I}from"path";function K(e){return`"${e.replace(/"/g,'""')}"`}function U(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 y extends D{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:"))F(I(t),{recursive:!0});if(this.db=new N(t,{create:!0}),this.db.run("PRAGMA busy_timeout = 5000"),t!==":memory:")U(this.db,5000);this.qualified=K(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?E(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 ye,MemoryDriver as Te,RedisDriver as be}from"@stacksjs/ts-cache";import{CacheAsidePattern as ve,MultiLevelPattern as we,RefreshAheadPattern as Pe,WriteThroughPattern as Se,BatchOperations as Ee,CacheInvalidation as Ce,CacheLock as Re,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 g=await t();return await this.manager.set(e,g,r),this.manager.emit("fetch",e,g,r),g})(),m=this.inflightTimeoutMs,d,T=new Promise((g,_)=>{d=setTimeout(()=>{_(Error(`[cache] getOrSet('${e}') timed out after ${m}ms`))},m)}),f=Promise.race([u,T]),S=()=>{if(clearTimeout(d),this.inflight.get(e)===f)this.inflight.delete(e)};return f.then(S,S),this.inflight.set(e,f),await f}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 C(e={}){let t=P({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 R(e={}){let t=P({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 k(e={}){let t=new p(e);return new h(t)}function L(e={}){return new h(new y(e))}function he(e,t){if(e==="redis")return R(t);if(e==="singlestore")return k(t);if(e==="sqlite")return L(t);return C(t)}var H=P({driver:"memory",stdTTL:0,checkPeriod:600,maxKeys:-1,useClones:!0}),x=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 R({...e.drivers?.redis,...r})}case"singlestore":return k({...e.drivers?.singlestore,...r});case"sqlite":return L({...e.drivers?.sqlite,...r});case"memory":{let s=e.drivers?.memory;if(e.ttl===void 0&&e.prefix===void 0&&e.maxKeys===void 0&&e.useClones===void 0&&!s)return x;return C({...s,stdTTL:e.ttl??s?.stdTTL,prefix:e.prefix??s?.prefix,maxKeys:e.maxKeys??s?.maxKeys,useClones:e.useClones??s?.useClones})}default:return x}}var l=null,w=!1;Promise.resolve(W).then(()=>{w=!0},()=>{w=!0});function le(){l=null,v=!1}function n(){if(l)return l;if(!w)return x;return l=B(),l}class O{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 O;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,ve as CacheAsidePattern,Ce as CacheInvalidation,Re as CacheLock,ye as CacheManager,ke as CircuitBreaker,Te as MemoryDriver,we as MultiLevelPattern,Oe as RateLimiter,be as RedisDriver,Pe as RefreshAheadPattern,p as SingleStoreCacheStore,y as SqliteCacheStore,h as StacksCache,a as TaggedCache,Se as WriteThroughPattern,me as cache,B as cacheFromConfig,_e as cacheKey,he as createCache,C as createMemoryCache,R as createRedisCache,k as createSingleStoreCache,L as createSqliteCache,Le as memoize,x as memory,z as redisNamespacesInside,le as resetConfiguredCache};
|
|
2
|
+
import{config as y,overridesReady as U}from"@stacksjs/config";import{createCache as v}from"@stacksjs/ts-cache";import{EventEmitter as O}from"events";var{SQL:q}=globalThis.Bun;function d(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function S(e){return d(e).replace(/\*/g,"%")}function A(e){return`\`${e.replace(/`/g,"``")}\``}class f extends O{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:a="stacks",table:c="stacks_cache",ssl:p=!1}=e;this.table=c,this.qualified=A(c),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0;let w=i?`${s}:${encodeURIComponent(i)}`:s,u=p?"?ssl=true":"";this.sql=new q(`mysql://${w}@${t}:${r}/${a}${u}`)}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}).catch((e)=>{throw this.ready=null,e});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((a)=>this.k(a)))).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 ?`,[`${d(this.prefix)}:%`]);else await this.sql.unsafe(`TRUNCATE TABLE ${this.qualified}`)}async keys(e){await this.ensureReady();let t=`${this.prefix?`${d(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 g 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){let e=`${this.prefix}:`;this.db.query(`DELETE FROM ${this.qualified} WHERE substr(cache_key, 1, length(?)) = ?`).run(e,e)}else this.db.run(`DELETE FROM ${this.qualified}`)}async keys(e){let t=this.prefix?`${this.prefix}:`:"",r=e?S(e):"%",s=this.db.query(`SELECT cache_key FROM ${this.qualified} WHERE substr(cache_key, 1, length(?)) = ? AND substr(cache_key, length(?) + 1) LIKE ? ESCAPE '\\' AND (expires_at IS NULL OR expires_at > ?)`).all(t,t,t,r,Date.now()),i=this.prefix?this.prefix.length+1:0;return s.map((a)=>i?a.cache_key.slice(i):a.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 = ? AND (expires_at IS NULL OR expires_at > ?)`).run(this.expiryFor(t),this.k(e),Date.now()).changes>0}async take(e){let t=this.db.query(`DELETE FROM ${this.qualified} WHERE cache_key = ? RETURNING value, expires_at`).get(this.k(e));if(!t||t.expires_at!=null&&t.expires_at<=Date.now()){this.misses++;return}return this.hits++,JSON.parse(t.value)}async getStats(){let e=this.prefix?`${this.prefix}:`:"",t=this.db.query(`SELECT COUNT(*) AS n FROM ${this.qualified} WHERE substr(cache_key, 1, length(?)) = ? AND (expires_at IS NULL OR expires_at > ?)`).get(e,e,Date.now());return{hits:this.hits,misses:this.misses,keys:Number(t?.n??0),ksize:0,vsize:0}}async close(){this.db.close()}}import{CacheManager as pe,MemoryDriver as ye,RedisDriver as Te}from"@stacksjs/ts-cache";import{CacheAsidePattern as xe,MultiLevelPattern as ve,RefreshAheadPattern as we,WriteThroughPattern as Pe,BatchOperations as Se,CacheInvalidation as Ee,CacheLock as Ce,CircuitBreaker as Re,memoize as ke,RateLimiter as _e}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 a=this.inflightTimeoutMs,c,p=new Promise((l,L)=>{c=setTimeout(()=>{L(Error(`[cache] getOrSet('${e}') timed out after ${a}ms`))},a)}),u=(async()=>{let l;try{l=await Promise.race([Promise.resolve().then(t),p])}finally{clearTimeout(c)}return await this.manager.set(e,l,r),this.manager.emit("fetch",e,l,r),l})(),P=()=>{if(this.inflight.get(e)===u)this.inflight.delete(e)};return u.then(P,P),this.inflight.set(e,u),await u}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 o(this,e)}}class o{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`${o.TAG_PREFIX}${new Bun.CryptoHasher("sha256").update(e).digest("hex").slice(0,32)}:`}legacyTagKey(e){return`${o.TAG_PREFIX}${e}`}serialize(e){let t=this.tags.map((i)=>this.tagScope(i)),r=t.map((i)=>o.flushLocks.get(i)).filter((i)=>i!==void 0),s=Promise.all(r.map((i)=>i.catch(()=>0))).then(e);for(let i of t)o.flushLocks.set(i,s);return s.finally(()=>{for(let i of t)if(o.flushLocks.get(i)===s)o.flushLocks.delete(i)})}async indexKey(e,t){for(let r of this.tags)await this.cache.set(`${this.tagScope(r)}${e}`,e,t)}async indexCachedKey(e){let t=await this.cache.getTtl(e);if(t===void 0)return;let r=t===0?0:Math.max(1,Math.ceil((t-Date.now())/1000)+1);await this.indexKey(e,r)}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.indexCachedKey(e)),s}async rememberForever(e,t){let r=await this.cache.rememberForever(e,t);return await this.serialize(()=>this.indexCachedKey(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.tagScope(t),s=o.flushLocks.get(r),i=s?s.catch(()=>0).then(()=>this.doFlushOne(t)):this.doFlushOne(t);o.flushLocks.set(r,i);try{e+=await i}finally{if(o.flushLocks.get(r)===i)o.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((c)=>c.slice(t.length)),...s])],a=0;if(i.length>0)a=await this.cache.del(i);return await this.cache.del([...r,this.legacyTagKey(e)]),a}}function E(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 C(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 R(e={}){let t=new f(e);return new h(t)}function k(e={}){return new h(new g(e))}function ue(e,t){if(e==="redis")return C(t);if(e==="singlestore")return R(t);if(e==="sqlite")return k(t);return E(t)}var W=v({driver:"memory",stdTTL:0,checkPeriod:600,maxKeys:-1,useClones:!0}),T=new h(W);function H(e,t=y){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 b=!1;function z(e=y.cache,t=y){let r={prefix:e?.prefix,stdTTL:e?.ttl};switch(e?.driver){case"redis":{let s=H(e.prefix,t);if(s.length>0&&!b)b=!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 C({...e.drivers?.redis,...r})}case"singlestore":return R({...e.drivers?.singlestore,...r});case"sqlite":return k({...e.drivers?.sqlite,...r});case"memory":{let s=e.drivers?.memory;if(e.ttl===void 0&&e.prefix===void 0&&e.maxKeys===void 0&&e.useClones===void 0&&!s)return T;return E({...s,stdTTL:e.ttl??s?.stdTTL,prefix:e.prefix??s?.prefix,maxKeys:e.maxKeys??s?.maxKeys,useClones:e.useClones??s?.useClones})}default:return T}}var m=null,x=!1;Promise.resolve(U).then(()=>{x=!0},()=>{x=!0});function he(){m=null,b=!1}function n(){if(m)return m;if(!x)return T;return m=z(),m}class _{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 le=new _;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{Se as BatchOperations,xe as CacheAsidePattern,Ee as CacheInvalidation,Ce as CacheLock,pe as CacheManager,Re as CircuitBreaker,ye as MemoryDriver,ve as MultiLevelPattern,_e as RateLimiter,Te as RedisDriver,we as RefreshAheadPattern,f as SingleStoreCacheStore,g as SqliteCacheStore,h as StacksCache,o as TaggedCache,Pe as WriteThroughPattern,le as cache,z as cacheFromConfig,Le as cacheKey,ue as createCache,E as createMemoryCache,C as createRedisCache,R as createSingleStoreCache,k as createSqliteCache,ke as memoize,T as memory,H as redisNamespacesInside,he 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.417",
|
|
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.
|
|
62
|
+
"@stacksjs/config": "0.75.417",
|
|
63
63
|
"@stacksjs/ts-cache": "^0.1.9"
|
|
64
64
|
}
|
|
65
65
|
}
|