@n8io/baseline-redis 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +36 -2
- package/dist/index.d.ts +36 -0
- package/dist/index.js +77 -0
- package/package.json +36 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nate Clark
|
|
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
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @n8io/baseline-redis
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The one Redis connection a process shares, for `@n8io/baseline-cache` and `@n8io/baseline-live`. It owns the parts every app gets wrong when it copies them: an unreachable Redis fails startup at once instead of retrying forever, a dropped connection reconnects for good after that, and the client's `error` event is always listened to, since node-redis exits the process on an unlistened one.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pnpm add @n8io/baseline-redis
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Exports
|
|
10
|
+
|
|
11
|
+
- `redisClientCreate({ url, vendor? })`: resolves with a connected node-redis client. The connect, handshake included, gives up after 3 s and never retries, so startup fails while Redis is unreachable or not answering. Once connected, a dropped connection reconnects every min(retries × 100 ms, 2 s), for as long as it takes. A command waits at most 1 s to be sent. Errors are logged at error, never with the URL, which may carry a password.
|
|
12
|
+
- `RedisClient`: what it resolves with, a node-redis client. Close it with `close()`; `await using` calls `close()` when its block ends.
|
|
13
|
+
- `RedisClientVendorOptions`: `vendor`, node-redis's own client settings (`socket.ca`, `name`, `keyPrefix`), outside the contract. A key the URL or this Package sets throws: `username`, `password`, `database`, `commandOptions`, `socket.host`, `socket.port`, `socket.path`, `socket.tls`, `socket.connectTimeout` and `socket.reconnectStrategy`, and `credentialsProvider` when the URL carries a user or password.
|
|
14
|
+
|
|
15
|
+
`url` is `redis://` or `rediss://` (TLS), with any user, password and database in it. One URL fits a highly available Redis whose endpoint follows the primary: a managed one, or a proxy in front of Sentinel. For Sentinel or Cluster addressed directly, `pnpm add redis` and build the client with node-redis's `createSentinel` or `createCluster` yourself, with your own `error` listener, and pass it to the cache and live adapters, which take any connected node-redis client. Nothing tests that path.
|
|
16
|
+
|
|
17
|
+
## Example
|
|
18
|
+
|
|
19
|
+
Open one connection per process and build the cache store and live hub on it:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { cacheStoreRedisCreate } from "@n8io/baseline-cache";
|
|
23
|
+
import { liveHubRedisCreate } from "@n8io/baseline-live";
|
|
24
|
+
import { redisClientCreate } from "@n8io/baseline-redis";
|
|
25
|
+
|
|
26
|
+
const redisClient = await redisClientCreate({ url: ENV.CACHE_URL });
|
|
27
|
+
const cacheStore = cacheStoreRedisCreate({ redisClient });
|
|
28
|
+
const liveHub = liveHubRedisCreate({ redisClient });
|
|
29
|
+
|
|
30
|
+
// At shutdown, after the live hub:
|
|
31
|
+
await liveHub.close();
|
|
32
|
+
await redisClient.close();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Tests
|
|
36
|
+
|
|
37
|
+
`pnpm test` runs every test; the `*.redis.test.ts` files start a Redis container, so they need Docker.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { RedisClientOptions as RedisClientOptions$1, RedisClientType } from "redis";
|
|
2
|
+
/**
|
|
3
|
+
* A connected node-redis client, for `cacheStoreRedisCreate`, `liveHubRedisCreate` and a Project's
|
|
4
|
+
* own adapters. Close it with `close()`; `await using` calls `close()` when its block ends.
|
|
5
|
+
*/
|
|
6
|
+
type RedisClient = RedisClientType & AsyncDisposable;
|
|
7
|
+
declare const redisVendorOwnedKeys: {
|
|
8
|
+
readonly commandOptions: "this Package (1 s to send a command)";
|
|
9
|
+
readonly database: "url (redis://host/<database>)";
|
|
10
|
+
readonly password: "url (redis://user:password@host)";
|
|
11
|
+
readonly url: "url";
|
|
12
|
+
readonly username: "url (redis://user:password@host)";
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* node-redis's own client settings, passed through as they are: `socket.ca`, `name`, `keyPrefix`
|
|
16
|
+
* and the like. Outside this Package's contract: nothing here is tested, and moving off
|
|
17
|
+
* node-redis deletes it. The keys the URL and this Package set are refused, and the ones that would
|
|
18
|
+
* change the client's type are left out.
|
|
19
|
+
*/
|
|
20
|
+
type RedisClientVendorOptions = Omit<RedisClientOptions$1, keyof typeof redisVendorOwnedKeys | "functions" | "modules" | "RESP" | "scripts" | "typeMapping">;
|
|
21
|
+
/** What `redisClientCreate` takes; not node-redis's own `RedisClientOptions`, which `vendor` carries. */
|
|
22
|
+
type RedisClientOptions = {
|
|
23
|
+
/** redis:// or rediss:// (TLS). It may carry a user, a password and a database number. */
|
|
24
|
+
url: string;
|
|
25
|
+
/** Settings only node-redis has. */
|
|
26
|
+
vendor?: RedisClientVendorOptions | null;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Opens the one Redis connection a process shares, and resolves once it is connected, so an
|
|
30
|
+
* unreachable Redis stops startup within the 3 s connect timeout instead of retrying. After that a
|
|
31
|
+
* dropped connection reconnects every min(retries × 100 ms, 2 s), for as long as it takes. One URL
|
|
32
|
+
* fits a highly available Redis whose endpoint follows the primary (a managed one, or a proxy in
|
|
33
|
+
* front of Sentinel); Sentinel or Cluster addressed directly is not supported.
|
|
34
|
+
*/
|
|
35
|
+
export declare const redisClientCreate: ({ url, vendor }: RedisClientOptions) => Promise<RedisClient>;
|
|
36
|
+
export type { RedisClient, RedisClientOptions, RedisClientVendorOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { logger } from "@n8io/baseline-logger";
|
|
2
|
+
import { createClient } from "redis";
|
|
3
|
+
// src/redis-client.ts
|
|
4
|
+
const redisVendorOwnedKeys = {
|
|
5
|
+
commandOptions: "this Package (1 s to send a command)",
|
|
6
|
+
database: "url (redis://host/<database>)",
|
|
7
|
+
password: "url (redis://user:password@host)",
|
|
8
|
+
url: "url",
|
|
9
|
+
username: "url (redis://user:password@host)"
|
|
10
|
+
};
|
|
11
|
+
const redisVendorOwnedSocketKeys = {
|
|
12
|
+
connectTimeout: "this Package (3 s)",
|
|
13
|
+
host: "url",
|
|
14
|
+
path: "url",
|
|
15
|
+
port: "url",
|
|
16
|
+
reconnectStrategy: "this Package (fail at startup, then retry for good)",
|
|
17
|
+
tls: "url (rediss:// for TLS)"
|
|
18
|
+
};
|
|
19
|
+
const redisConnectTimeoutMs = 3e3;
|
|
20
|
+
const redisVendorAssert = ({ url, vendor }) => {
|
|
21
|
+
const { password, username } = new URL(url);
|
|
22
|
+
if ("credentialsProvider" in vendor && (password || username)) throw new TypeError("vendor.credentialsProvider is not allowed with a user or password in url: node-redis lets the URL win; set credentials in one place");
|
|
23
|
+
const owned = [[
|
|
24
|
+
vendor,
|
|
25
|
+
"vendor",
|
|
26
|
+
redisVendorOwnedKeys
|
|
27
|
+
], [
|
|
28
|
+
vendor.socket ?? {},
|
|
29
|
+
"vendor.socket",
|
|
30
|
+
redisVendorOwnedSocketKeys
|
|
31
|
+
]];
|
|
32
|
+
for (const [settings, path, keys] of owned) for (const [key, owner] of Object.entries(keys)) if (key in settings) throw new TypeError(`${path}.${key} is not allowed: it is set by ${owner}`);
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Opens the one Redis connection a process shares, and resolves once it is connected, so an
|
|
36
|
+
* unreachable Redis stops startup within the 3 s connect timeout instead of retrying. After that a
|
|
37
|
+
* dropped connection reconnects every min(retries × 100 ms, 2 s), for as long as it takes. One URL
|
|
38
|
+
* fits a highly available Redis whose endpoint follows the primary (a managed one, or a proxy in
|
|
39
|
+
* front of Sentinel); Sentinel or Cluster addressed directly is not supported.
|
|
40
|
+
*/
|
|
41
|
+
const redisClientCreate = async ({ url, vendor }) => {
|
|
42
|
+
const settings = vendor ?? {};
|
|
43
|
+
redisVendorAssert({
|
|
44
|
+
url,
|
|
45
|
+
vendor: settings
|
|
46
|
+
});
|
|
47
|
+
let connected = false;
|
|
48
|
+
const redisClient = createClient({
|
|
49
|
+
...settings,
|
|
50
|
+
commandOptions: { timeout: 1e3 },
|
|
51
|
+
socket: {
|
|
52
|
+
...settings.socket,
|
|
53
|
+
connectTimeout: redisConnectTimeoutMs,
|
|
54
|
+
reconnectStrategy: (retries) => connected ? Math.min(retries * 100, 2e3) : false
|
|
55
|
+
},
|
|
56
|
+
url
|
|
57
|
+
});
|
|
58
|
+
redisClient.on("error", (err) => {
|
|
59
|
+
logger.error({ err }, "Redis client error");
|
|
60
|
+
});
|
|
61
|
+
let timer;
|
|
62
|
+
try {
|
|
63
|
+
await Promise.race([redisClient.connect(), new Promise((_, reject) => {
|
|
64
|
+
timer = setTimeout(() => {
|
|
65
|
+
reject(new DOMException(`Redis not ready within ${redisConnectTimeoutMs} ms`, "TimeoutError"));
|
|
66
|
+
}, redisConnectTimeoutMs);
|
|
67
|
+
})]);
|
|
68
|
+
} catch (err) {
|
|
69
|
+
if (redisClient.isOpen) redisClient.destroy();
|
|
70
|
+
throw err;
|
|
71
|
+
} finally {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
}
|
|
74
|
+
connected = true;
|
|
75
|
+
return Object.assign(redisClient, { [Symbol.asyncDispose]: () => redisClient.close() });
|
|
76
|
+
};
|
|
77
|
+
export { redisClientCreate };
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n8io/baseline-redis",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "The one Redis connection a baseline app shares: it fails fast at startup and reconnects for good after.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/n8io/baseline.git",
|
|
10
|
+
"directory": "packages/redis"
|
|
11
|
+
},
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=26"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public",
|
|
27
|
+
"registry": "https://registry.npmjs.org"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@n8io/baseline-logger": "^3.1.0",
|
|
31
|
+
"redis": "^6.3.1"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsdown",
|
|
35
|
+
"check": "tsc --noEmit && pnpm pack --out dist/package.tgz && publint dist/package.tgz --strict && attw dist/package.tgz --profile esm-only",
|
|
36
|
+
"test": "vitest run",
|
|
37
|
+
"test:unit": "vitest run --project unit --passWithNoTests"
|
|
38
|
+
}
|
|
6
39
|
}
|