joye-backend-utility 7.3.6-beta.1 → 7.3.6-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.
@@ -1,8 +1,15 @@
1
1
  import { createClient, createCluster } from 'redis';
2
- /** Connected standalone client or cluster client (commands used by callers are supported on both). */
2
+ /**
3
+ * Standalone or `node-redis` cluster client. Cluster mode uses `createCluster` + `nodeAddressMap` so slot
4
+ * topology (internal IPs from MOVED / CLUSTER SLOTS) maps to the Azure TLS hostname — avoids ioredis
5
+ * MOVED + `natMap` slot-key mismatch that caused “Too many Cluster redirections”.
6
+ */
3
7
  export declare type RedisConnection = Awaited<ReturnType<ReturnType<typeof createClient>['connect']>> | ReturnType<typeof createCluster>;
4
8
  declare class RedisClient {
5
9
  private static instance;
10
+ /** Ensures concurrent `getInstance()` share one in-flight connect (avoids duplicate clients / flaky MOVED). */
11
+ private static initPromise;
12
+ private static createConnection;
6
13
  static getInstance(): Promise<RedisConnection>;
7
14
  }
8
15
  export { RedisClient };
@@ -2,49 +2,107 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RedisClient = void 0;
4
4
  const redis_1 = require("redis");
5
+ function trimEnv(value) {
6
+ if (value === undefined)
7
+ return undefined;
8
+ let t = value.trim();
9
+ if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
10
+ t = t.slice(1, -1).trim();
11
+ }
12
+ return t;
13
+ }
14
+ function envBool(value, defaultValue) {
15
+ var _a;
16
+ const v = (_a = trimEnv(value)) === null || _a === void 0 ? void 0 : _a.toLowerCase();
17
+ if (v === undefined || v === '')
18
+ return defaultValue;
19
+ if (v === 'true' || v === '1' || v === 'yes')
20
+ return true;
21
+ if (v === 'false' || v === '0' || v === 'no')
22
+ return false;
23
+ return defaultValue;
24
+ }
25
+ /**
26
+ * Azure Managed Redis (ACL): default user is `default`.
27
+ * Set `REDIS_CACHE_USERNAME=none` (or empty after trim) to omit username for legacy password-only caches.
28
+ */
29
+ function redisUsername() {
30
+ const raw = process.env.REDIS_CACHE_USERNAME;
31
+ if (raw === undefined)
32
+ return 'default';
33
+ const t = trimEnv(raw);
34
+ if (t === '' || t.toLowerCase() === 'none')
35
+ return undefined;
36
+ return t;
37
+ }
38
+ function mapClusterAddressToPublicEndpoint(address, publicHost, fallbackPort) {
39
+ const idx = address.lastIndexOf(':');
40
+ if (idx === -1)
41
+ return { host: publicHost, port: fallbackPort };
42
+ const p = Number.parseInt(address.slice(idx + 1), 10);
43
+ return Number.isNaN(p) ? { host: publicHost, port: fallbackPort } : { host: publicHost, port: p };
44
+ }
5
45
  class RedisClient {
46
+ static async createConnection() {
47
+ const cachePortRaw = trimEnv(process.env.REDIS_CACHE_PORT);
48
+ const cacheHostName = trimEnv(process.env.REDIS_CACHE_HOST);
49
+ const cachePassword = trimEnv(process.env.REDIS_CACHE_PASSWORD);
50
+ const cachePort = cachePortRaw ? Number.parseInt(cachePortRaw, 10) : Number.NaN;
51
+ const username = redisUsername();
52
+ const useCluster = envBool(process.env.REDIS_CACHE_CLUSTER, false);
53
+ const unifiedClusterEndpoint = useCluster && envBool(process.env.REDIS_CACHE_CLUSTER_UNIFIED_ENDPOINT, true);
54
+ if (!cacheHostName || Number.isNaN(cachePort)) {
55
+ throw new Error('RedisClient: REDIS_CACHE_HOST and a numeric REDIS_CACHE_PORT are required');
56
+ }
57
+ const tlsSocket = {
58
+ tls: true,
59
+ servername: cacheHostName,
60
+ };
61
+ const standaloneSocket = Object.assign({ host: cacheHostName, port: cachePort }, tlsSocket);
62
+ const authOptions = Object.assign(Object.assign({}, (username !== undefined ? { username } : {})), (cachePassword !== undefined ? { password: cachePassword } : {}));
63
+ if (useCluster) {
64
+ console.log('RedisClient: CLUSTER mode (node-redis createCluster), unifiedEndpoint=%s, maxCommandRedirections=64', String(unifiedClusterEndpoint));
65
+ const clusterRoot = Object.assign({ socket: standaloneSocket }, authOptions);
66
+ const cluster = (0, redis_1.createCluster)(Object.assign({ rootNodes: [clusterRoot], defaults: Object.assign(Object.assign({}, authOptions), { socket: tlsSocket }), maxCommandRedirections: 64 }, (unifiedClusterEndpoint
67
+ ? {
68
+ nodeAddressMap: (address) => mapClusterAddressToPublicEndpoint(address, cacheHostName, cachePort),
69
+ }
70
+ : {})))
71
+ .on('error', err => {
72
+ console.log('Redis Client Error', err);
73
+ })
74
+ .on('connect', () => {
75
+ console.log('Connected to Redis');
76
+ })
77
+ .on('end', () => {
78
+ console.log('Connection to Redis end');
79
+ });
80
+ await cluster.connect();
81
+ return cluster;
82
+ }
83
+ console.log('RedisClient: STANDALONE mode (node-redis createClient) — not for OSS cluster endpoints (MOVED).');
84
+ const client = (0, redis_1.createClient)(Object.assign({ socket: standaloneSocket }, authOptions))
85
+ .on('error', err => {
86
+ console.log('Redis Client Error', err);
87
+ })
88
+ .on('connect', () => {
89
+ console.log('Connected to Redis');
90
+ })
91
+ .on('end', () => {
92
+ console.log('Connection to Redis end');
93
+ });
94
+ return await client.connect();
95
+ }
6
96
  static async getInstance() {
7
97
  if (!RedisClient.instance) {
8
- const cachePort = process.env.REDIS_CACHE_PORT;
9
- const cacheHostName = process.env.REDIS_CACHE_HOST;
10
- const cachePassword = process.env.REDIS_CACHE_PASSWORD;
11
- const url = `rediss://${cacheHostName}:${cachePort}`;
12
- const useCluster = process.env.REDIS_CACHE_CLUSTER === 'true';
13
- const clientOptions = {
14
- url,
15
- password: cachePassword,
16
- };
17
- if (useCluster) {
18
- const cluster = (0, redis_1.createCluster)({
19
- rootNodes: [clientOptions],
20
- defaults: {
21
- password: cachePassword,
22
- },
23
- })
24
- .on('error', err => {
25
- console.log('Redis Client Error', err);
26
- })
27
- .on('connect', () => {
28
- console.log('Connected to Redis');
29
- })
30
- .on('end', () => {
31
- console.log('Connection to Redis end');
32
- });
33
- await cluster.connect();
34
- RedisClient.instance = cluster;
98
+ if (!RedisClient.initPromise) {
99
+ RedisClient.initPromise = RedisClient.createConnection();
100
+ }
101
+ try {
102
+ RedisClient.instance = await RedisClient.initPromise;
35
103
  }
36
- else {
37
- const client = (0, redis_1.createClient)(clientOptions)
38
- .on('error', err => {
39
- console.log('Redis Client Error', err);
40
- })
41
- .on('connect', () => {
42
- console.log('Connected to Redis');
43
- })
44
- .on('end', () => {
45
- console.log('Connection to Redis end');
46
- });
47
- RedisClient.instance = await client.connect();
104
+ finally {
105
+ RedisClient.initPromise = null;
48
106
  }
49
107
  }
50
108
  if (!RedisClient.instance.isOpen) {
@@ -55,3 +113,5 @@ class RedisClient {
55
113
  }
56
114
  exports.RedisClient = RedisClient;
57
115
  RedisClient.instance = null;
116
+ /** Ensures concurrent `getInstance()` share one in-flight connect (avoids duplicate clients / flaky MOVED). */
117
+ RedisClient.initPromise = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "joye-backend-utility",
3
- "version": "7.3.6-beta.1",
3
+ "version": "7.3.6-beta.2",
4
4
  "description": "Joye backend utility for db functions and common functions",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",