@baeta/cache-ioredis 0.0.0 → 2.0.0-next.13
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/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +164 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.js +127 -0
- package/dist/index.js.map +1 -0
- package/package.json +62 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @baeta/cache-ioredis
|
|
2
|
+
|
|
3
|
+
## 2.0.0-next.13
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#283](https://github.com/andreisergiu98/baeta/pull/283) [`762c26f`](https://github.com/andreisergiu98/baeta/commit/762c26fba654c27d0ed53405d576cac9339476e4) Thanks [@andreisergiu98](https://github.com/andreisergiu98)! - fix: do not overwrite with query items if they already exist to avoid missing invalidation events
|
|
8
|
+
|
|
9
|
+
- Updated dependencies [[`762c26f`](https://github.com/andreisergiu98/baeta/commit/762c26fba654c27d0ed53405d576cac9339476e4)]:
|
|
10
|
+
- @baeta/cache@2.0.0-next.13
|
|
11
|
+
|
|
12
|
+
## 2.0.0-next.12
|
|
13
|
+
|
|
14
|
+
### Minor Changes
|
|
15
|
+
|
|
16
|
+
- [#275](https://github.com/andreisergiu98/baeta/pull/275) [`54f4361`](https://github.com/andreisergiu98/baeta/commit/54f4361c857f2a3d32a29dd898b2be648ac0bb2c) Thanks [@andreisergiu98](https://github.com/andreisergiu98)! - Decouple cache from graphql
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- Updated dependencies [[`54f4361`](https://github.com/andreisergiu98/baeta/commit/54f4361c857f2a3d32a29dd898b2be648ac0bb2c)]:
|
|
21
|
+
- @baeta/cache-redis-common@2.0.0-next.12
|
|
22
|
+
- @baeta/cache@2.0.0-next.12
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Pampu Andrei
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/andreisergiu98/baeta/refs/heads/main/website/static/img/logo-baeta.svg" alt="Baeta Logo" width="150"/>
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<div align="center">
|
|
6
|
+
<h1>Baeta</h1>
|
|
7
|
+
<a href="https://www.npmjs.com/package/@baeta/cli"><img src="https://img.shields.io/npm/v/@baeta/cli.svg?style=flat" /></a>
|
|
8
|
+
<a href="https://github.com/andreisergiu98/baeta/actions/workflows/checks.yml"><img src="https://img.shields.io/github/actions/workflow/status/andreisergiu98/baeta/checks.yml" /></a>
|
|
9
|
+
<a href="https://github.com/andreisergiu98/baeta/pulls"><img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" /></a>
|
|
10
|
+
<a href="https://github.com/andreisergiu98/baeta/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" /></a>
|
|
11
|
+
<br />
|
|
12
|
+
<br />
|
|
13
|
+
<a href="https://baeta.io/docs/getting-started/installation">Getting Started</a>
|
|
14
|
+
<span> • </span>
|
|
15
|
+
<a href="https://www.baeta.io/">Website</a>
|
|
16
|
+
<span> • </span>
|
|
17
|
+
<a href="https://baeta.io/docs/intro">Docs</a>
|
|
18
|
+
<span> • </span>
|
|
19
|
+
<a href="https://github.com/andreisergiu98/baeta/tree/main/examples">Examples</a>
|
|
20
|
+
<span> • </span>
|
|
21
|
+
<a href="https://discord.gg/BHFXHvyj">Discord</a>
|
|
22
|
+
<br />
|
|
23
|
+
<hr />
|
|
24
|
+
</div>
|
|
25
|
+
|
|
26
|
+
# What is Baeta?
|
|
27
|
+
|
|
28
|
+
Building GraphQL APIs shouldn't be complicated. **Baeta** is a modern, modular, open-source GraphQL framework designed with flexibility in mind. It follows a granular approach where you only add what you need, helping developers focus on what matters most - creating powerful, scalable APIs without the boilerplate.
|
|
29
|
+
|
|
30
|
+
### Key Features
|
|
31
|
+
|
|
32
|
+
- **Modular Architecture**: Organize your API into manageable modules
|
|
33
|
+
- **Schema-First Development**: Define your API contract upfront
|
|
34
|
+
- **Type Safety**: Automatic code generation for type-safe development
|
|
35
|
+
- **Middleware & Directives**: Easy integration of custom behaviors
|
|
36
|
+
- **High Performance**: Built for scalability and efficiency
|
|
37
|
+
|
|
38
|
+
#### And optional extensions and plugins
|
|
39
|
+
|
|
40
|
+
- **@baeta/extension-auth**: Add powerful scope-based authorization
|
|
41
|
+
- **@baeta/extension-cache**: Implement automatic caching with simple update patterns
|
|
42
|
+
- ... and more!
|
|
43
|
+
|
|
44
|
+
## Why use Baeta?
|
|
45
|
+
|
|
46
|
+
Baeta makes it easy to build better GraphQL APIs while staying flexible. Here's how:
|
|
47
|
+
|
|
48
|
+
**Granular and Progressive:** Start small and add features as you need them. Whether you're building a simple API or a complex system, Baeta scales with your needs.
|
|
49
|
+
|
|
50
|
+
**Modular architecture:** Baeta's modular design allows you to organize your GraphQL API into smaller, more manageable modules that can be added or removed as needed. This makes it easier to maintain and scale your API over time.
|
|
51
|
+
|
|
52
|
+
**Schema-first approach:** With Baeta, you define your schema first, and then logic and resolvers. This approach ensures a consistent and well-defined API for your clients and reduces boilerplate code.
|
|
53
|
+
|
|
54
|
+
## How it Works
|
|
55
|
+
|
|
56
|
+
#### 1. Define your schema
|
|
57
|
+
|
|
58
|
+
```graphql
|
|
59
|
+
type User {
|
|
60
|
+
id: ID!
|
|
61
|
+
name: String!
|
|
62
|
+
email: String!
|
|
63
|
+
age: Int
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
input UserWhereUnique {
|
|
67
|
+
id: ID
|
|
68
|
+
email: String
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
type Query {
|
|
72
|
+
user(where: UserWhereUnique!): User!
|
|
73
|
+
users: [User!]!
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
#### 2. Implement your resolvers
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { UserModule } from "./typedef.ts";
|
|
81
|
+
|
|
82
|
+
const { Query } = UserModule;
|
|
83
|
+
|
|
84
|
+
const userQuery = Query.user.resolve(({ args }) => {
|
|
85
|
+
return dataSource.user.find(args.where);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const usersQuery = Query.users.resolve(() => {
|
|
89
|
+
return dataSource.user.findMany();
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
Query.$fields({
|
|
93
|
+
user: userQuery,
|
|
94
|
+
users: usersQuery,
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
#### 3. Add authorization
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
import { UserModule } from "./typedef.ts";
|
|
102
|
+
|
|
103
|
+
const { Query } = UserModule;
|
|
104
|
+
|
|
105
|
+
const userQuery = Query.user
|
|
106
|
+
.$auth({
|
|
107
|
+
$or: {
|
|
108
|
+
isPublic: true,
|
|
109
|
+
isLoggedIn: true,
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
.resolve(async ({ args }) => {
|
|
113
|
+
// ...
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
#### 4. Add caching
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
const { Query, Mutation, User } = UserModule;
|
|
121
|
+
|
|
122
|
+
export const userCache = User.$createCache();
|
|
123
|
+
|
|
124
|
+
const userQuery = Query.user
|
|
125
|
+
.$auth({
|
|
126
|
+
// ...
|
|
127
|
+
})
|
|
128
|
+
.$useCache(userCache)
|
|
129
|
+
.resolve(async ({ args }) => {
|
|
130
|
+
// ...
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const updateUserMutation = Mutation.updateUser
|
|
134
|
+
.$use(async (next) => {
|
|
135
|
+
const user = await next();
|
|
136
|
+
await userCache.save(user);
|
|
137
|
+
return user;
|
|
138
|
+
})
|
|
139
|
+
.resolve(async ({ args }) => {
|
|
140
|
+
// ...
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Compatibility
|
|
145
|
+
|
|
146
|
+
Baeta is compatible with all GraphQL servers, which makes it easy to integrate with your existing stack. It works seamlessly with popular GraphQL server libraries such as **Graphql Yoga** and **Apollo Server**, as well as other popular tools like **Prisma**, **Drizzle** and **Kysely**.
|
|
147
|
+
|
|
148
|
+
Baeta's development tools are built for Node.js, but the runtime code is environment-agnostic. This means your Baeta applications can run anywhere JavaScript runs, including:
|
|
149
|
+
|
|
150
|
+
- Deno
|
|
151
|
+
- Cloudflare Workers
|
|
152
|
+
- AWS Lambda
|
|
153
|
+
- Vercel Edge Functions
|
|
154
|
+
- Bun
|
|
155
|
+
- Node.js
|
|
156
|
+
- Any other JavaScript runtime
|
|
157
|
+
|
|
158
|
+
## Credits
|
|
159
|
+
|
|
160
|
+
Baeta was inspired by several amazing projects and people in the GraphQL ecosystem. Check out our [Credits page](https://baeta.io/docs/credits) to learn more about the individuals and projects that influenced Baeta's development.
|
|
161
|
+
|
|
162
|
+
## License
|
|
163
|
+
|
|
164
|
+
Baeta is licensed under the [MIT License](./LICENSE).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { CacheClient, CacheClientArgs, CacheClientOptions, CacheClientSaveOptions, ItemCacheKey, QueryCacheIndexKey, QueryCacheKey } from "@baeta/cache";
|
|
2
|
+
import { RedisScripts } from "@baeta/cache-redis-common";
|
|
3
|
+
import Redis, { Cluster } from "ioredis";
|
|
4
|
+
|
|
5
|
+
//#region lib/cache-client.d.ts
|
|
6
|
+
interface RedisCacheClientOptions extends CacheClientOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Maximum total size of commands in a single pipeline batch. If the batch exceeds this size, it will be executed immediately.
|
|
9
|
+
* @defaultValue 50 * 1024 * 1024 (50MB)
|
|
10
|
+
*/
|
|
11
|
+
maxPipelineSizeLimit?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Maximum number of commands in a single pipeline batch. If the batch exceeds this number, it will be executed immediately.
|
|
14
|
+
* @defaultValue 100_000
|
|
15
|
+
*/
|
|
16
|
+
maxPipelineCommandLimit?: number;
|
|
17
|
+
/**
|
|
18
|
+
* Maximum number of keys in a single command. If the number of keys exceeds this limit, multiple commands will be executed.
|
|
19
|
+
* @defaultValue 100_000
|
|
20
|
+
*/
|
|
21
|
+
maxCommandKeysLimit?: number;
|
|
22
|
+
}
|
|
23
|
+
declare class RedisCacheClient extends CacheClient {
|
|
24
|
+
redis: Redis | Cluster;
|
|
25
|
+
protected maxPipelineSizeLimit: number;
|
|
26
|
+
protected maxPipelineCommandLimit: number;
|
|
27
|
+
protected maxCommandKeysLimit: number;
|
|
28
|
+
protected scripts: RedisScripts;
|
|
29
|
+
constructor(redis: Redis | Cluster, options?: RedisCacheClientOptions);
|
|
30
|
+
getPartialItems<Item>(keys: ItemCacheKey[], options: CacheClientArgs<Item>): Promise<Array<Item | null>>;
|
|
31
|
+
saveItems<Item>(items: Array<[ItemCacheKey, Item]>, options: CacheClientArgs<Item>, saveOptions?: CacheClientSaveOptions): Promise<void>;
|
|
32
|
+
saveItemsWithDiff<Item>(items: Array<[ItemCacheKey, Item]>, options: CacheClientArgs<Item>): Promise<Array<Item | null>>;
|
|
33
|
+
deleteItems(keys: ItemCacheKey[]): Promise<void>;
|
|
34
|
+
deleteItemsWithDiff<Item>(keys: ItemCacheKey[], options: CacheClientArgs<Item>): Promise<Array<Item | null>>;
|
|
35
|
+
getQuery<QueryMetadata>(key: QueryCacheKey, options: CacheClientArgs<QueryMetadata>): Promise<QueryMetadata | null>;
|
|
36
|
+
saveQuery<QueryMetadata>(key: QueryCacheKey, indexes: QueryCacheIndexKey[], metadata: QueryMetadata, options: CacheClientArgs<QueryMetadata>): Promise<void>;
|
|
37
|
+
deleteQueries(indexes: QueryCacheIndexKey[]): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
export { RedisCacheClient, RedisCacheClientOptions };
|
|
41
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { CacheClient } from "@baeta/cache";
|
|
2
|
+
import { doBatched } from "@baeta/cache/sdk";
|
|
3
|
+
import { assertNoPipelineErrors, batchPipeline, createRedisScripts } from "@baeta/cache-redis-common";
|
|
4
|
+
//#region lib/cache-client.ts
|
|
5
|
+
const INDEX_BUFFER_MS = 1e3;
|
|
6
|
+
const MAX_PIPELINE_SIZE_LIMIT = 50 * 1024 * 1024;
|
|
7
|
+
const MAX_PIPELINE_COMMAND_LIMIT = 1e5;
|
|
8
|
+
const MAX_COMMAND_KEYS_LIMIT = 1e5;
|
|
9
|
+
var RedisCacheClient = class extends CacheClient {
|
|
10
|
+
redis;
|
|
11
|
+
maxPipelineSizeLimit;
|
|
12
|
+
maxPipelineCommandLimit;
|
|
13
|
+
maxCommandKeysLimit;
|
|
14
|
+
scripts;
|
|
15
|
+
constructor(redis, options) {
|
|
16
|
+
super({
|
|
17
|
+
namespace: options?.namespace,
|
|
18
|
+
revision: options?.revision,
|
|
19
|
+
ttlMs: options?.ttlMs
|
|
20
|
+
});
|
|
21
|
+
this.redis = redis;
|
|
22
|
+
this.maxPipelineSizeLimit = options?.maxPipelineSizeLimit ?? MAX_PIPELINE_SIZE_LIMIT;
|
|
23
|
+
this.maxPipelineCommandLimit = options?.maxPipelineCommandLimit ?? MAX_PIPELINE_COMMAND_LIMIT;
|
|
24
|
+
this.maxCommandKeysLimit = options?.maxCommandKeysLimit ?? MAX_COMMAND_KEYS_LIMIT;
|
|
25
|
+
const loadScript = async (script) => {
|
|
26
|
+
return await this.redis.script("LOAD", script);
|
|
27
|
+
};
|
|
28
|
+
const evalSha = async (sha, keys, args) => {
|
|
29
|
+
return await this.redis.evalsha(sha, keys.length, ...keys, ...args);
|
|
30
|
+
};
|
|
31
|
+
this.scripts = createRedisScripts(loadScript, evalSha);
|
|
32
|
+
}
|
|
33
|
+
async getPartialItems(keys, options) {
|
|
34
|
+
if (keys.length === 0) return [];
|
|
35
|
+
const values = [];
|
|
36
|
+
await doBatched(keys, this.maxCommandKeysLimit, async (batch) => {
|
|
37
|
+
const batchValues = await this.redis.mget(batch);
|
|
38
|
+
for (const value of batchValues) values.push(value == null ? null : options.parse(value));
|
|
39
|
+
});
|
|
40
|
+
return values;
|
|
41
|
+
}
|
|
42
|
+
async saveItems(items, options, saveOptions = {}) {
|
|
43
|
+
if (items.length === 0) return;
|
|
44
|
+
const expiresAt = Date.now() + options.ttlMs;
|
|
45
|
+
await batchPipeline({
|
|
46
|
+
makePipeline: () => this.redis.pipeline(),
|
|
47
|
+
addCommand: (pipeline, item) => {
|
|
48
|
+
if (saveOptions.disableOverwrite !== true) pipeline.set(item.key, item.value, "PXAT", expiresAt);
|
|
49
|
+
else {
|
|
50
|
+
pipeline.setnx(item.key, item.value);
|
|
51
|
+
pipeline.pexpireat(item.key, expiresAt);
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
executePipeline: async (pipeline) => {
|
|
55
|
+
const result = await pipeline.exec();
|
|
56
|
+
if (result == null) throw new Error("Unexpected null result from Redis pipeline");
|
|
57
|
+
assertNoPipelineErrors(result);
|
|
58
|
+
return [];
|
|
59
|
+
},
|
|
60
|
+
estimateSize: (item) => {
|
|
61
|
+
return item.key.length + item.value.length;
|
|
62
|
+
},
|
|
63
|
+
items: items.map(([key, value]) => ({
|
|
64
|
+
key,
|
|
65
|
+
value: options.serialize(value)
|
|
66
|
+
})),
|
|
67
|
+
maxBatchBytes: this.maxPipelineSizeLimit,
|
|
68
|
+
maxBatchCount: this.maxPipelineCommandLimit
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
async saveItemsWithDiff(items, options) {
|
|
72
|
+
if (items.length === 0) return [];
|
|
73
|
+
const expiresAt = Date.now() + options.ttlMs;
|
|
74
|
+
const keys = new Array(items.length);
|
|
75
|
+
const values = new Array(items.length);
|
|
76
|
+
for (let i = 0; i < items.length; i++) {
|
|
77
|
+
keys[i] = items[i][0];
|
|
78
|
+
values[i] = options.serialize(items[i][1]);
|
|
79
|
+
}
|
|
80
|
+
const result = await this.scripts.saveWithDiffScript(keys, [...values, expiresAt.toString()]);
|
|
81
|
+
if (!Array.isArray(result)) throw new Error(`Unexpected non-array result from Redis script: ${typeof result}`);
|
|
82
|
+
return result.map((value) => {
|
|
83
|
+
if (typeof value === "string") return options.parse(value);
|
|
84
|
+
return null;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
async deleteItems(keys) {
|
|
88
|
+
if (keys.length === 0) return;
|
|
89
|
+
await doBatched(keys, this.maxCommandKeysLimit, async (batch) => {
|
|
90
|
+
await this.redis.unlink(batch);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
async deleteItemsWithDiff(keys, options) {
|
|
94
|
+
if (keys.length === 0) return [];
|
|
95
|
+
const result = await this.scripts.deleteWithDiffScript(keys, []);
|
|
96
|
+
if (!Array.isArray(result)) throw new Error(`Unexpected non-array result from Redis script: ${typeof result}`);
|
|
97
|
+
return result.map((value) => {
|
|
98
|
+
if (typeof value === "string") return options.parse(value);
|
|
99
|
+
return null;
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
async getQuery(key, options) {
|
|
103
|
+
const meta = await this.redis.get(key);
|
|
104
|
+
return meta == null ? null : options.parse(meta);
|
|
105
|
+
}
|
|
106
|
+
async saveQuery(key, indexes, metadata, options) {
|
|
107
|
+
const now = Date.now();
|
|
108
|
+
const expiresAt = now + options.ttlMs;
|
|
109
|
+
const pipeline = this.redis.pipeline();
|
|
110
|
+
pipeline.set(key, options.serialize(metadata), "PXAT", expiresAt);
|
|
111
|
+
for (const indexKey of indexes) {
|
|
112
|
+
pipeline.zadd(indexKey, expiresAt, key);
|
|
113
|
+
pipeline.zremrangebyscore(indexKey, "-inf", now - INDEX_BUFFER_MS);
|
|
114
|
+
pipeline.pexpireat(indexKey, expiresAt + INDEX_BUFFER_MS);
|
|
115
|
+
}
|
|
116
|
+
assertNoPipelineErrors(await pipeline.exec());
|
|
117
|
+
}
|
|
118
|
+
async deleteQueries(indexes) {
|
|
119
|
+
if (indexes.length === 0) return;
|
|
120
|
+
const result = await this.scripts.deleteQueriesScript(indexes, []);
|
|
121
|
+
if (typeof result !== "number") throw new Error(`Unexpected non-number result from Redis script: ${typeof result}`);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
//#endregion
|
|
125
|
+
export { RedisCacheClient };
|
|
126
|
+
|
|
127
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../lib/cache-client.ts"],"sourcesContent":["import type {\n\tCacheClientSaveOptions,\n\tItemCacheKey,\n\tQueryCacheIndexKey,\n\tQueryCacheKey,\n} from '@baeta/cache';\nimport { CacheClient, type CacheClientArgs, type CacheClientOptions } from '@baeta/cache';\nimport { doBatched } from '@baeta/cache/sdk';\nimport {\n\tassertNoPipelineErrors,\n\tbatchPipeline,\n\tcreateRedisScripts,\n\ttype RedisScripts,\n} from '@baeta/cache-redis-common';\nimport type Redis from 'ioredis';\nimport type { Cluster as RedisCluster } from 'ioredis';\n\nconst INDEX_BUFFER_MS = 1_000;\nconst MAX_PIPELINE_SIZE_LIMIT = 50 * 1024 * 1024; // 50MB\nconst MAX_PIPELINE_COMMAND_LIMIT = 100_000;\nconst MAX_COMMAND_KEYS_LIMIT = 100_000;\n\nexport interface RedisCacheClientOptions extends CacheClientOptions {\n\t/**\n\t * Maximum total size of commands in a single pipeline batch. If the batch exceeds this size, it will be executed immediately.\n\t * @defaultValue 50 * 1024 * 1024 (50MB)\n\t */\n\tmaxPipelineSizeLimit?: number;\n\t/**\n\t * Maximum number of commands in a single pipeline batch. If the batch exceeds this number, it will be executed immediately.\n\t * @defaultValue 100_000\n\t */\n\tmaxPipelineCommandLimit?: number;\n\t/**\n\t * Maximum number of keys in a single command. If the number of keys exceeds this limit, multiple commands will be executed.\n\t * @defaultValue 100_000\n\t */\n\tmaxCommandKeysLimit?: number;\n}\n\nexport class RedisCacheClient extends CacheClient {\n\tredis: Redis | RedisCluster;\n\tprotected maxPipelineSizeLimit: number;\n\tprotected maxPipelineCommandLimit: number;\n\tprotected maxCommandKeysLimit: number;\n\tprotected scripts: RedisScripts;\n\n\tconstructor(redis: Redis | RedisCluster, options?: RedisCacheClientOptions) {\n\t\tsuper({\n\t\t\tnamespace: options?.namespace,\n\t\t\trevision: options?.revision,\n\t\t\tttlMs: options?.ttlMs,\n\t\t});\n\t\tthis.redis = redis;\n\t\tthis.maxPipelineSizeLimit = options?.maxPipelineSizeLimit ?? MAX_PIPELINE_SIZE_LIMIT;\n\t\tthis.maxPipelineCommandLimit = options?.maxPipelineCommandLimit ?? MAX_PIPELINE_COMMAND_LIMIT;\n\t\tthis.maxCommandKeysLimit = options?.maxCommandKeysLimit ?? MAX_COMMAND_KEYS_LIMIT;\n\t\tconst loadScript = async (script: string) => {\n\t\t\treturn await this.redis.script('LOAD', script);\n\t\t};\n\t\tconst evalSha = async (sha: string, keys: string[], args: string[]) => {\n\t\t\treturn await this.redis.evalsha(sha, keys.length, ...keys, ...args);\n\t\t};\n\t\tthis.scripts = createRedisScripts(loadScript, evalSha);\n\t}\n\n\tasync getPartialItems<Item>(\n\t\tkeys: ItemCacheKey[],\n\t\toptions: CacheClientArgs<Item>,\n\t): Promise<Array<Item | null>> {\n\t\tif (keys.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst values: Array<Item | null> = [];\n\t\tawait doBatched(keys, this.maxCommandKeysLimit, async (batch) => {\n\t\t\tconst batchValues = await this.redis.mget(batch);\n\t\t\tfor (const value of batchValues) {\n\t\t\t\tvalues.push(value == null ? null : options.parse(value));\n\t\t\t}\n\t\t});\n\t\treturn values;\n\t}\n\n\tasync saveItems<Item>(\n\t\titems: Array<[ItemCacheKey, Item]>,\n\t\toptions: CacheClientArgs<Item>,\n\t\tsaveOptions: CacheClientSaveOptions = {},\n\t): Promise<void> {\n\t\tif (items.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst expiresAt = Date.now() + options.ttlMs;\n\t\tconst serialized = items.map(([key, value]) => ({\n\t\t\tkey,\n\t\t\tvalue: options.serialize(value),\n\t\t}));\n\t\tawait batchPipeline({\n\t\t\tmakePipeline: () => this.redis.pipeline(),\n\t\t\taddCommand: (pipeline, item) => {\n\t\t\t\tif (saveOptions.disableOverwrite !== true) {\n\t\t\t\t\tpipeline.set(item.key, item.value, 'PXAT', expiresAt);\n\t\t\t\t} else {\n\t\t\t\t\tpipeline.setnx(item.key, item.value);\n\t\t\t\t\tpipeline.pexpireat(item.key, expiresAt);\n\t\t\t\t}\n\t\t\t},\n\t\t\texecutePipeline: async (pipeline) => {\n\t\t\t\tconst result = await pipeline.exec();\n\t\t\t\tif (result == null) {\n\t\t\t\t\tthrow new Error('Unexpected null result from Redis pipeline');\n\t\t\t\t}\n\t\t\t\tassertNoPipelineErrors(result);\n\t\t\t\treturn [];\n\t\t\t},\n\t\t\testimateSize: (item) => {\n\t\t\t\treturn item.key.length + item.value.length;\n\t\t\t},\n\t\t\titems: serialized,\n\t\t\tmaxBatchBytes: this.maxPipelineSizeLimit,\n\t\t\tmaxBatchCount: this.maxPipelineCommandLimit,\n\t\t});\n\t}\n\n\tasync saveItemsWithDiff<Item>(\n\t\titems: Array<[ItemCacheKey, Item]>,\n\t\toptions: CacheClientArgs<Item>,\n\t): Promise<Array<Item | null>> {\n\t\tif (items.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst expiresAt = Date.now() + options.ttlMs;\n\t\tconst keys: ItemCacheKey[] = new Array(items.length);\n\t\tconst values: string[] = new Array(items.length);\n\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\tkeys[i] = items[i][0];\n\t\t\tvalues[i] = options.serialize(items[i][1]);\n\t\t}\n\t\tconst result = await this.scripts.saveWithDiffScript(keys, [...values, expiresAt.toString()]);\n\t\tif (!Array.isArray(result)) {\n\t\t\tthrow new Error(`Unexpected non-array result from Redis script: ${typeof result}`);\n\t\t}\n\t\treturn result.map((value) => {\n\t\t\tif (typeof value === 'string') {\n\t\t\t\treturn options.parse(value);\n\t\t\t}\n\t\t\treturn null;\n\t\t});\n\t}\n\n\tasync deleteItems(keys: ItemCacheKey[]): Promise<void> {\n\t\tif (keys.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tawait doBatched(keys, this.maxCommandKeysLimit, async (batch) => {\n\t\t\tawait this.redis.unlink(batch);\n\t\t});\n\t}\n\n\tasync deleteItemsWithDiff<Item>(\n\t\tkeys: ItemCacheKey[],\n\t\toptions: CacheClientArgs<Item>,\n\t): Promise<Array<Item | null>> {\n\t\tif (keys.length === 0) {\n\t\t\treturn [];\n\t\t}\n\t\tconst result = await this.scripts.deleteWithDiffScript(keys, []);\n\t\tif (!Array.isArray(result)) {\n\t\t\tthrow new Error(`Unexpected non-array result from Redis script: ${typeof result}`);\n\t\t}\n\t\treturn result.map((value) => {\n\t\t\tif (typeof value === 'string') {\n\t\t\t\treturn options.parse(value);\n\t\t\t}\n\t\t\treturn null;\n\t\t});\n\t}\n\n\tasync getQuery<QueryMetadata>(\n\t\tkey: QueryCacheKey,\n\t\toptions: CacheClientArgs<QueryMetadata>,\n\t): Promise<QueryMetadata | null> {\n\t\tconst meta = await this.redis.get(key);\n\t\treturn meta == null ? null : options.parse(meta);\n\t}\n\n\tasync saveQuery<QueryMetadata>(\n\t\tkey: QueryCacheKey,\n\t\tindexes: QueryCacheIndexKey[],\n\t\tmetadata: QueryMetadata,\n\t\toptions: CacheClientArgs<QueryMetadata>,\n\t): Promise<void> {\n\t\tconst now = Date.now();\n\t\tconst expiresAt = now + options.ttlMs;\n\t\tconst pipeline = this.redis.pipeline();\n\t\tpipeline.set(key, options.serialize(metadata), 'PXAT', expiresAt);\n\t\tfor (const indexKey of indexes) {\n\t\t\tpipeline.zadd(indexKey, expiresAt, key);\n\t\t\tpipeline.zremrangebyscore(indexKey, '-inf', now - INDEX_BUFFER_MS);\n\t\t\tpipeline.pexpireat(indexKey, expiresAt + INDEX_BUFFER_MS);\n\t\t}\n\t\tconst result = await pipeline.exec();\n\t\tassertNoPipelineErrors(result);\n\t}\n\n\tasync deleteQueries(indexes: QueryCacheIndexKey[]): Promise<void> {\n\t\tif (indexes.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst result = await this.scripts.deleteQueriesScript(indexes, []);\n\t\tif (typeof result !== 'number') {\n\t\t\tthrow new Error(`Unexpected non-number result from Redis script: ${typeof result}`);\n\t\t}\n\t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ql",
|
|
@@ -25,10 +25,69 @@
|
|
|
25
25
|
"url": "https://github.com/andreisergiu98"
|
|
26
26
|
},
|
|
27
27
|
"type": "module",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"default": "./dist/index.js"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"types": "dist/index.d.ts",
|
|
28
35
|
"files": [
|
|
36
|
+
"dist",
|
|
29
37
|
"package.json"
|
|
30
38
|
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "builder build",
|
|
41
|
+
"check:deps": "builder check-deps",
|
|
42
|
+
"prepack": "builder prepare",
|
|
43
|
+
"postpack": "builder prepare --restore",
|
|
44
|
+
"test": "builder test --skip-coverage",
|
|
45
|
+
"types": "tsc --noEmit"
|
|
46
|
+
},
|
|
47
|
+
"ava": {
|
|
48
|
+
"extensions": [
|
|
49
|
+
"ts"
|
|
50
|
+
]
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@baeta/cache-redis-common": "^2.0.0-next.12"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@baeta/builder": "^0.0.0",
|
|
57
|
+
"@baeta/cache": "^2.0.0-next.13",
|
|
58
|
+
"@baeta/testing": "^0.0.0",
|
|
59
|
+
"@baeta/tests-cache-clients": "^0.0.0",
|
|
60
|
+
"@baeta/tsconfig": "^0.0.0",
|
|
61
|
+
"ioredis": "^5.10.1",
|
|
62
|
+
"typescript": "^6.0.0"
|
|
63
|
+
},
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"@baeta/cache": "^2.0.0-next.13",
|
|
66
|
+
"ioredis": "^5.10.0"
|
|
67
|
+
},
|
|
68
|
+
"engines": {
|
|
69
|
+
"node": ">=22.20.0"
|
|
70
|
+
},
|
|
31
71
|
"publishConfig": {
|
|
32
|
-
"access": "public"
|
|
72
|
+
"access": "public",
|
|
73
|
+
"exports": {
|
|
74
|
+
".": {
|
|
75
|
+
"types": "./dist/index.d.ts",
|
|
76
|
+
"default": "./dist/index.js"
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
"typedocOptions": {
|
|
81
|
+
"entryPoints": [
|
|
82
|
+
"./index.ts"
|
|
83
|
+
],
|
|
84
|
+
"readme": "none",
|
|
85
|
+
"tsconfig": "./tsconfig.json",
|
|
86
|
+
"sort": [
|
|
87
|
+
"kind",
|
|
88
|
+
"instance-first",
|
|
89
|
+
"required-first",
|
|
90
|
+
"alphabetical-ignoring-documents"
|
|
91
|
+
]
|
|
33
92
|
}
|
|
34
|
-
}
|
|
93
|
+
}
|