@postgresx/noredis 0.5.2 → 0.6.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.
@@ -1,4 +1,4 @@
1
- import { N as PgredisClient, Y as PipelineFacade, S as PgredisMigrationAliases } from '../client-Dpoe2LdN.js';
1
+ import { Q as PgredisClient, _ as PipelineFacade, U as PgredisMigrationAliases } from '../client-DP3ssToT.js';
2
2
  import '../kv-cache.js';
3
3
  import '../sql-DKf2TDlu.js';
4
4
  import '../hash-index.js';
@@ -1,4 +1,4 @@
1
- import { N as PgredisClient, Y as PipelineFacade, S as PgredisMigrationAliases } from '../client-Dpoe2LdN.js';
1
+ import { Q as PgredisClient, _ as PipelineFacade, U as PgredisMigrationAliases } from '../client-DP3ssToT.js';
2
2
  import '../kv-cache.js';
3
3
  import '../sql-DKf2TDlu.js';
4
4
  import '../hash-index.js';
@@ -179,6 +179,14 @@ interface PgRateLimitHitOptions {
179
179
  windowMs?: number;
180
180
  cost?: number;
181
181
  }
182
+ interface PgRateLimitStateOptions {
183
+ limit?: number;
184
+ windowMs?: number;
185
+ }
186
+ interface PgRateLimitBlockOptions extends PgRateLimitStateOptions {
187
+ blockMs: number;
188
+ count?: number;
189
+ }
182
190
  interface PgRateLimitSchemaOptions {
183
191
  unlogged?: boolean;
184
192
  }
@@ -226,7 +234,14 @@ declare class PgFixedWindowRateLimiter {
226
234
  constructor(options: PgRateLimiterOptions);
227
235
  ensureSchema(options?: PgRateLimitSchemaOptions): Promise<void>;
228
236
  hit(key: string, options?: PgRateLimitHitOptions): Promise<PgRateLimitResult>;
237
+ get(key: string, options?: PgRateLimitStateOptions): Promise<PgRateLimitResult | null>;
238
+ reward(key: string, cost?: number, options?: PgRateLimitStateOptions): Promise<PgRateLimitResult | null>;
239
+ private decrementWindow;
240
+ block(key: string, options: PgRateLimitBlockOptions): Promise<PgRateLimitResult>;
241
+ delete(key: string): Promise<boolean>;
229
242
  cleanupExpired(limit?: number): Promise<number>;
243
+ private resultFromRow;
244
+ private getActiveBlock;
230
245
  }
231
246
  declare function createPgFixedWindowRateLimiter(options: PgRateLimiterOptions): PgFixedWindowRateLimiter;
