@stacksjs/cache 0.75.71 → 0.75.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/drivers/index.d.ts +15 -4
- package/dist/drivers/singlestore.d.ts +7 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/drivers/index.d.ts
CHANGED
|
@@ -17,8 +17,7 @@ export declare function createRedisCache(options?: RedisOptions): CacheDriver;
|
|
|
17
17
|
*
|
|
18
18
|
* Wraps a SingleStore-backed store in the same `StacksCache` façade the memory
|
|
19
19
|
* and Redis drivers use, so it inherits the stampede-protection + tag logic.
|
|
20
|
-
* The store implements the
|
|
21
|
-
* cast bridges the structural gap (it is not a literal `CacheManager` subclass).
|
|
20
|
+
* The store implements {@link CacheBackend}, the surface `StacksCache` consumes.
|
|
22
21
|
*/
|
|
23
22
|
export declare function createSingleStoreCache(options?: SingleStoreCacheOptions): CacheDriver;
|
|
24
23
|
/**
|
|
@@ -65,8 +64,20 @@ export declare interface RedisOptions {
|
|
|
65
64
|
* Wraps ts-cache's CacheManager to provide a consistent API
|
|
66
65
|
* that matches the Stacks CacheDriver interface.
|
|
67
66
|
*/
|
|
67
|
+
/**
|
|
68
|
+
* What `StacksCache` needs from the store beneath it: ts-cache's
|
|
69
|
+
* `CacheManager` (memory, Redis) or the SingleStore store.
|
|
70
|
+
*
|
|
71
|
+
* Named so the compiler holds every store to it. The SingleStore store was
|
|
72
|
+
* passed in through `as unknown as CacheManager` and had no `emit`, which
|
|
73
|
+
* `getOrSet` calls after storing a computed value - so every `remember()` on
|
|
74
|
+
* SingleStore wrote its value and then threw a TypeError, and nothing could
|
|
75
|
+
* see it until it ran.
|
|
76
|
+
*/
|
|
77
|
+
export type CacheBackend = Pick<CacheManager,
|
|
78
|
+
'get' | 'mget' | 'set' | 'mset' | 'del' | 'has' | 'flush' | 'keys' | 'getTtl' | 'ttl' | 'take' | 'getStats' | 'close' | 'emit'>;
|
|
68
79
|
export declare class StacksCache implements CacheDriver {
|
|
69
|
-
constructor(manager:
|
|
80
|
+
constructor(manager: CacheBackend, opts?: { inflightTimeoutMs?: number });
|
|
70
81
|
get<T>(key: string): Promise<T | undefined>;
|
|
71
82
|
mget<T>(keys: string[]): Promise<Record<string, T>>;
|
|
72
83
|
set<T>(key: string, value: T, ttl?: number): Promise<boolean>;
|
|
@@ -89,7 +100,7 @@ export declare class StacksCache implements CacheDriver {
|
|
|
89
100
|
getStats(): Promise<CacheStats>;
|
|
90
101
|
close(): Promise<void>;
|
|
91
102
|
disconnect(): Promise<void>;
|
|
92
|
-
get cacheManager():
|
|
103
|
+
get cacheManager(): CacheBackend;
|
|
93
104
|
tags(tags: readonly string[]): TaggedCache;
|
|
94
105
|
}
|
|
95
106
|
/**
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
1
2
|
export declare interface SingleStoreCacheOptions {
|
|
2
3
|
host?: string
|
|
3
4
|
port?: number
|
|
@@ -16,7 +17,12 @@ declare interface CacheStatsShape {
|
|
|
16
17
|
ksize: number
|
|
17
18
|
vsize: number
|
|
18
19
|
}
|
|
19
|
-
|
|
20
|
+
/**
|
|
21
|
+
* An `EventEmitter`, as ts-cache's `CacheManager` is: `StacksCache` emits a
|
|
22
|
+
* `fetch` event through its store when it computes a value, and listeners can
|
|
23
|
+
* subscribe to it the same way on every driver.
|
|
24
|
+
*/
|
|
25
|
+
export declare class SingleStoreCacheStore extends EventEmitter {
|
|
20
26
|
constructor(options?: SingleStoreCacheOptions);
|
|
21
27
|
get<T>(key: string): Promise<T | undefined>;
|
|
22
28
|
mget<T>(keys: string[]): Promise<Record<string, T>>;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{createCache as
|
|
2
|
+
import{createCache as f}from"@stacksjs/ts-cache";import{EventEmitter as T}from"events";var{SQL:w}=globalThis.Bun;function v(e){return`\`${e.replace(/`/g,"``")}\``}class g extends T{sql;table;qualified;prefix;stdTTL;ready=null;hits=0;misses=0;constructor(e={}){super();let{host:t="127.0.0.1",port:s=3306,username:r="root",password:i="",database:o="stacks",table:c="stacks_cache",ssl:h=!1}=e;this.table=c,this.qualified=v(c),this.prefix=e.prefix??"",this.stdTTL=e.stdTTL??0;let u=i?`${r}:${encodeURIComponent(i)}`:r,d=h?"?ssl=true":"";this.sql=new w(`mysql://${u}@${t}:${s}/${o}${d}`)}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 s=(await this.sql.unsafe(`SELECT value, expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!s){this.misses++;return}if(s.expires_at!=null&&s.expires_at<=this.nowMs()){await this.del(e),this.misses++;return}return this.hits++,JSON.parse(s.value)}async mget(e){let t={};for(let s of e){let r=await this.get(s);if(r!==void 0)t[s]=r}return t}async set(e,t,s){await this.ensureReady();let r=this.expiryFor(s);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),r]),!0}async mset(e){for(let t of e)await this.set(t.key,t.value,t.ttl);return!0}async fetch(e,t,s){let r=await this.get(e);if(r!==void 0)return r;let i=await t();return await this.set(e,i,s),i}async del(e){await this.ensureReady();let t=Array.isArray(e)?e:[e];if(t.length===0)return 0;let s=t.map(()=>"?").join(", "),i=(await this.sql.unsafe(`DELETE FROM ${this.qualified} WHERE cache_key IN (${s})`,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 ?`,[`${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,"%"):"%"}`,s=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()]),r=this.prefix?this.prefix.length+1:0;return s.map((i)=>r?i.cache_key.slice(r):i.cache_key)}async getTtl(e){await this.ensureReady();let s=(await this.sql.unsafe(`SELECT expires_at FROM ${this.qualified} WHERE cache_key = ? LIMIT 1`,[this.k(e)]))[0];if(!s)return;return s.expires_at==null?0:s.expires_at}async ttl(e,t){await this.ensureReady();let s=this.expiryFor(t);if(((await this.sql.unsafe(`UPDATE ${this.qualified} SET expires_at = ? WHERE cache_key = ?`,[s,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{CacheManager as K,MemoryDriver as U,RedisDriver as W}from"@stacksjs/ts-cache";import{CacheAsidePattern as H,MultiLevelPattern as z,RefreshAheadPattern as G,WriteThroughPattern as V,BatchOperations as X,CacheInvalidation as Y,CacheLock as j,CircuitBreaker as J,memoize as Q,RateLimiter as Z}from"@stacksjs/ts-cache";class n{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,s){return await this.manager.set(e,t,s)}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,s){let r=await this.manager.get(e);if(r!==void 0)return r;let i=this.inflight.get(e);if(i)return await i;let c=(async()=>{let l=await t();return await this.manager.set(e,l,s),this.manager.emit("fetch",e,l,s),l})(),h=this.inflightTimeoutMs,u,d=new Promise((l,p)=>{u=setTimeout(()=>{p(Error(`[cache] getOrSet('${e}') timed out after ${h}ms`))},h)}),m=Promise.race([c,d]),y=()=>{if(clearTimeout(u),this.inflight.get(e)===m)this.inflight.delete(e)};return m.then(y,y),this.inflight.set(e,m),await m}async remember(e,t,s){return await this.getOrSet(e,s,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 s=this.tagKey(t),r=await this.cache.get(s)??[],i=new Set(r);if(!i.has(e))i.add(e),await this.cache.setForever(s,[...i])}}async put(e,t,s){let r=await this.cache.set(e,t,s);if(r)await this.indexKey(e);return r}async set(e,t,s){return this.put(e,t,s)}async setForever(e,t){let s=await this.cache.setForever(e,t);if(s)await this.indexKey(e);return s}async remember(e,t,s){let r=await this.cache.remember(e,t,s);return await this.indexKey(e),r}async rememberForever(e,t){let s=await this.cache.rememberForever(e,t);return await this.indexKey(e),s}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 s=this.tagKey(t),r=a.flushLocks.get(s),i=r?r.catch(()=>0).then(()=>this.doFlushOne(s)):this.doFlushOne(s);a.flushLocks.set(s,i);try{e+=await i}finally{if(a.flushLocks.get(s)===i)a.flushLocks.delete(s)}}return e}async doFlushOne(e){let t=await this.cache.get(e)??[],s=0;if(t.length>0)s=await this.cache.del(t);return await this.cache.del(e),s}}function b(e={}){let t=f({driver:"memory",stdTTL:e.stdTTL??0,checkPeriod:e.checkPeriod??600,maxKeys:e.maxKeys??-1,useClones:e.useClones??!0,prefix:e.prefix});return new n(t)}function P(e={}){let t=f({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 n(t)}function x(e={}){let t=new g(e);return new n(t)}function q(e,t){if(e==="redis")return P(t);if(e==="singlestore")return x(t);return b(t)}var S=f({driver:"memory",stdTTL:0,checkPeriod:600,maxKeys:-1,useClones:!0}),E=new n(S),F=E;export{X as BatchOperations,H as CacheAsidePattern,Y as CacheInvalidation,j as CacheLock,K as CacheManager,J as CircuitBreaker,U as MemoryDriver,z as MultiLevelPattern,Z as RateLimiter,W as RedisDriver,G as RefreshAheadPattern,g as SingleStoreCacheStore,n as StacksCache,a as TaggedCache,V as WriteThroughPattern,F as cache,q as createCache,b as createMemoryCache,P as createRedisCache,x as createSingleStoreCache,Q as memoize,E as memory};
|
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.73",
|
|
5
5
|
"description": "Caching the Stacks way.",
|
|
6
6
|
"author": "Chris Breuer",
|
|
7
7
|
"contributors": [
|
|
@@ -62,6 +62,6 @@
|
|
|
62
62
|
"@stacksjs/ts-cache": "^0.1.7"
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
65
|
-
"@stacksjs/config": "0.75.
|
|
65
|
+
"@stacksjs/config": "0.75.73"
|
|
66
66
|
}
|
|
67
67
|
}
|