@johnhenry/browsermesh-apps 0.0.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.
package/src/quotas.mjs ADDED
@@ -0,0 +1,621 @@
1
+ /**
2
+ * clawser-mesh-quotas.js -- Per-identity resource quotas with enforcement.
3
+ *
4
+ * Provides QuotaRule definitions, usage tracking (UsageRecord), a
5
+ * QuotaManager for CRUD on per-pod quota rules, and a QuotaEnforcer
6
+ * for recording usage, checking limits, and tracking violations.
7
+ *
8
+ * No browser-only imports at module level.
9
+ *
10
+ * Run tests:
11
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-quotas.test.mjs
12
+ */
13
+
14
+ import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
15
+ import { silentCatch } from './silent-catch.mjs'
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Wire constants — imported from canonical registry
19
+ // ---------------------------------------------------------------------------
20
+
21
+ /** Wire code sent when a quota rule is created or updated. */
22
+ export const QUOTA_UPDATE = MESH_TYPE.QUOTA_UPDATE;
23
+
24
+ /** Wire code sent when a quota violation is detected. */
25
+ export const QUOTA_VIOLATION = MESH_TYPE.QUOTA_VIOLATION;
26
+
27
+ /** Wire code for periodic usage reports. */
28
+ export const USAGE_REPORT = MESH_TYPE.USAGE_REPORT;
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Default limits
32
+ // ---------------------------------------------------------------------------
33
+
34
+ /**
35
+ * Sensible default resource limits applied when no explicit quota exists.
36
+ */
37
+ export const DEFAULT_LIMITS = Object.freeze({
38
+ cpuMs: 60_000,
39
+ memoryMb: 512,
40
+ storageMb: 100,
41
+ bandwidthMb: 1000,
42
+ jobsPerHour: 100,
43
+ maxConcurrentJobs: 5,
44
+ });
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // QuotaRule
48
+ // ---------------------------------------------------------------------------
49
+
50
+ /**
51
+ * A quota rule describes the resource limits for a specific pod (identity).
52
+ */
53
+ export class QuotaRule {
54
+ /**
55
+ * @param {object} opts
56
+ * @param {string} opts.podId - Identity fingerprint
57
+ * @param {object} opts.limits - Resource limits (partial, merged with defaults)
58
+ * @param {number} [opts.limits.cpuMs]
59
+ * @param {number} [opts.limits.memoryMb]
60
+ * @param {number} [opts.limits.storageMb]
61
+ * @param {number} [opts.limits.bandwidthMb]
62
+ * @param {number} [opts.limits.jobsPerHour]
63
+ * @param {number} [opts.limits.maxConcurrentJobs]
64
+ * @param {'block'|'throttle'|'charge'} [opts.overagePolicy='block']
65
+ * @param {number} [opts.createdAt]
66
+ * @param {number|null} [opts.expiresAt]
67
+ */
68
+ constructor({ podId, limits, overagePolicy = 'block', createdAt, expiresAt = null }) {
69
+ if (!podId || typeof podId !== 'string') {
70
+ throw new Error('podId is required and must be a non-empty string');
71
+ }
72
+ this.podId = podId;
73
+ this.limits = { ...limits };
74
+ this.overagePolicy = overagePolicy;
75
+ this.createdAt = createdAt ?? Date.now();
76
+ this.expiresAt = expiresAt;
77
+ }
78
+
79
+ /**
80
+ * Check if this rule has expired.
81
+ * @param {number} [now]
82
+ * @returns {boolean}
83
+ */
84
+ isExpired(now = Date.now()) {
85
+ if (this.expiresAt == null) return false;
86
+ return now >= this.expiresAt;
87
+ }
88
+
89
+ /**
90
+ * Serialize to a plain JSON-safe object.
91
+ * @returns {object}
92
+ */
93
+ toJSON() {
94
+ return {
95
+ podId: this.podId,
96
+ limits: { ...this.limits },
97
+ overagePolicy: this.overagePolicy,
98
+ createdAt: this.createdAt,
99
+ expiresAt: this.expiresAt,
100
+ };
101
+ }
102
+
103
+ /**
104
+ * Re-hydrate from a plain object.
105
+ * @param {object} data
106
+ * @returns {QuotaRule}
107
+ */
108
+ static fromJSON(data) {
109
+ return new QuotaRule({
110
+ podId: data.podId,
111
+ limits: data.limits,
112
+ overagePolicy: data.overagePolicy,
113
+ createdAt: data.createdAt,
114
+ expiresAt: data.expiresAt,
115
+ });
116
+ }
117
+ }
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // UsageRecord
121
+ // ---------------------------------------------------------------------------
122
+
123
+ /**
124
+ * Tracks resource consumption for a single pod during a specific time period.
125
+ * Periods are hourly by default (ISO 8601 truncated to the hour).
126
+ */
127
+ export class UsageRecord {
128
+ /**
129
+ * @param {object} opts
130
+ * @param {string} opts.podId
131
+ * @param {string} opts.period - Hourly period key, e.g. '2026-03-02T06'
132
+ * @param {object} [opts.usage]
133
+ * @param {number} [opts.usage.cpuMs]
134
+ * @param {number} [opts.usage.memoryMb]
135
+ * @param {number} [opts.usage.storageMb]
136
+ * @param {number} [opts.usage.bandwidthMb]
137
+ * @param {number} [opts.usage.jobCount]
138
+ * @param {number} [opts.usage.concurrentJobs]
139
+ * @param {number} [opts.updatedAt]
140
+ */
141
+ constructor({ podId, period, usage, updatedAt }) {
142
+ this.podId = podId;
143
+ this.period = period;
144
+ this.usage = {
145
+ cpuMs: 0,
146
+ memoryMb: 0,
147
+ storageMb: 0,
148
+ bandwidthMb: 0,
149
+ jobCount: 0,
150
+ concurrentJobs: 0,
151
+ ...(usage || {}),
152
+ };
153
+ this.updatedAt = updatedAt ?? Date.now();
154
+ }
155
+
156
+ /**
157
+ * Generate the current hourly period key.
158
+ * @param {Date} [date]
159
+ * @returns {string} e.g. '2026-03-02T06'
160
+ */
161
+ static currentPeriod(date = new Date()) {
162
+ const iso = date.toISOString(); // '2026-03-02T06:45:12.345Z'
163
+ return iso.slice(0, 13); // '2026-03-02T06'
164
+ }
165
+
166
+ /**
167
+ * Serialize to a plain JSON-safe object.
168
+ * @returns {object}
169
+ */
170
+ toJSON() {
171
+ return {
172
+ podId: this.podId,
173
+ period: this.period,
174
+ usage: { ...this.usage },
175
+ updatedAt: this.updatedAt,
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Re-hydrate from a plain object.
181
+ * @param {object} data
182
+ * @returns {UsageRecord}
183
+ */
184
+ static fromJSON(data) {
185
+ return new UsageRecord({
186
+ podId: data.podId,
187
+ period: data.period,
188
+ usage: data.usage,
189
+ updatedAt: data.updatedAt,
190
+ });
191
+ }
192
+ }
193
+
194
+ // ---------------------------------------------------------------------------
195
+ // Resource-to-usage field mapping
196
+ // ---------------------------------------------------------------------------
197
+
198
+ /** @type {Record<string, string>} */
199
+ const RESOURCE_FIELD_MAP = Object.freeze({
200
+ cpuMs: 'cpuMs',
201
+ memoryMb: 'memoryMb',
202
+ storageMb: 'storageMb',
203
+ bandwidthMb: 'bandwidthMb',
204
+ jobsPerHour: 'jobCount',
205
+ maxConcurrentJobs: 'concurrentJobs',
206
+ });
207
+
208
+ /** @type {Record<string, string>} inverse: usage field -> limit field */
209
+ const USAGE_TO_LIMIT_MAP = Object.freeze({
210
+ cpuMs: 'cpuMs',
211
+ memoryMb: 'memoryMb',
212
+ storageMb: 'storageMb',
213
+ bandwidthMb: 'bandwidthMb',
214
+ jobCount: 'jobsPerHour',
215
+ concurrentJobs: 'maxConcurrentJobs',
216
+ });
217
+
218
+ // ---------------------------------------------------------------------------
219
+ // QuotaManager
220
+ // ---------------------------------------------------------------------------
221
+
222
+ /**
223
+ * CRUD manager for per-pod quota rules.
224
+ */
225
+ export class QuotaManager {
226
+ /** @type {Map<string, QuotaRule>} podId -> QuotaRule */
227
+ #rules = new Map();
228
+
229
+ /** @type {object} */
230
+ #defaultLimits;
231
+
232
+ /** @type {boolean} */
233
+ #enforcementEnabled;
234
+
235
+ /**
236
+ * @param {object} [opts]
237
+ * @param {object} [opts.defaultLimits] - Override DEFAULT_LIMITS
238
+ * @param {boolean} [opts.enforcementEnabled=true]
239
+ */
240
+ constructor(opts = {}) {
241
+ this.#defaultLimits = opts.defaultLimits
242
+ ? { ...DEFAULT_LIMITS, ...opts.defaultLimits }
243
+ : { ...DEFAULT_LIMITS };
244
+ this.#enforcementEnabled = opts.enforcementEnabled !== false;
245
+ }
246
+
247
+ /**
248
+ * Get the default limits used for pods without explicit quotas.
249
+ * @returns {object}
250
+ */
251
+ get defaultLimits() {
252
+ return { ...this.#defaultLimits };
253
+ }
254
+
255
+ /**
256
+ * Whether enforcement is enabled.
257
+ * @returns {boolean}
258
+ */
259
+ get enforcementEnabled() {
260
+ return this.#enforcementEnabled;
261
+ }
262
+
263
+ /**
264
+ * Number of quota rules stored.
265
+ * @returns {number}
266
+ */
267
+ get size() {
268
+ return this.#rules.size;
269
+ }
270
+
271
+ /**
272
+ * Create or update a quota rule for a pod.
273
+ *
274
+ * @param {string} podId
275
+ * @param {object} limits - Partial limits; missing keys default from defaultLimits
276
+ * @param {'block'|'throttle'|'charge'} [overagePolicy='block']
277
+ * @param {object} [opts]
278
+ * @param {number|null} [opts.expiresAt]
279
+ * @returns {QuotaRule}
280
+ */
281
+ setQuota(podId, limits, overagePolicy = 'block', opts = {}) {
282
+ const merged = { ...this.#defaultLimits, ...limits };
283
+ const rule = new QuotaRule({
284
+ podId,
285
+ limits: merged,
286
+ overagePolicy,
287
+ expiresAt: opts.expiresAt ?? null,
288
+ });
289
+ this.#rules.set(podId, rule);
290
+ return rule;
291
+ }
292
+
293
+ /**
294
+ * Get the quota rule for a pod.
295
+ * @param {string} podId
296
+ * @returns {QuotaRule|null}
297
+ */
298
+ getQuota(podId) {
299
+ return this.#rules.get(podId) ?? null;
300
+ }
301
+
302
+ /**
303
+ * Remove the quota rule for a pod.
304
+ * @param {string} podId
305
+ * @returns {boolean}
306
+ */
307
+ removeQuota(podId) {
308
+ return this.#rules.delete(podId);
309
+ }
310
+
311
+ /**
312
+ * List all quota rules.
313
+ * @returns {QuotaRule[]}
314
+ */
315
+ listQuotas() {
316
+ return [...this.#rules.values()];
317
+ }
318
+
319
+ /**
320
+ * Resolve effective limits for a pod.
321
+ * If the pod has an explicit (non-expired) rule, use it; otherwise fall back to defaults.
322
+ *
323
+ * @param {string} podId
324
+ * @returns {{ limits: object, overagePolicy: string, source: 'explicit'|'default' }}
325
+ */
326
+ resolveEffective(podId) {
327
+ const rule = this.#rules.get(podId);
328
+ if (rule && !rule.isExpired()) {
329
+ return { limits: { ...rule.limits }, overagePolicy: rule.overagePolicy, source: 'explicit' };
330
+ }
331
+ return { limits: { ...this.#defaultLimits }, overagePolicy: 'block', source: 'default' };
332
+ }
333
+
334
+ /**
335
+ * Serialize to JSON.
336
+ * @returns {object}
337
+ */
338
+ toJSON() {
339
+ return {
340
+ defaultLimits: { ...this.#defaultLimits },
341
+ enforcementEnabled: this.#enforcementEnabled,
342
+ rules: [...this.#rules.values()].map(r => r.toJSON()),
343
+ };
344
+ }
345
+
346
+ /**
347
+ * Re-hydrate from JSON.
348
+ * @param {object} data
349
+ * @returns {QuotaManager}
350
+ */
351
+ static fromJSON(data) {
352
+ const mgr = new QuotaManager({
353
+ defaultLimits: data.defaultLimits,
354
+ enforcementEnabled: data.enforcementEnabled,
355
+ });
356
+ if (data.rules) {
357
+ for (const rd of data.rules) {
358
+ const rule = QuotaRule.fromJSON(rd);
359
+ mgr.#rules.set(rule.podId, rule);
360
+ }
361
+ }
362
+ return mgr;
363
+ }
364
+ }
365
+
366
+ // ---------------------------------------------------------------------------
367
+ // QuotaEnforcer
368
+ // ---------------------------------------------------------------------------
369
+
370
+ /**
371
+ * Tracks real-time resource consumption and enforces quota limits.
372
+ *
373
+ * Usage records are keyed by (podId, period). The enforcer compares
374
+ * recorded usage against the effective limits from a QuotaManager.
375
+ */
376
+ export class QuotaEnforcer {
377
+ /** @type {QuotaManager} */
378
+ #manager;
379
+
380
+ /** @type {Map<string, UsageRecord>} compositeKey -> UsageRecord */
381
+ #usage = new Map();
382
+
383
+ /** @type {Array<{podId: string, resource: string, limit: number, actual: number, policy: string, timestamp: number}>} */
384
+ #violations = [];
385
+
386
+ /** @type {Function|null} */
387
+ #onViolation;
388
+
389
+ /**
390
+ * @param {QuotaManager} quotaManager
391
+ * @param {object} [opts]
392
+ * @param {Function} [opts.onViolation] - Called with violation info on limit breach
393
+ */
394
+ constructor(quotaManager, opts = {}) {
395
+ this.#manager = quotaManager;
396
+ this.#onViolation = opts.onViolation || null;
397
+ }
398
+
399
+ // -- Usage key helpers ----------------------------------------------------
400
+
401
+ /**
402
+ * Build a composite key for the usage map.
403
+ * @param {string} podId
404
+ * @param {string} period
405
+ * @returns {string}
406
+ */
407
+ static _key(podId, period) {
408
+ return `${podId}::${period}`;
409
+ }
410
+
411
+ // -- Recording usage ------------------------------------------------------
412
+
413
+ /**
414
+ * Record resource consumption for a pod in the current period.
415
+ *
416
+ * @param {string} podId
417
+ * @param {string} resource - One of: cpuMs, memoryMb, storageMb, bandwidthMb, jobsPerHour, maxConcurrentJobs
418
+ * @param {number} amount - Amount consumed (additive for most; set for concurrentJobs)
419
+ */
420
+ recordUsage(podId, resource, amount) {
421
+ const period = UsageRecord.currentPeriod();
422
+ const key = QuotaEnforcer._key(podId, period);
423
+
424
+ let record = this.#usage.get(key);
425
+ if (!record) {
426
+ record = new UsageRecord({ podId, period });
427
+ this.#usage.set(key, record);
428
+ }
429
+
430
+ const usageField = RESOURCE_FIELD_MAP[resource];
431
+ if (!usageField) {
432
+ throw new Error(`Unknown resource: ${resource}`);
433
+ }
434
+
435
+ // concurrentJobs is set (high-water mark), others are additive
436
+ if (resource === 'maxConcurrentJobs') {
437
+ record.usage[usageField] = Math.max(record.usage[usageField], amount);
438
+ } else {
439
+ record.usage[usageField] += amount;
440
+ }
441
+ record.updatedAt = Date.now();
442
+
443
+ // Check for violation after recording
444
+ const { limits, overagePolicy } = this.#manager.resolveEffective(podId);
445
+ const limitValue = limits[resource];
446
+ const actual = record.usage[usageField];
447
+
448
+ if (limitValue != null && actual > limitValue) {
449
+ const violation = {
450
+ podId,
451
+ resource,
452
+ limit: limitValue,
453
+ actual,
454
+ policy: overagePolicy,
455
+ timestamp: Date.now(),
456
+ };
457
+ this.#violations.push(violation);
458
+ if (this.#onViolation) {
459
+ try { this.#onViolation(violation); } catch (e) { silentCatch('clawser-mesh-quotas', 'swallow-listener-errors', e) }
460
+ }
461
+ }
462
+ }
463
+
464
+ // -- Querying usage -------------------------------------------------------
465
+
466
+ /**
467
+ * Get the usage record for a pod in a given period (defaults to current).
468
+ *
469
+ * @param {string} podId
470
+ * @param {string} [period]
471
+ * @returns {UsageRecord|null}
472
+ */
473
+ getUsage(podId, period) {
474
+ const p = period ?? UsageRecord.currentPeriod();
475
+ const key = QuotaEnforcer._key(podId, p);
476
+ return this.#usage.get(key) ?? null;
477
+ }
478
+
479
+ // -- Quota checking -------------------------------------------------------
480
+
481
+ /**
482
+ * Check if a requested resource amount would exceed the pod's quota.
483
+ *
484
+ * @param {string} podId
485
+ * @param {string} resource
486
+ * @param {number} requestedAmount
487
+ * @returns {{ allowed: boolean, remaining?: number, overage?: number, policy?: string }}
488
+ */
489
+ checkQuota(podId, resource, requestedAmount) {
490
+ if (!this.#manager.enforcementEnabled) {
491
+ return { allowed: true };
492
+ }
493
+
494
+ const { limits, overagePolicy } = this.#manager.resolveEffective(podId);
495
+ const limitValue = limits[resource];
496
+
497
+ // No limit defined for this resource
498
+ if (limitValue == null) {
499
+ return { allowed: true };
500
+ }
501
+
502
+ const usageField = RESOURCE_FIELD_MAP[resource];
503
+ if (!usageField) {
504
+ return { allowed: true };
505
+ }
506
+
507
+ const period = UsageRecord.currentPeriod();
508
+ const key = QuotaEnforcer._key(podId, period);
509
+ const record = this.#usage.get(key);
510
+ const currentUsage = record ? record.usage[usageField] : 0;
511
+
512
+ const projectedUsage = currentUsage + requestedAmount;
513
+ const remaining = Math.max(0, limitValue - currentUsage);
514
+
515
+ if (projectedUsage <= limitValue) {
516
+ return { allowed: true, remaining };
517
+ }
518
+
519
+ const overage = projectedUsage - limitValue;
520
+
521
+ // Throttle policy allows usage but signals the overage
522
+ if (overagePolicy === 'throttle' || overagePolicy === 'charge') {
523
+ return { allowed: true, remaining: 0, overage, policy: overagePolicy };
524
+ }
525
+
526
+ // Block policy denies the request
527
+ return { allowed: false, remaining, overage, policy: overagePolicy };
528
+ }
529
+
530
+ // -- Reset ----------------------------------------------------------------
531
+
532
+ /**
533
+ * Reset usage for a pod in a given period (defaults to current).
534
+ *
535
+ * @param {string} podId
536
+ * @param {string} [period]
537
+ */
538
+ resetUsage(podId, period) {
539
+ const p = period ?? UsageRecord.currentPeriod();
540
+ const key = QuotaEnforcer._key(podId, p);
541
+ this.#usage.delete(key);
542
+ }
543
+
544
+ // -- Violations -----------------------------------------------------------
545
+
546
+ /**
547
+ * List recorded violations, optionally filtered by podId.
548
+ *
549
+ * @param {string} [podId] - If omitted, returns all violations
550
+ * @returns {Array<{podId: string, resource: string, limit: number, actual: number, policy: string, timestamp: number}>}
551
+ */
552
+ listViolations(podId) {
553
+ if (podId) {
554
+ return this.#violations.filter(v => v.podId === podId);
555
+ }
556
+ return [...this.#violations];
557
+ }
558
+
559
+ // -- Maintenance ----------------------------------------------------------
560
+
561
+ /**
562
+ * Remove usage records older than maxAgeMs (defaults to 24 hours).
563
+ *
564
+ * @param {number} [maxAgeMs=86400000]
565
+ * @returns {number} Number of pruned records
566
+ */
567
+ pruneOldUsage(maxAgeMs = 24 * 60 * 60 * 1000) {
568
+ const cutoff = Date.now() - maxAgeMs;
569
+ let count = 0;
570
+ for (const [key, record] of this.#usage) {
571
+ if (record.updatedAt < cutoff) {
572
+ this.#usage.delete(key);
573
+ count++;
574
+ }
575
+ }
576
+ return count;
577
+ }
578
+
579
+ /**
580
+ * Get the total number of usage records currently stored.
581
+ * @returns {number}
582
+ */
583
+ get usageCount() {
584
+ return this.#usage.size;
585
+ }
586
+
587
+ // -- Serialization --------------------------------------------------------
588
+
589
+ /**
590
+ * Serialize to JSON.
591
+ * @returns {object}
592
+ */
593
+ toJSON() {
594
+ return {
595
+ usage: [...this.#usage.values()].map(r => r.toJSON()),
596
+ violations: [...this.#violations],
597
+ };
598
+ }
599
+
600
+ /**
601
+ * Re-hydrate from JSON (requires an existing QuotaManager).
602
+ * @param {object} data
603
+ * @param {QuotaManager} quotaManager
604
+ * @param {object} [opts]
605
+ * @returns {QuotaEnforcer}
606
+ */
607
+ static fromJSON(data, quotaManager, opts = {}) {
608
+ const enforcer = new QuotaEnforcer(quotaManager, opts);
609
+ if (data.usage) {
610
+ for (const ud of data.usage) {
611
+ const record = UsageRecord.fromJSON(ud);
612
+ const key = QuotaEnforcer._key(record.podId, record.period);
613
+ enforcer.#usage.set(key, record);
614
+ }
615
+ }
616
+ if (data.violations) {
617
+ enforcer.#violations.push(...data.violations);
618
+ }
619
+ return enforcer;
620
+ }
621
+ }