@stacksjs/cache 0.75.256 → 0.75.257
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/index.js +1 -1
- package/dist/sql-like.d.ts +10 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{config as D,overridesReady as N}from"@stacksjs/config";import{createCache as v}from"@stacksjs/ts-cache";import{EventEmitter as k}from"events";var{SQL:O}=globalThis.Bun;function L(e){return`\`${e.replace(/`/g,"``")}\``}class f extends k{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:u="stacks",table:h="stacks_cache",ssl:l=!1}=e;this.table=h,this.qualified=L(h),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0;let m=i?`${s}:${encodeURIComponent(i)}`:s,T=l?"?ssl=true":"";this.sql=new O(`mysql://${m}@${t}:${r}/${u}${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((u)=>this.k(u)))).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 ?`,[`${this.prefix}:%`]);else await this.sql.unsafe(`TRUNCATE TABLE ${this.qualified}`)}async keys(e){await this.ensureReady();let t=`${this.prefix?`${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 _}from"bun:sqlite";import{EventEmitter as q}from"events";import{mkdirSync as A}from"fs";import{dirname as M}from"path";function F(e){return`"${e.replace(/"/g,'""')}"`}function y(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`).replace(/\*/g,"%")}class p extends q{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:"))A(M(t),{recursive:!0});if(this.db=new _(t,{create:!0}),this.db.run("PRAGMA busy_timeout = 5000"),t!==":memory:")this.db.run("PRAGMA journal_mode = WAL");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(`${y(this.prefix)}:%`);else this.db.run(`DELETE FROM ${this.qualified}`)}async keys(e){let t=`${this.prefix?`${y(this.prefix)}:`:""}${e?y(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 he,MemoryDriver as le,RedisDriver as me}from"@stacksjs/ts-cache";import{CacheAsidePattern as ge,MultiLevelPattern as fe,RefreshAheadPattern as pe,WriteThroughPattern as Te,BatchOperations as ye,CacheInvalidation as be,CacheLock as ve,CircuitBreaker as we,memoize as xe,RateLimiter as Pe}from"@stacksjs/ts-cache";class o{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 h=(async()=>{let g=await t();return await this.manager.set(e,g,r),this.manager.emit("fetch",e,g,r),g})(),l=this.inflightTimeoutMs,m,T=new Promise((g,R)=>{m=setTimeout(()=>{R(Error(`[cache] getOrSet('${e}') timed out after ${l}ms`))},l)}),d=Promise.race([h,T]),w=()=>{if(clearTimeout(m),this.inflight.get(e)===d)this.inflight.delete(e)};return d.then(w,w),this.inflight.set(e,d),await d}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}`}async indexKey(e){for(let t of this.tags){let r=this.tagKey(t),s=await this.cache.get(r)??[],i=new Set(s);if(!i.has(e))i.add(e),await this.cache.setForever(r,[...i])}}async put(e,t,r){let s=await this.cache.set(e,t,r);if(s)await this.indexKey(e);return s}async set(e,t,r){return this.put(e,t,r)}async setForever(e,t){let r=await this.cache.setForever(e,t);if(r)await this.indexKey(e);return r}async remember(e,t,r){let s=await this.cache.remember(e,t,r);return await this.indexKey(e),s}async rememberForever(e,t){let r=await this.cache.rememberForever(e,t);return await 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),s=a.flushLocks.get(r),i=s?s.catch(()=>0).then(()=>this.doFlushOne(r)):this.doFlushOne(r);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=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 I(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 o(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 o(t)}function P(e={}){let t=new f(e);return new o(t)}function E(e={}){return new o(new p(e))}function se(e,t){if(e==="redis")return x(t);if(e==="singlestore")return P(t);if(e==="sqlite")return E(t);return I(t)}var U=v({driver:"memory",stdTTL:0,checkPeriod:600,maxKeys:-1,useClones:!0}),S=new o(U);function K(e=D.cache){let t={prefix:e?.prefix,stdTTL:e?.ttl};switch(e?.driver){case"redis":return x({...e.drivers?.redis,...t});case"singlestore":return P({...e.drivers?.singlestore,...t});case"sqlite":return E({...e.drivers?.sqlite,...t});default:return S}}var c=null,b=!1;Promise.resolve(N).then(()=>{b=!0},()=>{b=!0});function ie(){c=null}function n(){if(c)return c;if(!b)return S;return c=K(),c}class C{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 ne=new C;function Ee(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{ye as BatchOperations,ge as CacheAsidePattern,be as CacheInvalidation,ve as CacheLock,he as CacheManager,we as CircuitBreaker,le as MemoryDriver,fe as MultiLevelPattern,Pe as RateLimiter,me as RedisDriver,pe as RefreshAheadPattern,f as SingleStoreCacheStore,p as SqliteCacheStore,o as StacksCache,a as TaggedCache,Te as WriteThroughPattern,ne as cache,K as cacheFromConfig,Ee as cacheKey,se as createCache,I as createMemoryCache,x as createRedisCache,P as createSingleStoreCache,E as createSqliteCache,xe as memoize,S as memory,ie as resetConfiguredCache};
|
|
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};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LIKE patterns for the SQL cache drivers.
|
|
3
|
+
*
|
|
4
|
+
* Both escape with a backslash: SingleStore and MySQL take it as LIKE's
|
|
5
|
+
* default escape character, and the SQLite driver names it with `ESCAPE '\'`.
|
|
6
|
+
*/
|
|
7
|
+
/** `value` as a LIKE pattern that matches it literally: `\`, `%` and `_` escaped. */
|
|
8
|
+
export declare function escapeLike(value: string): string;
|
|
9
|
+
/** `*` globs as LIKE patterns, with LIKE's own wildcards taken literally. */
|
|
10
|
+
export declare function likePattern(glob: string): string;
|
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.257",
|
|
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.257",
|
|
63
63
|
"@stacksjs/ts-cache": "^0.1.7"
|
|
64
64
|
}
|
|
65
65
|
}
|