@objectstack/service-cache 3.0.7
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/.turbo/turbo-build.log +22 -0
- package/CHANGELOG.md +10 -0
- package/LICENSE +202 -0
- package/dist/index.cjs +136 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +109 -0
- package/dist/index.d.ts +109 -0
- package/dist/index.js +107 -0
- package/dist/index.js.map +1 -0
- package/package.json +29 -0
- package/src/cache-service-plugin.ts +63 -0
- package/src/index.ts +8 -0
- package/src/memory-cache-adapter.test.ts +107 -0
- package/src/memory-cache-adapter.ts +90 -0
- package/src/redis-cache-adapter.ts +63 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
> @objectstack/service-cache@3.0.7 build /home/runner/work/spec/spec/packages/services/service-cache
|
|
3
|
+
> tsup --config ../../../tsup.config.ts
|
|
4
|
+
|
|
5
|
+
[34mCLI[39m Building entry: src/index.ts
|
|
6
|
+
[34mCLI[39m Using tsconfig: tsconfig.json
|
|
7
|
+
[34mCLI[39m tsup v8.5.1
|
|
8
|
+
[34mCLI[39m Using tsup config: /home/runner/work/spec/spec/tsup.config.ts
|
|
9
|
+
[34mCLI[39m Target: es2020
|
|
10
|
+
[34mCLI[39m Cleaning output folder
|
|
11
|
+
[34mESM[39m Build start
|
|
12
|
+
[34mCJS[39m Build start
|
|
13
|
+
[32mESM[39m [1mdist/index.js [22m[32m2.98 KB[39m
|
|
14
|
+
[32mESM[39m [1mdist/index.js.map [22m[32m8.94 KB[39m
|
|
15
|
+
[32mESM[39m ⚡️ Build success in 55ms
|
|
16
|
+
[32mCJS[39m [1mdist/index.cjs [22m[32m4.09 KB[39m
|
|
17
|
+
[32mCJS[39m [1mdist/index.cjs.map [22m[32m9.50 KB[39m
|
|
18
|
+
[32mCJS[39m ⚡️ Build success in 58ms
|
|
19
|
+
[34mDTS[39m Build start
|
|
20
|
+
[32mDTS[39m ⚡️ Build success in 13171ms
|
|
21
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m3.56 KB[39m
|
|
22
|
+
[32mDTS[39m [1mdist/index.d.cts [22m[32m3.56 KB[39m
|
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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
|
|
108
|
+
must include a readable copy of the attribution notices
|
|
109
|
+
contained within such NOTICE file, excluding those notices
|
|
110
|
+
that do not pertain to any part of the Derivative Works,
|
|
111
|
+
in at least one of the following places: within a NOTICE
|
|
112
|
+
text file distributed as part of the Derivative Works; within
|
|
113
|
+
the Source form or documentation, if provided along with
|
|
114
|
+
the Derivative Works; or, within a display generated by the
|
|
115
|
+
Derivative Works, if and wherever such third-party notices
|
|
116
|
+
normally appear. The contents of the NOTICE file are for
|
|
117
|
+
informational purposes only and do not modify the License.
|
|
118
|
+
You may add Your own attribution notices within Derivative
|
|
119
|
+
Works that You distribute, alongside or as an addendum to
|
|
120
|
+
the NOTICE text from the Work, provided that such additional
|
|
121
|
+
attribution notices cannot be construed as modifying the
|
|
122
|
+
License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 ObjectStack
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
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
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
CacheServicePlugin: () => CacheServicePlugin,
|
|
24
|
+
MemoryCacheAdapter: () => MemoryCacheAdapter,
|
|
25
|
+
RedisCacheAdapter: () => RedisCacheAdapter
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
|
|
29
|
+
// src/memory-cache-adapter.ts
|
|
30
|
+
var MemoryCacheAdapter = class {
|
|
31
|
+
constructor(options = {}) {
|
|
32
|
+
this.store = /* @__PURE__ */ new Map();
|
|
33
|
+
this.hits = 0;
|
|
34
|
+
this.misses = 0;
|
|
35
|
+
this.maxSize = options.maxSize ?? 0;
|
|
36
|
+
this.defaultTtl = options.defaultTtl ?? 0;
|
|
37
|
+
}
|
|
38
|
+
async get(key) {
|
|
39
|
+
const entry = this.store.get(key);
|
|
40
|
+
if (!entry || entry.expires && Date.now() > entry.expires) {
|
|
41
|
+
if (entry) this.store.delete(key);
|
|
42
|
+
this.misses++;
|
|
43
|
+
return void 0;
|
|
44
|
+
}
|
|
45
|
+
this.hits++;
|
|
46
|
+
return entry.value;
|
|
47
|
+
}
|
|
48
|
+
async set(key, value, ttl) {
|
|
49
|
+
const effectiveTtl = ttl ?? this.defaultTtl;
|
|
50
|
+
if (this.maxSize > 0 && !this.store.has(key) && this.store.size >= this.maxSize) {
|
|
51
|
+
const firstKey = this.store.keys().next().value;
|
|
52
|
+
if (firstKey !== void 0) this.store.delete(firstKey);
|
|
53
|
+
}
|
|
54
|
+
this.store.set(key, {
|
|
55
|
+
value,
|
|
56
|
+
expires: effectiveTtl > 0 ? Date.now() + effectiveTtl * 1e3 : void 0
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
async delete(key) {
|
|
60
|
+
return this.store.delete(key);
|
|
61
|
+
}
|
|
62
|
+
async has(key) {
|
|
63
|
+
const entry = this.store.get(key);
|
|
64
|
+
if (!entry) return false;
|
|
65
|
+
if (entry.expires && Date.now() > entry.expires) {
|
|
66
|
+
this.store.delete(key);
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
async clear() {
|
|
72
|
+
this.store.clear();
|
|
73
|
+
}
|
|
74
|
+
async stats() {
|
|
75
|
+
return {
|
|
76
|
+
hits: this.hits,
|
|
77
|
+
misses: this.misses,
|
|
78
|
+
keyCount: this.store.size
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// src/cache-service-plugin.ts
|
|
84
|
+
var CacheServicePlugin = class {
|
|
85
|
+
constructor(options = {}) {
|
|
86
|
+
this.name = "com.objectstack.service.cache";
|
|
87
|
+
this.version = "1.0.0";
|
|
88
|
+
this.type = "standard";
|
|
89
|
+
this.options = { adapter: "memory", ...options };
|
|
90
|
+
}
|
|
91
|
+
async init(ctx) {
|
|
92
|
+
const adapter = this.options.adapter;
|
|
93
|
+
if (adapter === "redis") {
|
|
94
|
+
throw new Error(
|
|
95
|
+
'Redis cache adapter is not yet implemented. Use adapter: "memory" or provide a custom ICacheService via ctx.registerService("cache", impl).'
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
const cache = new MemoryCacheAdapter(this.options.memory);
|
|
99
|
+
ctx.registerService("cache", cache);
|
|
100
|
+
ctx.logger.info("CacheServicePlugin: registered memory cache adapter");
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// src/redis-cache-adapter.ts
|
|
105
|
+
var RedisCacheAdapter = class {
|
|
106
|
+
constructor(options) {
|
|
107
|
+
this.url = options.url;
|
|
108
|
+
this.keyPrefix = options.keyPrefix ?? "os:";
|
|
109
|
+
this.defaultTtl = options.defaultTtl ?? 0;
|
|
110
|
+
}
|
|
111
|
+
async get(_key) {
|
|
112
|
+
throw new Error(`RedisCacheAdapter not yet implemented (url: ${this.url}, prefix: ${this.keyPrefix}, ttl: ${this.defaultTtl})`);
|
|
113
|
+
}
|
|
114
|
+
async set(_key, _value, _ttl) {
|
|
115
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
116
|
+
}
|
|
117
|
+
async delete(_key) {
|
|
118
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
119
|
+
}
|
|
120
|
+
async has(_key) {
|
|
121
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
122
|
+
}
|
|
123
|
+
async clear() {
|
|
124
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
125
|
+
}
|
|
126
|
+
async stats() {
|
|
127
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
131
|
+
0 && (module.exports = {
|
|
132
|
+
CacheServicePlugin,
|
|
133
|
+
MemoryCacheAdapter,
|
|
134
|
+
RedisCacheAdapter
|
|
135
|
+
});
|
|
136
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/memory-cache-adapter.ts","../src/cache-service-plugin.ts","../src/redis-cache-adapter.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport { CacheServicePlugin } from './cache-service-plugin.js';\nexport type { CacheServicePluginOptions } from './cache-service-plugin.js';\nexport { MemoryCacheAdapter } from './memory-cache-adapter.js';\nexport type { MemoryCacheAdapterOptions } from './memory-cache-adapter.js';\nexport { RedisCacheAdapter } from './redis-cache-adapter.js';\nexport type { RedisCacheAdapterOptions } from './redis-cache-adapter.js';\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ICacheService, CacheStats } from '@objectstack/spec/contracts';\n\n/**\n * In-memory cache entry with optional TTL expiry.\n */\ninterface CacheEntry<T = unknown> {\n value: T;\n expires?: number;\n}\n\n/**\n * Configuration options for MemoryCacheAdapter.\n */\nexport interface MemoryCacheAdapterOptions {\n /** Maximum number of entries before eviction (0 = unlimited) */\n maxSize?: number;\n /** Default TTL in seconds (0 = no expiry) */\n defaultTtl?: number;\n}\n\n/**\n * In-memory cache adapter implementing ICacheService.\n *\n * Uses a Map-backed store with TTL-based expiry and LRU-style eviction.\n * Suitable for single-process environments, development, and testing.\n */\nexport class MemoryCacheAdapter implements ICacheService {\n private readonly store = new Map<string, CacheEntry>();\n private hits = 0;\n private misses = 0;\n private readonly maxSize: number;\n private readonly defaultTtl: number;\n\n constructor(options: MemoryCacheAdapterOptions = {}) {\n this.maxSize = options.maxSize ?? 0;\n this.defaultTtl = options.defaultTtl ?? 0;\n }\n\n async get<T = unknown>(key: string): Promise<T | undefined> {\n const entry = this.store.get(key);\n if (!entry || (entry.expires && Date.now() > entry.expires)) {\n if (entry) this.store.delete(key);\n this.misses++;\n return undefined;\n }\n this.hits++;\n return entry.value as T;\n }\n\n async set<T = unknown>(key: string, value: T, ttl?: number): Promise<void> {\n const effectiveTtl = ttl ?? this.defaultTtl;\n if (this.maxSize > 0 && !this.store.has(key) && this.store.size >= this.maxSize) {\n // Evict oldest entry (first key in Map insertion order)\n const firstKey = this.store.keys().next().value;\n if (firstKey !== undefined) this.store.delete(firstKey);\n }\n this.store.set(key, {\n value,\n expires: effectiveTtl > 0 ? Date.now() + effectiveTtl * 1000 : undefined,\n });\n }\n\n async delete(key: string): Promise<boolean> {\n return this.store.delete(key);\n }\n\n async has(key: string): Promise<boolean> {\n const entry = this.store.get(key);\n if (!entry) return false;\n if (entry.expires && Date.now() > entry.expires) {\n this.store.delete(key);\n return false;\n }\n return true;\n }\n\n async clear(): Promise<void> {\n this.store.clear();\n }\n\n async stats(): Promise<CacheStats> {\n return {\n hits: this.hits,\n misses: this.misses,\n keyCount: this.store.size,\n };\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { MemoryCacheAdapter } from './memory-cache-adapter.js';\nimport type { MemoryCacheAdapterOptions } from './memory-cache-adapter.js';\n\n/**\n * Configuration options for the CacheServicePlugin.\n */\nexport interface CacheServicePluginOptions {\n /** Cache adapter type (default: 'memory') */\n adapter?: 'memory' | 'redis';\n /** Options for the memory cache adapter */\n memory?: MemoryCacheAdapterOptions;\n /** Redis connection URL (used when adapter is 'redis') */\n redisUrl?: string;\n}\n\n/**\n * CacheServicePlugin — Production ICacheService implementation.\n *\n * Registers a cache service with the kernel during the init phase.\n * Supports in-memory and Redis adapters.\n *\n * @example\n * ```ts\n * import { ObjectKernel } from '@objectstack/core';\n * import { CacheServicePlugin } from '@objectstack/service-cache';\n *\n * const kernel = new ObjectKernel();\n * kernel.use(new CacheServicePlugin({ adapter: 'memory', memory: { maxSize: 1000 } }));\n * await kernel.bootstrap();\n *\n * const cache = kernel.getService('cache');\n * await cache.set('key', 'value', 60);\n * ```\n */\nexport class CacheServicePlugin implements Plugin {\n name = 'com.objectstack.service.cache';\n version = '1.0.0';\n type = 'standard';\n\n private readonly options: CacheServicePluginOptions;\n\n constructor(options: CacheServicePluginOptions = {}) {\n this.options = { adapter: 'memory', ...options };\n }\n\n async init(ctx: PluginContext): Promise<void> {\n const adapter = this.options.adapter;\n if (adapter === 'redis') {\n // Redis adapter is a skeleton — throw an informative error for now\n throw new Error(\n 'Redis cache adapter is not yet implemented. ' +\n 'Use adapter: \"memory\" or provide a custom ICacheService via ctx.registerService(\"cache\", impl).'\n );\n }\n\n const cache = new MemoryCacheAdapter(this.options.memory);\n ctx.registerService('cache', cache);\n ctx.logger.info('CacheServicePlugin: registered memory cache adapter');\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ICacheService, CacheStats } from '@objectstack/spec/contracts';\n\n/**\n * Configuration for the Redis cache adapter.\n */\nexport interface RedisCacheAdapterOptions {\n /** Redis connection URL (e.g. 'redis://localhost:6379') */\n url: string;\n /** Key prefix for namespacing (default: 'os:') */\n keyPrefix?: string;\n /** Default TTL in seconds (0 = no expiry) */\n defaultTtl?: number;\n}\n\n/**\n * Redis cache adapter skeleton implementing ICacheService.\n *\n * This is a placeholder for future Redis integration.\n * Concrete implementation will use `ioredis` or `redis` client.\n *\n * @example\n * ```ts\n * const cache = new RedisCacheAdapter({ url: 'redis://localhost:6379' });\n * await cache.set('user:1', { name: 'Alice' }, 3600);\n * ```\n */\nexport class RedisCacheAdapter implements ICacheService {\n private readonly url: string;\n private readonly keyPrefix: string;\n private readonly defaultTtl: number;\n\n constructor(options: RedisCacheAdapterOptions) {\n this.url = options.url;\n this.keyPrefix = options.keyPrefix ?? 'os:';\n this.defaultTtl = options.defaultTtl ?? 0;\n }\n\n async get<T = unknown>(_key: string): Promise<T | undefined> {\n throw new Error(`RedisCacheAdapter not yet implemented (url: ${this.url}, prefix: ${this.keyPrefix}, ttl: ${this.defaultTtl})`);\n }\n\n async set<T = unknown>(_key: string, _value: T, _ttl?: number): Promise<void> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n\n async delete(_key: string): Promise<boolean> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n\n async has(_key: string): Promise<boolean> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n\n async clear(): Promise<void> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n\n async stats(): Promise<CacheStats> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n}\n"],"mappings":"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","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { Plugin, PluginContext } from '@objectstack/core';
|
|
2
|
+
import { ICacheService, CacheStats } from '@objectstack/spec/contracts';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Configuration options for MemoryCacheAdapter.
|
|
6
|
+
*/
|
|
7
|
+
interface MemoryCacheAdapterOptions {
|
|
8
|
+
/** Maximum number of entries before eviction (0 = unlimited) */
|
|
9
|
+
maxSize?: number;
|
|
10
|
+
/** Default TTL in seconds (0 = no expiry) */
|
|
11
|
+
defaultTtl?: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* In-memory cache adapter implementing ICacheService.
|
|
15
|
+
*
|
|
16
|
+
* Uses a Map-backed store with TTL-based expiry and LRU-style eviction.
|
|
17
|
+
* Suitable for single-process environments, development, and testing.
|
|
18
|
+
*/
|
|
19
|
+
declare class MemoryCacheAdapter implements ICacheService {
|
|
20
|
+
private readonly store;
|
|
21
|
+
private hits;
|
|
22
|
+
private misses;
|
|
23
|
+
private readonly maxSize;
|
|
24
|
+
private readonly defaultTtl;
|
|
25
|
+
constructor(options?: MemoryCacheAdapterOptions);
|
|
26
|
+
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
27
|
+
set<T = unknown>(key: string, value: T, ttl?: number): Promise<void>;
|
|
28
|
+
delete(key: string): Promise<boolean>;
|
|
29
|
+
has(key: string): Promise<boolean>;
|
|
30
|
+
clear(): Promise<void>;
|
|
31
|
+
stats(): Promise<CacheStats>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Configuration options for the CacheServicePlugin.
|
|
36
|
+
*/
|
|
37
|
+
interface CacheServicePluginOptions {
|
|
38
|
+
/** Cache adapter type (default: 'memory') */
|
|
39
|
+
adapter?: 'memory' | 'redis';
|
|
40
|
+
/** Options for the memory cache adapter */
|
|
41
|
+
memory?: MemoryCacheAdapterOptions;
|
|
42
|
+
/** Redis connection URL (used when adapter is 'redis') */
|
|
43
|
+
redisUrl?: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* CacheServicePlugin — Production ICacheService implementation.
|
|
47
|
+
*
|
|
48
|
+
* Registers a cache service with the kernel during the init phase.
|
|
49
|
+
* Supports in-memory and Redis adapters.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* import { ObjectKernel } from '@objectstack/core';
|
|
54
|
+
* import { CacheServicePlugin } from '@objectstack/service-cache';
|
|
55
|
+
*
|
|
56
|
+
* const kernel = new ObjectKernel();
|
|
57
|
+
* kernel.use(new CacheServicePlugin({ adapter: 'memory', memory: { maxSize: 1000 } }));
|
|
58
|
+
* await kernel.bootstrap();
|
|
59
|
+
*
|
|
60
|
+
* const cache = kernel.getService('cache');
|
|
61
|
+
* await cache.set('key', 'value', 60);
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
declare class CacheServicePlugin implements Plugin {
|
|
65
|
+
name: string;
|
|
66
|
+
version: string;
|
|
67
|
+
type: string;
|
|
68
|
+
private readonly options;
|
|
69
|
+
constructor(options?: CacheServicePluginOptions);
|
|
70
|
+
init(ctx: PluginContext): Promise<void>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Configuration for the Redis cache adapter.
|
|
75
|
+
*/
|
|
76
|
+
interface RedisCacheAdapterOptions {
|
|
77
|
+
/** Redis connection URL (e.g. 'redis://localhost:6379') */
|
|
78
|
+
url: string;
|
|
79
|
+
/** Key prefix for namespacing (default: 'os:') */
|
|
80
|
+
keyPrefix?: string;
|
|
81
|
+
/** Default TTL in seconds (0 = no expiry) */
|
|
82
|
+
defaultTtl?: number;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Redis cache adapter skeleton implementing ICacheService.
|
|
86
|
+
*
|
|
87
|
+
* This is a placeholder for future Redis integration.
|
|
88
|
+
* Concrete implementation will use `ioredis` or `redis` client.
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* ```ts
|
|
92
|
+
* const cache = new RedisCacheAdapter({ url: 'redis://localhost:6379' });
|
|
93
|
+
* await cache.set('user:1', { name: 'Alice' }, 3600);
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
declare class RedisCacheAdapter implements ICacheService {
|
|
97
|
+
private readonly url;
|
|
98
|
+
private readonly keyPrefix;
|
|
99
|
+
private readonly defaultTtl;
|
|
100
|
+
constructor(options: RedisCacheAdapterOptions);
|
|
101
|
+
get<T = unknown>(_key: string): Promise<T | undefined>;
|
|
102
|
+
set<T = unknown>(_key: string, _value: T, _ttl?: number): Promise<void>;
|
|
103
|
+
delete(_key: string): Promise<boolean>;
|
|
104
|
+
has(_key: string): Promise<boolean>;
|
|
105
|
+
clear(): Promise<void>;
|
|
106
|
+
stats(): Promise<CacheStats>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export { CacheServicePlugin, type CacheServicePluginOptions, MemoryCacheAdapter, type MemoryCacheAdapterOptions, RedisCacheAdapter, type RedisCacheAdapterOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { Plugin, PluginContext } from '@objectstack/core';
|
|
2
|
+
import { ICacheService, CacheStats } from '@objectstack/spec/contracts';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Configuration options for MemoryCacheAdapter.
|
|
6
|
+
*/
|
|
7
|
+
interface MemoryCacheAdapterOptions {
|
|
8
|
+
/** Maximum number of entries before eviction (0 = unlimited) */
|
|
9
|
+
maxSize?: number;
|
|
10
|
+
/** Default TTL in seconds (0 = no expiry) */
|
|
11
|
+
defaultTtl?: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* In-memory cache adapter implementing ICacheService.
|
|
15
|
+
*
|
|
16
|
+
* Uses a Map-backed store with TTL-based expiry and LRU-style eviction.
|
|
17
|
+
* Suitable for single-process environments, development, and testing.
|
|
18
|
+
*/
|
|
19
|
+
declare class MemoryCacheAdapter implements ICacheService {
|
|
20
|
+
private readonly store;
|
|
21
|
+
private hits;
|
|
22
|
+
private misses;
|
|
23
|
+
private readonly maxSize;
|
|
24
|
+
private readonly defaultTtl;
|
|
25
|
+
constructor(options?: MemoryCacheAdapterOptions);
|
|
26
|
+
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
27
|
+
set<T = unknown>(key: string, value: T, ttl?: number): Promise<void>;
|
|
28
|
+
delete(key: string): Promise<boolean>;
|
|
29
|
+
has(key: string): Promise<boolean>;
|
|
30
|
+
clear(): Promise<void>;
|
|
31
|
+
stats(): Promise<CacheStats>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Configuration options for the CacheServicePlugin.
|
|
36
|
+
*/
|
|
37
|
+
interface CacheServicePluginOptions {
|
|
38
|
+
/** Cache adapter type (default: 'memory') */
|
|
39
|
+
adapter?: 'memory' | 'redis';
|
|
40
|
+
/** Options for the memory cache adapter */
|
|
41
|
+
memory?: MemoryCacheAdapterOptions;
|
|
42
|
+
/** Redis connection URL (used when adapter is 'redis') */
|
|
43
|
+
redisUrl?: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* CacheServicePlugin — Production ICacheService implementation.
|
|
47
|
+
*
|
|
48
|
+
* Registers a cache service with the kernel during the init phase.
|
|
49
|
+
* Supports in-memory and Redis adapters.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* import { ObjectKernel } from '@objectstack/core';
|
|
54
|
+
* import { CacheServicePlugin } from '@objectstack/service-cache';
|
|
55
|
+
*
|
|
56
|
+
* const kernel = new ObjectKernel();
|
|
57
|
+
* kernel.use(new CacheServicePlugin({ adapter: 'memory', memory: { maxSize: 1000 } }));
|
|
58
|
+
* await kernel.bootstrap();
|
|
59
|
+
*
|
|
60
|
+
* const cache = kernel.getService('cache');
|
|
61
|
+
* await cache.set('key', 'value', 60);
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
declare class CacheServicePlugin implements Plugin {
|
|
65
|
+
name: string;
|
|
66
|
+
version: string;
|
|
67
|
+
type: string;
|
|
68
|
+
private readonly options;
|
|
69
|
+
constructor(options?: CacheServicePluginOptions);
|
|
70
|
+
init(ctx: PluginContext): Promise<void>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Configuration for the Redis cache adapter.
|
|
75
|
+
*/
|
|
76
|
+
interface RedisCacheAdapterOptions {
|
|
77
|
+
/** Redis connection URL (e.g. 'redis://localhost:6379') */
|
|
78
|
+
url: string;
|
|
79
|
+
/** Key prefix for namespacing (default: 'os:') */
|
|
80
|
+
keyPrefix?: string;
|
|
81
|
+
/** Default TTL in seconds (0 = no expiry) */
|
|
82
|
+
defaultTtl?: number;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Redis cache adapter skeleton implementing ICacheService.
|
|
86
|
+
*
|
|
87
|
+
* This is a placeholder for future Redis integration.
|
|
88
|
+
* Concrete implementation will use `ioredis` or `redis` client.
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* ```ts
|
|
92
|
+
* const cache = new RedisCacheAdapter({ url: 'redis://localhost:6379' });
|
|
93
|
+
* await cache.set('user:1', { name: 'Alice' }, 3600);
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
declare class RedisCacheAdapter implements ICacheService {
|
|
97
|
+
private readonly url;
|
|
98
|
+
private readonly keyPrefix;
|
|
99
|
+
private readonly defaultTtl;
|
|
100
|
+
constructor(options: RedisCacheAdapterOptions);
|
|
101
|
+
get<T = unknown>(_key: string): Promise<T | undefined>;
|
|
102
|
+
set<T = unknown>(_key: string, _value: T, _ttl?: number): Promise<void>;
|
|
103
|
+
delete(_key: string): Promise<boolean>;
|
|
104
|
+
has(_key: string): Promise<boolean>;
|
|
105
|
+
clear(): Promise<void>;
|
|
106
|
+
stats(): Promise<CacheStats>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export { CacheServicePlugin, type CacheServicePluginOptions, MemoryCacheAdapter, type MemoryCacheAdapterOptions, RedisCacheAdapter, type RedisCacheAdapterOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// src/memory-cache-adapter.ts
|
|
2
|
+
var MemoryCacheAdapter = class {
|
|
3
|
+
constructor(options = {}) {
|
|
4
|
+
this.store = /* @__PURE__ */ new Map();
|
|
5
|
+
this.hits = 0;
|
|
6
|
+
this.misses = 0;
|
|
7
|
+
this.maxSize = options.maxSize ?? 0;
|
|
8
|
+
this.defaultTtl = options.defaultTtl ?? 0;
|
|
9
|
+
}
|
|
10
|
+
async get(key) {
|
|
11
|
+
const entry = this.store.get(key);
|
|
12
|
+
if (!entry || entry.expires && Date.now() > entry.expires) {
|
|
13
|
+
if (entry) this.store.delete(key);
|
|
14
|
+
this.misses++;
|
|
15
|
+
return void 0;
|
|
16
|
+
}
|
|
17
|
+
this.hits++;
|
|
18
|
+
return entry.value;
|
|
19
|
+
}
|
|
20
|
+
async set(key, value, ttl) {
|
|
21
|
+
const effectiveTtl = ttl ?? this.defaultTtl;
|
|
22
|
+
if (this.maxSize > 0 && !this.store.has(key) && this.store.size >= this.maxSize) {
|
|
23
|
+
const firstKey = this.store.keys().next().value;
|
|
24
|
+
if (firstKey !== void 0) this.store.delete(firstKey);
|
|
25
|
+
}
|
|
26
|
+
this.store.set(key, {
|
|
27
|
+
value,
|
|
28
|
+
expires: effectiveTtl > 0 ? Date.now() + effectiveTtl * 1e3 : void 0
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
async delete(key) {
|
|
32
|
+
return this.store.delete(key);
|
|
33
|
+
}
|
|
34
|
+
async has(key) {
|
|
35
|
+
const entry = this.store.get(key);
|
|
36
|
+
if (!entry) return false;
|
|
37
|
+
if (entry.expires && Date.now() > entry.expires) {
|
|
38
|
+
this.store.delete(key);
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
async clear() {
|
|
44
|
+
this.store.clear();
|
|
45
|
+
}
|
|
46
|
+
async stats() {
|
|
47
|
+
return {
|
|
48
|
+
hits: this.hits,
|
|
49
|
+
misses: this.misses,
|
|
50
|
+
keyCount: this.store.size
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// src/cache-service-plugin.ts
|
|
56
|
+
var CacheServicePlugin = class {
|
|
57
|
+
constructor(options = {}) {
|
|
58
|
+
this.name = "com.objectstack.service.cache";
|
|
59
|
+
this.version = "1.0.0";
|
|
60
|
+
this.type = "standard";
|
|
61
|
+
this.options = { adapter: "memory", ...options };
|
|
62
|
+
}
|
|
63
|
+
async init(ctx) {
|
|
64
|
+
const adapter = this.options.adapter;
|
|
65
|
+
if (adapter === "redis") {
|
|
66
|
+
throw new Error(
|
|
67
|
+
'Redis cache adapter is not yet implemented. Use adapter: "memory" or provide a custom ICacheService via ctx.registerService("cache", impl).'
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
const cache = new MemoryCacheAdapter(this.options.memory);
|
|
71
|
+
ctx.registerService("cache", cache);
|
|
72
|
+
ctx.logger.info("CacheServicePlugin: registered memory cache adapter");
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// src/redis-cache-adapter.ts
|
|
77
|
+
var RedisCacheAdapter = class {
|
|
78
|
+
constructor(options) {
|
|
79
|
+
this.url = options.url;
|
|
80
|
+
this.keyPrefix = options.keyPrefix ?? "os:";
|
|
81
|
+
this.defaultTtl = options.defaultTtl ?? 0;
|
|
82
|
+
}
|
|
83
|
+
async get(_key) {
|
|
84
|
+
throw new Error(`RedisCacheAdapter not yet implemented (url: ${this.url}, prefix: ${this.keyPrefix}, ttl: ${this.defaultTtl})`);
|
|
85
|
+
}
|
|
86
|
+
async set(_key, _value, _ttl) {
|
|
87
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
88
|
+
}
|
|
89
|
+
async delete(_key) {
|
|
90
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
91
|
+
}
|
|
92
|
+
async has(_key) {
|
|
93
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
94
|
+
}
|
|
95
|
+
async clear() {
|
|
96
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
97
|
+
}
|
|
98
|
+
async stats() {
|
|
99
|
+
throw new Error("RedisCacheAdapter not yet implemented");
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
export {
|
|
103
|
+
CacheServicePlugin,
|
|
104
|
+
MemoryCacheAdapter,
|
|
105
|
+
RedisCacheAdapter
|
|
106
|
+
};
|
|
107
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/memory-cache-adapter.ts","../src/cache-service-plugin.ts","../src/redis-cache-adapter.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ICacheService, CacheStats } from '@objectstack/spec/contracts';\n\n/**\n * In-memory cache entry with optional TTL expiry.\n */\ninterface CacheEntry<T = unknown> {\n value: T;\n expires?: number;\n}\n\n/**\n * Configuration options for MemoryCacheAdapter.\n */\nexport interface MemoryCacheAdapterOptions {\n /** Maximum number of entries before eviction (0 = unlimited) */\n maxSize?: number;\n /** Default TTL in seconds (0 = no expiry) */\n defaultTtl?: number;\n}\n\n/**\n * In-memory cache adapter implementing ICacheService.\n *\n * Uses a Map-backed store with TTL-based expiry and LRU-style eviction.\n * Suitable for single-process environments, development, and testing.\n */\nexport class MemoryCacheAdapter implements ICacheService {\n private readonly store = new Map<string, CacheEntry>();\n private hits = 0;\n private misses = 0;\n private readonly maxSize: number;\n private readonly defaultTtl: number;\n\n constructor(options: MemoryCacheAdapterOptions = {}) {\n this.maxSize = options.maxSize ?? 0;\n this.defaultTtl = options.defaultTtl ?? 0;\n }\n\n async get<T = unknown>(key: string): Promise<T | undefined> {\n const entry = this.store.get(key);\n if (!entry || (entry.expires && Date.now() > entry.expires)) {\n if (entry) this.store.delete(key);\n this.misses++;\n return undefined;\n }\n this.hits++;\n return entry.value as T;\n }\n\n async set<T = unknown>(key: string, value: T, ttl?: number): Promise<void> {\n const effectiveTtl = ttl ?? this.defaultTtl;\n if (this.maxSize > 0 && !this.store.has(key) && this.store.size >= this.maxSize) {\n // Evict oldest entry (first key in Map insertion order)\n const firstKey = this.store.keys().next().value;\n if (firstKey !== undefined) this.store.delete(firstKey);\n }\n this.store.set(key, {\n value,\n expires: effectiveTtl > 0 ? Date.now() + effectiveTtl * 1000 : undefined,\n });\n }\n\n async delete(key: string): Promise<boolean> {\n return this.store.delete(key);\n }\n\n async has(key: string): Promise<boolean> {\n const entry = this.store.get(key);\n if (!entry) return false;\n if (entry.expires && Date.now() > entry.expires) {\n this.store.delete(key);\n return false;\n }\n return true;\n }\n\n async clear(): Promise<void> {\n this.store.clear();\n }\n\n async stats(): Promise<CacheStats> {\n return {\n hits: this.hits,\n misses: this.misses,\n keyCount: this.store.size,\n };\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { MemoryCacheAdapter } from './memory-cache-adapter.js';\nimport type { MemoryCacheAdapterOptions } from './memory-cache-adapter.js';\n\n/**\n * Configuration options for the CacheServicePlugin.\n */\nexport interface CacheServicePluginOptions {\n /** Cache adapter type (default: 'memory') */\n adapter?: 'memory' | 'redis';\n /** Options for the memory cache adapter */\n memory?: MemoryCacheAdapterOptions;\n /** Redis connection URL (used when adapter is 'redis') */\n redisUrl?: string;\n}\n\n/**\n * CacheServicePlugin — Production ICacheService implementation.\n *\n * Registers a cache service with the kernel during the init phase.\n * Supports in-memory and Redis adapters.\n *\n * @example\n * ```ts\n * import { ObjectKernel } from '@objectstack/core';\n * import { CacheServicePlugin } from '@objectstack/service-cache';\n *\n * const kernel = new ObjectKernel();\n * kernel.use(new CacheServicePlugin({ adapter: 'memory', memory: { maxSize: 1000 } }));\n * await kernel.bootstrap();\n *\n * const cache = kernel.getService('cache');\n * await cache.set('key', 'value', 60);\n * ```\n */\nexport class CacheServicePlugin implements Plugin {\n name = 'com.objectstack.service.cache';\n version = '1.0.0';\n type = 'standard';\n\n private readonly options: CacheServicePluginOptions;\n\n constructor(options: CacheServicePluginOptions = {}) {\n this.options = { adapter: 'memory', ...options };\n }\n\n async init(ctx: PluginContext): Promise<void> {\n const adapter = this.options.adapter;\n if (adapter === 'redis') {\n // Redis adapter is a skeleton — throw an informative error for now\n throw new Error(\n 'Redis cache adapter is not yet implemented. ' +\n 'Use adapter: \"memory\" or provide a custom ICacheService via ctx.registerService(\"cache\", impl).'\n );\n }\n\n const cache = new MemoryCacheAdapter(this.options.memory);\n ctx.registerService('cache', cache);\n ctx.logger.info('CacheServicePlugin: registered memory cache adapter');\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { ICacheService, CacheStats } from '@objectstack/spec/contracts';\n\n/**\n * Configuration for the Redis cache adapter.\n */\nexport interface RedisCacheAdapterOptions {\n /** Redis connection URL (e.g. 'redis://localhost:6379') */\n url: string;\n /** Key prefix for namespacing (default: 'os:') */\n keyPrefix?: string;\n /** Default TTL in seconds (0 = no expiry) */\n defaultTtl?: number;\n}\n\n/**\n * Redis cache adapter skeleton implementing ICacheService.\n *\n * This is a placeholder for future Redis integration.\n * Concrete implementation will use `ioredis` or `redis` client.\n *\n * @example\n * ```ts\n * const cache = new RedisCacheAdapter({ url: 'redis://localhost:6379' });\n * await cache.set('user:1', { name: 'Alice' }, 3600);\n * ```\n */\nexport class RedisCacheAdapter implements ICacheService {\n private readonly url: string;\n private readonly keyPrefix: string;\n private readonly defaultTtl: number;\n\n constructor(options: RedisCacheAdapterOptions) {\n this.url = options.url;\n this.keyPrefix = options.keyPrefix ?? 'os:';\n this.defaultTtl = options.defaultTtl ?? 0;\n }\n\n async get<T = unknown>(_key: string): Promise<T | undefined> {\n throw new Error(`RedisCacheAdapter not yet implemented (url: ${this.url}, prefix: ${this.keyPrefix}, ttl: ${this.defaultTtl})`);\n }\n\n async set<T = unknown>(_key: string, _value: T, _ttl?: number): Promise<void> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n\n async delete(_key: string): Promise<boolean> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n\n async has(_key: string): Promise<boolean> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n\n async clear(): Promise<void> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n\n async stats(): Promise<CacheStats> {\n throw new Error('RedisCacheAdapter not yet implemented');\n }\n}\n"],"mappings":"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","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@objectstack/service-cache",
|
|
3
|
+
"version": "3.0.7",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"description": "Cache Service for ObjectStack — implements ICacheService with in-memory and Redis adapters",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.mjs",
|
|
13
|
+
"require": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@objectstack/core": "3.0.7",
|
|
18
|
+
"@objectstack/spec": "3.0.7"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"typescript": "^5.0.0",
|
|
22
|
+
"vitest": "^4.0.18",
|
|
23
|
+
"@types/node": "^25.2.3"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsup --config ../../../tsup.config.ts",
|
|
27
|
+
"test": "vitest run"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import type { Plugin, PluginContext } from '@objectstack/core';
|
|
4
|
+
import { MemoryCacheAdapter } from './memory-cache-adapter.js';
|
|
5
|
+
import type { MemoryCacheAdapterOptions } from './memory-cache-adapter.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Configuration options for the CacheServicePlugin.
|
|
9
|
+
*/
|
|
10
|
+
export interface CacheServicePluginOptions {
|
|
11
|
+
/** Cache adapter type (default: 'memory') */
|
|
12
|
+
adapter?: 'memory' | 'redis';
|
|
13
|
+
/** Options for the memory cache adapter */
|
|
14
|
+
memory?: MemoryCacheAdapterOptions;
|
|
15
|
+
/** Redis connection URL (used when adapter is 'redis') */
|
|
16
|
+
redisUrl?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* CacheServicePlugin — Production ICacheService implementation.
|
|
21
|
+
*
|
|
22
|
+
* Registers a cache service with the kernel during the init phase.
|
|
23
|
+
* Supports in-memory and Redis adapters.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* import { ObjectKernel } from '@objectstack/core';
|
|
28
|
+
* import { CacheServicePlugin } from '@objectstack/service-cache';
|
|
29
|
+
*
|
|
30
|
+
* const kernel = new ObjectKernel();
|
|
31
|
+
* kernel.use(new CacheServicePlugin({ adapter: 'memory', memory: { maxSize: 1000 } }));
|
|
32
|
+
* await kernel.bootstrap();
|
|
33
|
+
*
|
|
34
|
+
* const cache = kernel.getService('cache');
|
|
35
|
+
* await cache.set('key', 'value', 60);
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export class CacheServicePlugin implements Plugin {
|
|
39
|
+
name = 'com.objectstack.service.cache';
|
|
40
|
+
version = '1.0.0';
|
|
41
|
+
type = 'standard';
|
|
42
|
+
|
|
43
|
+
private readonly options: CacheServicePluginOptions;
|
|
44
|
+
|
|
45
|
+
constructor(options: CacheServicePluginOptions = {}) {
|
|
46
|
+
this.options = { adapter: 'memory', ...options };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async init(ctx: PluginContext): Promise<void> {
|
|
50
|
+
const adapter = this.options.adapter;
|
|
51
|
+
if (adapter === 'redis') {
|
|
52
|
+
// Redis adapter is a skeleton — throw an informative error for now
|
|
53
|
+
throw new Error(
|
|
54
|
+
'Redis cache adapter is not yet implemented. ' +
|
|
55
|
+
'Use adapter: "memory" or provide a custom ICacheService via ctx.registerService("cache", impl).'
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const cache = new MemoryCacheAdapter(this.options.memory);
|
|
60
|
+
ctx.registerService('cache', cache);
|
|
61
|
+
ctx.logger.info('CacheServicePlugin: registered memory cache adapter');
|
|
62
|
+
}
|
|
63
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
export { CacheServicePlugin } from './cache-service-plugin.js';
|
|
4
|
+
export type { CacheServicePluginOptions } from './cache-service-plugin.js';
|
|
5
|
+
export { MemoryCacheAdapter } from './memory-cache-adapter.js';
|
|
6
|
+
export type { MemoryCacheAdapterOptions } from './memory-cache-adapter.js';
|
|
7
|
+
export { RedisCacheAdapter } from './redis-cache-adapter.js';
|
|
8
|
+
export type { RedisCacheAdapterOptions } from './redis-cache-adapter.js';
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect } from 'vitest';
|
|
4
|
+
import { MemoryCacheAdapter } from './memory-cache-adapter';
|
|
5
|
+
import type { ICacheService } from '@objectstack/spec/contracts';
|
|
6
|
+
|
|
7
|
+
describe('MemoryCacheAdapter', () => {
|
|
8
|
+
it('should implement ICacheService contract', () => {
|
|
9
|
+
const cache: ICacheService = new MemoryCacheAdapter();
|
|
10
|
+
expect(typeof cache.get).toBe('function');
|
|
11
|
+
expect(typeof cache.set).toBe('function');
|
|
12
|
+
expect(typeof cache.delete).toBe('function');
|
|
13
|
+
expect(typeof cache.has).toBe('function');
|
|
14
|
+
expect(typeof cache.clear).toBe('function');
|
|
15
|
+
expect(typeof cache.stats).toBe('function');
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('should set and get a value', async () => {
|
|
19
|
+
const cache = new MemoryCacheAdapter();
|
|
20
|
+
await cache.set('key1', 'value1');
|
|
21
|
+
expect(await cache.get('key1')).toBe('value1');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('should return undefined for missing key', async () => {
|
|
25
|
+
const cache = new MemoryCacheAdapter();
|
|
26
|
+
expect(await cache.get('nonexistent')).toBeUndefined();
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('should delete a key', async () => {
|
|
30
|
+
const cache = new MemoryCacheAdapter();
|
|
31
|
+
await cache.set('key1', 'value1');
|
|
32
|
+
expect(await cache.delete('key1')).toBe(true);
|
|
33
|
+
expect(await cache.get('key1')).toBeUndefined();
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('should return false when deleting missing key', async () => {
|
|
37
|
+
const cache = new MemoryCacheAdapter();
|
|
38
|
+
expect(await cache.delete('missing')).toBe(false);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('should check if a key exists with has()', async () => {
|
|
42
|
+
const cache = new MemoryCacheAdapter();
|
|
43
|
+
expect(await cache.has('key1')).toBe(false);
|
|
44
|
+
await cache.set('key1', 'value1');
|
|
45
|
+
expect(await cache.has('key1')).toBe(true);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('should clear all entries', async () => {
|
|
49
|
+
const cache = new MemoryCacheAdapter();
|
|
50
|
+
await cache.set('a', 1);
|
|
51
|
+
await cache.set('b', 2);
|
|
52
|
+
await cache.clear();
|
|
53
|
+
expect(await cache.has('a')).toBe(false);
|
|
54
|
+
expect(await cache.has('b')).toBe(false);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('should expire entries based on TTL', async () => {
|
|
58
|
+
const cache = new MemoryCacheAdapter();
|
|
59
|
+
await cache.set('temp', 'data', 0.001); // 1ms TTL
|
|
60
|
+
await new Promise(r => setTimeout(r, 20));
|
|
61
|
+
expect(await cache.get('temp')).toBeUndefined();
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('should track hit/miss stats', async () => {
|
|
65
|
+
const cache = new MemoryCacheAdapter();
|
|
66
|
+
await cache.set('key1', 'value1');
|
|
67
|
+
await cache.get('key1'); // hit
|
|
68
|
+
await cache.get('missing'); // miss
|
|
69
|
+
const stats = await cache.stats();
|
|
70
|
+
expect(stats.hits).toBe(1);
|
|
71
|
+
expect(stats.misses).toBe(1);
|
|
72
|
+
expect(stats.keyCount).toBe(1);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('should apply defaultTtl when no TTL is provided', async () => {
|
|
76
|
+
const cache = new MemoryCacheAdapter({ defaultTtl: 0.001 });
|
|
77
|
+
await cache.set('key', 'value');
|
|
78
|
+
await new Promise(r => setTimeout(r, 20));
|
|
79
|
+
expect(await cache.get('key')).toBeUndefined();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('should evict oldest entry when maxSize is reached', async () => {
|
|
83
|
+
const cache = new MemoryCacheAdapter({ maxSize: 2 });
|
|
84
|
+
await cache.set('a', 1);
|
|
85
|
+
await cache.set('b', 2);
|
|
86
|
+
await cache.set('c', 3); // should evict 'a'
|
|
87
|
+
expect(await cache.has('a')).toBe(false);
|
|
88
|
+
expect(await cache.get('b')).toBe(2);
|
|
89
|
+
expect(await cache.get('c')).toBe(3);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('should not evict when updating existing key at maxSize', async () => {
|
|
93
|
+
const cache = new MemoryCacheAdapter({ maxSize: 2 });
|
|
94
|
+
await cache.set('a', 1);
|
|
95
|
+
await cache.set('b', 2);
|
|
96
|
+
await cache.set('a', 10); // update, not new entry
|
|
97
|
+
expect(await cache.get('a')).toBe(10);
|
|
98
|
+
expect(await cache.get('b')).toBe(2);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('should handle has() with expired TTL', async () => {
|
|
102
|
+
const cache = new MemoryCacheAdapter();
|
|
103
|
+
await cache.set('expiring', 'val', 0.001);
|
|
104
|
+
await new Promise(r => setTimeout(r, 20));
|
|
105
|
+
expect(await cache.has('expiring')).toBe(false);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import type { ICacheService, CacheStats } from '@objectstack/spec/contracts';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* In-memory cache entry with optional TTL expiry.
|
|
7
|
+
*/
|
|
8
|
+
interface CacheEntry<T = unknown> {
|
|
9
|
+
value: T;
|
|
10
|
+
expires?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Configuration options for MemoryCacheAdapter.
|
|
15
|
+
*/
|
|
16
|
+
export interface MemoryCacheAdapterOptions {
|
|
17
|
+
/** Maximum number of entries before eviction (0 = unlimited) */
|
|
18
|
+
maxSize?: number;
|
|
19
|
+
/** Default TTL in seconds (0 = no expiry) */
|
|
20
|
+
defaultTtl?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* In-memory cache adapter implementing ICacheService.
|
|
25
|
+
*
|
|
26
|
+
* Uses a Map-backed store with TTL-based expiry and LRU-style eviction.
|
|
27
|
+
* Suitable for single-process environments, development, and testing.
|
|
28
|
+
*/
|
|
29
|
+
export class MemoryCacheAdapter implements ICacheService {
|
|
30
|
+
private readonly store = new Map<string, CacheEntry>();
|
|
31
|
+
private hits = 0;
|
|
32
|
+
private misses = 0;
|
|
33
|
+
private readonly maxSize: number;
|
|
34
|
+
private readonly defaultTtl: number;
|
|
35
|
+
|
|
36
|
+
constructor(options: MemoryCacheAdapterOptions = {}) {
|
|
37
|
+
this.maxSize = options.maxSize ?? 0;
|
|
38
|
+
this.defaultTtl = options.defaultTtl ?? 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async get<T = unknown>(key: string): Promise<T | undefined> {
|
|
42
|
+
const entry = this.store.get(key);
|
|
43
|
+
if (!entry || (entry.expires && Date.now() > entry.expires)) {
|
|
44
|
+
if (entry) this.store.delete(key);
|
|
45
|
+
this.misses++;
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
this.hits++;
|
|
49
|
+
return entry.value as T;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async set<T = unknown>(key: string, value: T, ttl?: number): Promise<void> {
|
|
53
|
+
const effectiveTtl = ttl ?? this.defaultTtl;
|
|
54
|
+
if (this.maxSize > 0 && !this.store.has(key) && this.store.size >= this.maxSize) {
|
|
55
|
+
// Evict oldest entry (first key in Map insertion order)
|
|
56
|
+
const firstKey = this.store.keys().next().value;
|
|
57
|
+
if (firstKey !== undefined) this.store.delete(firstKey);
|
|
58
|
+
}
|
|
59
|
+
this.store.set(key, {
|
|
60
|
+
value,
|
|
61
|
+
expires: effectiveTtl > 0 ? Date.now() + effectiveTtl * 1000 : undefined,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async delete(key: string): Promise<boolean> {
|
|
66
|
+
return this.store.delete(key);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async has(key: string): Promise<boolean> {
|
|
70
|
+
const entry = this.store.get(key);
|
|
71
|
+
if (!entry) return false;
|
|
72
|
+
if (entry.expires && Date.now() > entry.expires) {
|
|
73
|
+
this.store.delete(key);
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async clear(): Promise<void> {
|
|
80
|
+
this.store.clear();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async stats(): Promise<CacheStats> {
|
|
84
|
+
return {
|
|
85
|
+
hits: this.hits,
|
|
86
|
+
misses: this.misses,
|
|
87
|
+
keyCount: this.store.size,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import type { ICacheService, CacheStats } from '@objectstack/spec/contracts';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Configuration for the Redis cache adapter.
|
|
7
|
+
*/
|
|
8
|
+
export interface RedisCacheAdapterOptions {
|
|
9
|
+
/** Redis connection URL (e.g. 'redis://localhost:6379') */
|
|
10
|
+
url: string;
|
|
11
|
+
/** Key prefix for namespacing (default: 'os:') */
|
|
12
|
+
keyPrefix?: string;
|
|
13
|
+
/** Default TTL in seconds (0 = no expiry) */
|
|
14
|
+
defaultTtl?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Redis cache adapter skeleton implementing ICacheService.
|
|
19
|
+
*
|
|
20
|
+
* This is a placeholder for future Redis integration.
|
|
21
|
+
* Concrete implementation will use `ioredis` or `redis` client.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* const cache = new RedisCacheAdapter({ url: 'redis://localhost:6379' });
|
|
26
|
+
* await cache.set('user:1', { name: 'Alice' }, 3600);
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export class RedisCacheAdapter implements ICacheService {
|
|
30
|
+
private readonly url: string;
|
|
31
|
+
private readonly keyPrefix: string;
|
|
32
|
+
private readonly defaultTtl: number;
|
|
33
|
+
|
|
34
|
+
constructor(options: RedisCacheAdapterOptions) {
|
|
35
|
+
this.url = options.url;
|
|
36
|
+
this.keyPrefix = options.keyPrefix ?? 'os:';
|
|
37
|
+
this.defaultTtl = options.defaultTtl ?? 0;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async get<T = unknown>(_key: string): Promise<T | undefined> {
|
|
41
|
+
throw new Error(`RedisCacheAdapter not yet implemented (url: ${this.url}, prefix: ${this.keyPrefix}, ttl: ${this.defaultTtl})`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async set<T = unknown>(_key: string, _value: T, _ttl?: number): Promise<void> {
|
|
45
|
+
throw new Error('RedisCacheAdapter not yet implemented');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async delete(_key: string): Promise<boolean> {
|
|
49
|
+
throw new Error('RedisCacheAdapter not yet implemented');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async has(_key: string): Promise<boolean> {
|
|
53
|
+
throw new Error('RedisCacheAdapter not yet implemented');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async clear(): Promise<void> {
|
|
57
|
+
throw new Error('RedisCacheAdapter not yet implemented');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async stats(): Promise<CacheStats> {
|
|
61
|
+
throw new Error('RedisCacheAdapter not yet implemented');
|
|
62
|
+
}
|
|
63
|
+
}
|