232
247
  declare class PgSlidingWindowRateLimiter {
@@ -491,4 +506,4 @@ interface PgredisClient {
491
506
  }
492
507
  declare function createPgredis(options: PgredisOptions): PgredisClient;
493
508
 
494
- export { collectPgredisMetrics as $, type PgOutboxStreamSchemaOptions as A, type PgOutboxTrimOptions as B, type PgRateLimitHitOptions as C, type PgRateLimitResult as D, type PgRateLimitSchemaOptions as E, type PgRateLimiterOptions as F, PgSlidingWindowRateLimiter as G, type PgSlidingWindowRateLimiterOptions as H, PgTokenBucketRateLimiter as I, type PgTokenBucketRateLimiterOptions as J, type PgTokenBucketResult as K, type PgredisBatchOperation as L, type PgredisCleanupMetrics as M, type PgredisClient as N, type PgredisListenerMetrics as O, PgAdvisoryLockBusyError as P, type PgredisMetrics as Q, type PgredisMetricsOptions as R, type PgredisMigrationAliases as S, type PgredisOptions as T, PgredisPipeline as U, type PgredisQueueMetrics as V, type PgredisTableMetrics as W, type PipelineCommand as X, type PipelineFacade as Y, type RedisSetAliasOptions as Z, advisoryLockKeyToSqlArgs as _, type PgAdvisoryLockKey as a, createPgAdvisoryLocker as a0, createPgBossJobQueue as a1, createPgCounter as a2, createPgFixedWindowRateLimiter as a3, createPgOutboxStream as a4, createPgSlidingWindowRateLimiter as a5, createPgTokenBucketRateLimiter as a6, createPgredis as a7, createPgredisMigrationAliases as a8, withPgAdvisoryLock as a9, type PgAdvisoryLockOptions as b, PgAdvisoryLocker as c, type PgBossJob as d, PgBossJobQueue as e, type PgBossLike as f, type PgBossOptions as g, type PgBossQueueDefinition as h, type PgBossQueueMap as i, type PgBossQueueOptions as j, type PgBossQueueResult as k, type PgBossSendOptions as l, type PgBossWorkHandler as m, type PgBossWorkOptions as n, PgCounter as o, type PgCounterOptions as p, type PgCounterSchemaOptions as q, type PgCounterSetOptions as r, PgFixedWindowRateLimiter as s, type PgOutboxAppendOptions as t, type PgOutboxClaimOptions as u, type PgOutboxMessage as v, type PgOutboxPendingSummary as w, type PgOutboxReadOptions as x, PgOutboxStream as y, type PgOutboxStreamOptions as z };
509
+ export { type RedisSetAliasOptions as $, type PgOutboxStreamSchemaOptions as A, type PgOutboxTrimOptions as B, type PgRateLimitBlockOptions as C, type PgRateLimitHitOptions as D, type PgRateLimitResult as E, type PgRateLimitSchemaOptions as F, type PgRateLimitStateOptions as G, type PgRateLimiterOptions as H, PgSlidingWindowRateLimiter as I, type PgSlidingWindowRateLimiterOptions as J, PgTokenBucketRateLimiter as K, type PgTokenBucketRateLimiterOptions as L, type PgTokenBucketResult as M, type PgredisBatchOperation as N, type PgredisCleanupMetrics as O, PgAdvisoryLockBusyError as P, type PgredisClient as Q, type PgredisListenerMetrics as R, type PgredisMetrics as S, type PgredisMetricsOptions as T, type PgredisMigrationAliases as U, type PgredisOptions as V, PgredisPipeline as W, type PgredisQueueMetrics as X, type PgredisTableMetrics as Y, type PipelineCommand as Z, type PipelineFacade as _, type PgAdvisoryLockKey as a, advisoryLockKeyToSqlArgs as a0, collectPgredisMetrics as a1, createPgAdvisoryLocker as a2, createPgBossJobQueue as a3, createPgCounter as a4, createPgFixedWindowRateLimiter as a5, createPgOutboxStream as a6, createPgSlidingWindowRateLimiter as a7, createPgTokenBucketRateLimiter as a8, createPgredis as a9, createPgredisMigrationAliases as aa, withPgAdvisoryLock as ab, type PgAdvisoryLockOptions as b, PgAdvisoryLocker as c, type PgBossJob as d, PgBossJobQueue as e, type PgBossLike as f, type PgBossOptions as g, type PgBossQueueDefinition as h, type PgBossQueueMap as i, type PgBossQueueOptions as j, type PgBossQueueResult as k, type PgBossSendOptions as l, type PgBossWorkHandler as m, type PgBossWorkOptions as n, PgCounter as o, type PgCounterOptions as p, type PgCounterSchemaOptions as q, type PgCounterSetOptions as r, PgFixedWindowRateLimiter as s, type PgOutboxAppendOptions as t, type PgOutboxClaimOptions as u, type PgOutboxMessage as v, type PgOutboxPendingSummary as w, type PgOutboxReadOptions as x, PgOutboxStream as y, type PgOutboxStreamOptions as z };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { BunSqlLike, PgKvCache, PgKvCacheL1Options, PgKvCacheNotifyOptions, PgKvCacheOptions, PgKvCacheStats, PgKvNotification, PgKvSchemaOptions, PgKvSetOptions, createPgKvCache } from './kv-cache.js';
2
- export { d as Job, P as PgAdvisoryLockBusyError, a as PgAdvisoryLockKey, b as PgAdvisoryLockOptions, c as PgAdvisoryLocker, f as PgBoss, d as PgBossJob, e as PgBossJobQueue, f as PgBossLike, g as PgBossOptions, h as PgBossQueueDefinition, i as PgBossQueueMap, j as PgBossQueueOptions, k as PgBossQueueResult, l as PgBossSendOptions, m as PgBossWorkHandler, n as PgBossWorkOptions, o as PgCounter, p as PgCounterOptions, q as PgCounterSchemaOptions, r as PgCounterSetOptions, s as PgFixedWindowRateLimiter, t as PgOutboxAppendOptions, u as PgOutboxClaimOptions, v as PgOutboxMessage, w as PgOutboxPendingSummary, x as PgOutboxReadOptions, y as PgOutboxStream, z as PgOutboxStreamOptions, A as PgOutboxStreamSchemaOptions, B as PgOutboxTrimOptions, C as PgRateLimitHitOptions, D as PgRateLimitResult, E as PgRateLimitSchemaOptions, F as PgRateLimiterOptions, G as PgSlidingWindowRateLimiter, H as PgSlidingWindowRateLimiterOptions, I as PgTokenBucketRateLimiter, J as PgTokenBucketRateLimiterOptions, K as PgTokenBucketResult, L as PgredisBatchOperation, M as PgredisCleanupMetrics, N as PgredisClient, O as PgredisListenerMetrics, Q as PgredisMetrics, R as PgredisMetricsOptions, S as PgredisMigrationAliases, T as PgredisOptions, U as PgredisPipeline, V as PgredisQueueMetrics, W as PgredisTableMetrics, X as PipelineCommand, Y as PipelineFacade, h as Queue, k as QueueResult, Z as RedisSetAliasOptions, l as SendOptions, m as WorkHandler, n as WorkOptions, _ as advisoryLockKeyToSqlArgs, $ as collectPgredisMetrics, a0 as createPgAdvisoryLocker, a1 as createPgBossJobQueue, a2 as createPgCounter, a3 as createPgFixedWindowRateLimiter, a4 as createPgOutboxStream, a5 as createPgSlidingWindowRateLimiter, a6 as createPgTokenBucketRateLimiter, a7 as createPgredis, a8 as createPgredisMigrationAliases, a9 as withPgAdvisoryLock } from './client-Dpoe2LdN.js';
2
+ export { d as Job, P as PgAdvisoryLockBusyError, a as PgAdvisoryLockKey, b as PgAdvisoryLockOptions, c as PgAdvisoryLocker, f as PgBoss, d as PgBossJob, e as PgBossJobQueue, f as PgBossLike, g as PgBossOptions, h as PgBossQueueDefinition, i as PgBossQueueMap, j as PgBossQueueOptions, k as PgBossQueueResult, l as PgBossSendOptions, m as PgBossWorkHandler, n as PgBossWorkOptions, o as PgCounter, p as PgCounterOptions, q as PgCounterSchemaOptions, r as PgCounterSetOptions, s as PgFixedWindowRateLimiter, t as PgOutboxAppendOptions, u as PgOutboxClaimOptions, v as PgOutboxMessage, w as PgOutboxPendingSummary, x as PgOutboxReadOptions, y as PgOutboxStream, z as PgOutboxStreamOptions, A as PgOutboxStreamSchemaOptions, B as PgOutboxTrimOptions, C as PgRateLimitBlockOptions, D as PgRateLimitHitOptions, E as PgRateLimitResult, F as PgRateLimitSchemaOptions, G as PgRateLimitStateOptions, H as PgRateLimiterOptions, I as PgSlidingWindowRateLimiter, J as PgSlidingWindowRateLimiterOptions, K as PgTokenBucketRateLimiter, L as PgTokenBucketRateLimiterOptions, M as PgTokenBucketResult, N as PgredisBatchOperation, O as PgredisCleanupMetrics, Q as PgredisClient, R as PgredisListenerMetrics, S as PgredisMetrics, T as PgredisMetricsOptions, U as PgredisMigrationAliases, V as PgredisOptions, W as PgredisPipeline, X as PgredisQueueMetrics, Y as PgredisTableMetrics, Z as PipelineCommand, _ as PipelineFacade, h as Queue, k as QueueResult, $ as RedisSetAliasOptions, l as SendOptions, m as WorkHandler, n as WorkOptions, a0 as advisoryLockKeyToSqlArgs, a1 as collectPgredisMetrics, a2 as createPgAdvisoryLocker, a3 as createPgBossJobQueue, a4 as createPgCounter, a5 as createPgFixedWindowRateLimiter, a6 as createPgOutboxStream, a7 as createPgSlidingWindowRateLimiter, a8 as createPgTokenBucketRateLimiter, a9 as createPgredis, aa as createPgredisMigrationAliases, ab as withPgAdvisoryLock } from './client-DP3ssToT.js';
3
3
  export { PgHash, PgHashOptions, PgHashScanResult, PgHashSchemaOptions, createPgHash } from './hash-index.js';
4
4
  export { PgList, PgListBlockingPopOptions, PgListBlockingPopResult, PgListOptions, PgListScanResult, PgListSchemaOptions, createPgList } from './list-index.js';
5
5
  export { NotifyHandler, PgListenerEvents, PgListenerHandle, PgListenerHealth, PgListenerOptions, PgNotifyPayload, PgPublisher, createBunPgListener, createPgListener, createPgPublisher, publishPgNotify } from './pubsub-index.js';
package/dist/index.js CHANGED
@@ -414,6 +414,20 @@ var DEFAULT_TABLE_NAME2 = "pg_rate_limit";
414
414
  var DEFAULT_NAMESPACE2 = "default";
415
415
  var DEFAULT_SLIDING_TABLE_NAME = "pg_sliding_rate_limit";
416
416
  var DEFAULT_TOKEN_BUCKET_TABLE_NAME = "pg_token_bucket_rate_limit";
417
+ var BLOCK_WINDOW_START = -1;
418
+ function normalizeLimit(value, name) {
419
+ if (!Number.isFinite(value) || value < 0) throw new Error(`Invalid ${name}: ${value}`);
420
+ return Math.floor(value);
421
+ }
422
+ function dateMs(value, fallback) {
423
+ if (value instanceof Date) return value.getTime();
424
+ if (typeof value === "number" && Number.isFinite(value)) return value;
425
+ if (typeof value === "string") {
426
+ const parsed = Date.parse(value);
427
+ if (!Number.isNaN(parsed)) return parsed;
428
+ }
429
+ return fallback;
430
+ }
417
431
  var PgFixedWindowRateLimiter = class {
418
432
  namespace;
419
433
  tableName;
@@ -456,6 +470,8 @@ var PgFixedWindowRateLimiter = class {
456
470
  const now = this.now();
457
471
  const windowStart = Math.floor(now / windowMs) * windowMs;
458
472
  const resetAtMs = windowStart + windowMs;
473
+ const blocked = await this.getActiveBlock(key, limit, now, resetAtMs);
474
+ if (blocked) return blocked;
459
475
  const rows = await this.sql.unsafe(
460
476
  `INSERT INTO ${this.quotedTableName} (namespace, key, window_start, count, expires_at, updated_at)
461
477
  VALUES (
@@ -485,6 +501,90 @@ var PgFixedWindowRateLimiter = class {
485
501
  retryAfterMs
486
502
  };
487
503
  }
504
+ async get(key, options = {}) {
505
+ const limit = normalizeLimit(options.limit ?? this.limit, "limit");
506
+ const windowMs = normalizePositiveInteger(options.windowMs ?? this.windowMs, "windowMs");
507
+ const now = this.now();
508
+ const windowStart = Math.floor(now / windowMs) * windowMs;
509
+ const resetAtMs = windowStart + windowMs;
510
+ const blocked = await this.getActiveBlock(key, limit, now, resetAtMs);
511
+ if (blocked) return blocked;
512
+ const rows = await this.sql.unsafe(
513
+ `SELECT count, expires_at
514
+ FROM ${this.quotedTableName}
515
+ WHERE namespace = $1
516
+ AND key = $2
517
+ AND window_start = $3
518
+ AND expires_at > NOW()
519
+ LIMIT 1`,
520
+ [this.namespace, key, windowStart]
521
+ );
522
+ const row = rows[0];
523
+ if (!row) return null;
524
+ return this.resultFromRow(row, limit, now, resetAtMs);
525
+ }
526
+ async reward(key, cost = 1, options = {}) {
527
+ const limit = normalizeLimit(options.limit ?? this.limit, "limit");
528
+ const windowMs = normalizePositiveInteger(options.windowMs ?? this.windowMs, "windowMs");
529
+ const normalizedCost = normalizePositiveInteger(cost, "cost");
530
+ const now = this.now();
531
+ const windowStart = Math.floor(now / windowMs) * windowMs;
532
+ const resetAtMs = windowStart + windowMs;
533
+ const blockRows = await this.decrementWindow(key, BLOCK_WINDOW_START, normalizedCost);
534
+ const blockRow = blockRows[0];
535
+ if (blockRow) return this.resultFromRow(blockRow, limit, now, resetAtMs);
536
+ const rows = await this.decrementWindow(key, windowStart, normalizedCost);
537
+ const row = rows[0];
538
+ if (!row) return null;
539
+ return this.resultFromRow(row, limit, now, resetAtMs);
540
+ }
541
+ async decrementWindow(key, windowStart, cost) {
542
+ return await this.sql.unsafe(
543
+ `UPDATE ${this.quotedTableName}
544
+ SET count = GREATEST(count - $4, 0),
545
+ updated_at = NOW()
546
+ WHERE namespace = $1
547
+ AND key = $2
548
+ AND window_start = $3
549
+ AND expires_at > NOW()
550
+ RETURNING count, expires_at`,
551
+ [this.namespace, key, windowStart, cost]
552
+ );
553
+ }
554
+ async block(key, options) {
555
+ const limit = normalizeLimit(options.limit ?? this.limit, "limit");
556
+ const blockMs = normalizePositiveInteger(options.blockMs, "blockMs");
557
+ const count = normalizePositiveInteger(options.count ?? Math.max(limit + 1, 1), "count");
558
+ const now = this.now();
559
+ const resetAtMs = now + blockMs;
560
+ const rows = await this.sql.unsafe(
561
+ `INSERT INTO ${this.quotedTableName} (namespace, key, window_start, count, expires_at, updated_at)
562
+ VALUES (
563
+ $1,
564
+ $2,
565
+ $3,
566
+ $4,
567
+ NOW() + ($5::bigint * INTERVAL '1 millisecond'),
568
+ NOW()
569
+ )
570
+ ON CONFLICT (namespace, key, window_start) DO UPDATE
571
+ SET count = GREATEST(${this.quotedTableName}.count, EXCLUDED.count),
572
+ expires_at = GREATEST(${this.quotedTableName}.expires_at, EXCLUDED.expires_at),
573
+ updated_at = NOW()
574
+ RETURNING count, expires_at`,
575
+ [this.namespace, key, BLOCK_WINDOW_START, count, blockMs]
576
+ );
577
+ return this.resultFromRow(rows[0] ?? { count }, limit, now, resetAtMs);
578
+ }
579
+ async delete(key) {
580
+ const rows = await this.sql.unsafe(
581
+ `DELETE FROM ${this.quotedTableName}
582
+ WHERE namespace = $1 AND key = $2
583
+ RETURNING key`,
584
+ [this.namespace, key]
585
+ );
586
+ return rows.length > 0;
587
+ }
488
588
  async cleanupExpired(limit = 1e3) {
489
589
  const rows = await this.sql.unsafe(
490
590
  `DELETE FROM ${this.quotedTableName}
@@ -499,6 +599,34 @@ var PgFixedWindowRateLimiter = class {
499
599
  );
500
600
  return rows.length;
501
601
  }
602
+ resultFromRow(row, limit, now, fallbackResetAtMs) {
603
+ const count = Number(row.count);
604
+ const resetAtMs = dateMs(row.expires_at, fallbackResetAtMs);
605
+ const allowed = count <= limit;
606
+ return {
607
+ allowed,
608
+ limit,
609
+ count,
610
+ remaining: Math.max(0, limit - count),
611
+ resetAt: new Date(resetAtMs),
612
+ retryAfterMs: allowed ? 0 : Math.max(0, resetAtMs - now)
613
+ };
614
+ }
615
+ async getActiveBlock(key, limit, now, fallbackResetAtMs) {
616
+ const rows = await this.sql.unsafe(
617
+ `SELECT count, expires_at
618
+ FROM ${this.quotedTableName}
619
+ WHERE namespace = $1
620
+ AND key = $2
621
+ AND window_start = $3
622
+ AND expires_at > NOW()
623
+ LIMIT 1`,
624
+ [this.namespace, key, BLOCK_WINDOW_START]
625
+ );
626
+ const row = rows[0];
627
+ if (!row || Number(row.count) <= limit) return null;
628
+ return this.resultFromRow(row, limit, now, fallbackResetAtMs);
629
+ }
502
630
  };
503
631
  function createPgFixedWindowRateLimiter(options) {
504
632
  return new PgFixedWindowRateLimiter(options);
@@ -709,7 +837,7 @@ function toDate2(value) {
709
837
  if (value === null) return null;
710
838
  return value instanceof Date ? value : new Date(value);
711
839
  }
712
- function normalizeLimit(limit, fallback) {
840
+ function normalizeLimit2(limit, fallback) {
713
841
  if (limit === void 0) return fallback;
714
842
  if (!Number.isFinite(limit)) throw new Error(`Invalid limit: ${limit}`);
715
843
  return Math.max(1, Math.floor(limit));
@@ -779,7 +907,7 @@ var PgOutboxStream = class {
779
907
  this.namespace,
780
908
  stream,
781
909
  options.afterId ?? 0,
782
- normalizeLimit(options.limit, 100),
910
+ normalizeLimit2(options.limit, 100),
783
911
  options.includeProcessed ?? false
784
912
  ]
785
913
  );
@@ -809,7 +937,7 @@ var PgOutboxStream = class {
809
937
  WHERE target.id = picked.id
810
938
  RETURNING target.id, target.stream, target.payload, target.consumer, target.delivery_count,
811
939
  target.available_at, target.locked_until, target.processed_at, target.created_at`,
812
- [this.namespace, stream, consumer, normalizeLimit(options.limit, 1), visibilityTimeoutMs]
940
+ [this.namespace, stream, consumer, normalizeLimit2(options.limit, 1), visibilityTimeoutMs]
813
941
  );
814
942
  return rows.map((row) => this.mapMessage(row));
815
943
  }
@@ -863,7 +991,7 @@ var PgOutboxStream = class {
863
991
  options.stream ?? null,
864
992
  options.beforeId ?? null,
865
993
  options.maxAgeMs ?? null,
866
- normalizeLimit(options.limit, 1e3)
994
+ normalizeLimit2(options.limit, 1e3)
867
995
  ]
868
996
  );
869
997
  return rows.length;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postgresx/noredis",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "description": "PostgreSQL-backed Redis feature replacement toolkit: KV/TTL cache, pub/sub, advisory locks, rate limiting, and pg-boss queues",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -92,7 +92,7 @@
92
92
  "@types/bun": "^1.3.14",
93
93
  "@types/node": "^25.0.0",
94
94
  "@types/pg": "^8.16.0",
95
- "@postgresx/bun-listen": "^0.3.0",
95
+ "@postgresx/bun-listen": "^0.3.1",
96
96
  "tsup": "^8.5.0",
97
97
  "typescript": "^6.0.3"
98
98
  }