@niledatabase/server 5.0.0-alpha.32 → 5.0.0-alpha.33

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.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import pg, { PoolConfig, PoolClient } from 'pg';
1
+ import pg, { Pool, PoolConfig, PoolClient } from 'pg';
2
2
 
3
3
  type LogFunction = (message: string | unknown, meta?: Record<string, unknown>) => void;
4
4
  type Loggable = {
@@ -523,6 +523,14 @@ declare class Server {
523
523
  tenants: Tenants;
524
524
  auth: Auth;
525
525
  constructor(config?: NileConfig);
526
+ /**
527
+ * Query the database with the current context
528
+ */
529
+ query: Pool['query'];
530
+ /**
531
+ * Return a db object that can be used to talk to the database
532
+ * Does not have a context by default
533
+ */
526
534
  get db(): pg.Pool & {
527
535
  clearConnections: () => void;
528
536
  };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import pg, { PoolConfig, PoolClient } from 'pg';
1
+ import pg, { Pool, PoolConfig, PoolClient } from 'pg';
2
2
 
3
3
  type LogFunction = (message: string | unknown, meta?: Record<string, unknown>) => void;
4
4
  type Loggable = {
@@ -523,6 +523,14 @@ declare class Server {
523
523
  tenants: Tenants;
524
524
  auth: Auth;
525
525
  constructor(config?: NileConfig);
526
+ /**
527
+ * Query the database with the current context
528
+ */
529
+ query: Pool['query'];
530
+ /**
531
+ * Return a db object that can be used to talk to the database
532
+ * Does not have a context by default
533
+ */
526
534
  get db(): pg.Pool & {
527
535
  clearConnections: () => void;
528
536
  };
package/dist/index.js CHANGED
@@ -2116,17 +2116,17 @@ var updateHeaders = (val) => {
2116
2116
  var watchHeaders = (cb) => eventer.subscribe("headers" /* Headers */, cb);
2117
2117
 
2118
2118
  // src/db/PoolProxy.ts
2119
- function createProxyForPool(pool, config) {
2120
- const { info, error } = config.logger("[pool]");
2119
+ function createProxyForPool(pool, config, logger, context) {
2120
+ const { info, error } = logger("[pool]");
2121
2121
  return new Proxy(pool, {
2122
2122
  get(target, property) {
2123
2123
  if (property === "query") {
2124
- if (!config.db.connectionString) {
2125
- if (!config.db.user || !config.db.password) {
2124
+ if (!config.connectionString) {
2125
+ if (!config.user || !config.password) {
2126
2126
  error(
2127
2127
  "Cannot connect to the database. User and/or password are missing. Generate them at https://console.thenile.dev"
2128
2128
  );
2129
- } else if (!config.db.database) {
2129
+ } else if (!config.database) {
2130
2130
  error(
2131
2131
  "Unable to obtain database name. Is process.env.NILEDB_POSTGRES_URL set?"
2132
2132
  );
@@ -2135,7 +2135,7 @@ function createProxyForPool(pool, config) {
2135
2135
  const caller = target[property];
2136
2136
  return function query(...args) {
2137
2137
  let log = "[QUERY]";
2138
- const { userId, tenantId } = config.context;
2138
+ const [tenantId, userId] = context;
2139
2139
  if (tenantId) {
2140
2140
  log = `${log}[TENANT:${tenantId}]`;
2141
2141
  }
@@ -2158,39 +2158,44 @@ var NileDatabase = class {
2158
2158
  tenantId;
2159
2159
  userId;
2160
2160
  id;
2161
- config;
2161
+ logger;
2162
2162
  timer;
2163
- constructor(config, id) {
2164
- const { warn: warn2, info, debug } = config.logger("[NileInstance]");
2163
+ config;
2164
+ constructor(config, logger, id) {
2165
+ this.logger = logger("[NileInstance]");
2165
2166
  this.id = id;
2166
2167
  const poolConfig = {
2167
2168
  min: 0,
2168
2169
  max: 10,
2169
2170
  idleTimeoutMillis: 3e4,
2170
- ...config.db
2171
+ ...config
2171
2172
  };
2172
2173
  const { afterCreate, ...remaining } = poolConfig;
2173
- config.db = poolConfig;
2174
- this.config = config;
2175
- const cloned = { ...this.config.db };
2174
+ this.config = remaining;
2175
+ const cloned = { ...config };
2176
2176
  cloned.password = "***";
2177
- debug(`Connection pool config ${JSON.stringify(cloned)}`);
2178
- this.pool = createProxyForPool(new pg__default.default.Pool(remaining), this.config);
2177
+ this.logger.debug(`Connection pool config ${JSON.stringify(cloned)}`);
2178
+ this.pool = createProxyForPool(
2179
+ new pg__default.default.Pool(remaining),
2180
+ this.config,
2181
+ logger,
2182
+ id === "base" ? [] : id.split(":")
2183
+ );
2179
2184
  if (typeof afterCreate === "function") {
2180
- warn2(
2185
+ this.logger.warn(
2181
2186
  "Providing an pool configuration will stop automatic tenant context setting."
2182
2187
  );
2183
2188
  }
2184
2189
  this.startTimeout();
2185
2190
  this.pool.on("connect", async (client) => {
2186
- debug(`pool connected ${this.id}`);
2191
+ this.logger.debug(`pool connected ${this.id}`);
2187
2192
  this.startTimeout();
2188
2193
  const afterCreate2 = makeAfterCreate(
2189
- config,
2190
- `${this.id}-${this.timer}`
2194
+ logger,
2195
+ `${this.id}|${this.timer}`
2191
2196
  );
2192
2197
  afterCreate2(client, (err) => {
2193
- const { error } = config.logger("[after create callback]");
2198
+ const { error } = logger("[after create callback]");
2194
2199
  if (err) {
2195
2200
  clearTimeout(this.timer);
2196
2201
  error("after create failed", {
@@ -2203,7 +2208,7 @@ var NileDatabase = class {
2203
2208
  });
2204
2209
  this.pool.on("error", (err) => {
2205
2210
  clearTimeout(this.timer);
2206
- info(`pool ${this.id} failed`, {
2211
+ this.logger.info(`pool ${this.id} failed`, {
2207
2212
  message: err.message,
2208
2213
  stack: err.stack
2209
2214
  });
@@ -2213,27 +2218,27 @@ var NileDatabase = class {
2213
2218
  if (destroy) {
2214
2219
  clearTimeout(this.timer);
2215
2220
  evictPool(this.id);
2216
- debug(`destroying pool ${this.id}`);
2221
+ this.logger.debug(`destroying pool ${this.id}`);
2217
2222
  }
2218
2223
  });
2219
2224
  }
2220
2225
  startTimeout() {
2221
- const { debug } = this.config.logger("[NileInstance]");
2226
+ const { debug } = this.logger;
2222
2227
  if (this.timer) {
2223
2228
  clearTimeout(this.timer);
2224
2229
  }
2225
2230
  this.timer = setTimeout(() => {
2226
2231
  debug(
2227
- `Pool reached idleTimeoutMillis. ${this.id} evicted after ${Number(this.config.db.idleTimeoutMillis) ?? 3e4}ms`
2232
+ `Pool reached idleTimeoutMillis. ${this.id} evicted after ${Number(this.config.idleTimeoutMillis) ?? 3e4}ms`
2228
2233
  );
2229
2234
  this.pool.end(() => {
2230
2235
  clearTimeout(this.timer);
2231
2236
  evictPool(this.id);
2232
2237
  });
2233
- }, Number(this.config.db.idleTimeoutMillis) ?? 3e4);
2238
+ }, Number(this.config.idleTimeoutMillis) ?? 3e4);
2234
2239
  }
2235
2240
  shutdown() {
2236
- const { debug } = this.config.logger("[NileInstance]");
2241
+ const { debug } = this.logger;
2237
2242
  debug(`attempting to shut down ${this.id}`);
2238
2243
  clearTimeout(this.timer);
2239
2244
  this.pool.end(() => {
@@ -2242,8 +2247,8 @@ var NileDatabase = class {
2242
2247
  }
2243
2248
  };
2244
2249
  var NileInstance_default = NileDatabase;
2245
- function makeAfterCreate(config, id) {
2246
- const { error, warn: warn2, debug } = config.logger("[afterCreate]");
2250
+ function makeAfterCreate(logger, id) {
2251
+ const { error, warn: warn2, debug } = logger("[afterCreate]");
2247
2252
  return (conn, done) => {
2248
2253
  conn.on("error", function errorHandler(e) {
2249
2254
  error(`Connection ${id} was terminated by server`, {
@@ -2252,8 +2257,9 @@ function makeAfterCreate(config, id) {
2252
2257
  });
2253
2258
  done(e, conn);
2254
2259
  });
2255
- const { tenantId, userId } = ctx.getLastUsed();
2256
- if (tenantId) {
2260
+ const [context] = id.split("|");
2261
+ const [tenantId, userId] = context.split(":");
2262
+ if (tenantId !== "base") {
2257
2263
  const query = [`SET nile.tenant_id = '${tenantId}'`];
2258
2264
  if (userId) {
2259
2265
  if (!tenantId) {
@@ -2318,9 +2324,9 @@ var DBManager = class {
2318
2324
  warn2(`missed eviction of ${id}`);
2319
2325
  }
2320
2326
  };
2321
- getConnection = (config) => {
2327
+ getConnection = (config, noContext = false) => {
2322
2328
  const { info } = Logger(config)("[DBManager]");
2323
- const { tenantId, userId } = ctx.getLastUsed();
2329
+ const { tenantId, userId } = noContext ? {} : ctx.getLastUsed();
2324
2330
  const id = this.makeId(tenantId, userId);
2325
2331
  const existing = this.connections.get(id);
2326
2332
  info(`# of instances: ${this.connections.size}`);
@@ -2329,7 +2335,7 @@ var DBManager = class {
2329
2335
  existing.startTimeout();
2330
2336
  return existing.pool;
2331
2337
  }
2332
- const newOne = new NileInstance_default(config, id);
2338
+ const newOne = new NileInstance_default(config.db, config.logger, id);
2333
2339
  this.connections.set(id, newOne);
2334
2340
  info(`created new ${id}`);
2335
2341
  info(`# of instances: ${this.connections.size}`);
@@ -3477,9 +3483,21 @@ var Server = class {
3477
3483
  }
3478
3484
  }
3479
3485
  }
3480
- get db() {
3486
+ /**
3487
+ * Query the database with the current context
3488
+ */
3489
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3490
+ query = (queryStream, values) => {
3481
3491
  this.#config.context = { ...this.getContext() };
3482
3492
  const pool = this.#manager.getConnection(this.#config);
3493
+ return pool.query(queryStream, values);
3494
+ };
3495
+ /**
3496
+ * Return a db object that can be used to talk to the database
3497
+ * Does not have a context by default
3498
+ */
3499
+ get db() {
3500
+ const pool = this.#manager.getConnection(this.#config, true);
3483
3501
  return Object.assign(pool, {
3484
3502
  clearConnections: () => {
3485
3503
  this.#manager.clear(this.#config);