@tachybase/cache 0.23.8

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.
@@ -0,0 +1,9 @@
1
+
2
+ 
3
+ > @tachybase/cache@0.23.7 build /Users/seal/Documents/projects/tachybase/packages/cache
4
+ > tachybase-build --no-dts @tachybase/cache
5
+
6
+ The CJS build of Vite's Node API is deprecated. See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.
7
+ @tachybase/cache: cache build start
8
+ @tachybase/cache: build cjs
9
+
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2023-2024] [Tachybase team]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ export interface BloomFilter {
2
+ reserve(key: string, errorRate: number, capacity: number): Promise<void>;
3
+ add(key: string, val: string): Promise<void>;
4
+ mAdd(key: string, vals: string[]): Promise<void>;
5
+ exists(key: string, val: string): Promise<boolean>;
6
+ }
@@ -0,0 +1,15 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from))
8
+ if (!__hasOwnProp.call(to, key) && key !== except)
9
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
+ }
11
+ return to;
12
+ };
13
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
14
+ var bloom_filter_exports = {};
15
+ module.exports = __toCommonJS(bloom_filter_exports);
@@ -0,0 +1,10 @@
1
+ import { BloomFilter as IBloomFilter } from '.';
2
+ import { Cache } from '../cache';
3
+ export declare class MemoryBloomFilter implements IBloomFilter {
4
+ cache: Cache;
5
+ constructor(cache: Cache);
6
+ reserve(key: string, errorRate: number, capacity: number): Promise<void>;
7
+ add(key: string, value: string): Promise<void>;
8
+ mAdd(key: string, values: string[]): Promise<void>;
9
+ exists(key: string, value: string): Promise<boolean>;
10
+ }
@@ -0,0 +1,61 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var memory_bloom_filter_exports = {};
20
+ __export(memory_bloom_filter_exports, {
21
+ MemoryBloomFilter: () => MemoryBloomFilter
22
+ });
23
+ module.exports = __toCommonJS(memory_bloom_filter_exports);
24
+ var import_bloom_filters = require("bloom-filters");
25
+ const _MemoryBloomFilter = class _MemoryBloomFilter {
26
+ cache;
27
+ constructor(cache) {
28
+ this.cache = cache;
29
+ }
30
+ async reserve(key, errorRate, capacity) {
31
+ const filter = import_bloom_filters.BloomFilter.create(capacity, errorRate);
32
+ await this.cache.set(key, filter);
33
+ }
34
+ async add(key, value) {
35
+ const filter = await this.cache.get(key);
36
+ if (!filter) {
37
+ return;
38
+ }
39
+ filter.add(value);
40
+ }
41
+ async mAdd(key, values) {
42
+ const filter = await this.cache.get(key);
43
+ if (!filter) {
44
+ return;
45
+ }
46
+ values.forEach((value) => filter.add(value));
47
+ }
48
+ async exists(key, value) {
49
+ const filter = await this.cache.get(key);
50
+ if (!filter) {
51
+ return false;
52
+ }
53
+ return filter.has(value);
54
+ }
55
+ };
56
+ __name(_MemoryBloomFilter, "MemoryBloomFilter");
57
+ let MemoryBloomFilter = _MemoryBloomFilter;
58
+ // Annotate the CommonJS export names for ESM import in node:
59
+ 0 && (module.exports = {
60
+ MemoryBloomFilter
61
+ });
@@ -0,0 +1,11 @@
1
+ import { BloomFilter } from '.';
2
+ import { Cache } from '../cache';
3
+ export declare class RedisBloomFilter implements BloomFilter {
4
+ cache: Cache;
5
+ constructor(cache: Cache);
6
+ getStore(): import("cache-manager").Store;
7
+ reserve(key: string, errorRate: number, capacity: number): Promise<void>;
8
+ add(key: string, value: string): Promise<void>;
9
+ mAdd(key: string, values: string[]): Promise<void>;
10
+ exists(key: string, value: string): Promise<boolean>;
11
+ }
@@ -0,0 +1,54 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var redis_bloom_filter_exports = {};
20
+ __export(redis_bloom_filter_exports, {
21
+ RedisBloomFilter: () => RedisBloomFilter
22
+ });
23
+ module.exports = __toCommonJS(redis_bloom_filter_exports);
24
+ const _RedisBloomFilter = class _RedisBloomFilter {
25
+ cache;
26
+ constructor(cache) {
27
+ this.cache = cache;
28
+ }
29
+ getStore() {
30
+ return this.cache.store.store;
31
+ }
32
+ async reserve(key, errorRate, capacity) {
33
+ const store = this.getStore();
34
+ await store.client.bf.reserve(key, errorRate, capacity);
35
+ }
36
+ async add(key, value) {
37
+ const store = this.getStore();
38
+ await store.client.bf.add(key, value);
39
+ }
40
+ async mAdd(key, values) {
41
+ const store = this.getStore();
42
+ await store.client.bf.mAdd(key, values);
43
+ }
44
+ async exists(key, value) {
45
+ const store = this.getStore();
46
+ return await store.client.bf.exists(key, value);
47
+ }
48
+ };
49
+ __name(_RedisBloomFilter, "RedisBloomFilter");
50
+ let RedisBloomFilter = _RedisBloomFilter;
51
+ // Annotate the CommonJS export names for ESM import in node:
52
+ 0 && (module.exports = {
53
+ RedisBloomFilter
54
+ });
@@ -0,0 +1,39 @@
1
+ import { FactoryStore, Store } from 'cache-manager';
2
+ import { BloomFilter } from './bloom-filter';
3
+ import { Cache } from './cache';
4
+ export type { FactoryStore } from 'cache-manager';
5
+ export type StoreOptions = {
6
+ store?: 'memory' | FactoryStore<Store, any>;
7
+ close?: (store: Store) => Promise<void>;
8
+ [key: string]: any;
9
+ };
10
+ export type CacheManagerOptions = Partial<{
11
+ defaultStore: string;
12
+ stores: {
13
+ [storeType: string]: StoreOptions;
14
+ };
15
+ }>;
16
+ export declare class CacheManager {
17
+ defaultStore: string;
18
+ private stores;
19
+ storeTypes: Map<string, StoreOptions>;
20
+ caches: Map<string, Cache>;
21
+ constructor(options?: CacheManagerOptions);
22
+ private createStore;
23
+ registerStore(options: {
24
+ name: string;
25
+ } & StoreOptions): void;
26
+ private newCache;
27
+ createCache(options: {
28
+ name: string;
29
+ prefix?: string;
30
+ store?: string;
31
+ [key: string]: any;
32
+ }): Promise<Cache>;
33
+ getCache(name: string): Cache;
34
+ flushAll(): Promise<void>;
35
+ close(): Promise<void>;
36
+ createBloomFilter(options?: {
37
+ store?: string;
38
+ }): Promise<BloomFilter>;
39
+ }
@@ -0,0 +1,162 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var cache_manager_exports = {};
30
+ __export(cache_manager_exports, {
31
+ CacheManager: () => CacheManager
32
+ });
33
+ module.exports = __toCommonJS(cache_manager_exports);
34
+ var import_cache_manager = require("cache-manager");
35
+ var import_cache_manager_redis_yet = require("cache-manager-redis-yet");
36
+ var import_deepmerge = __toESM(require("deepmerge"));
37
+ var import_lodash = __toESM(require("lodash"));
38
+ var import_memory_bloom_filter = require("./bloom-filter/memory-bloom-filter");
39
+ var import_redis_bloom_filter = require("./bloom-filter/redis-bloom-filter");
40
+ var import_cache = require("./cache");
41
+ var import_utils = require("./utils");
42
+ const _CacheManager = class _CacheManager {
43
+ defaultStore;
44
+ stores = /* @__PURE__ */ new Map();
45
+ storeTypes = /* @__PURE__ */ new Map();
46
+ caches = /* @__PURE__ */ new Map();
47
+ constructor(options) {
48
+ const defaultOptions = {
49
+ defaultStore: "memory",
50
+ stores: {
51
+ memory: {
52
+ store: "memory",
53
+ // global config
54
+ max: 2e3
55
+ },
56
+ redis: {
57
+ store: import_cache_manager_redis_yet.redisStore,
58
+ close: /* @__PURE__ */ __name(async (redis) => {
59
+ await redis.client.quit();
60
+ }, "close")
61
+ }
62
+ }
63
+ };
64
+ const cacheOptions = (0, import_deepmerge.default)(defaultOptions, options || {});
65
+ const { defaultStore = "memory", stores } = cacheOptions;
66
+ this.defaultStore = defaultStore;
67
+ for (const [name, store] of Object.entries(stores)) {
68
+ const { store: s, ...globalConfig } = store;
69
+ this.registerStore({ name, store: s, ...globalConfig });
70
+ }
71
+ }
72
+ async createStore(options) {
73
+ const { name, storeType: type, ...config } = options;
74
+ const storeType = this.storeTypes.get(type);
75
+ if (!storeType) {
76
+ throw new Error(`Create cache failed, store type [${type}] is unavailable or not registered`);
77
+ }
78
+ const { store: s, close, ...globalConfig } = storeType;
79
+ let store;
80
+ if (name === "redis") {
81
+ store = await (0, import_utils.retryOperation)(
82
+ async () => {
83
+ return await (0, import_cache_manager.caching)(s, { ...globalConfig, ...config });
84
+ },
85
+ { name: "connect to redis" }
86
+ );
87
+ } else {
88
+ store = await (0, import_cache_manager.caching)(s, { ...globalConfig, ...config });
89
+ }
90
+ this.stores.set(name, { close, store });
91
+ return store;
92
+ }
93
+ registerStore(options) {
94
+ const { name, ...rest } = options;
95
+ this.storeTypes.set(name, rest);
96
+ }
97
+ newCache(options) {
98
+ const { name, prefix, store } = options;
99
+ const cache = new import_cache.Cache({ name, prefix, store });
100
+ this.caches.set(name, cache);
101
+ return cache;
102
+ }
103
+ async createCache(options) {
104
+ const { name, prefix, store = this.defaultStore, ...config } = options;
105
+ if (!import_lodash.default.isEmpty(config)) {
106
+ const newStore = await this.createStore({ name, storeType: store, ...config });
107
+ return this.newCache({ name, prefix, store: newStore });
108
+ }
109
+ const s = this.stores.get(store);
110
+ if (!s) {
111
+ const defaultStore = await this.createStore({ name: store, storeType: store });
112
+ return this.newCache({ name, prefix, store: defaultStore });
113
+ }
114
+ return this.newCache({ name, prefix, store: s.store });
115
+ }
116
+ getCache(name) {
117
+ const cache = this.caches.get(name);
118
+ if (!cache) {
119
+ throw new Error(`Get cache failed, ${name} is not found`);
120
+ }
121
+ return cache;
122
+ }
123
+ async flushAll() {
124
+ const promises = [];
125
+ for (const cache of this.caches.values()) {
126
+ promises.push(cache.reset());
127
+ }
128
+ await Promise.all(promises);
129
+ }
130
+ async close() {
131
+ const promises = [];
132
+ for (const s of this.stores.values()) {
133
+ const { close, store } = s;
134
+ close && promises.push(close(store.store));
135
+ }
136
+ await Promise.all(promises);
137
+ }
138
+ async createBloomFilter(options) {
139
+ const name = "bloom-filter";
140
+ const { store = this.defaultStore } = options || {};
141
+ let cache;
142
+ try {
143
+ cache = this.getCache(name);
144
+ } catch (error) {
145
+ cache = await this.createCache({ name, store });
146
+ }
147
+ switch (store) {
148
+ case "memory":
149
+ return new import_memory_bloom_filter.MemoryBloomFilter(cache);
150
+ case "redis":
151
+ return new import_redis_bloom_filter.RedisBloomFilter(cache);
152
+ default:
153
+ throw new Error(`BloomFilter store [${store}] is not supported`);
154
+ }
155
+ }
156
+ };
157
+ __name(_CacheManager, "CacheManager");
158
+ let CacheManager = _CacheManager;
159
+ // Annotate the CommonJS export names for ESM import in node:
160
+ 0 && (module.exports = {
161
+ CacheManager
162
+ });
package/lib/cache.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { Cache as BasicCache, Milliseconds } from 'cache-manager';
2
+ export declare class Cache {
3
+ name: string;
4
+ prefix?: string;
5
+ store: BasicCache;
6
+ constructor({ name, prefix, store }: {
7
+ name: string;
8
+ store: BasicCache;
9
+ prefix?: string;
10
+ });
11
+ key(key: string): string;
12
+ set(key: string, value: unknown, ttl?: Milliseconds): Promise<void>;
13
+ get<T>(key: string): Promise<T>;
14
+ del(key: string): Promise<void>;
15
+ reset(): Promise<void>;
16
+ wrap<T>(key: string, fn: () => Promise<T>, ttl?: Milliseconds): Promise<T>;
17
+ wrapWithCondition<T>(key: string, fn: () => T | Promise<T>, options?: {
18
+ useCache?: boolean;
19
+ isCacheable?: (val: unknown) => boolean | Promise<boolean>;
20
+ ttl?: Milliseconds;
21
+ }): Promise<T>;
22
+ mset(args: [string, unknown][], ttl?: Milliseconds): Promise<void>;
23
+ mget(...args: string[]): Promise<unknown[]>;
24
+ mdel(...args: string[]): Promise<void>;
25
+ keys(pattern?: string): Promise<string[]>;
26
+ ttl(key: string): Promise<number>;
27
+ setValueInObject(key: string, objectKey: string, value: unknown): Promise<void>;
28
+ getValueInObject(key: string, objectKey: string): Promise<any>;
29
+ delValueInObject(key: string, objectKey: string): Promise<void>;
30
+ }
package/lib/cache.js ADDED
@@ -0,0 +1,109 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var cache_exports = {};
20
+ __export(cache_exports, {
21
+ Cache: () => Cache
22
+ });
23
+ module.exports = __toCommonJS(cache_exports);
24
+ const _Cache = class _Cache {
25
+ name;
26
+ prefix;
27
+ store;
28
+ constructor({ name, prefix, store }) {
29
+ this.name = name;
30
+ this.prefix = prefix;
31
+ this.store = store;
32
+ }
33
+ key(key) {
34
+ return this.prefix ? `${this.prefix}:${key}` : key;
35
+ }
36
+ async set(key, value, ttl) {
37
+ await this.store.set(this.key(key), value, ttl);
38
+ }
39
+ async get(key) {
40
+ return await this.store.get(this.key(key));
41
+ }
42
+ async del(key) {
43
+ await this.store.del(this.key(key));
44
+ }
45
+ async reset() {
46
+ await this.store.reset();
47
+ }
48
+ async wrap(key, fn, ttl) {
49
+ return await this.store.wrap(this.key(key), fn, ttl);
50
+ }
51
+ async wrapWithCondition(key, fn, options) {
52
+ const { useCache, isCacheable, ttl } = options || {};
53
+ if (useCache === false) {
54
+ return await fn();
55
+ }
56
+ const value = await this.get(key);
57
+ if (value) {
58
+ return value;
59
+ }
60
+ const result = await fn();
61
+ const cacheable = isCacheable ? await isCacheable(result) : result;
62
+ if (!cacheable) {
63
+ return result;
64
+ }
65
+ await this.set(key, result, ttl);
66
+ return result;
67
+ }
68
+ async mset(args, ttl) {
69
+ await this.store.store.mset(
70
+ args.map(([key, value]) => [this.key(key), value]),
71
+ ttl
72
+ );
73
+ }
74
+ async mget(...args) {
75
+ args = args.map((key) => this.key(key));
76
+ return await this.store.store.mget(...args);
77
+ }
78
+ async mdel(...args) {
79
+ args = args.map((key) => this.key(key));
80
+ await this.store.store.mdel(...args);
81
+ }
82
+ async keys(pattern) {
83
+ const keys = await this.store.store.keys(pattern);
84
+ return keys.map((key) => key.replace(`${this.name}:`, ""));
85
+ }
86
+ async ttl(key) {
87
+ return await this.store.store.ttl(this.key(key));
88
+ }
89
+ async setValueInObject(key, objectKey, value) {
90
+ const object = await this.get(key) || {};
91
+ object[objectKey] = value;
92
+ await this.set(key, object);
93
+ }
94
+ async getValueInObject(key, objectKey) {
95
+ const object = await this.get(key) || {};
96
+ return object[objectKey];
97
+ }
98
+ async delValueInObject(key, objectKey) {
99
+ const object = await this.get(key) || {};
100
+ delete object[objectKey];
101
+ await this.set(key, object);
102
+ }
103
+ };
104
+ __name(_Cache, "Cache");
105
+ let Cache = _Cache;
106
+ // Annotate the CommonJS export names for ESM import in node:
107
+ 0 && (module.exports = {
108
+ Cache
109
+ });
package/lib/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './cache-manager';
2
+ export * from './cache';
3
+ export * from './bloom-filter';
package/lib/index.js ADDED
@@ -0,0 +1,25 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from))
8
+ if (!__hasOwnProp.call(to, key) && key !== except)
9
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
+ }
11
+ return to;
12
+ };
13
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var src_exports = {};
16
+ module.exports = __toCommonJS(src_exports);
17
+ __reExport(src_exports, require("./cache-manager"), module.exports);
18
+ __reExport(src_exports, require("./cache"), module.exports);
19
+ __reExport(src_exports, require("./bloom-filter"), module.exports);
20
+ // Annotate the CommonJS export names for ESM import in node:
21
+ 0 && (module.exports = {
22
+ ...require("./cache-manager"),
23
+ ...require("./cache"),
24
+ ...require("./bloom-filter")
25
+ });
package/lib/utils.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ interface Logger {
2
+ info(message: string): void;
3
+ warn(message: string): void;
4
+ error(message: string): void;
5
+ }
6
+ /**
7
+ * Generic retry function for async operations
8
+ * @param operation - Async operation to execute
9
+ * @param options - Configuration options including operation name, max retries, initial delay, and delay multiplier
10
+ * @param options.timeout - Maximum time in milliseconds to wait for each operation attempt
11
+ * @param options.logger - Logger instance for operation status and errors
12
+ * @returns {Promise<T>} - Returns the result of the successful operation
13
+ */
14
+ export declare function retryOperation<T>(operation: () => Promise<T>, { name, retry, startingDelay, timeMultiple, timeout, logger, }: {
15
+ name: string;
16
+ retry?: number;
17
+ startingDelay?: number;
18
+ timeMultiple?: number;
19
+ timeout?: number;
20
+ logger?: Logger;
21
+ }): Promise<T>;
22
+ export {};
package/lib/utils.js ADDED
@@ -0,0 +1,64 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var utils_exports = {};
20
+ __export(utils_exports, {
21
+ retryOperation: () => retryOperation
22
+ });
23
+ module.exports = __toCommonJS(utils_exports);
24
+ async function retryOperation(operation, {
25
+ name,
26
+ retry = 10,
27
+ startingDelay = 50,
28
+ timeMultiple = 2,
29
+ timeout = 5e3,
30
+ logger = {
31
+ info: console.log,
32
+ warn: console.warn,
33
+ error: console.error
34
+ }
35
+ }) {
36
+ let attemptNumber = 1;
37
+ while (attemptNumber <= retry) {
38
+ try {
39
+ const result = await Promise.race([
40
+ operation(),
41
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`${name} operation timeout`)), timeout))
42
+ ]);
43
+ logger.info(`${name} success!`);
44
+ return result;
45
+ } catch (error) {
46
+ const wrappedError = error instanceof Error ? error : new Error(String(error));
47
+ logger.warn(`Attempt ${name} ${attemptNumber}/${retry}: ${wrappedError.message}`);
48
+ if (attemptNumber === retry) {
49
+ logger.error(`${name} failed after ${retry} attempts.`);
50
+ throw wrappedError;
51
+ }
52
+ const nextDelay = startingDelay * Math.pow(timeMultiple, attemptNumber - 1);
53
+ logger.warn(`Retrying ${name} in ${nextDelay}ms...`);
54
+ await new Promise((resolve) => setTimeout(resolve, nextDelay));
55
+ attemptNumber++;
56
+ }
57
+ }
58
+ throw new Error(`${name} failed after ${retry} attempts`);
59
+ }
60
+ __name(retryOperation, "retryOperation");
61
+ // Annotate the CommonJS export names for ESM import in node:
62
+ 0 && (module.exports = {
63
+ retryOperation
64
+ });
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@tachybase/cache",
3
+ "version": "0.23.8",
4
+ "description": "",
5
+ "license": "Apache-2.0",
6
+ "main": "./lib/index.js",
7
+ "types": "./lib/index.d.ts",
8
+ "dependencies": {
9
+ "bloom-filters": "^3.0.4",
10
+ "cache-manager": "^5.7.6",
11
+ "cache-manager-redis-yet": "^4.2.0",
12
+ "deepmerge": "^4.3.1",
13
+ "lodash": "4.17.21"
14
+ },
15
+ "devDependencies": {
16
+ "@types/lodash": "^4.17.13",
17
+ "redis": "^4.7.0",
18
+ "vitest": "^1.6.0"
19
+ },
20
+ "scripts": {
21
+ "build": "tachybase-build --no-dts @tachybase/cache"
22
+ }
23
+ }