@vritti/api-sdk 0.0.1 → 0.0.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/dist/index.cjs +824 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +533 -2
- package/dist/index.d.ts +533 -2
- package/dist/index.js +815 -5
- package/dist/index.js.map +1 -1
- package/package.json +17 -3
package/dist/index.js
CHANGED
|
@@ -1,11 +1,821 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
2
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
3
|
|
|
4
|
-
// src/
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
// src/database/database.module.ts
|
|
5
|
+
import { Global, Module } from "@nestjs/common";
|
|
6
|
+
|
|
7
|
+
// src/database/constants.ts
|
|
8
|
+
var DATABASE_MODULE_OPTIONS = Symbol("DATABASE_MODULE_OPTIONS");
|
|
9
|
+
|
|
10
|
+
// src/database/services/primary-database.service.ts
|
|
11
|
+
import { Inject, Injectable, InternalServerErrorException, Logger } from "@nestjs/common";
|
|
12
|
+
function _ts_decorate(decorators, target, key, desc) {
|
|
13
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
14
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
15
|
+
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;
|
|
16
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
17
|
+
}
|
|
18
|
+
__name(_ts_decorate, "_ts_decorate");
|
|
19
|
+
function _ts_metadata(k, v) {
|
|
20
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
21
|
+
}
|
|
22
|
+
__name(_ts_metadata, "_ts_metadata");
|
|
23
|
+
function _ts_param(paramIndex, decorator) {
|
|
24
|
+
return function(target, key) {
|
|
25
|
+
decorator(target, key, paramIndex);
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
__name(_ts_param, "_ts_param");
|
|
29
|
+
var PrimaryDatabaseService = class _PrimaryDatabaseService {
|
|
30
|
+
static {
|
|
31
|
+
__name(this, "PrimaryDatabaseService");
|
|
32
|
+
}
|
|
33
|
+
options;
|
|
34
|
+
logger = new Logger(_PrimaryDatabaseService.name);
|
|
35
|
+
/** Primary database client for querying tenant registry */
|
|
36
|
+
primaryDbClient;
|
|
37
|
+
/** In-memory cache: Map<tenantIdentifier, TenantConfig> */
|
|
38
|
+
tenantConfigCache = /* @__PURE__ */ new Map();
|
|
39
|
+
/** Cache TTL in milliseconds */
|
|
40
|
+
cacheTTL;
|
|
41
|
+
constructor(options) {
|
|
42
|
+
this.options = options;
|
|
43
|
+
this.cacheTTL = options.connectionCacheTTL || 3e5;
|
|
44
|
+
}
|
|
45
|
+
async onModuleInit() {
|
|
46
|
+
if (this.options.primaryDb) {
|
|
47
|
+
await this.initializePrimaryDbClient();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Initialize connection to primary database
|
|
52
|
+
*/
|
|
53
|
+
async initializePrimaryDbClient() {
|
|
54
|
+
try {
|
|
55
|
+
const PrimaryDbClient = this.options.prismaClientConstructor;
|
|
56
|
+
const databaseUrl = this.buildPrimaryDbUrl();
|
|
57
|
+
this.primaryDbClient = new PrimaryDbClient({
|
|
58
|
+
datasources: {
|
|
59
|
+
db: {
|
|
60
|
+
url: databaseUrl
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
log: [
|
|
64
|
+
"error",
|
|
65
|
+
"warn"
|
|
66
|
+
]
|
|
67
|
+
});
|
|
68
|
+
await this.primaryDbClient.$connect();
|
|
69
|
+
this.logger.log("Connected to primary database (tenant registry)");
|
|
70
|
+
} catch (error) {
|
|
71
|
+
this.logger.error("Failed to connect to primary database", error);
|
|
72
|
+
throw new InternalServerErrorException("Failed to initialize tenant registry");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Build connection URL from primary database properties
|
|
77
|
+
*/
|
|
78
|
+
buildPrimaryDbUrl() {
|
|
79
|
+
if (!this.options.primaryDb) {
|
|
80
|
+
throw new Error("Primary database configuration not provided");
|
|
81
|
+
}
|
|
82
|
+
const { host, port = 5432, username, password, database, schema = "public", sslMode = "require" } = this.options.primaryDb;
|
|
83
|
+
let url = `postgresql://${username}:${password}@${host}:${port}/${database}`;
|
|
84
|
+
const params = new URLSearchParams();
|
|
85
|
+
if (schema) {
|
|
86
|
+
params.set("schema", schema);
|
|
87
|
+
}
|
|
88
|
+
params.set("sslmode", sslMode);
|
|
89
|
+
const queryString = params.toString();
|
|
90
|
+
if (queryString) {
|
|
91
|
+
url += `?${queryString}`;
|
|
92
|
+
}
|
|
93
|
+
this.logger.debug(`Primary DB connection URL: ${this.maskPassword(url)}`);
|
|
94
|
+
return url;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Mask password in connection URL for logging
|
|
98
|
+
*/
|
|
99
|
+
maskPassword(url) {
|
|
100
|
+
return url.replace(/:([^@]+)@/, ":****@");
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Get tenant configuration by identifier (ID or slug)
|
|
104
|
+
*
|
|
105
|
+
* @param tenantIdentifier Tenant ID or slug
|
|
106
|
+
* @returns Tenant configuration or null if not found
|
|
107
|
+
*/
|
|
108
|
+
async getTenantInfo(tenantIdentifier) {
|
|
109
|
+
const cached = this.tenantConfigCache.get(tenantIdentifier);
|
|
110
|
+
if (cached) {
|
|
111
|
+
this.logger.debug(`Cache hit for tenant: ${tenantIdentifier}`);
|
|
112
|
+
return cached;
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
if (!this.primaryDbClient) {
|
|
116
|
+
throw new Error("Primary database client not initialized");
|
|
117
|
+
}
|
|
118
|
+
this.logger.debug(`Querying primary database for tenant: ${tenantIdentifier}`);
|
|
119
|
+
const tenant = await this.primaryDbClient.tenant.findFirst({
|
|
120
|
+
where: {
|
|
121
|
+
OR: [
|
|
122
|
+
{
|
|
123
|
+
id: tenantIdentifier
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
subDomain: tenantIdentifier
|
|
127
|
+
}
|
|
128
|
+
],
|
|
129
|
+
status: "ACTIVE"
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
if (!tenant) {
|
|
133
|
+
this.logger.warn(`Tenant not found: ${tenantIdentifier}`);
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
const info = {
|
|
137
|
+
id: tenant.id,
|
|
138
|
+
subdomain: tenant.subdomain,
|
|
139
|
+
type: tenant.type,
|
|
140
|
+
status: tenant.status,
|
|
141
|
+
schemaName: tenant.schemaName || void 0,
|
|
142
|
+
databaseName: tenant.databaseName || void 0,
|
|
143
|
+
databaseHost: tenant.databaseHost || void 0,
|
|
144
|
+
databasePort: tenant.databasePort || void 0,
|
|
145
|
+
databaseUsername: tenant.databaseUsername ? this.decrypt(tenant.databaseUsername) : void 0,
|
|
146
|
+
databasePassword: tenant.databasePassword ? this.decrypt(tenant.databasePassword) : void 0,
|
|
147
|
+
databaseSslMode: tenant.databaseSslMode || void 0,
|
|
148
|
+
connectionPoolSize: tenant.connectionPoolSize || void 0
|
|
149
|
+
};
|
|
150
|
+
this.cacheInfo(info);
|
|
151
|
+
return info;
|
|
152
|
+
} catch (error) {
|
|
153
|
+
this.logger.error(`Failed to fetch tenant info: ${tenantIdentifier}`, error);
|
|
154
|
+
throw new InternalServerErrorException("Failed to resolve tenant");
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Cache tenant information with TTL
|
|
159
|
+
*/
|
|
160
|
+
cacheInfo(info) {
|
|
161
|
+
this.tenantConfigCache.set(info.id, info);
|
|
162
|
+
this.tenantConfigCache.set(info.subdomain, info);
|
|
163
|
+
setTimeout(() => {
|
|
164
|
+
this.tenantConfigCache.delete(info.id);
|
|
165
|
+
this.tenantConfigCache.delete(info.subdomain);
|
|
166
|
+
this.logger.debug(`Cache expired for tenant: ${info.subdomain}`);
|
|
167
|
+
}, this.cacheTTL);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Clear cached tenant information
|
|
171
|
+
*
|
|
172
|
+
* Useful when tenant settings are updated and cache needs to be invalidated
|
|
173
|
+
*
|
|
174
|
+
* @param tenantIdentifier Tenant ID or slug
|
|
175
|
+
*/
|
|
176
|
+
clearTenantCache(tenantIdentifier) {
|
|
177
|
+
const config = this.tenantConfigCache.get(tenantIdentifier);
|
|
178
|
+
if (config) {
|
|
179
|
+
this.tenantConfigCache.delete(config.id);
|
|
180
|
+
this.tenantConfigCache.delete(config.subdomain);
|
|
181
|
+
this.logger.log(`Cleared cache for tenant: ${tenantIdentifier}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Clear all cached tenant configurations
|
|
186
|
+
*/
|
|
187
|
+
clearAllCaches() {
|
|
188
|
+
const size = this.tenantConfigCache.size;
|
|
189
|
+
this.tenantConfigCache.clear();
|
|
190
|
+
this.logger.log(`Cleared ${size} cached tenant configs`);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Get primary database client for direct database access
|
|
194
|
+
*
|
|
195
|
+
* This is useful for platform admin operations (creating tenants, billing, etc.)
|
|
196
|
+
*
|
|
197
|
+
* @returns Primary database client instance
|
|
198
|
+
* @throws Error if primary database client is not initialized
|
|
199
|
+
*/
|
|
200
|
+
getPrimaryDbClient() {
|
|
201
|
+
if (!this.primaryDbClient) {
|
|
202
|
+
throw new Error("Primary database client not initialized. Are you in gateway mode?");
|
|
203
|
+
}
|
|
204
|
+
return this.primaryDbClient;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Decrypt database credentials
|
|
208
|
+
*
|
|
209
|
+
* Override this method to implement your encryption strategy
|
|
210
|
+
*
|
|
211
|
+
* @param encrypted Encrypted value
|
|
212
|
+
* @returns Decrypted value
|
|
213
|
+
*/
|
|
214
|
+
decrypt(encrypted) {
|
|
215
|
+
return encrypted;
|
|
216
|
+
}
|
|
217
|
+
async onModuleDestroy() {
|
|
218
|
+
if (this.primaryDbClient) {
|
|
219
|
+
await this.primaryDbClient.$disconnect();
|
|
220
|
+
this.logger.log("Disconnected from primary database");
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
PrimaryDatabaseService = _ts_decorate([
|
|
225
|
+
Injectable(),
|
|
226
|
+
_ts_param(0, Inject(DATABASE_MODULE_OPTIONS)),
|
|
227
|
+
_ts_metadata("design:type", Function),
|
|
228
|
+
_ts_metadata("design:paramtypes", [
|
|
229
|
+
typeof DatabaseModuleOptions === "undefined" ? Object : DatabaseModuleOptions
|
|
230
|
+
])
|
|
231
|
+
], PrimaryDatabaseService);
|
|
232
|
+
|
|
233
|
+
// src/database/services/tenant-context.service.ts
|
|
234
|
+
import { Injectable as Injectable2, Scope, UnauthorizedException } from "@nestjs/common";
|
|
235
|
+
function _ts_decorate2(decorators, target, key, desc) {
|
|
236
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
237
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
238
|
+
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;
|
|
239
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
240
|
+
}
|
|
241
|
+
__name(_ts_decorate2, "_ts_decorate");
|
|
242
|
+
var TenantContextService = class {
|
|
243
|
+
static {
|
|
244
|
+
__name(this, "TenantContextService");
|
|
245
|
+
}
|
|
246
|
+
tenantInfo = null;
|
|
247
|
+
/**
|
|
248
|
+
* Set tenant information for this request/message
|
|
249
|
+
*
|
|
250
|
+
* This is typically called by:
|
|
251
|
+
* - TenantContextInterceptor (for HTTP requests in gateway)
|
|
252
|
+
* - MessageTenantContextInterceptor (for RabbitMQ messages in microservices)
|
|
253
|
+
* - Manual context setup in message handlers
|
|
254
|
+
*
|
|
255
|
+
* @param tenantInfo Complete tenant information
|
|
256
|
+
* @throws Error if tenant context is already set (prevents accidental overwrites)
|
|
257
|
+
*/
|
|
258
|
+
setTenant(tenantInfo) {
|
|
259
|
+
if (this.tenantInfo) {
|
|
260
|
+
throw new Error("Tenant context already set for this request");
|
|
261
|
+
}
|
|
262
|
+
this.tenantInfo = tenantInfo;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Get tenant information for this request/message
|
|
266
|
+
*
|
|
267
|
+
* @returns Tenant information
|
|
268
|
+
* @throws UnauthorizedException if tenant context hasn't been set
|
|
269
|
+
*/
|
|
270
|
+
getTenant() {
|
|
271
|
+
if (!this.tenantInfo) {
|
|
272
|
+
throw new UnauthorizedException("Tenant context not set");
|
|
273
|
+
}
|
|
274
|
+
return this.tenantInfo;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Check if tenant context has been set
|
|
278
|
+
*
|
|
279
|
+
* @returns true if tenant context is available
|
|
280
|
+
*/
|
|
281
|
+
hasTenant() {
|
|
282
|
+
return this.tenantInfo !== null;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Clear tenant context
|
|
286
|
+
*
|
|
287
|
+
* This is useful for cleanup in RabbitMQ message handlers
|
|
288
|
+
* after the message has been processed.
|
|
289
|
+
*
|
|
290
|
+
* HTTP requests don't need manual cleanup as the service
|
|
291
|
+
* instance is destroyed when the request ends.
|
|
292
|
+
*/
|
|
293
|
+
clearTenant() {
|
|
294
|
+
this.tenantInfo = null;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Get tenant ID safely (returns null if not set)
|
|
298
|
+
*
|
|
299
|
+
* @returns Tenant ID or null
|
|
300
|
+
*/
|
|
301
|
+
getTenantIdSafe() {
|
|
302
|
+
return this.tenantInfo?.id ?? null;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Get tenant subdomain safely (returns null if not set)
|
|
306
|
+
*
|
|
307
|
+
* @returns Tenant subdomain or null
|
|
308
|
+
*/
|
|
309
|
+
getTenantSubdomainSafe() {
|
|
310
|
+
return this.tenantInfo?.subdomain ?? null;
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
TenantContextService = _ts_decorate2([
|
|
314
|
+
Injectable2({
|
|
315
|
+
scope: Scope.REQUEST
|
|
316
|
+
})
|
|
317
|
+
], TenantContextService);
|
|
318
|
+
|
|
319
|
+
// src/database/services/tenant-database.service.ts
|
|
320
|
+
import { Inject as Inject2, Injectable as Injectable3, InternalServerErrorException as InternalServerErrorException2, Logger as Logger2 } from "@nestjs/common";
|
|
321
|
+
function _ts_decorate3(decorators, target, key, desc) {
|
|
322
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
323
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
324
|
+
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;
|
|
325
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
326
|
+
}
|
|
327
|
+
__name(_ts_decorate3, "_ts_decorate");
|
|
328
|
+
function _ts_metadata2(k, v) {
|
|
329
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
330
|
+
}
|
|
331
|
+
__name(_ts_metadata2, "_ts_metadata");
|
|
332
|
+
function _ts_param2(paramIndex, decorator) {
|
|
333
|
+
return function(target, key) {
|
|
334
|
+
decorator(target, key, paramIndex);
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
__name(_ts_param2, "_ts_param");
|
|
338
|
+
var TenantDatabaseService = class _TenantDatabaseService {
|
|
339
|
+
static {
|
|
340
|
+
__name(this, "TenantDatabaseService");
|
|
341
|
+
}
|
|
342
|
+
options;
|
|
343
|
+
tenantContext;
|
|
344
|
+
logger = new Logger2(_TenantDatabaseService.name);
|
|
345
|
+
/** Connection pool: Map<cacheKey, DbClient> */
|
|
346
|
+
clients = /* @__PURE__ */ new Map();
|
|
347
|
+
/** Track last usage time for idle connection cleanup */
|
|
348
|
+
clientLastUsed = /* @__PURE__ */ new Map();
|
|
349
|
+
/** Cleanup interval timer */
|
|
350
|
+
cleanupInterval;
|
|
351
|
+
constructor(options, tenantContext) {
|
|
352
|
+
this.options = options;
|
|
353
|
+
this.tenantContext = tenantContext;
|
|
354
|
+
this.startConnectionCleaner();
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Get tenant-scoped database client for the current request/message
|
|
358
|
+
*
|
|
359
|
+
* This method:
|
|
360
|
+
* 1. Gets tenant info from TenantContextService
|
|
361
|
+
* 2. Builds a connection URL based on tenant type
|
|
362
|
+
* 3. Returns cached client if exists, otherwise creates new one
|
|
363
|
+
*
|
|
364
|
+
* @returns Promise<Database client instance>
|
|
365
|
+
* @throws UnauthorizedException if tenant context not set
|
|
366
|
+
* @throws InternalServerErrorException if connection fails
|
|
367
|
+
*
|
|
368
|
+
* @example
|
|
369
|
+
* const dbClient = await tenantDatabase.getDbClient<PrismaClient>();
|
|
370
|
+
* const users = await dbClient.user.findMany();
|
|
371
|
+
*/
|
|
372
|
+
async getDbClient() {
|
|
373
|
+
const tenant = this.tenantContext.getTenant();
|
|
374
|
+
const cacheKey = this.buildCacheKey(tenant);
|
|
375
|
+
if (this.clients.has(cacheKey)) {
|
|
376
|
+
this.clientLastUsed.set(cacheKey, Date.now());
|
|
377
|
+
this.logger.debug(`Reusing cached connection: ${cacheKey}`);
|
|
378
|
+
return this.clients.get(cacheKey);
|
|
379
|
+
}
|
|
380
|
+
this.logger.log(`Creating new database connection: ${cacheKey}`);
|
|
381
|
+
const client = await this.createDbClient(tenant);
|
|
382
|
+
this.clients.set(cacheKey, client);
|
|
383
|
+
this.clientLastUsed.set(cacheKey, Date.now());
|
|
384
|
+
return client;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Create a new database client for the given tenant
|
|
388
|
+
*/
|
|
389
|
+
async createDbClient(tenant) {
|
|
390
|
+
try {
|
|
391
|
+
const databaseUrl = this.buildTenantDbUrl(tenant);
|
|
392
|
+
const PrismaClient = await this.options.prismaClientConstructor;
|
|
393
|
+
const client = new PrismaClient({
|
|
394
|
+
datasources: {
|
|
395
|
+
db: {
|
|
396
|
+
url: databaseUrl
|
|
397
|
+
}
|
|
398
|
+
},
|
|
399
|
+
log: [
|
|
400
|
+
"error",
|
|
401
|
+
"warn"
|
|
402
|
+
]
|
|
403
|
+
});
|
|
404
|
+
await client.$connect();
|
|
405
|
+
this.logger.log(`Connected to database for tenant: ${tenant.subdomain}`);
|
|
406
|
+
return client;
|
|
407
|
+
} catch (error) {
|
|
408
|
+
this.logger.error(`Failed to create database connection for tenant: ${tenant.subdomain}`, error);
|
|
409
|
+
throw new InternalServerErrorException2("Failed to connect to tenant database");
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Build connection URL for enterprise tenant (dedicated database)
|
|
414
|
+
*/
|
|
415
|
+
buildTenantDbUrl(tenant) {
|
|
416
|
+
const { databaseHost, databasePort, databaseName, databaseUsername, databasePassword, databaseSslMode } = tenant;
|
|
417
|
+
if (!databaseHost || !databaseName || !databaseUsername) {
|
|
418
|
+
throw new Error(`Enterprise tenant ${tenant.subdomain} missing database configuration`);
|
|
419
|
+
}
|
|
420
|
+
const port = databasePort || 5432;
|
|
421
|
+
const sslMode = databaseSslMode || "require";
|
|
422
|
+
const connectionUrl = `postgresql://${databaseUsername}:${databasePassword}@${databaseHost}:${port}/${databaseName}?sslmode=${sslMode}`;
|
|
423
|
+
this.logger.debug(`Enterprise connection URL: ${this.maskPassword(connectionUrl)}`);
|
|
424
|
+
return connectionUrl;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Build cache key for connection pooling
|
|
428
|
+
*/
|
|
429
|
+
buildCacheKey(tenant) {
|
|
430
|
+
return `${tenant.type}:${tenant.databaseName}@${tenant.databaseHost}`;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Start periodic cleanup of idle connections
|
|
434
|
+
*/
|
|
435
|
+
startConnectionCleaner() {
|
|
436
|
+
const interval = this.options.connectionCacheTTL || 3e5;
|
|
437
|
+
this.cleanupInterval = setInterval(() => {
|
|
438
|
+
this.cleanupIdleConnections();
|
|
439
|
+
}, interval);
|
|
440
|
+
this.logger.log(`Connection cleanup scheduled every ${interval / 1e3} seconds`);
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Clean up idle connections that haven't been used recently
|
|
444
|
+
*/
|
|
445
|
+
cleanupIdleConnections() {
|
|
446
|
+
const now = Date.now();
|
|
447
|
+
const maxIdle = this.options.connectionCacheTTL || 3e5;
|
|
448
|
+
let cleaned = 0;
|
|
449
|
+
for (const [key, lastUsed] of this.clientLastUsed.entries()) {
|
|
450
|
+
if (now - lastUsed > maxIdle) {
|
|
451
|
+
const client = this.clients.get(key);
|
|
452
|
+
if (client) {
|
|
453
|
+
client.$disconnect().then(() => {
|
|
454
|
+
this.logger.debug(`Cleaned up idle connection: ${key}`);
|
|
455
|
+
}).catch((error) => {
|
|
456
|
+
this.logger.error(`Error disconnecting idle client: ${key}`, error);
|
|
457
|
+
});
|
|
458
|
+
this.clients.delete(key);
|
|
459
|
+
this.clientLastUsed.delete(key);
|
|
460
|
+
cleaned++;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (cleaned > 0) {
|
|
465
|
+
this.logger.log(`Cleaned up ${cleaned} idle connections`);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Get current connection pool statistics
|
|
470
|
+
*/
|
|
471
|
+
getPoolStats() {
|
|
472
|
+
return {
|
|
473
|
+
activeConnections: this.clients.size,
|
|
474
|
+
tenants: Array.from(this.clients.keys())
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Mask password in connection URL for logging
|
|
479
|
+
*/
|
|
480
|
+
maskPassword(url) {
|
|
481
|
+
return url.replace(/:([^@]+)@/, ":****@");
|
|
482
|
+
}
|
|
483
|
+
async onModuleDestroy() {
|
|
484
|
+
if (this.cleanupInterval) {
|
|
485
|
+
clearInterval(this.cleanupInterval);
|
|
486
|
+
}
|
|
487
|
+
this.logger.log(`Disconnecting ${this.clients.size} database connections`);
|
|
488
|
+
const disconnectPromises = Array.from(this.clients.entries()).map(async ([key, client]) => {
|
|
489
|
+
try {
|
|
490
|
+
await client.$disconnect();
|
|
491
|
+
this.logger.debug(`Disconnected: ${key}`);
|
|
492
|
+
} catch (error) {
|
|
493
|
+
this.logger.error(`Error disconnecting client: ${key}`, error);
|
|
494
|
+
}
|
|
495
|
+
});
|
|
496
|
+
await Promise.all(disconnectPromises);
|
|
497
|
+
this.logger.log("All database connections closed");
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
TenantDatabaseService = _ts_decorate3([
|
|
501
|
+
Injectable3(),
|
|
502
|
+
_ts_param2(0, Inject2(DATABASE_MODULE_OPTIONS)),
|
|
503
|
+
_ts_metadata2("design:type", Function),
|
|
504
|
+
_ts_metadata2("design:paramtypes", [
|
|
505
|
+
typeof DatabaseModuleOptions === "undefined" ? Object : DatabaseModuleOptions,
|
|
506
|
+
typeof TenantContextService === "undefined" ? Object : TenantContextService
|
|
507
|
+
])
|
|
508
|
+
], TenantDatabaseService);
|
|
509
|
+
|
|
510
|
+
// src/database/database.module.ts
|
|
511
|
+
function _ts_decorate4(decorators, target, key, desc) {
|
|
512
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
513
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
514
|
+
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;
|
|
515
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
516
|
+
}
|
|
517
|
+
__name(_ts_decorate4, "_ts_decorate");
|
|
518
|
+
var DatabaseModule = class _DatabaseModule {
|
|
519
|
+
static {
|
|
520
|
+
__name(this, "DatabaseModule");
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Synchronous configuration
|
|
524
|
+
*
|
|
525
|
+
* @param options Module configuration options
|
|
526
|
+
* @returns Dynamic module configuration
|
|
527
|
+
*/
|
|
528
|
+
static forRoot(options) {
|
|
529
|
+
const providers = [
|
|
530
|
+
{
|
|
531
|
+
provide: DATABASE_MODULE_OPTIONS,
|
|
532
|
+
useValue: options
|
|
533
|
+
},
|
|
534
|
+
TenantDatabaseService,
|
|
535
|
+
TenantContextService,
|
|
536
|
+
PrimaryDatabaseService
|
|
537
|
+
];
|
|
538
|
+
return {
|
|
539
|
+
module: _DatabaseModule,
|
|
540
|
+
providers,
|
|
541
|
+
exports: [
|
|
542
|
+
TenantDatabaseService,
|
|
543
|
+
TenantContextService,
|
|
544
|
+
PrimaryDatabaseService
|
|
545
|
+
]
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Asynchronous configuration (recommended)
|
|
550
|
+
*
|
|
551
|
+
* Allows injecting ConfigService or other dependencies
|
|
552
|
+
*
|
|
553
|
+
* @param options Async configuration options
|
|
554
|
+
* @returns Dynamic module configuration
|
|
555
|
+
*
|
|
556
|
+
* @example
|
|
557
|
+
* DatabaseModule.forRootAsync({
|
|
558
|
+
* imports: [ConfigModule],
|
|
559
|
+
* useFactory: async (config: ConfigService) => ({
|
|
560
|
+
* cloudDatabaseUrl: config.get('CLOUD_DATABASE_URL'),
|
|
561
|
+
* prismaClientConstructor: PrismaClient,
|
|
562
|
+
* tenantResolver: 'subdomain',
|
|
563
|
+
* }),
|
|
564
|
+
* inject: [ConfigService],
|
|
565
|
+
* })
|
|
566
|
+
*/
|
|
567
|
+
static forRootAsync(options) {
|
|
568
|
+
const asyncProvider = {
|
|
569
|
+
provide: DATABASE_MODULE_OPTIONS,
|
|
570
|
+
useFactory: options.useFactory,
|
|
571
|
+
inject: options.inject || []
|
|
572
|
+
};
|
|
573
|
+
return {
|
|
574
|
+
module: _DatabaseModule,
|
|
575
|
+
providers: [
|
|
576
|
+
asyncProvider,
|
|
577
|
+
TenantContextService,
|
|
578
|
+
PrimaryDatabaseService,
|
|
579
|
+
TenantDatabaseService
|
|
580
|
+
],
|
|
581
|
+
exports: [
|
|
582
|
+
TenantDatabaseService,
|
|
583
|
+
TenantContextService,
|
|
584
|
+
PrimaryDatabaseService,
|
|
585
|
+
asyncProvider
|
|
586
|
+
]
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
DatabaseModule = _ts_decorate4([
|
|
591
|
+
Global(),
|
|
592
|
+
Module({})
|
|
593
|
+
], DatabaseModule);
|
|
594
|
+
|
|
595
|
+
// src/database/interceptors/message-tenant-context.interceptor.ts
|
|
596
|
+
import { Injectable as Injectable4, Logger as Logger3, Scope as Scope2 } from "@nestjs/common";
|
|
597
|
+
import { tap } from "rxjs/operators";
|
|
598
|
+
function _ts_decorate5(decorators, target, key, desc) {
|
|
599
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
600
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
601
|
+
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;
|
|
602
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
603
|
+
}
|
|
604
|
+
__name(_ts_decorate5, "_ts_decorate");
|
|
605
|
+
function _ts_metadata3(k, v) {
|
|
606
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
607
|
+
}
|
|
608
|
+
__name(_ts_metadata3, "_ts_metadata");
|
|
609
|
+
var MessageTenantContextInterceptor = class _MessageTenantContextInterceptor {
|
|
610
|
+
static {
|
|
611
|
+
__name(this, "MessageTenantContextInterceptor");
|
|
612
|
+
}
|
|
613
|
+
tenantContext;
|
|
614
|
+
logger = new Logger3(_MessageTenantContextInterceptor.name);
|
|
615
|
+
constructor(tenantContext) {
|
|
616
|
+
this.tenantContext = tenantContext;
|
|
617
|
+
}
|
|
618
|
+
intercept(context, next) {
|
|
619
|
+
const contextType = context.getType();
|
|
620
|
+
if (contextType === "rpc") {
|
|
621
|
+
const rpcContext = context.switchToRpc();
|
|
622
|
+
const payload = rpcContext.getData();
|
|
623
|
+
if (payload && payload.tenant) {
|
|
624
|
+
const tenant = payload.tenant;
|
|
625
|
+
this.logger.debug(`Setting tenant context from message: ${tenant.subdomain}`);
|
|
626
|
+
try {
|
|
627
|
+
this.tenantContext.setTenant(tenant);
|
|
628
|
+
this.logger.log(`Tenant context set: ${tenant.subdomain} (${tenant.type})`);
|
|
629
|
+
} catch (error) {
|
|
630
|
+
this.logger.error("Failed to set tenant context from message", error);
|
|
631
|
+
}
|
|
632
|
+
} else {
|
|
633
|
+
this.logger.warn("Message payload missing tenant information");
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
return next.handle().pipe(tap({
|
|
637
|
+
next: /* @__PURE__ */ __name(() => {
|
|
638
|
+
this.cleanupContext();
|
|
639
|
+
}, "next"),
|
|
640
|
+
error: /* @__PURE__ */ __name(() => {
|
|
641
|
+
this.cleanupContext();
|
|
642
|
+
}, "error"),
|
|
643
|
+
complete: /* @__PURE__ */ __name(() => {
|
|
644
|
+
this.cleanupContext();
|
|
645
|
+
}, "complete")
|
|
646
|
+
}));
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Clean up tenant context after message is processed
|
|
650
|
+
*/
|
|
651
|
+
cleanupContext() {
|
|
652
|
+
if (this.tenantContext.hasTenant()) {
|
|
653
|
+
const tenant = this.tenantContext.getTenantIdSafe();
|
|
654
|
+
this.tenantContext.clearTenant();
|
|
655
|
+
this.logger.debug(`Cleaned up tenant context: ${tenant}`);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
MessageTenantContextInterceptor = _ts_decorate5([
|
|
660
|
+
Injectable4({
|
|
661
|
+
scope: Scope2.REQUEST
|
|
662
|
+
}),
|
|
663
|
+
_ts_metadata3("design:type", Function),
|
|
664
|
+
_ts_metadata3("design:paramtypes", [
|
|
665
|
+
typeof TenantContextService === "undefined" ? Object : TenantContextService
|
|
666
|
+
])
|
|
667
|
+
], MessageTenantContextInterceptor);
|
|
668
|
+
|
|
669
|
+
// src/database/interceptors/tenant-context.interceptor.ts
|
|
670
|
+
import { Inject as Inject3, Injectable as Injectable5, Logger as Logger4, Scope as Scope3, UnauthorizedException as UnauthorizedException2 } from "@nestjs/common";
|
|
671
|
+
|
|
672
|
+
// src/database/utils/subdomain-parser.util.ts
|
|
673
|
+
function extractSubdomain(host) {
|
|
674
|
+
if (!host) {
|
|
675
|
+
return null;
|
|
676
|
+
}
|
|
677
|
+
const hostname = host.split(":")[0];
|
|
678
|
+
if (!hostname) {
|
|
679
|
+
return null;
|
|
680
|
+
}
|
|
681
|
+
const parts = hostname.split(".");
|
|
682
|
+
if (parts.length < 3) {
|
|
683
|
+
return null;
|
|
684
|
+
}
|
|
685
|
+
return parts[0] ?? null;
|
|
686
|
+
}
|
|
687
|
+
__name(extractSubdomain, "extractSubdomain");
|
|
688
|
+
|
|
689
|
+
// src/database/interceptors/tenant-context.interceptor.ts
|
|
690
|
+
function _ts_decorate6(decorators, target, key, desc) {
|
|
691
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
692
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
693
|
+
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;
|
|
694
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
695
|
+
}
|
|
696
|
+
__name(_ts_decorate6, "_ts_decorate");
|
|
697
|
+
function _ts_metadata4(k, v) {
|
|
698
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
699
|
+
}
|
|
700
|
+
__name(_ts_metadata4, "_ts_metadata");
|
|
701
|
+
function _ts_param3(paramIndex, decorator) {
|
|
702
|
+
return function(target, key) {
|
|
703
|
+
decorator(target, key, paramIndex);
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
__name(_ts_param3, "_ts_param");
|
|
707
|
+
var TenantContextInterceptor = class _TenantContextInterceptor {
|
|
708
|
+
static {
|
|
709
|
+
__name(this, "TenantContextInterceptor");
|
|
710
|
+
}
|
|
711
|
+
tenantContext;
|
|
712
|
+
primaryDatabase;
|
|
713
|
+
options;
|
|
714
|
+
logger = new Logger4(_TenantContextInterceptor.name);
|
|
715
|
+
constructor(tenantContext, primaryDatabase, options) {
|
|
716
|
+
this.tenantContext = tenantContext;
|
|
717
|
+
this.primaryDatabase = primaryDatabase;
|
|
718
|
+
this.options = options;
|
|
719
|
+
}
|
|
720
|
+
async intercept(context, next) {
|
|
721
|
+
const request = context.switchToHttp().getRequest();
|
|
722
|
+
this.logger.debug(`Processing request: ${request.method} ${request.url}`);
|
|
723
|
+
try {
|
|
724
|
+
const tenantIdentifier = this.extractTenantIdentifier(request);
|
|
725
|
+
if (!tenantIdentifier) {
|
|
726
|
+
throw new UnauthorizedException2("Tenant identifier not found in request");
|
|
727
|
+
}
|
|
728
|
+
this.logger.debug(`Tenant identifier extracted: ${tenantIdentifier}`);
|
|
729
|
+
if (tenantIdentifier === "cloud") {
|
|
730
|
+
this.logger.log("Cloud platform access detected, skipping tenant context setup");
|
|
731
|
+
return next.handle();
|
|
732
|
+
}
|
|
733
|
+
const tenantInfo = await this.primaryDatabase.getTenantInfo(tenantIdentifier);
|
|
734
|
+
if (!tenantInfo) {
|
|
735
|
+
this.logger.warn(`Invalid tenant: ${tenantIdentifier}`);
|
|
736
|
+
throw new UnauthorizedException2("Invalid tenant");
|
|
737
|
+
}
|
|
738
|
+
if (tenantInfo.status !== "ACTIVE") {
|
|
739
|
+
this.logger.warn(`Tenant ${tenantIdentifier} has status: ${tenantInfo.status}`);
|
|
740
|
+
throw new UnauthorizedException2(`Tenant is ${tenantInfo.status}`);
|
|
741
|
+
}
|
|
742
|
+
this.logger.debug(`Tenant config loaded: ${tenantInfo.subdomain} (${tenantInfo.type})`);
|
|
743
|
+
this.tenantContext.setTenant(tenantInfo);
|
|
744
|
+
request.tenant = tenantInfo;
|
|
745
|
+
this.logger.log(`Tenant context set: ${tenantInfo.subdomain}`);
|
|
746
|
+
} catch (error) {
|
|
747
|
+
this.logger.error("Failed to set tenant context", error);
|
|
748
|
+
throw error;
|
|
749
|
+
}
|
|
750
|
+
return next.handle();
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* Extract tenant identifier: tries subdomain first, then falls back to header
|
|
754
|
+
*/
|
|
755
|
+
extractTenantIdentifier(request) {
|
|
756
|
+
let tenantIdentifier = this.extractFromSubdomain(request);
|
|
757
|
+
if (!tenantIdentifier) {
|
|
758
|
+
tenantIdentifier = this.extractFromHeader(request);
|
|
759
|
+
if (tenantIdentifier) {
|
|
760
|
+
this.logger.debug("Using tenant from header (subdomain not found)");
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
return tenantIdentifier;
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* Extract tenant from subdomain
|
|
767
|
+
* @example acme.vritti.com → 'acme'
|
|
768
|
+
*/
|
|
769
|
+
extractFromSubdomain(request) {
|
|
770
|
+
if (request.subdomain) {
|
|
771
|
+
return request.subdomain;
|
|
772
|
+
}
|
|
773
|
+
const host = request.headers?.host || request.hostname;
|
|
774
|
+
return extractSubdomain(host);
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Extract tenant from HTTP headers
|
|
778
|
+
* Checks x-tenant-id and x-subdomain headers
|
|
779
|
+
*/
|
|
780
|
+
extractFromHeader(request) {
|
|
781
|
+
const getHeader = /* @__PURE__ */ __name((key) => {
|
|
782
|
+
const value = request.headers?.[key];
|
|
783
|
+
return Array.isArray(value) ? value[0] : value;
|
|
784
|
+
}, "getHeader");
|
|
785
|
+
return getHeader("x-tenant-id") || getHeader("x-subdomain") || null;
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
TenantContextInterceptor = _ts_decorate6([
|
|
789
|
+
Injectable5({
|
|
790
|
+
scope: Scope3.REQUEST
|
|
791
|
+
}),
|
|
792
|
+
_ts_param3(2, Inject3(DATABASE_MODULE_OPTIONS)),
|
|
793
|
+
_ts_metadata4("design:type", Function),
|
|
794
|
+
_ts_metadata4("design:paramtypes", [
|
|
795
|
+
typeof TenantContextService === "undefined" ? Object : TenantContextService,
|
|
796
|
+
typeof PrimaryDatabaseService === "undefined" ? Object : PrimaryDatabaseService,
|
|
797
|
+
typeof DatabaseModuleOptions === "undefined" ? Object : DatabaseModuleOptions
|
|
798
|
+
])
|
|
799
|
+
], TenantContextInterceptor);
|
|
800
|
+
|
|
801
|
+
// src/database/decorators/tenant.decorator.ts
|
|
802
|
+
import { createParamDecorator } from "@nestjs/common";
|
|
803
|
+
var Tenant = createParamDecorator((data, ctx) => {
|
|
804
|
+
const request = ctx.switchToHttp().getRequest();
|
|
805
|
+
const tenantContext = request.app?.get?.(TenantContextService);
|
|
806
|
+
if (!tenantContext) {
|
|
807
|
+
throw new Error("TenantContextService not found.");
|
|
808
|
+
}
|
|
809
|
+
return tenantContext.getTenant();
|
|
810
|
+
});
|
|
8
811
|
export {
|
|
9
|
-
|
|
812
|
+
DatabaseModule,
|
|
813
|
+
MessageTenantContextInterceptor,
|
|
814
|
+
PrimaryDatabaseService,
|
|
815
|
+
Tenant,
|
|
816
|
+
TenantContextInterceptor,
|
|
817
|
+
TenantContextService,
|
|
818
|
+
TenantDatabaseService,
|
|
819
|
+
extractSubdomain
|
|
10
820
|
};
|
|
11
821
|
//# sourceMappingURL=index.js.map
|