@innvoid/getmarket-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +93 -0
- package/dist/cache/index.cjs +321 -0
- package/dist/cache/index.cjs.map +1 -0
- package/dist/cache/index.d.cts +82 -0
- package/dist/cache/index.d.ts +82 -0
- package/dist/cache/index.js +11 -0
- package/dist/cache/index.js.map +1 -0
- package/dist/chunk-65HACONF.js +33 -0
- package/dist/chunk-65HACONF.js.map +1 -0
- package/dist/chunk-GG7EI74E.js +169 -0
- package/dist/chunk-GG7EI74E.js.map +1 -0
- package/dist/chunk-HTHX24NK.js +106 -0
- package/dist/chunk-HTHX24NK.js.map +1 -0
- package/dist/chunk-LBFFAXER.js +293 -0
- package/dist/chunk-LBFFAXER.js.map +1 -0
- package/dist/core/index.cjs +211 -0
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.cts +58 -0
- package/dist/core/index.d.ts +58 -0
- package/dist/core/index.js +19 -0
- package/dist/core/index.js.map +1 -0
- package/dist/headers/index.cjs +65 -0
- package/dist/headers/index.cjs.map +1 -0
- package/dist/headers/index.d.cts +25 -0
- package/dist/headers/index.d.ts +25 -0
- package/dist/headers/index.js +19 -0
- package/dist/headers/index.js.map +1 -0
- package/dist/index.cjs +644 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +55 -0
- package/dist/index.js.map +1 -0
- package/dist/middlewares/index.cjs +163 -0
- package/dist/middlewares/index.cjs.map +1 -0
- package/dist/middlewares/index.d.cts +18 -0
- package/dist/middlewares/index.d.ts +18 -0
- package/dist/middlewares/index.js +16 -0
- package/dist/middlewares/index.js.map +1 -0
- package/package.json +59 -0
package/README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# getmarket-sdk
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
## Getting started
|
|
6
|
+
|
|
7
|
+
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
|
8
|
+
|
|
9
|
+
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
|
10
|
+
|
|
11
|
+
## Add your files
|
|
12
|
+
|
|
13
|
+
* [Create](https://docs.gitlab.com/user/project/repository/web_editor/#create-a-file) or [upload](https://docs.gitlab.com/user/project/repository/web_editor/#upload-a-file) files
|
|
14
|
+
* [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
cd existing_repo
|
|
18
|
+
git remote add origin https://gitlab.com/innvoid-devs/getmarket-sdk.git
|
|
19
|
+
git branch -M main
|
|
20
|
+
git push -uf origin main
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Integrate with your tools
|
|
24
|
+
|
|
25
|
+
* [Set up project integrations](https://gitlab.com/innvoid-devs/getmarket-sdk/-/settings/integrations)
|
|
26
|
+
|
|
27
|
+
## Collaborate with your team
|
|
28
|
+
|
|
29
|
+
* [Invite team members and collaborators](https://docs.gitlab.com/user/project/members/)
|
|
30
|
+
* [Create a new merge request](https://docs.gitlab.com/user/project/merge_requests/creating_merge_requests/)
|
|
31
|
+
* [Automatically close issues from merge requests](https://docs.gitlab.com/user/project/issues/managing_issues/#closing-issues-automatically)
|
|
32
|
+
* [Enable merge request approvals](https://docs.gitlab.com/user/project/merge_requests/approvals/)
|
|
33
|
+
* [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
|
|
34
|
+
|
|
35
|
+
## Test and Deploy
|
|
36
|
+
|
|
37
|
+
Use the built-in continuous integration in GitLab.
|
|
38
|
+
|
|
39
|
+
* [Get started with GitLab CI/CD](https://docs.gitlab.com/ci/quick_start/)
|
|
40
|
+
* [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/user/application_security/sast/)
|
|
41
|
+
* [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/topics/autodevops/requirements/)
|
|
42
|
+
* [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/user/clusters/agent/)
|
|
43
|
+
* [Set up protected environments](https://docs.gitlab.com/ci/environments/protected_environments/)
|
|
44
|
+
|
|
45
|
+
***
|
|
46
|
+
|
|
47
|
+
# Editing this README
|
|
48
|
+
|
|
49
|
+
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
|
50
|
+
|
|
51
|
+
## Suggestions for a good README
|
|
52
|
+
|
|
53
|
+
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
|
54
|
+
|
|
55
|
+
## Name
|
|
56
|
+
Choose a self-explaining name for your project.
|
|
57
|
+
|
|
58
|
+
## Description
|
|
59
|
+
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
|
60
|
+
|
|
61
|
+
## Badges
|
|
62
|
+
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
|
63
|
+
|
|
64
|
+
## Visuals
|
|
65
|
+
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
|
66
|
+
|
|
67
|
+
## Installation
|
|
68
|
+
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
|
69
|
+
|
|
70
|
+
## Usage
|
|
71
|
+
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
|
72
|
+
|
|
73
|
+
## Support
|
|
74
|
+
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
|
75
|
+
|
|
76
|
+
## Roadmap
|
|
77
|
+
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
|
78
|
+
|
|
79
|
+
## Contributing
|
|
80
|
+
State if you are open to contributions and what your requirements are for accepting them.
|
|
81
|
+
|
|
82
|
+
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
|
83
|
+
|
|
84
|
+
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
|
85
|
+
|
|
86
|
+
## Authors and acknowledgment
|
|
87
|
+
Show your appreciation to those who have contributed to the project.
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
For open source projects, say how it is licensed.
|
|
91
|
+
|
|
92
|
+
## Project status
|
|
93
|
+
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
|
@@ -0,0 +1,321 @@
|
|
|
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/cache/index.ts
|
|
21
|
+
var cache_exports = {};
|
|
22
|
+
__export(cache_exports, {
|
|
23
|
+
closeCache: () => closeCache,
|
|
24
|
+
getOrSet: () => getOrSet,
|
|
25
|
+
getTwoLevelCache: () => getTwoLevelCache
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(cache_exports);
|
|
28
|
+
|
|
29
|
+
// src/cache/redisCacheProvider.ts
|
|
30
|
+
var import_redis = require("redis");
|
|
31
|
+
function buildRedisUrl(opts) {
|
|
32
|
+
if (opts.url && opts.url.trim()) return opts.url.trim();
|
|
33
|
+
if (!opts.host) return void 0;
|
|
34
|
+
const port = opts.port ?? 6379;
|
|
35
|
+
const db = opts.db ?? 0;
|
|
36
|
+
const auth = opts.password ? `:${encodeURIComponent(opts.password)}@` : "";
|
|
37
|
+
return `redis://${auth}${opts.host}:${port}/${db}`;
|
|
38
|
+
}
|
|
39
|
+
var RedisCacheProvider = class {
|
|
40
|
+
constructor(opts) {
|
|
41
|
+
this.opts = opts;
|
|
42
|
+
const url = buildRedisUrl(opts);
|
|
43
|
+
if (!url) {
|
|
44
|
+
throw new Error("[RedisCacheProvider] Missing redis config (REDIS_URL or REDIS_HOST)");
|
|
45
|
+
}
|
|
46
|
+
this.keyPrefix = opts.keyPrefix?.trim() || void 0;
|
|
47
|
+
this.client = (0, import_redis.createClient)({
|
|
48
|
+
url,
|
|
49
|
+
socket: {
|
|
50
|
+
connectTimeout: opts.connectTimeoutMs ?? 3e3,
|
|
51
|
+
tls: opts.tls ? true : void 0
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
this.client.on("error", (err) => {
|
|
55
|
+
const msg = err instanceof Error ? err.message : typeof err === "object" && err !== null && "message" in err ? String(err.message) : String(err);
|
|
56
|
+
console.error("[redis] error", msg, err);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
kind = "redis";
|
|
60
|
+
// ✅ tip "amplio" para evitar TS2322 por typings genéricos
|
|
61
|
+
client;
|
|
62
|
+
ready = false;
|
|
63
|
+
keyPrefix;
|
|
64
|
+
k(key) {
|
|
65
|
+
if (!this.keyPrefix) return key;
|
|
66
|
+
return `${this.keyPrefix}:${key}`;
|
|
67
|
+
}
|
|
68
|
+
async ensureConnected() {
|
|
69
|
+
if (this.ready) return;
|
|
70
|
+
await this.client.connect();
|
|
71
|
+
this.ready = true;
|
|
72
|
+
}
|
|
73
|
+
async get(key) {
|
|
74
|
+
await this.ensureConnected();
|
|
75
|
+
const v = await this.client.get(this.k(key));
|
|
76
|
+
return v ?? null;
|
|
77
|
+
}
|
|
78
|
+
async set(key, value, options) {
|
|
79
|
+
await this.ensureConnected();
|
|
80
|
+
const ttlMs = options?.ttlMs;
|
|
81
|
+
if (ttlMs && ttlMs > 0) {
|
|
82
|
+
await this.client.set(this.k(key), value, { PX: ttlMs });
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
await this.client.set(this.k(key), value);
|
|
86
|
+
}
|
|
87
|
+
async del(key) {
|
|
88
|
+
await this.ensureConnected();
|
|
89
|
+
await this.client.del(this.k(key));
|
|
90
|
+
}
|
|
91
|
+
async close() {
|
|
92
|
+
try {
|
|
93
|
+
if (this.ready) await this.client.quit();
|
|
94
|
+
} catch {
|
|
95
|
+
try {
|
|
96
|
+
await this.client.disconnect();
|
|
97
|
+
} catch {
|
|
98
|
+
}
|
|
99
|
+
} finally {
|
|
100
|
+
this.ready = false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// src/cache/cacheProvider.ts
|
|
106
|
+
var NoopCacheProvider = class {
|
|
107
|
+
kind = "noop";
|
|
108
|
+
async get(_key) {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
async set(_key, _value, _options) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
async del(_key) {
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
async close() {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
function createCacheProvider(opts = {}) {
|
|
122
|
+
const envHasRedis = Boolean(process.env.REDIS_URL || process.env.REDIS_HOST);
|
|
123
|
+
const enabled = typeof opts.enabled === "boolean" ? opts.enabled : envHasRedis;
|
|
124
|
+
if (!enabled) return new NoopCacheProvider();
|
|
125
|
+
const redisOpts = {
|
|
126
|
+
url: process.env.REDIS_URL,
|
|
127
|
+
host: process.env.REDIS_HOST,
|
|
128
|
+
port: process.env.REDIS_PORT ? Number(process.env.REDIS_PORT) : void 0,
|
|
129
|
+
password: process.env.REDIS_PASSWORD,
|
|
130
|
+
db: process.env.REDIS_DB ? Number(process.env.REDIS_DB) : void 0,
|
|
131
|
+
tls: (process.env.REDIS_TLS || "").toLowerCase() === "true",
|
|
132
|
+
connectTimeoutMs: process.env.REDIS_CONNECT_TIMEOUT_MS ? Number(process.env.REDIS_CONNECT_TIMEOUT_MS) : 3e3,
|
|
133
|
+
keyPrefix: opts.keyPrefix || process.env.REDIS_KEY_PREFIX || void 0,
|
|
134
|
+
...opts.redis || {}
|
|
135
|
+
};
|
|
136
|
+
return new RedisCacheProvider(redisOpts);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// src/cache/ttlCache.ts
|
|
140
|
+
var TtlCache = class {
|
|
141
|
+
constructor(defaultTtlMs) {
|
|
142
|
+
this.defaultTtlMs = defaultTtlMs;
|
|
143
|
+
}
|
|
144
|
+
store = /* @__PURE__ */ new Map();
|
|
145
|
+
get(key) {
|
|
146
|
+
const e = this.store.get(key);
|
|
147
|
+
if (!e) return null;
|
|
148
|
+
if (Date.now() > e.expiresAt) {
|
|
149
|
+
this.store.delete(key);
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
return e.value;
|
|
153
|
+
}
|
|
154
|
+
set(key, value, ttlMs) {
|
|
155
|
+
this.store.set(key, { value, expiresAt: Date.now() + (ttlMs ?? this.defaultTtlMs) });
|
|
156
|
+
}
|
|
157
|
+
del(key) {
|
|
158
|
+
this.store.delete(key);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// src/cache/twoLevelCache.ts
|
|
163
|
+
function safeJsonParse(raw) {
|
|
164
|
+
try {
|
|
165
|
+
return JSON.parse(raw);
|
|
166
|
+
} catch {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function safeJsonStringify(v) {
|
|
171
|
+
try {
|
|
172
|
+
return JSON.stringify(v);
|
|
173
|
+
} catch {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
var TwoLevelCache = class {
|
|
178
|
+
constructor(l2, opts = {}) {
|
|
179
|
+
this.l2 = l2;
|
|
180
|
+
this.opts = opts;
|
|
181
|
+
const defaultTtl = this.opts.ttlMsL1 ?? 2 * 60 * 1e3;
|
|
182
|
+
this.l1 = new TtlCache(defaultTtl);
|
|
183
|
+
}
|
|
184
|
+
l1;
|
|
185
|
+
inflight = /* @__PURE__ */ new Map();
|
|
186
|
+
key(k) {
|
|
187
|
+
const ns = (this.opts.namespace || "").trim();
|
|
188
|
+
return ns ? `${ns}:${k}` : k;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* GET "best effort": primero L1, luego L2.
|
|
192
|
+
* (No llama loader)
|
|
193
|
+
*/
|
|
194
|
+
async get(k) {
|
|
195
|
+
const key = this.key(k);
|
|
196
|
+
const v1 = this.l1.get(key);
|
|
197
|
+
if (v1 !== void 0) return v1;
|
|
198
|
+
const raw = await this.l2.get(key);
|
|
199
|
+
if (!raw) return null;
|
|
200
|
+
const parsed = safeJsonParse(raw);
|
|
201
|
+
if (parsed === null && raw !== "null") {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
this.l1.set(key, parsed, this.opts.ttlMsL1);
|
|
205
|
+
return parsed;
|
|
206
|
+
}
|
|
207
|
+
async set(k, value, ttlOverride) {
|
|
208
|
+
const key = this.key(k);
|
|
209
|
+
const ttlL1 = ttlOverride?.ttlMsL1 ?? this.opts.ttlMsL1 ?? 2 * 60 * 1e3;
|
|
210
|
+
const ttlL2 = ttlOverride?.ttlMsL2 ?? this.opts.ttlMsL2 ?? 10 * 60 * 1e3;
|
|
211
|
+
this.l1.set(key, value, ttlL1);
|
|
212
|
+
const raw = safeJsonStringify(value);
|
|
213
|
+
if (raw == null) return;
|
|
214
|
+
await this.l2.set(key, raw, { ttlMs: ttlL2 });
|
|
215
|
+
}
|
|
216
|
+
async del(k) {
|
|
217
|
+
const key = this.key(k);
|
|
218
|
+
this.l1.del?.(key);
|
|
219
|
+
await this.l2.del(key);
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Cache-aside real con L1 + L2 + loader.
|
|
223
|
+
*
|
|
224
|
+
* - Dedup de concurrencia por key (inflight)
|
|
225
|
+
* - Soporta negative caching (si loader retorna null)
|
|
226
|
+
*/
|
|
227
|
+
async getOrSet(k, loader, options) {
|
|
228
|
+
const key = this.key(k);
|
|
229
|
+
const v1 = this.l1.get(key);
|
|
230
|
+
if (v1 !== void 0) return v1;
|
|
231
|
+
const raw = await this.l2.get(key);
|
|
232
|
+
if (raw) {
|
|
233
|
+
const parsed = safeJsonParse(raw);
|
|
234
|
+
if (parsed !== null || raw === "null") {
|
|
235
|
+
this.l1.set(key, parsed, options?.ttlMsL1 ?? this.opts.ttlMsL1);
|
|
236
|
+
return parsed;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (this.inflight.has(key)) {
|
|
240
|
+
return this.inflight.get(key);
|
|
241
|
+
}
|
|
242
|
+
const promise = (async () => {
|
|
243
|
+
try {
|
|
244
|
+
const value = await loader();
|
|
245
|
+
const ttlMsL1 = options?.ttlMsL1 ?? this.opts.ttlMsL1 ?? 2 * 60 * 1e3;
|
|
246
|
+
const ttlMsL2 = options?.ttlMsL2 ?? this.opts.ttlMsL2 ?? 10 * 60 * 1e3;
|
|
247
|
+
const negL1 = options?.negativeTtlMsL1 ?? this.opts.negativeTtlMsL1 ?? 0;
|
|
248
|
+
const negL2 = options?.negativeTtlMsL2 ?? this.opts.negativeTtlMsL2 ?? 0;
|
|
249
|
+
if (value === null) {
|
|
250
|
+
if (negL1 > 0) this.l1.set(key, null, negL1);
|
|
251
|
+
if (negL2 > 0) await this.l2.set(key, "null", { ttlMs: negL2 });
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
this.l1.set(key, value, ttlMsL1);
|
|
255
|
+
const rawValue = safeJsonStringify(value);
|
|
256
|
+
if (rawValue != null) {
|
|
257
|
+
await this.l2.set(key, rawValue, { ttlMs: ttlMsL2 });
|
|
258
|
+
}
|
|
259
|
+
return value;
|
|
260
|
+
} finally {
|
|
261
|
+
this.inflight.delete(key);
|
|
262
|
+
}
|
|
263
|
+
})();
|
|
264
|
+
this.inflight.set(key, promise);
|
|
265
|
+
return promise;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
// src/cache/index.ts
|
|
270
|
+
var envInt = (v, dflt = 0) => {
|
|
271
|
+
const n = Number(v);
|
|
272
|
+
return Number.isFinite(n) && n > 0 ? Math.floor(n) : dflt;
|
|
273
|
+
};
|
|
274
|
+
var DEFAULT_L1_TTL_MS = envInt(process.env.CACHE_L1_DEFAULT_TTL_MS, 3e4);
|
|
275
|
+
var DEFAULT_L2_TTL_MS = envInt(process.env.CACHE_L2_DEFAULT_TTL_MS, 3e5);
|
|
276
|
+
var DEFAULT_NEG_TTL_MS = envInt(process.env.CACHE_NEGATIVE_TTL_MS, 3e4);
|
|
277
|
+
var l2Provider = null;
|
|
278
|
+
var twoLevelByNamespace = /* @__PURE__ */ new Map();
|
|
279
|
+
function getL2() {
|
|
280
|
+
if (l2Provider) return l2Provider;
|
|
281
|
+
l2Provider = createCacheProvider();
|
|
282
|
+
return l2Provider;
|
|
283
|
+
}
|
|
284
|
+
function getTwoLevelCache(namespace, opts = {}) {
|
|
285
|
+
const existing = twoLevelByNamespace.get(namespace);
|
|
286
|
+
if (existing) return existing;
|
|
287
|
+
const l2 = getL2();
|
|
288
|
+
const cacheOptions = {
|
|
289
|
+
// ✅ dejamos que TwoLevelCache prefije keys con namespace internamente
|
|
290
|
+
namespace,
|
|
291
|
+
ttlMsL1: opts.ttlMsL1 ?? DEFAULT_L1_TTL_MS,
|
|
292
|
+
ttlMsL2: opts.ttlMsL2 ?? DEFAULT_L2_TTL_MS,
|
|
293
|
+
// ✅ negative caching
|
|
294
|
+
negativeTtlMsL1: opts.negativeTtlMsL1 ?? DEFAULT_NEG_TTL_MS,
|
|
295
|
+
negativeTtlMsL2: opts.negativeTtlMsL2 ?? DEFAULT_NEG_TTL_MS
|
|
296
|
+
};
|
|
297
|
+
const cache = new TwoLevelCache(l2, cacheOptions);
|
|
298
|
+
twoLevelByNamespace.set(namespace, cache);
|
|
299
|
+
return cache;
|
|
300
|
+
}
|
|
301
|
+
async function getOrSet(namespace, key, loader, opts = {}) {
|
|
302
|
+
const cache = getTwoLevelCache(namespace, opts);
|
|
303
|
+
return cache.getOrSet(key, loader, opts);
|
|
304
|
+
}
|
|
305
|
+
async function closeCache() {
|
|
306
|
+
try {
|
|
307
|
+
if (l2Provider && typeof l2Provider.close === "function") {
|
|
308
|
+
await l2Provider.close();
|
|
309
|
+
}
|
|
310
|
+
} finally {
|
|
311
|
+
l2Provider = null;
|
|
312
|
+
twoLevelByNamespace.clear();
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
316
|
+
0 && (module.exports = {
|
|
317
|
+
closeCache,
|
|
318
|
+
getOrSet,
|
|
319
|
+
getTwoLevelCache
|
|
320
|
+
});
|
|
321
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/cache/index.ts","../../src/cache/redisCacheProvider.ts","../../src/cache/cacheProvider.ts","../../src/cache/ttlCache.ts","../../src/cache/twoLevelCache.ts"],"sourcesContent":["// clients/cache/index.ts\nimport {createCacheProvider, CacheProvider} from \"./cacheProvider\";\nimport {TwoLevelCache, TwoLevelCacheOptions} from \"./twoLevelCache\";\n\nconst envInt = (v?: string, dflt: number = 0) => {\n const n = Number(v);\n return Number.isFinite(n) && n > 0 ? Math.floor(n) : dflt;\n};\n\nconst DEFAULT_L1_TTL_MS = envInt(process.env.CACHE_L1_DEFAULT_TTL_MS, 30_000);\nconst DEFAULT_L2_TTL_MS = envInt(process.env.CACHE_L2_DEFAULT_TTL_MS, 300_000);\nconst DEFAULT_NEG_TTL_MS = envInt(process.env.CACHE_NEGATIVE_TTL_MS, 30_000);\n\nlet l2Provider: CacheProvider | null = null;\nconst twoLevelByNamespace = new Map<string, TwoLevelCache<any>>();\n\nfunction getL2(): CacheProvider {\n if (l2Provider) return l2Provider;\n l2Provider = createCacheProvider();\n return l2Provider;\n}\n\n/**\n * Retorna (o crea) un TwoLevelCache por namespace.\n * Namespace recomendado: auth:employee | md:country | platform:tenant-resolve ...\n */\nexport function getTwoLevelCache<T = any>(\n namespace: string,\n opts: Partial<TwoLevelCacheOptions> = {}\n): TwoLevelCache<T> {\n const existing = twoLevelByNamespace.get(namespace);\n if (existing) return existing as TwoLevelCache<T>;\n\n const l2 = getL2();\n\n const cacheOptions: TwoLevelCacheOptions = {\n // ✅ dejamos que TwoLevelCache prefije keys con namespace internamente\n namespace,\n\n ttlMsL1: opts.ttlMsL1 ?? DEFAULT_L1_TTL_MS,\n ttlMsL2: opts.ttlMsL2 ?? DEFAULT_L2_TTL_MS,\n\n // ✅ negative caching\n negativeTtlMsL1: opts.negativeTtlMsL1 ?? DEFAULT_NEG_TTL_MS,\n negativeTtlMsL2: opts.negativeTtlMsL2 ?? DEFAULT_NEG_TTL_MS,\n };\n\n const cache = new TwoLevelCache<T>(l2, cacheOptions);\n twoLevelByNamespace.set(namespace, cache as TwoLevelCache<any>);\n return cache;\n}\n\n/**\n * Helper: cache.getOrSet\n *\n * IMPORTANT:\n * - No prefijar manualmente la key.\n * - TwoLevelCache ya usa opts.namespace.\n */\nexport async function getOrSet<T>(\n namespace: string,\n key: string,\n loader: () => Promise<T | null>,\n opts: Partial<TwoLevelCacheOptions> = {}\n): Promise<T | null> {\n const cache = getTwoLevelCache<T>(namespace, opts);\n return cache.getOrSet(key, loader, opts);\n}\n\nexport async function closeCache(): Promise<void> {\n try {\n if (l2Provider && typeof (l2Provider as any).close === \"function\") {\n await (l2Provider as any).close();\n }\n } finally {\n l2Provider = null;\n twoLevelByNamespace.clear();\n }\n}\n","// clients/cache/redisCacheProvider.ts\nimport {createClient, type RedisClientType} from \"redis\";\nimport type {CacheProvider, CacheSetOptions, CacheValue} from \"./cacheProvider\";\n\nexport type RedisCacheProviderOptions = {\n url?: string;\n\n host?: string;\n port?: number;\n password?: string;\n db?: number;\n\n tls?: boolean;\n\n connectTimeoutMs?: number;\n\n keyPrefix?: string;\n};\n\nfunction buildRedisUrl(opts: RedisCacheProviderOptions): string | undefined {\n if (opts.url && opts.url.trim()) return opts.url.trim();\n\n if (!opts.host) return undefined;\n const port = opts.port ?? 6379;\n const db = opts.db ?? 0;\n\n const auth = opts.password ? `:${encodeURIComponent(opts.password)}@` : \"\";\n return `redis://${auth}${opts.host}:${port}/${db}`;\n}\n\nexport class RedisCacheProvider implements CacheProvider {\n readonly kind = \"redis\" as const;\n\n // ✅ tip \"amplio\" para evitar TS2322 por typings genéricos\n private client: RedisClientType<any, any, any>;\n private ready = false;\n private readonly keyPrefix?: string;\n\n constructor(private readonly opts: RedisCacheProviderOptions) {\n const url = buildRedisUrl(opts);\n if (!url) {\n throw new Error(\"[RedisCacheProvider] Missing redis config (REDIS_URL or REDIS_HOST)\");\n }\n\n this.keyPrefix = opts.keyPrefix?.trim() || undefined;\n\n this.client = createClient({\n url,\n socket: {\n connectTimeout: opts.connectTimeoutMs ?? 3000,\n tls: opts.tls ? true : undefined,\n },\n }) as RedisClientType<any, any, any>;\n\n this.client.on(\"error\", (err: unknown) => {\n const msg =\n err instanceof Error\n ? err.message\n : typeof err === \"object\" && err !== null && \"message\" in err\n ? String((err as any).message)\n : String(err);\n\n console.error(\"[redis] error\", msg, err);\n });\n }\n\n private k(key: string): string {\n if (!this.keyPrefix) return key;\n return `${this.keyPrefix}:${key}`;\n }\n\n private async ensureConnected() {\n if (this.ready) return;\n await this.client.connect();\n this.ready = true;\n }\n\n async get(key: string): Promise<CacheValue | null> {\n await this.ensureConnected();\n const v = (await this.client.get(this.k(key))) as string | null;\n return v ?? null;\n }\n\n async set(key: string, value: CacheValue, options?: CacheSetOptions): Promise<void> {\n await this.ensureConnected();\n\n const ttlMs = options?.ttlMs;\n if (ttlMs && ttlMs > 0) {\n await this.client.set(this.k(key), value, {PX: ttlMs});\n return;\n }\n\n await this.client.set(this.k(key), value);\n }\n\n async del(key: string): Promise<void> {\n await this.ensureConnected();\n await this.client.del(this.k(key));\n }\n\n async close(): Promise<void> {\n try {\n if (this.ready) await this.client.quit();\n } catch {\n try {\n await this.client.disconnect();\n } catch {\n }\n } finally {\n this.ready = false;\n }\n }\n}\n","// clients/cache/cacheProvider.ts\nimport type {RedisCacheProviderOptions} from \"./redisCacheProvider\";\nimport {RedisCacheProvider} from \"./redisCacheProvider\";\n\nexport type CacheValue = string;\n\nexport type CacheSetOptions = {\n ttlMs?: number; // TTL en milisegundos (PX)\n};\n\nexport interface CacheProvider {\n readonly kind: \"redis\" | \"noop\";\n\n get(key: string): Promise<CacheValue | null>;\n\n set(key: string, value: CacheValue, options?: CacheSetOptions): Promise<void>;\n\n del(key: string): Promise<void>;\n\n /**\n * Cierra conexiones si aplica.\n */\n close(): Promise<void>;\n}\n\nexport class NoopCacheProvider implements CacheProvider {\n readonly kind = \"noop\" as const;\n\n async get(_key: string): Promise<CacheValue | null> {\n return null;\n }\n\n async set(_key: string, _value: CacheValue, _options?: CacheSetOptions): Promise<void> {\n return;\n }\n\n async del(_key: string): Promise<void> {\n return;\n }\n\n async close(): Promise<void> {\n return;\n }\n}\n\nexport type CacheProviderFactoryOptions = {\n /**\n * Si false, devuelve Noop (útil en local si no quieres Redis).\n * Default: true si hay REDIS_URL o REDIS_HOST.\n */\n enabled?: boolean;\n\n /**\n * Prefijo global opcional para keys.\n * Ej: \"getmarket:erp\"\n */\n keyPrefix?: string;\n\n /**\n * Redis options\n */\n redis?: Partial<RedisCacheProviderOptions>;\n};\n\n/**\n * Factory simple para L2 (Redis).\n * - Si no está habilitado / no hay config => Noop\n * - Si hay config => RedisCacheProvider\n */\nexport function createCacheProvider(opts: CacheProviderFactoryOptions = {}): CacheProvider {\n const envHasRedis = Boolean(process.env.REDIS_URL || process.env.REDIS_HOST);\n\n const enabled =\n typeof opts.enabled === \"boolean\" ? opts.enabled : envHasRedis;\n\n if (!enabled) return new NoopCacheProvider();\n\n // Construye options redis desde env + overrides\n const redisOpts: RedisCacheProviderOptions = {\n url: process.env.REDIS_URL,\n host: process.env.REDIS_HOST,\n port: process.env.REDIS_PORT ? Number(process.env.REDIS_PORT) : undefined,\n password: process.env.REDIS_PASSWORD,\n db: process.env.REDIS_DB ? Number(process.env.REDIS_DB) : undefined,\n tls: (process.env.REDIS_TLS || \"\").toLowerCase() === \"true\",\n connectTimeoutMs: process.env.REDIS_CONNECT_TIMEOUT_MS\n ? Number(process.env.REDIS_CONNECT_TIMEOUT_MS)\n : 3000,\n keyPrefix: opts.keyPrefix || process.env.REDIS_KEY_PREFIX || undefined,\n ...(opts.redis || {}),\n };\n\n return new RedisCacheProvider(redisOpts);\n}\n","// clients/cache/ttlCache.ts\ntype CacheEntry<T> = { value: T; expiresAt: number };\n\nexport class TtlCache<T> {\n private store = new Map<string, CacheEntry<T>>();\n\n constructor(private defaultTtlMs: number) {\n }\n\n get(key: string): T | null {\n const e = this.store.get(key);\n if (!e) return null;\n if (Date.now() > e.expiresAt) {\n this.store.delete(key);\n return null;\n }\n return e.value;\n }\n\n set(key: string, value: T, ttlMs?: number): void {\n this.store.set(key, {value, expiresAt: Date.now() + (ttlMs ?? this.defaultTtlMs)});\n }\n\n del(key: string): void {\n this.store.delete(key);\n }\n}\n","// clients/cache/twoLevelCache.ts\nimport type {CacheProvider} from \"./cacheProvider\";\nimport {TtlCache} from \"./ttlCache\";\n\nexport type TwoLevelCacheOptions = {\n /**\n * TTL para L1 (in-memory).\n * Default: 2 min\n */\n ttlMsL1?: number;\n\n /**\n * TTL para L2 (redis).\n * Default: 10 min\n */\n ttlMsL2?: number;\n\n /**\n * Si quieres cachear \"no encontrado\" (null) por un TTL corto,\n * para evitar golpear upstream repetidamente.\n * Default: 0 (deshabilitado)\n */\n negativeTtlMsL1?: number;\n negativeTtlMsL2?: number;\n\n /**\n * Prefijo lógico extra por instancia (además del keyPrefix del provider).\n * Ej: \"res:variety\"\n */\n namespace?: string;\n};\n\ntype Loader<T> = () => Promise<T>;\n\nfunction safeJsonParse<T>(raw: string): T | null {\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\nfunction safeJsonStringify(v: any): string | null {\n try {\n return JSON.stringify(v);\n } catch {\n return null;\n }\n}\n\nexport class TwoLevelCache<T> {\n private readonly l1: TtlCache<T | null>;\n private readonly inflight = new Map<string, Promise<T>>();\n\n constructor(\n private readonly l2: CacheProvider,\n private readonly opts: TwoLevelCacheOptions = {}\n ) {\n // El TTL real lo controla set(key, ttl), pero TTLCache necesita \"default ttl\"\n const defaultTtl = this.opts.ttlMsL1 ?? 2 * 60 * 1000;\n this.l1 = new TtlCache<T | null>(defaultTtl);\n }\n\n private key(k: string): string {\n const ns = (this.opts.namespace || \"\").trim();\n return ns ? `${ns}:${k}` : k;\n }\n\n /**\n * GET \"best effort\": primero L1, luego L2.\n * (No llama loader)\n */\n async get(k: string): Promise<T | null> {\n const key = this.key(k);\n\n const v1 = this.l1.get(key);\n if (v1 !== undefined) return v1; // Ojo: TTLCache puede devolver null también\n\n const raw = await this.l2.get(key);\n if (!raw) return null;\n\n const parsed = safeJsonParse<T | null>(raw);\n if (parsed === null && raw !== \"null\") {\n // payload corrupto\n return null;\n }\n\n // Rehidrata L1 con ttl L1\n this.l1.set(key, parsed, this.opts.ttlMsL1);\n return parsed;\n }\n\n async set(k: string, value: T | null, ttlOverride?: { ttlMsL1?: number; ttlMsL2?: number }) {\n const key = this.key(k);\n\n const ttlL1 = ttlOverride?.ttlMsL1 ?? this.opts.ttlMsL1 ?? 2 * 60 * 1000;\n const ttlL2 = ttlOverride?.ttlMsL2 ?? this.opts.ttlMsL2 ?? 10 * 60 * 1000;\n\n this.l1.set(key, value, ttlL1);\n\n const raw = safeJsonStringify(value);\n if (raw == null) return;\n\n await this.l2.set(key, raw, {ttlMs: ttlL2});\n }\n\n async del(k: string) {\n const key = this.key(k);\n this.l1.del?.(key as any); // si tu TtlCache no tiene del(), ignora (ver comentario abajo)\n await this.l2.del(key);\n }\n\n /**\n * Cache-aside real con L1 + L2 + loader.\n *\n * - Dedup de concurrencia por key (inflight)\n * - Soporta negative caching (si loader retorna null)\n */\n async getOrSet(\n k: string,\n loader: Loader<T | null>,\n options?: TwoLevelCacheOptions\n ): Promise<T | null> {\n const key = this.key(k);\n\n // 1) L1\n const v1 = this.l1.get(key);\n if (v1 !== undefined) return v1;\n\n // 2) L2\n const raw = await this.l2.get(key);\n if (raw) {\n const parsed = safeJsonParse<T | null>(raw);\n if (parsed !== null || raw === \"null\") {\n this.l1.set(key, parsed, options?.ttlMsL1 ?? this.opts.ttlMsL1);\n return parsed;\n }\n }\n\n // 3) Dedup inflight (anti stampede)\n if (this.inflight.has(key)) {\n return this.inflight.get(key)! as any;\n }\n\n const promise = (async () => {\n try {\n const value = await loader();\n\n const ttlMsL1 = options?.ttlMsL1 ?? this.opts.ttlMsL1 ?? 2 * 60 * 1000;\n const ttlMsL2 = options?.ttlMsL2 ?? this.opts.ttlMsL2 ?? 10 * 60 * 1000;\n\n // negative caching\n const negL1 = options?.negativeTtlMsL1 ?? this.opts.negativeTtlMsL1 ?? 0;\n const negL2 = options?.negativeTtlMsL2 ?? this.opts.negativeTtlMsL2 ?? 0;\n\n if (value === null) {\n if (negL1 > 0) this.l1.set(key, null, negL1);\n if (negL2 > 0) await this.l2.set(key, \"null\", {ttlMs: negL2});\n return null;\n }\n\n // normal set\n this.l1.set(key, value, ttlMsL1);\n\n const rawValue = safeJsonStringify(value);\n if (rawValue != null) {\n await this.l2.set(key, rawValue, {ttlMs: ttlMsL2});\n }\n\n return value;\n } finally {\n this.inflight.delete(key);\n }\n })();\n\n this.inflight.set(key, promise as any);\n return promise;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,mBAAiD;AAkBjD,SAAS,cAAc,MAAqD;AACxE,MAAI,KAAK,OAAO,KAAK,IAAI,KAAK,EAAG,QAAO,KAAK,IAAI,KAAK;AAEtD,MAAI,CAAC,KAAK,KAAM,QAAO;AACvB,QAAM,OAAO,KAAK,QAAQ;AAC1B,QAAM,KAAK,KAAK,MAAM;AAEtB,QAAM,OAAO,KAAK,WAAW,IAAI,mBAAmB,KAAK,QAAQ,CAAC,MAAM;AACxE,SAAO,WAAW,IAAI,GAAG,KAAK,IAAI,IAAI,IAAI,IAAI,EAAE;AACpD;AAEO,IAAM,qBAAN,MAAkD;AAAA,EAQrD,YAA6B,MAAiC;AAAjC;AACzB,UAAM,MAAM,cAAc,IAAI;AAC9B,QAAI,CAAC,KAAK;AACN,YAAM,IAAI,MAAM,qEAAqE;AAAA,IACzF;AAEA,SAA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+
get(key: string): Promise<CacheValue | null>;
|
|
8
|
+
set(key: string, value: CacheValue, options?: CacheSetOptions): Promise<void>;
|
|
9
|
+
del(key: string): Promise<void>;
|
|
10
|
+
/**
|
|
11
|
+
* Cierra conexiones si aplica.
|
|
12
|
+
*/
|
|
13
|
+
close(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type TwoLevelCacheOptions = {
|
|
17
|
+
/**
|
|
18
|
+
* TTL para L1 (in-memory).
|
|
19
|
+
* Default: 2 min
|
|
20
|
+
*/
|
|
21
|
+
ttlMsL1?: number;
|
|
22
|
+
/**
|
|
23
|
+
* TTL para L2 (redis).
|
|
24
|
+
* Default: 10 min
|
|
25
|
+
*/
|
|
26
|
+
ttlMsL2?: number;
|
|
27
|
+
/**
|
|
28
|
+
* Si quieres cachear "no encontrado" (null) por un TTL corto,
|
|
29
|
+
* para evitar golpear upstream repetidamente.
|
|
30
|
+
* Default: 0 (deshabilitado)
|
|
31
|
+
*/
|
|
32
|
+
negativeTtlMsL1?: number;
|
|
33
|
+
negativeTtlMsL2?: number;
|
|
34
|
+
/**
|
|
35
|
+
* Prefijo lógico extra por instancia (además del keyPrefix del provider).
|
|
36
|
+
* Ej: "res:variety"
|
|
37
|
+
*/
|
|
38
|
+
namespace?: string;
|
|
39
|
+
};
|
|
40
|
+
type Loader<T> = () => Promise<T>;
|
|
41
|
+
declare class TwoLevelCache<T> {
|
|
42
|
+
private readonly l2;
|
|
43
|
+
private readonly opts;
|
|
44
|
+
private readonly l1;
|
|
45
|
+
private readonly inflight;
|
|
46
|
+
constructor(l2: CacheProvider, opts?: TwoLevelCacheOptions);
|
|
47
|
+
private key;
|
|
48
|
+
/**
|
|
49
|
+
* GET "best effort": primero L1, luego L2.
|
|
50
|
+
* (No llama loader)
|
|
51
|
+
*/
|
|
52
|
+
get(k: string): Promise<T | null>;
|
|
53
|
+
set(k: string, value: T | null, ttlOverride?: {
|
|
54
|
+
ttlMsL1?: number;
|
|
55
|
+
ttlMsL2?: number;
|
|
56
|
+
}): Promise<void>;
|
|
57
|
+
del(k: string): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Cache-aside real con L1 + L2 + loader.
|
|
60
|
+
*
|
|
61
|
+
* - Dedup de concurrencia por key (inflight)
|
|
62
|
+
* - Soporta negative caching (si loader retorna null)
|
|
63
|
+
*/
|
|
64
|
+
getOrSet(k: string, loader: Loader<T | null>, options?: TwoLevelCacheOptions): Promise<T | null>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Retorna (o crea) un TwoLevelCache por namespace.
|
|
69
|
+
* Namespace recomendado: auth:employee | md:country | platform:tenant-resolve ...
|
|
70
|
+
*/
|
|
71
|
+
declare function getTwoLevelCache<T = any>(namespace: string, opts?: Partial<TwoLevelCacheOptions>): TwoLevelCache<T>;
|
|
72
|
+
/**
|
|
73
|
+
* Helper: cache.getOrSet
|
|
74
|
+
*
|
|
75
|
+
* IMPORTANT:
|
|
76
|
+
* - No prefijar manualmente la key.
|
|
77
|
+
* - TwoLevelCache ya usa opts.namespace.
|
|
78
|
+
*/
|
|
79
|
+
declare function getOrSet<T>(namespace: string, key: string, loader: () => Promise<T | null>, opts?: Partial<TwoLevelCacheOptions>): Promise<T | null>;
|
|
80
|
+
declare function closeCache(): Promise<void>;
|
|
81
|
+
|
|
82
|
+
export { closeCache, getOrSet, getTwoLevelCache };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
type CacheValue = string;
|
|
2
|
+
type CacheSetOptions = {
|
|
3
|
+
ttlMs?: number;
|
|
4
|
+
};
|
|
5
|
+
interface CacheProvider {
|
|
6
|
+
readonly kind: "redis" | "noop";
|
|
7
|
+
get(key: string): Promise<CacheValue | null>;
|
|
8
|
+
set(key: string, value: CacheValue, options?: CacheSetOptions): Promise<void>;
|
|
9
|
+
del(key: string): Promise<void>;
|
|
10
|
+
/**
|
|
11
|
+
* Cierra conexiones si aplica.
|
|
12
|
+
*/
|
|
13
|
+
close(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type TwoLevelCacheOptions = {
|
|
17
|
+
/**
|
|
18
|
+
* TTL para L1 (in-memory).
|
|
19
|
+
* Default: 2 min
|
|
20
|
+
*/
|
|
21
|
+
ttlMsL1?: number;
|
|
22
|
+
/**
|
|
23
|
+
* TTL para L2 (redis).
|
|
24
|
+
* Default: 10 min
|
|
25
|
+
*/
|
|
26
|
+
ttlMsL2?: number;
|
|
27
|
+
/**
|
|
28
|
+
* Si quieres cachear "no encontrado" (null) por un TTL corto,
|
|
29
|
+
* para evitar golpear upstream repetidamente.
|
|
30
|
+
* Default: 0 (deshabilitado)
|
|
31
|
+
*/
|
|
32
|
+
negativeTtlMsL1?: number;
|
|
33
|
+
negativeTtlMsL2?: number;
|
|
34
|
+
/**
|
|
35
|
+
* Prefijo lógico extra por instancia (además del keyPrefix del provider).
|
|
36
|
+
* Ej: "res:variety"
|
|
37
|
+
*/
|
|
38
|
+
namespace?: string;
|
|
39
|
+
};
|
|
40
|
+
type Loader<T> = () => Promise<T>;
|
|
41
|
+
declare class TwoLevelCache<T> {
|
|
42
|
+
private readonly l2;
|
|
43
|
+
private readonly opts;
|
|
44
|
+
private readonly l1;
|
|
45
|
+
private readonly inflight;
|
|
46
|
+
constructor(l2: CacheProvider, opts?: TwoLevelCacheOptions);
|
|
47
|
+
private key;
|
|
48
|
+
/**
|
|
49
|
+
* GET "best effort": primero L1, luego L2.
|
|
50
|
+
* (No llama loader)
|
|
51
|
+
*/
|
|
52
|
+
get(k: string): Promise<T | null>;
|
|
53
|
+
set(k: string, value: T | null, ttlOverride?: {
|
|
54
|
+
ttlMsL1?: number;
|
|
55
|
+
ttlMsL2?: number;
|
|
56
|
+
}): Promise<void>;
|
|
57
|
+
del(k: string): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Cache-aside real con L1 + L2 + loader.
|
|
60
|
+
*
|
|
61
|
+
* - Dedup de concurrencia por key (inflight)
|
|
62
|
+
* - Soporta negative caching (si loader retorna null)
|
|
63
|
+
*/
|
|
64
|
+
getOrSet(k: string, loader: Loader<T | null>, options?: TwoLevelCacheOptions): Promise<T | null>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Retorna (o crea) un TwoLevelCache por namespace.
|
|
69
|
+
* Namespace recomendado: auth:employee | md:country | platform:tenant-resolve ...
|
|
70
|
+
*/
|
|
71
|
+
declare function getTwoLevelCache<T = any>(namespace: string, opts?: Partial<TwoLevelCacheOptions>): TwoLevelCache<T>;
|
|
72
|
+
/**
|
|
73
|
+
* Helper: cache.getOrSet
|
|
74
|
+
*
|
|
75
|
+
* IMPORTANT:
|
|
76
|
+
* - No prefijar manualmente la key.
|
|
77
|
+
* - TwoLevelCache ya usa opts.namespace.
|
|
78
|
+
*/
|
|
79
|
+
declare function getOrSet<T>(namespace: string, key: string, loader: () => Promise<T | null>, opts?: Partial<TwoLevelCacheOptions>): Promise<T | null>;
|
|
80
|
+
declare function closeCache(): Promise<void>;
|
|
81
|
+
|
|
82
|
+
export { closeCache, getOrSet, getTwoLevelCache };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// src/headers/constants.ts
|
|
2
|
+
var HEADER_REQUEST_ID = "x-request-id";
|
|
3
|
+
var HEADER_COMPANY_UID = "x-company";
|
|
4
|
+
var HEADER_BRANCH_UID = "x-branch";
|
|
5
|
+
var HEADER_EMPLOYEE_UID = "x-employee-uid";
|
|
6
|
+
var HEADER_INTERNAL_API_KEY = "x-internal-api-key";
|
|
7
|
+
var HEADER_AUTHORIZATION = "authorization";
|
|
8
|
+
|
|
9
|
+
// src/headers/parse.ts
|
|
10
|
+
function asString(v) {
|
|
11
|
+
if (typeof v !== "string") return null;
|
|
12
|
+
const s = v.trim();
|
|
13
|
+
return s ? s : null;
|
|
14
|
+
}
|
|
15
|
+
function getRequestContextFromHeaders(headers) {
|
|
16
|
+
return {
|
|
17
|
+
requestId: asString(headers[HEADER_REQUEST_ID]) ?? null,
|
|
18
|
+
company_uid: asString(headers[HEADER_COMPANY_UID]) ?? null,
|
|
19
|
+
branch_uid: asString(headers[HEADER_BRANCH_UID]) ?? null,
|
|
20
|
+
employee_uid: asString(headers[HEADER_EMPLOYEE_UID]) ?? null
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export {
|
|
25
|
+
HEADER_REQUEST_ID,
|
|
26
|
+
HEADER_COMPANY_UID,
|
|
27
|
+
HEADER_BRANCH_UID,
|
|
28
|
+
HEADER_EMPLOYEE_UID,
|
|
29
|
+
HEADER_INTERNAL_API_KEY,
|
|
30
|
+
HEADER_AUTHORIZATION,
|
|
31
|
+
getRequestContextFromHeaders
|
|
32
|
+
};
|
|
33
|
+
//# sourceMappingURL=chunk-65HACONF.js.map
|