@nage-api/cache 1.0.0-beta.2
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/LICENSE +202 -0
- package/README.md +127 -0
- package/dist/cache.module.d.ts +34 -0
- package/dist/cache.module.js +100 -0
- package/dist/cache.service.d.ts +73 -0
- package/dist/cache.service.js +147 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +27 -0
- package/dist/memory.store.d.ts +44 -0
- package/dist/memory.store.js +128 -0
- package/dist/ports.d.ts +51 -0
- package/dist/ports.js +14 -0
- package/dist/redis.store.d.ts +48 -0
- package/dist/redis.store.js +101 -0
- package/dist/tokens.d.ts +14 -0
- package/dist/tokens.js +15 -0
- package/dist/two-tier.store.d.ts +41 -0
- package/dist/two-tier.store.js +102 -0
- package/package.json +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the 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 [yyyy] [name of copyright owner]
|
|
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/README.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# @nage-api/cache
|
|
2
|
+
|
|
3
|
+
A typed cache that fails soft (PLAN.md §8, §25 P1).
|
|
4
|
+
|
|
5
|
+
Three drivers behind one service: `memory` for a single instance, `redis` for a
|
|
6
|
+
shared one, `two-tier` for both. Application code injects `CacheService` and
|
|
7
|
+
never learns which it got.
|
|
8
|
+
|
|
9
|
+
## Wiring it up
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { Module } from '@nestjs/common';
|
|
13
|
+
import { NageCacheModule, type RedisClientPort } from '@nage-api/cache';
|
|
14
|
+
import type { LoggerPort } from '@nage-api/contracts';
|
|
15
|
+
|
|
16
|
+
// Whichever client the application already has: ioredis, node-redis, or a fake
|
|
17
|
+
// in tests. This package names the six commands it needs and depends on none of
|
|
18
|
+
// them. Only `redis` and `two-tier` require one.
|
|
19
|
+
declare const redis: RedisClientPort;
|
|
20
|
+
declare const logger: LoggerPort;
|
|
21
|
+
|
|
22
|
+
@Module({
|
|
23
|
+
imports: [
|
|
24
|
+
NageCacheModule.forRoot({
|
|
25
|
+
cache: { driver: 'two-tier', namespace: 'shop', ttl: '5m' },
|
|
26
|
+
redis,
|
|
27
|
+
// A broken shared tier is reported, not thrown. Without a handler the
|
|
28
|
+
// failure is silent and the only symptom is a slower application.
|
|
29
|
+
onRemoteError: (operation, error) => {
|
|
30
|
+
logger.warn('cache: remote tier failed', { operation, error });
|
|
31
|
+
},
|
|
32
|
+
}),
|
|
33
|
+
],
|
|
34
|
+
})
|
|
35
|
+
export class AppModule {}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Using it
|
|
39
|
+
|
|
40
|
+
`CacheService` is exported by the module, so injecting the class is enough.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { Injectable } from '@nestjs/common';
|
|
44
|
+
import { CacheService } from '@nage-api/cache';
|
|
45
|
+
|
|
46
|
+
interface Product {
|
|
47
|
+
readonly id: string;
|
|
48
|
+
readonly name: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
declare const repository: { findById(id: string): Promise<Product | undefined> };
|
|
52
|
+
|
|
53
|
+
@Injectable()
|
|
54
|
+
export class ProductService {
|
|
55
|
+
constructor(private readonly cache: CacheService) {}
|
|
56
|
+
|
|
57
|
+
async find(id: string): Promise<Product | undefined> {
|
|
58
|
+
return this.cache.wrap(`product:${id}`, () => repository.findById(id), {
|
|
59
|
+
ttl: '5m',
|
|
60
|
+
tags: [`product:${id}`],
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async onProductChanged(id: string): Promise<void> {
|
|
65
|
+
// Drops the row's own entry and every list that included it.
|
|
66
|
+
await this.cache.invalidateTag(`product:${id}`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async onBulkImport(): Promise<void> {
|
|
70
|
+
await this.cache.namespace('product').invalidateNamespace();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## What it adds over a `Map`
|
|
76
|
+
|
|
77
|
+
**Single-flight.** Concurrent `wrap` calls for one key run the loader once. A
|
|
78
|
+
popular key expiring under load otherwise starts one identical query per
|
|
79
|
+
in-flight request — the stampede that turns a cache miss into an outage. The
|
|
80
|
+
in-flight entry is cleared in a `finally`, so a failed load doesn't poison the
|
|
81
|
+
key for everyone who asks next.
|
|
82
|
+
|
|
83
|
+
**Bounded memory.** The in-process store evicts least-recently-used entries and
|
|
84
|
+
sweeps expired ones on a timer. An unbounded map keyed by anything a request can
|
|
85
|
+
influence is a memory leak with a slow fuse. The timer is `unref`'d, so a cache
|
|
86
|
+
never keeps a process alive.
|
|
87
|
+
|
|
88
|
+
**Namespaces and tags.** Every key is prefixed, so a namespace can be dropped
|
|
89
|
+
without knowing which keys it wrote, and an entry can carry labels so a write to
|
|
90
|
+
one row invalidates every list that included it.
|
|
91
|
+
|
|
92
|
+
**Absence is not cached by default.** Caching `undefined` is how a race writes a
|
|
93
|
+
tombstone over a value that arrived a millisecond later. `cacheEmpty: true`
|
|
94
|
+
turns it on where "not found" is the common answer.
|
|
95
|
+
|
|
96
|
+
## Two tiers
|
|
97
|
+
|
|
98
|
+
L1 is in-process, L2 is shared, and L1 holds a **shorter** TTL than L2 —
|
|
99
|
+
capped by `l1TtlMs`, five seconds by default. That cap is the safety argument:
|
|
100
|
+
an in-process copy is the one nothing can invalidate remotely, so staleness is
|
|
101
|
+
bounded by a number you chose rather than by when a process happens to restart.
|
|
102
|
+
A local delete clears L1 immediately, so the instance that made a change never
|
|
103
|
+
reads its own stale value.
|
|
104
|
+
|
|
105
|
+
A cache is an optimisation, so a broken L2 degrades rather than throws: remote
|
|
106
|
+
failures are reported through `onRemoteError` and the request is served from L1
|
|
107
|
+
or from the source. A value Redis returns that will not parse is a miss, not an
|
|
108
|
+
exception.
|
|
109
|
+
|
|
110
|
+
## Redis without a Redis dependency
|
|
111
|
+
|
|
112
|
+
`RedisCacheStore` is written against `RedisClientPort` — six commands — rather
|
|
113
|
+
than against ioredis or node-redis. The heavyweight client stays out of the
|
|
114
|
+
install for the deployments that never use it, and the store is testable
|
|
115
|
+
without a daemon, which is what the suite does.
|
|
116
|
+
|
|
117
|
+
Two details worth keeping: prefix invalidation uses `SCAN`, never `KEYS` (which
|
|
118
|
+
is O(n) over the keyspace and blocks the server every other service depends
|
|
119
|
+
on), and `clear()` is scoped to the store's own prefix rather than flushing the
|
|
120
|
+
database out from under its neighbours.
|
|
121
|
+
|
|
122
|
+
## Not yet implemented
|
|
123
|
+
|
|
124
|
+
- A `@Cacheable()` method decorator. The explicit `wrap` call is currently the
|
|
125
|
+
only entry point, which keeps the cache key visible at the call site.
|
|
126
|
+
- Stale-while-revalidate: `CacheOutcome` reserves a `stale` case for it.
|
|
127
|
+
- Redis Cluster tag indexes; the tag set assumes a single keyspace.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `NageCacheModule.forRoot(config)` (PLAN.md §11.1 item 6).
|
|
3
|
+
*
|
|
4
|
+
* Disabled is the default, and a disabled feature contributes **no provider** —
|
|
5
|
+
* not a no-op one. The acceptance criterion for Phase 8 is that enabling and
|
|
6
|
+
* disabling a feature cleanly adds and removes providers, so a module that
|
|
7
|
+
* always registered a null cache would pass by cheating.
|
|
8
|
+
*
|
|
9
|
+
* The driver is chosen here, once, from configuration: `memory` for a single
|
|
10
|
+
* instance, `redis` for a shared one, `two-tier` for both. Application code
|
|
11
|
+
* injects `CacheService` and never learns which it got.
|
|
12
|
+
*/
|
|
13
|
+
import { type DynamicModule, type OnApplicationShutdown } from '@nestjs/common';
|
|
14
|
+
import type { CacheConfig } from '@nage-api/contracts';
|
|
15
|
+
import { type RedisClientPort } from './redis.store.js';
|
|
16
|
+
import type { CacheStore, Clock } from './ports.js';
|
|
17
|
+
export interface NageCacheModuleOptions {
|
|
18
|
+
readonly cache?: CacheConfig;
|
|
19
|
+
/** Required when the driver is `redis` or `two-tier`. */
|
|
20
|
+
readonly redis?: RedisClientPort;
|
|
21
|
+
/** Supply a store directly, bypassing driver selection. */
|
|
22
|
+
readonly store?: CacheStore;
|
|
23
|
+
readonly clock?: Clock;
|
|
24
|
+
/** Reported when the shared tier fails; a broken L2 degrades, never throws. */
|
|
25
|
+
readonly onRemoteError?: (operation: string, error: unknown) => void;
|
|
26
|
+
}
|
|
27
|
+
export declare class NageCacheModule implements OnApplicationShutdown {
|
|
28
|
+
static forRoot(options?: NageCacheModuleOptions): DynamicModule;
|
|
29
|
+
/** Stop the sweep timers so a test suite and a `SIGTERM` both exit cleanly. */
|
|
30
|
+
onApplicationShutdown(): void;
|
|
31
|
+
private static buildStore;
|
|
32
|
+
private static memoryStore;
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=cache.module.d.ts.map
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `NageCacheModule.forRoot(config)` (PLAN.md §11.1 item 6).
|
|
4
|
+
*
|
|
5
|
+
* Disabled is the default, and a disabled feature contributes **no provider** —
|
|
6
|
+
* not a no-op one. The acceptance criterion for Phase 8 is that enabling and
|
|
7
|
+
* disabling a feature cleanly adds and removes providers, so a module that
|
|
8
|
+
* always registered a null cache would pass by cheating.
|
|
9
|
+
*
|
|
10
|
+
* The driver is chosen here, once, from configuration: `memory` for a single
|
|
11
|
+
* instance, `redis` for a shared one, `two-tier` for both. Application code
|
|
12
|
+
* injects `CacheService` and never learns which it got.
|
|
13
|
+
*/
|
|
14
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
15
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
16
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
17
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
18
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
19
|
+
};
|
|
20
|
+
var NageCacheModule_1;
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.NageCacheModule = void 0;
|
|
23
|
+
const common_1 = require("@nestjs/common");
|
|
24
|
+
const core_1 = require("@nage-api/core");
|
|
25
|
+
const cache_service_js_1 = require("./cache.service.js");
|
|
26
|
+
const memory_store_js_1 = require("./memory.store.js");
|
|
27
|
+
const redis_store_js_1 = require("./redis.store.js");
|
|
28
|
+
const two_tier_store_js_1 = require("./two-tier.store.js");
|
|
29
|
+
const tokens_js_1 = require("./tokens.js");
|
|
30
|
+
/**
|
|
31
|
+
* Sweep timers created by `forRoot`, so shutdown can stop them.
|
|
32
|
+
*
|
|
33
|
+
* Module-scope rather than a static field: a decorated class may not carry a
|
|
34
|
+
* static private identifier, and a public static would be part of the API.
|
|
35
|
+
*/
|
|
36
|
+
const sweepers = [];
|
|
37
|
+
let NageCacheModule = NageCacheModule_1 = class NageCacheModule {
|
|
38
|
+
static forRoot(options = {}) {
|
|
39
|
+
const config = options.cache ?? {};
|
|
40
|
+
// Off means off: no store, no service, nothing to inject.
|
|
41
|
+
if (config.enabled === false) {
|
|
42
|
+
return { module: NageCacheModule_1, providers: [], exports: [] };
|
|
43
|
+
}
|
|
44
|
+
const store = options.store ?? NageCacheModule_1.buildStore(config, options);
|
|
45
|
+
const service = new cache_service_js_1.CacheService({
|
|
46
|
+
store,
|
|
47
|
+
...(config.namespace === undefined ? {} : { namespace: config.namespace }),
|
|
48
|
+
defaultTtlMs: config.ttl === undefined ? 0 : (0, core_1.parseDurationMs)(config.ttl),
|
|
49
|
+
...(options.clock === undefined ? {} : { clock: options.clock }),
|
|
50
|
+
});
|
|
51
|
+
const providers = [
|
|
52
|
+
{ provide: tokens_js_1.NAGE_CACHE_STORE, useValue: store },
|
|
53
|
+
{ provide: tokens_js_1.NAGE_CACHE, useValue: service },
|
|
54
|
+
{ provide: cache_service_js_1.CacheService, useValue: service },
|
|
55
|
+
];
|
|
56
|
+
return {
|
|
57
|
+
module: NageCacheModule_1,
|
|
58
|
+
providers,
|
|
59
|
+
exports: [tokens_js_1.NAGE_CACHE, tokens_js_1.NAGE_CACHE_STORE, cache_service_js_1.CacheService],
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** Stop the sweep timers so a test suite and a `SIGTERM` both exit cleanly. */
|
|
63
|
+
onApplicationShutdown() {
|
|
64
|
+
for (const store of sweepers.splice(0))
|
|
65
|
+
store.stop();
|
|
66
|
+
}
|
|
67
|
+
static buildStore(config, options) {
|
|
68
|
+
const driver = config.driver ?? 'memory';
|
|
69
|
+
if (driver === 'memory')
|
|
70
|
+
return NageCacheModule_1.memoryStore(options);
|
|
71
|
+
if (options.redis === undefined) {
|
|
72
|
+
throw new core_1.ConfigurationError({
|
|
73
|
+
detail: `cache.driver "${driver}" needs a Redis client; pass one to NageCacheModule.forRoot({ redis })`,
|
|
74
|
+
meta: { setting: 'cache.driver', driver },
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const remote = new redis_store_js_1.RedisCacheStore({
|
|
78
|
+
client: options.redis,
|
|
79
|
+
...(config.namespace === undefined ? {} : { keyPrefix: `${config.namespace}:` }),
|
|
80
|
+
});
|
|
81
|
+
if (driver === 'redis')
|
|
82
|
+
return remote;
|
|
83
|
+
return new two_tier_store_js_1.TwoTierCacheStore({
|
|
84
|
+
l1: NageCacheModule_1.memoryStore(options),
|
|
85
|
+
l2: remote,
|
|
86
|
+
...(options.clock === undefined ? {} : { clock: options.clock }),
|
|
87
|
+
...(options.onRemoteError === undefined ? {} : { onRemoteError: options.onRemoteError }),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
static memoryStore(options) {
|
|
91
|
+
const store = new memory_store_js_1.MemoryCacheStore(options.clock === undefined ? {} : { clock: options.clock });
|
|
92
|
+
sweepers.push(store);
|
|
93
|
+
return store;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
exports.NageCacheModule = NageCacheModule;
|
|
97
|
+
exports.NageCacheModule = NageCacheModule = NageCacheModule_1 = __decorate([
|
|
98
|
+
(0, common_1.Module)({})
|
|
99
|
+
], NageCacheModule);
|
|
100
|
+
//# sourceMappingURL=cache.module.js.map
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The typed cache application code uses (PLAN.md §8).
|
|
3
|
+
*
|
|
4
|
+
* Three things it adds over a bare store:
|
|
5
|
+
*
|
|
6
|
+
* **Namespacing.** Every key is prefixed, so `cache.namespace('product')` can
|
|
7
|
+
* be dropped wholesale without knowing which keys it wrote. The legacy
|
|
8
|
+
* framework shared one flat keyspace, which meant invalidation was either
|
|
9
|
+
* surgical-and-wrong or a full flush.
|
|
10
|
+
*
|
|
11
|
+
* **Single-flight.** Concurrent `wrap` calls for the same key run the loader
|
|
12
|
+
* once. Without it, a popular key expiring under load starts one identical
|
|
13
|
+
* database query per in-flight request — the cache stampede that turns a cache
|
|
14
|
+
* miss into an outage.
|
|
15
|
+
*
|
|
16
|
+
* **Typing.** `wrap<T>` returns `T`, not `any`. A cache that hands back
|
|
17
|
+
* `unknown` pushes a cast to every call site, and those casts are where a
|
|
18
|
+
* schema change stops being a type error.
|
|
19
|
+
*/
|
|
20
|
+
import type { CacheStats, CacheStore, Clock } from './ports.js';
|
|
21
|
+
export interface CacheServiceOptions {
|
|
22
|
+
readonly store: CacheStore;
|
|
23
|
+
/** Prefix applied to every key, e.g. the application name. */
|
|
24
|
+
readonly namespace?: string;
|
|
25
|
+
/** Default entry lifetime; `0` means "until invalidated". */
|
|
26
|
+
readonly defaultTtlMs?: number;
|
|
27
|
+
readonly clock?: Clock;
|
|
28
|
+
}
|
|
29
|
+
export interface CacheSetOptions {
|
|
30
|
+
/** Milliseconds, or a duration string like `5m`. */
|
|
31
|
+
readonly ttl?: number | string;
|
|
32
|
+
readonly tags?: readonly string[];
|
|
33
|
+
}
|
|
34
|
+
export interface CacheWrapOptions extends CacheSetOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Skip the read and refresh the entry. For a "force refresh" button, not for
|
|
37
|
+
* routine use.
|
|
38
|
+
*/
|
|
39
|
+
readonly refresh?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Cache a loader's `undefined` result too.
|
|
42
|
+
*
|
|
43
|
+
* Off by default, because caching absence is how a race writes a tombstone
|
|
44
|
+
* over a value that arrived a millisecond later. Turn it on for lookups where
|
|
45
|
+
* "not found" is the common answer and the cost of a stale miss is low.
|
|
46
|
+
*/
|
|
47
|
+
readonly cacheEmpty?: boolean;
|
|
48
|
+
}
|
|
49
|
+
export declare class CacheService {
|
|
50
|
+
#private;
|
|
51
|
+
constructor(options: CacheServiceOptions);
|
|
52
|
+
/** A view scoped to a sub-namespace, sharing the same store and counters. */
|
|
53
|
+
namespace(name: string): CacheService;
|
|
54
|
+
get<TValue>(key: string): Promise<TValue | undefined>;
|
|
55
|
+
set(key: string, value: unknown, options?: CacheSetOptions): Promise<void>;
|
|
56
|
+
delete(key: string): Promise<void>;
|
|
57
|
+
/** Drop everything this namespace wrote. */
|
|
58
|
+
invalidateNamespace(name?: string): Promise<number>;
|
|
59
|
+
/** Drop every entry labelled with a tag, wherever it was written. */
|
|
60
|
+
invalidateTag(tag: string): Promise<number>;
|
|
61
|
+
/**
|
|
62
|
+
* Read through the cache, loading on a miss.
|
|
63
|
+
*
|
|
64
|
+
* Concurrent calls for the same key share one loader invocation, so a key
|
|
65
|
+
* expiring under load costs one query rather than one per request.
|
|
66
|
+
*/
|
|
67
|
+
wrap<TValue>(key: string, load: () => Promise<TValue>, options?: CacheWrapOptions): Promise<TValue>;
|
|
68
|
+
get stats(): CacheStats;
|
|
69
|
+
resetStats(): void;
|
|
70
|
+
}
|
|
71
|
+
/** Accepts milliseconds or a duration string, so config and code agree. */
|
|
72
|
+
export declare function toMilliseconds(ttl: number | string | undefined): number | undefined;
|
|
73
|
+
//# sourceMappingURL=cache.service.d.ts.map
|