@nodefony/redis 10.0.0-alpha.1
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 +544 -0
- package/README.md +110 -0
- package/dist/_virtual/_@oxc-project_runtime@0.148.0/helpers/esm/decorate.js +9 -0
- package/dist/_virtual/_@oxc-project_runtime@0.148.0/helpers/esm/decorateMetadata.js +6 -0
- package/dist/index.js +58 -0
- package/dist/nodefony/config/config.js +98 -0
- package/dist/nodefony/config/defineModuleConfig.js +90 -0
- package/dist/nodefony/interfaces/IRedisConfig.js +1 -0
- package/dist/nodefony/interfaces/index.js +1 -0
- package/dist/nodefony/registerStores.js +38 -0
- package/dist/nodefony/service/redis.js +177 -0
- package/dist/nodefony/src/Connection.js +111 -0
- package/dist/nodefony/src/RedisTokenStore.js +390 -0
- package/dist/nodefony/src/RedisWebAuthnCredentialStore.js +247 -0
- package/dist/nodefony/src/SessionStorage.js +249 -0
- package/dist/nodefony/src/buildClientOptions.js +63 -0
- package/dist/nodefony/src/keyNamespace.js +80 -0
- package/dist/nodefony/src/scanCursor.js +69 -0
- package/dist/types/index.d.ts +53 -0
- package/dist/types/nodefony/config/config.d.ts +41 -0
- package/dist/types/nodefony/config/defineModuleConfig.d.ts +26 -0
- package/dist/types/nodefony/interfaces/IRedisConfig.d.ts +17 -0
- package/dist/types/nodefony/interfaces/index.d.ts +5 -0
- package/dist/types/nodefony/registerStores.d.ts +5 -0
- package/dist/types/nodefony/service/redis.d.ts +82 -0
- package/dist/types/nodefony/src/Connection.d.ts +39 -0
- package/dist/types/nodefony/src/RedisTokenStore.d.ts +121 -0
- package/dist/types/nodefony/src/RedisWebAuthnCredentialStore.d.ts +108 -0
- package/dist/types/nodefony/src/SessionStorage.d.ts +87 -0
- package/dist/types/nodefony/src/buildClientOptions.d.ts +21 -0
- package/dist/types/nodefony/src/keyNamespace.d.ts +12 -0
- package/dist/types/nodefony/src/scanCursor.d.ts +50 -0
- package/docs/architecture.md +718 -0
- package/docs/configuration.md +773 -0
- package/docs/index.md +295 -0
- package/package.json +95 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import RedisService from "./nodefony/service/redis.js";
|
|
2
|
+
import config, { redisConfigSchema } from "./nodefony/config/config.js";
|
|
3
|
+
import { defineRedisConfig, redisConfigJsonSchema } from "./nodefony/config/defineModuleConfig.js";
|
|
4
|
+
import { RedisTokenStore } from "./nodefony/src/RedisTokenStore.js";
|
|
5
|
+
import { RedisWebAuthnCredentialStore } from "./nodefony/src/RedisWebAuthnCredentialStore.js";
|
|
6
|
+
import { registerRedisFrameworkStores } from "./nodefony/registerStores.js";
|
|
7
|
+
import __decorateMetadata from "./_virtual/_@oxc-project_runtime@0.148.0/helpers/esm/decorateMetadata.js";
|
|
8
|
+
import __decorate from "./_virtual/_@oxc-project_runtime@0.148.0/helpers/esm/decorate.js";
|
|
9
|
+
import RedisSessionStorage from "./nodefony/src/SessionStorage.js";
|
|
10
|
+
import { Kernel, Module, services } from "nodefony";
|
|
11
|
+
import * as redis from "redis";
|
|
12
|
+
//#region index.ts
|
|
13
|
+
/**
|
|
14
|
+
* @nodefony/redis — Accès Redis générique pour Nodefony.
|
|
15
|
+
*
|
|
16
|
+
* Module d'infrastructure : gère N connexions Redis nommées (lib `redis` v6) à
|
|
17
|
+
* partir d'une config validée par Zod. Il N'IMPOSE aucun usage — il expose le
|
|
18
|
+
* client Redis brut par connexion (`RedisService.getClient(name)`), donc on
|
|
19
|
+
* l'utilise pour TOUT : cache clé-valeur, sessions, files (streams/lists),
|
|
20
|
+
* compteurs, verrous, pub/sub… Les couches qui le consomment (P13.5
|
|
21
|
+
* `RedisBackplane` realtime, P5.12 `RedisSessionStorage`) sont AILLEURS — ce
|
|
22
|
+
* module reste un fournisseur d'accès neutre.
|
|
23
|
+
*
|
|
24
|
+
* Trois connexions par défaut (`main`/`publish`/`subscribe`) : un client Redis
|
|
25
|
+
* abonné (SUBSCRIBE) ne peut plus émettre de commandes normales → le pub/sub
|
|
26
|
+
* impose des clients dédiés. `main` sert les commandes clé-valeur / storage.
|
|
27
|
+
*
|
|
28
|
+
* Voir aussi : CLAUDE.md (décisions figées), MEMORY.md (internals IA),
|
|
29
|
+
* README.md (usage humain), docs/ (doc vulgarisée surfacée dans Studio).
|
|
30
|
+
*/
|
|
31
|
+
let Redis = class Redis extends Module {
|
|
32
|
+
/** Module optionnel : un échec de son boot ne tue jamais le process (résilience Ph.3). */
|
|
33
|
+
static critical = false;
|
|
34
|
+
constructor(kernel) {
|
|
35
|
+
super("redis", kernel, import.meta.url, config);
|
|
36
|
+
}
|
|
37
|
+
/** JSON Schema de la config redis → data plane admin (config riche Studio). */
|
|
38
|
+
configSchema() {
|
|
39
|
+
return redisConfigJsonSchema();
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Valide la config (défauts + `module.options` + surcharge env) au boot via
|
|
43
|
+
* `defineRedisConfig`, et l'expose au container sous `redisConfig` pour que le
|
|
44
|
+
* `RedisService` la consomme sans redupliquer la validation. Plante propre
|
|
45
|
+
* avec messages clairs si la config est invalide (cf convention Zod figée
|
|
46
|
+
* 2026-05-28).
|
|
47
|
+
*/
|
|
48
|
+
async onKernelRegister() {
|
|
49
|
+
const validated = defineRedisConfig(this.options ?? {});
|
|
50
|
+
this.options = validated;
|
|
51
|
+
registerRedisFrameworkStores();
|
|
52
|
+
return this;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
Redis = __decorate([services([RedisService]), __decorateMetadata("design:paramtypes", [typeof Kernel === "undefined" ? Object : Kernel])], Redis);
|
|
56
|
+
var redis_default = Redis;
|
|
57
|
+
//#endregion
|
|
58
|
+
export { RedisService, RedisSessionStorage, RedisTokenStore, RedisWebAuthnCredentialStore, redis_default as default, defineRedisConfig, redis, redisConfigJsonSchema, redisConfigSchema, registerRedisFrameworkStores };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region nodefony/config/config.ts
|
|
3
|
+
/**
|
|
4
|
+
* @nodefony/redis — CONFIGURATION DU MODULE (schéma Zod = source unique).
|
|
5
|
+
*
|
|
6
|
+
* ⭐ TL;DR : CE SCHÉMA EST LA CONFIG. Chaque `.default(...)` = la valeur d'usine ;
|
|
7
|
+
* changer un défaut du module = ÉDITER ICI (et nulle part ailleurs). L'app, elle,
|
|
8
|
+
* surcharge via `use("@nodefony/...", { … })` dans SON `nodefony.config.ts`.
|
|
9
|
+
*
|
|
10
|
+
* RÈGLE D'OR (ADR-0006) : ce fichier porte le **schéma Zod commenté** (type +
|
|
11
|
+
* validation + défaut + doc) ET matérialise les défauts via `parse({})`. Aucune
|
|
12
|
+
* valeur n'est re-tapée ailleurs. Le builder (`defineModuleConfig.ts` →
|
|
13
|
+
* `defineRedisConfig`) et les types (`interfaces/IRedisConfig.ts`) importent le
|
|
14
|
+
* schéma D'ICI (nœud bas : ce fichier n'importe que `zod` → pas de cycle).
|
|
15
|
+
*
|
|
16
|
+
* La config est validée au boot du Module class (hook `onKernelRegister`, via
|
|
17
|
+
* le builder {@link defineRedisConfig}) → plante propre avec messages clairs si
|
|
18
|
+
* la config est invalide, plutôt qu'un `undefined.x` silencieux en runtime.
|
|
19
|
+
*
|
|
20
|
+
* ⚠️ ENV : ce schéma reste PUR (pas de lecture `process.env` ici, sinon il
|
|
21
|
+
* deviendrait non déterministe et non sérialisable en JSON Schema). La surcharge
|
|
22
|
+
* par variables d'environnement (`REDIS_URL`, `NF_REDIS_HOST`, `NF_REDIS_PORT`,
|
|
23
|
+
* `NF_REDIS_PASSWORD`) est appliquée dans {@link defineRedisConfig}, APRÈS le parse.
|
|
24
|
+
*
|
|
25
|
+
* SURCHARGE PAR L'APPLICATION (fusion récursive) :
|
|
26
|
+
*
|
|
27
|
+
* // nodefony.config.ts
|
|
28
|
+
* use("@nodefony/redis", {
|
|
29
|
+
* globalOptions: { socket: { host: "redis.internal", tls: true } },
|
|
30
|
+
* connections: { cache: { name: "cache", database: 1 } },
|
|
31
|
+
* })
|
|
32
|
+
*
|
|
33
|
+
* ⚠️ NE PAS éditer les défauts matérialisés en bas de fichier : modifier les
|
|
34
|
+
* `.default(...)` du schéma. La validation + le merge env finaux sont faits dans
|
|
35
|
+
* `index.ts` au hook `onKernelRegister` via `defineRedisConfig`.
|
|
36
|
+
*/
|
|
37
|
+
const reconnectStrategySchema = z.strictObject({
|
|
38
|
+
baseMs: z.number().int().positive().default(100).describe("Délai de base (ms) du back-off de reconnexion. Le délai effectif = min(tentative × baseMs, maxMs). Défaut 100 ms (1ʳᵉ retry à 100 ms, 2ᵉ à 200 ms…). Remplace l'ancien `retry_strategy` JS hardcodé."),
|
|
39
|
+
maxMs: z.number().int().positive().default(1e4).describe("Plafond (ms) du délai de reconnexion — évite un back-off qui explose. Défaut 10 s. Au-delà, le client retente à intervalle constant `maxMs`."),
|
|
40
|
+
maxRetries: z.number().int().nonnegative().default(0).describe("Nombre maximal de tentatives de reconnexion avant abandon définitif. 0 (défaut) = illimité (résilience prod : le client retente sans fin). Mettre une valeur finie pour fail-fast en CI/test.")
|
|
41
|
+
}).describe("Politique de reconnexion (back-off linéaire borné). Convertie en fonction `socket.reconnectStrategy` de redis v5 au runtime, dans la connexion.");
|
|
42
|
+
const socketSchema = z.strictObject({
|
|
43
|
+
host: z.string().min(1).default("localhost").describe("Hôte du serveur Redis. Défaut `localhost` (jamais d'hôte d'infra hardcodé). Surchargeable par l'env `NF_REDIS_HOST`. Aligné sur l'infra `docker/docker-compose.yml` (Redis bindé `127.0.0.1:6379`)."),
|
|
44
|
+
port: z.number().int().min(1).max(65535).default(6379).describe("Port TCP du serveur Redis. Défaut 6379. Env `NF_REDIS_PORT`."),
|
|
45
|
+
family: z.union([
|
|
46
|
+
z.literal(0),
|
|
47
|
+
z.literal(4),
|
|
48
|
+
z.literal(6)
|
|
49
|
+
]).default(0).describe("Famille IP pour la résolution DNS : 0 = auto (IPv4+IPv6), 4 = IPv4, 6 = IPv6. Défaut 0 (laisse Node choisir)."),
|
|
50
|
+
connectTimeout: z.number().int().positive().default(5e3).describe("Délai max (ms) d'établissement de la connexion TCP avant échec. Défaut 5 s. Empêche un boot qui pend indéfiniment si Redis est injoignable."),
|
|
51
|
+
tls: z.boolean().default(false).describe("Active TLS (Redis over SSL, schéma `rediss://`). Défaut false (dev local en clair). Mettre true en prod managée / cross-host non fiable. Recommandation sécurité : true dès que le réseau n'est pas de confiance."),
|
|
52
|
+
reconnectStrategy: reconnectStrategySchema.default(() => reconnectStrategySchema.parse({}))
|
|
53
|
+
}).describe("Options socket TCP/TLS communes à toutes les connexions.");
|
|
54
|
+
const socketOverrideSchema = z.strictObject({
|
|
55
|
+
host: z.string().min(1).optional(),
|
|
56
|
+
port: z.number().int().min(1).max(65535).optional(),
|
|
57
|
+
family: z.union([
|
|
58
|
+
z.literal(0),
|
|
59
|
+
z.literal(4),
|
|
60
|
+
z.literal(6)
|
|
61
|
+
]).optional(),
|
|
62
|
+
connectTimeout: z.number().int().positive().optional(),
|
|
63
|
+
tls: z.boolean().optional()
|
|
64
|
+
}).describe("Surcharge socket par connexion (champs optionnels, sans défaut).");
|
|
65
|
+
const connectionSchema = z.strictObject({
|
|
66
|
+
name: z.string().min(1).describe("Nom logique de la connexion (clé dans `connections` + `CLIENT SETNAME` côté Redis pour l'introspection `CLIENT LIST`)."),
|
|
67
|
+
database: z.number().int().nonnegative().default(0).describe("Numéro de base Redis (`SELECT`). Défaut 0. ⚠️ Le pub/sub Redis est GLOBAL (ignore la base) ; `database` n'isole que les commandes clé-valeur (storage). À utiliser pour cloisonner des apps sur une même instance."),
|
|
68
|
+
socket: socketOverrideSchema.optional().describe("Surcharge socket spécifique à cette connexion (host/port/tls…). Fusionnée par-dessus `globalOptions.socket`. Champs omis = hérités du global (PAS de défaut local, sinon ils clobberaient le global).")
|
|
69
|
+
}).describe("Définition d'une connexion Redis nommée.");
|
|
70
|
+
const globalOptionsSchema = z.strictObject({
|
|
71
|
+
socket: socketSchema.default(() => socketSchema.parse({})),
|
|
72
|
+
username: z.string().optional().describe("Nom d'utilisateur ACL Redis 6+ (`ACL`). Optionnel. Si absent et `password` présent → auth legacy `requirepass` (utilisateur `default`). Env : non surchargé (mettre dans la config app)."),
|
|
73
|
+
password: z.string().optional().meta({
|
|
74
|
+
secret: true,
|
|
75
|
+
description: "Mot de passe Redis (`requirepass` ou ACL). Optionnel en dev sans auth. ⚠️ Zero Trust : Redis DOIT avoir une auth même en dev (cf docker compose `--requirepass`). Surchargé par l'env `NF_REDIS_PASSWORD` — NE JAMAIS committer un secret dans la config."
|
|
76
|
+
})
|
|
77
|
+
}).describe("Options communes fusionnées dans CHAQUE connexion (socket + credentials).");
|
|
78
|
+
const redisConfigSchema = z.strictObject({
|
|
79
|
+
enabled: z.boolean().default(true).describe("Active le module au boot. true = les connexions définies sont ouvertes à l'init du service. false = module chargé mais inerte (aucune connexion, 0 socket) — utile pour désactiver Redis en CI."),
|
|
80
|
+
url: z.string().optional().meta({
|
|
81
|
+
secret: true,
|
|
82
|
+
description: "URL Redis complète `redis[s]://[[user][:pass]@]host[:port][/db]`. Si fournie (ou via env `REDIS_URL`), elle prend PRÉCÉDENCE sur `globalOptions`/`socket` pour TOUTES les connexions (host/port/auth extraits de l'URL). Pratique pour les PaaS (Heroku, Upstash…). Porte potentiellement le credential (user:pass) → traitée comme un secret."
|
|
83
|
+
}),
|
|
84
|
+
globalOptions: globalOptionsSchema.default(() => globalOptionsSchema.parse({})),
|
|
85
|
+
keyNamespace: z.string().min(1).regex(/^[\w.-]+$/).optional().describe("Cloison des CLÉS par application sur un Redis mutualisé — préfixe `nf:<keyNamespace>:<type>` au lieu de `nf:<type>`. Sans elle, deux applications écrivent dans le même espace de clés (`database` vaut 0 par défaut et ne cloisonne rien de plus) : l'écran Sessions de l'une LISTE les sessions de l'autre, son balayage `nf:sess:*` ne pouvant pas les distinguer. Défaut : dérivé du nom d'app (`kernel.projectName`). À poser EXPLICITEMENT quand deux déploiements de la même app (préproduction/production) partagent un Redis. Caractères : alphanumériques, `_`, `.`, `-`. Env : `NF_REDIS_KEY_NAMESPACE` (prioritaire — une cloison distingue des DÉPLOIEMENTS, elle n'a pas à être figée dans le code)."),
|
|
86
|
+
connections: z.record(z.string(), connectionSchema).default(() => ({
|
|
87
|
+
main: connectionSchema.parse({ name: "main" }),
|
|
88
|
+
publish: connectionSchema.parse({ name: "publish" }),
|
|
89
|
+
subscribe: connectionSchema.parse({ name: "subscribe" })
|
|
90
|
+
})).describe("Connexions nommées. Défaut : 3 connexions `main` (commandes/storage), `publish` (PUBLISH) et `subscribe` (SUBSCRIBE). Pourquoi 3 : un client Redis abonné ne peut plus émettre de commandes normales (contrainte protocole) → pub/sub exige des clients dédiés.")
|
|
91
|
+
}).describe("Configuration de @nodefony/redis.");
|
|
92
|
+
/**
|
|
93
|
+
* Défauts du module, matérialisés depuis le schéma (source unique). Toujours
|
|
94
|
+
* valides par construction ; passés au `super(..., config)` du Module class.
|
|
95
|
+
*/
|
|
96
|
+
const config = redisConfigSchema.parse({});
|
|
97
|
+
//#endregion
|
|
98
|
+
export { config as default, redisConfigSchema };
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { redisConfigSchema } from "./config.js";
|
|
2
|
+
import { parseModuleConfig, resolveInfra } from "nodefony";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
//#region nodefony/config/defineModuleConfig.ts
|
|
5
|
+
/**
|
|
6
|
+
* Applique la surcharge par variables d'environnement APRÈS le parse Zod.
|
|
7
|
+
*
|
|
8
|
+
* Le schéma reste pur (déterministe, sérialisable en JSON Schema) ; l'env est
|
|
9
|
+
* une couche explicite par-dessus. Précédence : env > config app > défauts.
|
|
10
|
+
*
|
|
11
|
+
* - Infra cache `NF_REDIS_URL` (alias plateforme `REDIS_URL`) → `config.url`
|
|
12
|
+
* (gagne sur host/port/auth pour toutes les connexions). La résolution de
|
|
13
|
+
* l'URL de cache est déléguée à `resolveInfra` (core) — source UNIQUE des
|
|
14
|
+
* alias, partagée avec drizzle/mongoose ; pas de réimplémentation locale.
|
|
15
|
+
* - `NF_REDIS_HOST` → `globalOptions.socket.host`
|
|
16
|
+
* - `NF_REDIS_PORT` → `globalOptions.socket.port`
|
|
17
|
+
* - `NF_REDIS_PASSWORD` → `globalOptions.password` (secret JAMAIS dans la config)
|
|
18
|
+
* - `NF_REDIS_KEY_NAMESPACE` → `keyNamespace` (cloison de DÉPLOIEMENT, pas de code)
|
|
19
|
+
*/
|
|
20
|
+
function applyEnvOverrides(config) {
|
|
21
|
+
const env = process.env;
|
|
22
|
+
const cacheUrl = resolveInfra(env).cache?.url;
|
|
23
|
+
if (cacheUrl) config.url = cacheUrl;
|
|
24
|
+
if (env.NF_REDIS_HOST) config.globalOptions.socket.host = env.NF_REDIS_HOST;
|
|
25
|
+
if (env.NF_REDIS_PORT) {
|
|
26
|
+
const port = Number.parseInt(env.NF_REDIS_PORT, 10);
|
|
27
|
+
if (Number.isInteger(port) && port > 0 && port <= 65535) config.globalOptions.socket.port = port;
|
|
28
|
+
}
|
|
29
|
+
if (env.NF_REDIS_PASSWORD) config.globalOptions.password = env.NF_REDIS_PASSWORD;
|
|
30
|
+
if (env.NF_REDIS_KEY_NAMESPACE) config.keyNamespace = env.NF_REDIS_KEY_NAMESPACE;
|
|
31
|
+
return config;
|
|
32
|
+
}
|
|
33
|
+
/** Plafond de reconnexions appliqué hors production quand l'app n'en fixe pas. */
|
|
34
|
+
const DEV_DEFAULT_MAX_RETRIES = 5;
|
|
35
|
+
/**
|
|
36
|
+
* Hors production, borne les reconnexions Redis à un nombre **fini** quand l'app
|
|
37
|
+
* ne l'a PAS surchargé.
|
|
38
|
+
*
|
|
39
|
+
* Pourquoi : le défaut du schéma est `0` = illimité (résilience prod légitime,
|
|
40
|
+
* un orchestrateur relèvera Redis). Mais en dev avec Redis absent, node-redis
|
|
41
|
+
* retente sans fin et sa **file offline fait pendre** tout `await client.subscribe()`
|
|
42
|
+
* au boot → le backplane realtime ne rend jamais la main → les serveurs ne montent
|
|
43
|
+
* pas. Un plafond fini fait que `reconnectStrategy` finit par renvoyer une `Error`
|
|
44
|
+
* → node-redis abandonne → la file offline **rejette** au lieu de pendre.
|
|
45
|
+
*
|
|
46
|
+
* Détection « non surchargé » : on inspecte l'**input brut** (le défaut `0` du
|
|
47
|
+
* schéma est indistinguable d'un `0` explicite après le parse). Prod = inchangé.
|
|
48
|
+
*
|
|
49
|
+
* @param config - config déjà parsée (mutée en place avant le `freeze`).
|
|
50
|
+
* @param input - config brute fournie par l'app, pour détecter une surcharge.
|
|
51
|
+
* @returns la même config.
|
|
52
|
+
*/
|
|
53
|
+
function applyResilienceDefaults(config, input) {
|
|
54
|
+
if (process.env.NODE_ENV === "production") return config;
|
|
55
|
+
if (input.globalOptions?.socket?.reconnectStrategy?.maxRetries === void 0) config.globalOptions.socket.reconnectStrategy.maxRetries = DEV_DEFAULT_MAX_RETRIES;
|
|
56
|
+
return config;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Builder type-safe de la configuration de `@nodefony/redis`.
|
|
60
|
+
*
|
|
61
|
+
* ⭐ TL;DR : MACHINERIE DE BOOT — on n'édite (presque) jamais ce fichier. Même
|
|
62
|
+
* pattern que `nodefony.config.ts` ↔ `defineConfig()` du core : `config.ts` PORTE
|
|
63
|
+
* la config (schéma + défauts), `define<X>Config()` la VALIDE au boot (parse +
|
|
64
|
+
* env + freeze) et publie le JSON Schema Studio.
|
|
65
|
+
*
|
|
66
|
+
* Principes (alignés sur `defineRealtimeConfig` / `defineSecurityConfig`) :
|
|
67
|
+
* - **Source unique** : `./config.ts` (Zod). Le builder VALIDE, applique l'ENV,
|
|
68
|
+
* puis GÈLE — il ne dévie jamais du schéma.
|
|
69
|
+
* - **Auto-documenté** : chaque champ Zod porte un `.describe()` →
|
|
70
|
+
* {@link redisConfigJsonSchema} produit un JSON Schema qu'un formulaire Studio
|
|
71
|
+
* (futur) consommera pour générer son UI d'édition.
|
|
72
|
+
*
|
|
73
|
+
* @param config - configuration brute (sections omises = défauts sûrs).
|
|
74
|
+
* @returns config validée, surchargée par l'env, et gelée.
|
|
75
|
+
* @throws ZodError si la config est invalide.
|
|
76
|
+
*/
|
|
77
|
+
function defineRedisConfig(config = {}) {
|
|
78
|
+
const parsed = parseModuleConfig(redisConfigSchema, config, "@nodefony/redis");
|
|
79
|
+
applyResilienceDefaults(parsed, config);
|
|
80
|
+
return Object.freeze(applyEnvOverrides(parsed));
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* JSON Schema introspectable de la config Redis — destiné au formulaire
|
|
84
|
+
* d'édition Studio (futur) et à la documentation générée.
|
|
85
|
+
*/
|
|
86
|
+
function redisConfigJsonSchema() {
|
|
87
|
+
return z.toJSONSchema(redisConfigSchema);
|
|
88
|
+
}
|
|
89
|
+
//#endregion
|
|
90
|
+
export { defineRedisConfig, redisConfigJsonSchema };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { RedisTokenStore } from "./src/RedisTokenStore.js";
|
|
2
|
+
import { RedisWebAuthnCredentialStore } from "./src/RedisWebAuthnCredentialStore.js";
|
|
3
|
+
import { getTokenStoreFactory, getWebAuthnStoreFactory, registerTokenStore, registerWebAuthnStore } from "@nodefony/security";
|
|
4
|
+
//#region nodefony/registerStores.ts
|
|
5
|
+
/**
|
|
6
|
+
* AUTO-ENREGISTREMENT des backends framework portés par Redis — « charger le
|
|
7
|
+
* module = ses backends deviennent sélectionnables par simple nom » (convention-
|
|
8
|
+
* frère : `registerDrizzleFrameworkStores` / `registerMongooseFrameworkStores`).
|
|
9
|
+
*
|
|
10
|
+
* Appelé par `Redis.onKernelRegister`. Pas d'entité (clés + TTL natifs, aucun
|
|
11
|
+
* schéma à déclarer). Le client est résolu LAZY par le store (connexion `main`,
|
|
12
|
+
* dégradation gracieuse pendant boot/shutdown — pattern `RedisSessionStorage`).
|
|
13
|
+
*
|
|
14
|
+
* Fabriques `get`-guarded : une fabrique déjà posée par l'app garde la main.
|
|
15
|
+
* Session (`session.store: "redis"`) et idempotence (`NF_IDEMPOTENCY_STORE=redis`,
|
|
16
|
+
* builtin `@nodefony/framework`) restent enregistrées ailleurs — ici : tokens
|
|
17
|
+
* (PAT + denylist JWT) et credentials WebAuthn.
|
|
18
|
+
*/
|
|
19
|
+
/** Résout le service redis du container — échec FRANC avec la cause exacte. */
|
|
20
|
+
function resolveRedisService(store, container) {
|
|
21
|
+
const service = container?.get?.("redis") ?? null;
|
|
22
|
+
if (!service) throw new Error(`${store} : service "redis" introuvable — le module @nodefony/redis est-il chargé (manifeste "modules") ?`);
|
|
23
|
+
return service;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Enregistre les fabriques de stores Redis dans les registres de
|
|
27
|
+
* `@nodefony/security`. Idempotent (guards) — rejouable sans effet.
|
|
28
|
+
*/
|
|
29
|
+
function registerRedisFrameworkStores() {
|
|
30
|
+
if (!getTokenStoreFactory("redis")) registerTokenStore("redis", (ctx) => {
|
|
31
|
+
const service = resolveRedisService(`tokenStore "redis"`, ctx?.container);
|
|
32
|
+
const days = ctx?.config?.tokenStore?.retentionRevokedDays;
|
|
33
|
+
return RedisTokenStore.from(service, void 0, typeof days === "number" ? days * 864e5 : void 0);
|
|
34
|
+
});
|
|
35
|
+
if (!getWebAuthnStoreFactory("redis")) registerWebAuthnStore("redis", (ctx) => RedisWebAuthnCredentialStore.from(resolveRedisService(`passkeys.store "redis"`, ctx?.container)));
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
export { registerRedisFrameworkStores };
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import Connection from "../src/Connection.js";
|
|
2
|
+
import { buildClientOptions } from "../src/buildClientOptions.js";
|
|
3
|
+
import { resolveKeyPrefix } from "../src/keyNamespace.js";
|
|
4
|
+
import { Nodefony, Service } from "nodefony";
|
|
5
|
+
//#region nodefony/service/redis.ts
|
|
6
|
+
const serviceName = "redis";
|
|
7
|
+
/**
|
|
8
|
+
* Service Redis Nodefony — orchestre N connexions nommées (par défaut `main`,
|
|
9
|
+
* `publish`, `subscribe`) à partir de la config validée par Zod.
|
|
10
|
+
*
|
|
11
|
+
* La config est validée + gelée au boot du Module class (`onKernelRegister`,
|
|
12
|
+
* exposée au container sous `redisConfig`). Le service la consomme sans
|
|
13
|
+
* redupliquer la validation.
|
|
14
|
+
*
|
|
15
|
+
* Perf/mémoire : la map de connexions est en **lazy alloc** (`null` jusqu'à la
|
|
16
|
+
* 1ʳᵉ connexion ouverte) et toutes les connexions sont fermées au `onTerminate`
|
|
17
|
+
* du kernel (listeners retirés explicitement côté `Connection`).
|
|
18
|
+
*/
|
|
19
|
+
var RedisService = class extends Service {
|
|
20
|
+
module;
|
|
21
|
+
/** Connexions ouvertes — `null` tant qu'aucune n'est créée (lazy). */
|
|
22
|
+
#connections = null;
|
|
23
|
+
/** Config validée + gelée (résolue à l'init). */
|
|
24
|
+
#config = null;
|
|
25
|
+
/**
|
|
26
|
+
* Cloison de clés résolue — `undefined` tant que non calculée, `null` quand la
|
|
27
|
+
* résolution a conclu qu'il n'y en a pas (distinction nécessaire : sans elle,
|
|
28
|
+
* une application anonyme recalculerait à chaque clé).
|
|
29
|
+
*/
|
|
30
|
+
#keyNamespace = void 0;
|
|
31
|
+
/**
|
|
32
|
+
* Connexions actuellement signalées indisponibles — sert à ne journaliser
|
|
33
|
+
* qu'aux TRANSITIONS (une session écrit à chaque requête : journaliser à
|
|
34
|
+
* chaque appel noierait le journal au lieu d'alerter).
|
|
35
|
+
*
|
|
36
|
+
* Lazy : `null` tant que tout va bien, et remis à `null` dès que la dernière
|
|
37
|
+
* connexion est rétablie (aucune structure allouée sur le chemin nominal).
|
|
38
|
+
*/
|
|
39
|
+
#unavailable = null;
|
|
40
|
+
constructor(module) {
|
|
41
|
+
super(serviceName, module.container, null, {});
|
|
42
|
+
this.module = module;
|
|
43
|
+
module.kernel?.once("onTerminate", async () => {
|
|
44
|
+
await this.closeConnections();
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
log(pci, severity, msgid, msg) {
|
|
48
|
+
if (!msgid) msgid = `\x1b[36mREDIS SERVICE ${this.name} \x1b[0m`;
|
|
49
|
+
return super.log(pci, severity, msgid, msg);
|
|
50
|
+
}
|
|
51
|
+
/** Connexions ouvertes (vide si aucune). */
|
|
52
|
+
get connections() {
|
|
53
|
+
return this.#connections ?? {};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Cloison des clés de CETTE application, résolue une fois.
|
|
57
|
+
*
|
|
58
|
+
* `keyNamespace` explicite, sinon le nom de l'application. Les stores composent
|
|
59
|
+
* leur préfixe avec (`resolveKeyPrefix`) pour que deux applications sur un même
|
|
60
|
+
* Redis n'écrivent — et surtout ne BALAIENT — jamais le même espace de clés.
|
|
61
|
+
*
|
|
62
|
+
* `undefined` = aucune cloison résolue (application anonyme) → les stores
|
|
63
|
+
* gardent leur préfixe historique : une application seule n'a rien à séparer.
|
|
64
|
+
*/
|
|
65
|
+
get keyNamespace() {
|
|
66
|
+
if (this.#keyNamespace === void 0) this.#keyNamespace = this.#resolveConfig().keyNamespace ?? this.module.kernel?.projectName ?? null;
|
|
67
|
+
return this.#keyNamespace ?? void 0;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Préfixe de clés d'un store, cloisonné par application.
|
|
71
|
+
*
|
|
72
|
+
* @param base - préfixe historique du store (`nf:sess`, `nf:tok`, `nf:wac`).
|
|
73
|
+
* @returns le préfixe à utiliser pour composer les clés ET les motifs de balayage.
|
|
74
|
+
*/
|
|
75
|
+
keyPrefix(base) {
|
|
76
|
+
return resolveKeyPrefix(base, this.keyNamespace);
|
|
77
|
+
}
|
|
78
|
+
/** Config Redis validée (résout depuis le container, fallback options). */
|
|
79
|
+
#resolveConfig() {
|
|
80
|
+
if (this.#config) return this.#config;
|
|
81
|
+
this.#config = this.module.config;
|
|
82
|
+
return this.#config;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Ouvre toutes les connexions déclarées dans la config (si `enabled`).
|
|
86
|
+
* Appelé par le cycle de vie du Module. Une connexion en échec est loguée
|
|
87
|
+
* sans bloquer les autres (résilience boot).
|
|
88
|
+
*/
|
|
89
|
+
async init() {
|
|
90
|
+
const config = this.#resolveConfig();
|
|
91
|
+
if (!config.enabled) {
|
|
92
|
+
this.log("Module Redis désactivé (enabled=false) — 0 connexion", "INFO");
|
|
93
|
+
return this;
|
|
94
|
+
}
|
|
95
|
+
for (const name in config.connections) try {
|
|
96
|
+
await this.createConnection(name);
|
|
97
|
+
} catch (e) {
|
|
98
|
+
this.log(e, "ERROR");
|
|
99
|
+
}
|
|
100
|
+
return this;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Crée et ouvre une connexion nommée.
|
|
104
|
+
*
|
|
105
|
+
* @param name - clé de la connexion dans `config.connections`.
|
|
106
|
+
* @returns la connexion ouverte.
|
|
107
|
+
* @throws si le nom est déjà ouvert ou inconnu, ou si la connexion échoue.
|
|
108
|
+
*/
|
|
109
|
+
async createConnection(name) {
|
|
110
|
+
const config = this.#resolveConfig();
|
|
111
|
+
if (this.#connections?.[name]) throw new Error(`${this.name} client "${name}" already exists`);
|
|
112
|
+
const definition = config.connections[name];
|
|
113
|
+
if (!definition) throw new Error(`${this.name} connection "${name}" undefined in config`);
|
|
114
|
+
const options = buildClientOptions(config, definition);
|
|
115
|
+
const conn = new Connection(name, options, this);
|
|
116
|
+
if (this.#connections === null) this.#connections = Object.create(null);
|
|
117
|
+
this.#connections[name] = conn;
|
|
118
|
+
await conn.create();
|
|
119
|
+
this.fire("connection", conn.client, conn);
|
|
120
|
+
return conn;
|
|
121
|
+
}
|
|
122
|
+
/** Connexion par nom (ou `undefined`). */
|
|
123
|
+
getConnection(name) {
|
|
124
|
+
return this.#connections?.[name];
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Client redis brut d'une connexion **utilisable**, ou `null`.
|
|
128
|
+
*
|
|
129
|
+
* `null` ne veut pas dire « connexion inconnue » mais « ne prends pas la
|
|
130
|
+
* peine » : tous les consommateurs (stores de session, de jetons, de
|
|
131
|
+
* passkeys, backplane realtime, idempotence) traitent `null` comme une
|
|
132
|
+
* indisponibilité et dégradent. Rendre un client fermé leur ferait prendre un
|
|
133
|
+
* `ClientClosedError` là où leur contrat promet un repli.
|
|
134
|
+
*
|
|
135
|
+
* Pourquoi tester l'ouverture et pas seulement la présence : `createClient()`
|
|
136
|
+
* rend un objet AVANT `connect()` (`Connection.create()`), et une connexion
|
|
137
|
+
* dont l'ouverture a échoué reste inscrite dans la map — le client existe donc
|
|
138
|
+
* **sans jamais avoir été ouvert**. `isOpen` (et non `isReady`) est le bon
|
|
139
|
+
* critère : pendant une reconnexion le socket est ouvert et node-redis met les
|
|
140
|
+
* commandes en file, ce qui est exactement la résilience recherchée.
|
|
141
|
+
*
|
|
142
|
+
* L'indisponibilité est **journalisée à la transition** — une dégradation
|
|
143
|
+
* muette contredit le principe de résilience du framework (tout repli
|
|
144
|
+
* s'annonce), mais journaliser à chaque appel noierait le journal.
|
|
145
|
+
*/
|
|
146
|
+
getClient(name) {
|
|
147
|
+
const client = this.#connections?.[name]?.client ?? null;
|
|
148
|
+
if (client?.isOpen) {
|
|
149
|
+
if (this.#unavailable?.delete(name)) {
|
|
150
|
+
if (this.#unavailable.size === 0) this.#unavailable = null;
|
|
151
|
+
this.log(`connexion "${name}" rétablie`, "INFO");
|
|
152
|
+
}
|
|
153
|
+
return client;
|
|
154
|
+
}
|
|
155
|
+
if (!this.#unavailable) this.#unavailable = /* @__PURE__ */ new Set();
|
|
156
|
+
if (!this.#unavailable.has(name)) {
|
|
157
|
+
this.#unavailable.add(name);
|
|
158
|
+
this.log(`connexion "${name}" indisponible (${client ? "socket fermé" : "jamais ouverte"}) — les consommateurs de cette connexion dégradent tant qu'elle ne revient pas`, "WARNING");
|
|
159
|
+
}
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
/** Ferme toutes les connexions ouvertes (idempotent). */
|
|
163
|
+
async closeConnections() {
|
|
164
|
+
if (!this.#connections) return;
|
|
165
|
+
for (const name in this.#connections) try {
|
|
166
|
+
await this.#connections[name].close();
|
|
167
|
+
} catch (e) {
|
|
168
|
+
this.log(e, "ERROR");
|
|
169
|
+
}
|
|
170
|
+
this.#connections = null;
|
|
171
|
+
}
|
|
172
|
+
generateId() {
|
|
173
|
+
return Nodefony.generateId();
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
//#endregion
|
|
177
|
+
export { RedisService as default };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { Service } from "nodefony";
|
|
2
|
+
import { createClient } from "redis";
|
|
3
|
+
//#region nodefony/src/Connection.ts
|
|
4
|
+
/**
|
|
5
|
+
* Une connexion Redis nommée — enveloppe un client `redis` v6 et gère son cycle
|
|
6
|
+
* de vie (création, écoute des événements, fermeture propre).
|
|
7
|
+
*
|
|
8
|
+
* Perf/mémoire : les handlers d'événements sont conservés en propriété et
|
|
9
|
+
* **explicitement retirés** à la fermeture (`removeListener`) pour éviter toute
|
|
10
|
+
* fuite si la connexion est recréée — règle absolue perf-mémoire du framework.
|
|
11
|
+
*/
|
|
12
|
+
var Connection = class extends Service {
|
|
13
|
+
/** Client redis v6 — `null` tant que `create()` n'a pas réussi. */
|
|
14
|
+
client = null;
|
|
15
|
+
/** Service Redis parent (accès container / kernel / événements). */
|
|
16
|
+
service;
|
|
17
|
+
/** true entre les événements `connect` et `end`. */
|
|
18
|
+
connected = false;
|
|
19
|
+
/** Options `createClient` assemblées (par `buildClientOptions`). */
|
|
20
|
+
options;
|
|
21
|
+
#onError = null;
|
|
22
|
+
#onConnect = null;
|
|
23
|
+
#onReady = null;
|
|
24
|
+
#onEnd = null;
|
|
25
|
+
#onReconnecting = null;
|
|
26
|
+
constructor(name, options, redisService) {
|
|
27
|
+
super(name, redisService.container, redisService.notificationsCenter, options);
|
|
28
|
+
this.service = redisService;
|
|
29
|
+
this.options = options;
|
|
30
|
+
}
|
|
31
|
+
log(pci, severity, msgid, msg) {
|
|
32
|
+
if (!msgid) msgid = `\x1b[36mREDIS CONNECTION ${this.name} \x1b[0m`;
|
|
33
|
+
return super.log(pci, severity, msgid, msg);
|
|
34
|
+
}
|
|
35
|
+
/** Hôte:port lisible pour les logs (gère le cas `url`). */
|
|
36
|
+
#endpoint() {
|
|
37
|
+
if (this.options.url) return this.options.url.replace(/:[^:@/]*@/, ":***@");
|
|
38
|
+
const socket = this.options.socket;
|
|
39
|
+
return `${socket?.host ?? "?"}:${socket?.port ?? "?"}`;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Crée le client, attache les listeners, ouvre la connexion.
|
|
43
|
+
*
|
|
44
|
+
* @returns le client connecté.
|
|
45
|
+
* @throws si la connexion échoue (propagé au service, qui logue).
|
|
46
|
+
*/
|
|
47
|
+
async create() {
|
|
48
|
+
this.client = createClient(this.options);
|
|
49
|
+
this.#onError = (error) => {
|
|
50
|
+
this.log(error, "ERROR");
|
|
51
|
+
this.fire("onError", error, this);
|
|
52
|
+
};
|
|
53
|
+
this.#onConnect = () => {
|
|
54
|
+
this.connected = true;
|
|
55
|
+
this.log(`CONNECT ${this.#endpoint()}`, "INFO");
|
|
56
|
+
this.fire("onConnect", this);
|
|
57
|
+
};
|
|
58
|
+
this.#onReady = () => {
|
|
59
|
+
this.fire("onReady", this);
|
|
60
|
+
};
|
|
61
|
+
this.#onEnd = () => {
|
|
62
|
+
this.connected = false;
|
|
63
|
+
this.log(`END ${this.#endpoint()}`, "INFO");
|
|
64
|
+
this.fire("onEnd", this);
|
|
65
|
+
};
|
|
66
|
+
this.#onReconnecting = () => {
|
|
67
|
+
this.log(`RECONNECTING ${this.#endpoint()}`, "WARNING");
|
|
68
|
+
this.fire("onReconnecting", this);
|
|
69
|
+
};
|
|
70
|
+
this.client.on("error", this.#onError);
|
|
71
|
+
this.client.on("connect", this.#onConnect);
|
|
72
|
+
this.client.on("ready", this.#onReady);
|
|
73
|
+
this.client.on("end", this.#onEnd);
|
|
74
|
+
this.client.on("reconnecting", this.#onReconnecting);
|
|
75
|
+
await this.client.connect();
|
|
76
|
+
return this.client;
|
|
77
|
+
}
|
|
78
|
+
/** Retire tous les listeners attachés dans `create()` (anti-fuite). */
|
|
79
|
+
#removeListeners() {
|
|
80
|
+
if (!this.client) return;
|
|
81
|
+
if (this.#onError) this.client.removeListener("error", this.#onError);
|
|
82
|
+
if (this.#onConnect) this.client.removeListener("connect", this.#onConnect);
|
|
83
|
+
if (this.#onReady) this.client.removeListener("ready", this.#onReady);
|
|
84
|
+
if (this.#onEnd) this.client.removeListener("end", this.#onEnd);
|
|
85
|
+
if (this.#onReconnecting) this.client.removeListener("reconnecting", this.#onReconnecting);
|
|
86
|
+
this.#onError = null;
|
|
87
|
+
this.#onConnect = null;
|
|
88
|
+
this.#onReady = null;
|
|
89
|
+
this.#onEnd = null;
|
|
90
|
+
this.#onReconnecting = null;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Ferme proprement la connexion et nettoie les listeners.
|
|
94
|
+
*
|
|
95
|
+
* redis v6 : `client.close()` remplace `quit()` (déprécié, envoyait `QUIT` —
|
|
96
|
+
* lui-même déprécié côté Redis 7.2). Fermeture gracieuse : draine les commandes
|
|
97
|
+
* en vol puis ferme le socket. (`destroy()` = fermeture forcée, non souhaitée ici.)
|
|
98
|
+
*/
|
|
99
|
+
async close() {
|
|
100
|
+
if (!this.client) return;
|
|
101
|
+
try {
|
|
102
|
+
if (this.client.isOpen) await this.client.close();
|
|
103
|
+
} finally {
|
|
104
|
+
this.#removeListeners();
|
|
105
|
+
this.connected = false;
|
|
106
|
+
this.log("REDIS client close", "INFO");
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
//#endregion
|
|
111
|
+
export { Connection as default };
|