@johnhenry/browsermesh-apps 0.4.0 → 0.4.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/package.json +2 -1
- package/src/marketplace.mjs +290 -26
- package/src/peer-encrypted-store.mjs +4 -4
- package/src/peer-escrow.mjs +12 -8
- package/src/quotas.mjs +311 -12
- package/src/serverless-executor-andbox.mjs +11 -6
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-apps",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
4
4
|
"description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
}
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
+
"@johnhenry/andbox": ">=0.0.1 <1.0.0",
|
|
53
54
|
"node-datachannel": "^0.33.4",
|
|
54
55
|
"fake-indexeddb": "^6.2.5",
|
|
55
56
|
"webgpu": "^0.6.1"
|
package/src/marketplace.mjs
CHANGED
|
@@ -1,17 +1,64 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* marketplace.mjs -- Service marketplace for BrowserMesh.
|
|
3
3
|
*
|
|
4
4
|
* Publish, discover, and review services offered by mesh peers. Includes
|
|
5
5
|
* text search, category/tag filtering, rating aggregation, and an efficient
|
|
6
6
|
* inverted index for O(1) lookups.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
8
|
+
* ---------------------------------------------------------------------------
|
|
9
|
+
* `Marketplace` predated this package's `MeshService` convention
|
|
10
|
+
* (`mesh-service.mjs`) and, until now, stayed purely local: no
|
|
11
|
+
* `sendTo`/`onIncomingData`/`attachService()` anywhere, used by nothing
|
|
12
|
+
* else in this package. Its observability surface used three hand-rolled
|
|
13
|
+
* callback-array methods (`onPublish`/`onUnpublish`/`onReview`, no
|
|
14
|
+
* unsubscribe). Modernized to use `mesh-service.mjs`'s `createEventBus()`
|
|
15
|
+
* instead -- `on(event, cb)`/`onEvent(cb)` replace the three named methods
|
|
16
|
+
* outright (not shimmed: nothing outside this file's own tests ever called
|
|
17
|
+
* them, and no other modernized class in this family -- `CloudStorage`,
|
|
18
|
+
* `MeshKv` -- has per-event named methods either; adding them back here
|
|
19
|
+
* would be a new, inconsistent pattern, not a restored one).
|
|
20
|
+
*
|
|
21
|
+
* The `LISTING_*`/`REVIEW_*` constants below are `browsermesh-primitives`
|
|
22
|
+
* wire-registry codes, re-exported but never used as an `envelope.type` --
|
|
23
|
+
* `MeshService`'s `ctx.onIncomingData()` filters on a plain string, which
|
|
24
|
+
* this numeric registry is structurally incompatible with. `createMarketplaceNetworkService()`
|
|
25
|
+
* below mints its own string envelope type (`'mesh-marketplace'`) instead
|
|
26
|
+
* of repurposing them, matching `mesh-swarm.mjs`'s identical precedent for
|
|
27
|
+
* the same situation. They stay exactly as they are: unused as routing,
|
|
28
|
+
* re-exported for whatever documentation/continuity value they still have.
|
|
29
|
+
*
|
|
30
|
+
* `Marketplace` itself is, and stays, a fully open directory: no
|
|
31
|
+
* `GrantLog`/ACL on publish, search, or review-read, locally or over the
|
|
32
|
+
* network. The only attribution property that matters (a listing's
|
|
33
|
+
* `providerPodId` must equal its actual owner) already exists in the
|
|
34
|
+
* local class and is untouched here -- it protects a remote-*publish*
|
|
35
|
+
* path (`LISTING_PUBLISH`/`REVIEW_SUBMIT`/`LISTING_PURCHASE`) this file
|
|
36
|
+
* still does not build, deliberately deferred pending its own payment/
|
|
37
|
+
* reputation design. `createMarketplaceNetworkService()`'s `SEARCH`/
|
|
38
|
+
* `REVIEWS` methods are read-only and need no such check.
|
|
39
|
+
*
|
|
40
|
+
* ---------------------------------------------------------------------------
|
|
41
|
+
* `createMarketplaceNetworkService()` reuses `mesh-rpc.mjs`'s
|
|
42
|
+
* `createMeshRpcService()` directly (under a dedicated `envelopeType` so
|
|
43
|
+
* it never collides with a pod's own general-purpose `mesh-rpc` service --
|
|
44
|
+
* the same reasoning `serverless-router.mjs`'s `createSiteMeshRpcService()`
|
|
45
|
+
* already established for this identical problem) rather than hand-rolling
|
|
46
|
+
* request/response correlation and timeouts from scratch: `SEARCH`/
|
|
47
|
+
* `REVIEWS` are genuinely request/response-shaped, so `mesh-rpc.mjs`'s
|
|
48
|
+
* machinery is the right fit, not a borrowed one.
|
|
9
49
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
50
|
+
* `MeshMarketplace` is the ergonomic wrapper -- the two-layer split
|
|
51
|
+
* `mesh-kv.mjs` already established (a bare `MeshService` descriptor
|
|
52
|
+
* factory plus a class that composes it via `attachService()` and exposes
|
|
53
|
+
* its own forwarding `EventBus`). `Marketplace` itself never gains a
|
|
54
|
+
* `PeerNode` reference; only `MeshMarketplace` does.
|
|
55
|
+
*
|
|
56
|
+
* No browser-only imports at module level.
|
|
12
57
|
*/
|
|
13
58
|
|
|
14
59
|
import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
|
|
60
|
+
import { createEventBus, attachService } from './mesh-service.mjs';
|
|
61
|
+
import { createMeshRpcService } from './mesh-rpc.mjs';
|
|
15
62
|
|
|
16
63
|
// ---------------------------------------------------------------------------
|
|
17
64
|
// Wire constants (re-exported from canonical registry)
|
|
@@ -276,11 +323,8 @@ export class Marketplace {
|
|
|
276
323
|
#reviewIds = new Set();
|
|
277
324
|
/** @type {MarketplaceIndex} */
|
|
278
325
|
#index = new MarketplaceIndex();
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
#onPublish = [];
|
|
282
|
-
#onUnpublish = [];
|
|
283
|
-
#onReview = [];
|
|
326
|
+
/** @type {import('./mesh-service.mjs').EventBus} */
|
|
327
|
+
#events = createEventBus();
|
|
284
328
|
|
|
285
329
|
/**
|
|
286
330
|
* @param {object} opts
|
|
@@ -311,7 +355,7 @@ export class Marketplace {
|
|
|
311
355
|
}
|
|
312
356
|
this.#listings.set(listing.id, listing);
|
|
313
357
|
this.#index.addListing(listing);
|
|
314
|
-
|
|
358
|
+
this.#events.emit('marketplace:listing-published', listing);
|
|
315
359
|
return listing.id;
|
|
316
360
|
}
|
|
317
361
|
|
|
@@ -328,7 +372,7 @@ export class Marketplace {
|
|
|
328
372
|
}
|
|
329
373
|
this.#listings.delete(listingId);
|
|
330
374
|
this.#index.removeListing(listingId);
|
|
331
|
-
|
|
375
|
+
this.#events.emit('marketplace:listing-unpublished', listingId);
|
|
332
376
|
return true;
|
|
333
377
|
}
|
|
334
378
|
|
|
@@ -454,7 +498,7 @@ export class Marketplace {
|
|
|
454
498
|
this.#reviews.get(review.listingId).push(review);
|
|
455
499
|
this.#reviewIds.add(review.id);
|
|
456
500
|
|
|
457
|
-
|
|
501
|
+
this.#events.emit('marketplace:review-added', review);
|
|
458
502
|
}
|
|
459
503
|
|
|
460
504
|
/**
|
|
@@ -510,27 +554,30 @@ export class Marketplace {
|
|
|
510
554
|
return active.slice(0, limit).map(e => e.listing);
|
|
511
555
|
}
|
|
512
556
|
|
|
513
|
-
// --
|
|
514
|
-
|
|
515
|
-
/**
|
|
516
|
-
* @param {function(ServiceListing)} cb
|
|
517
|
-
*/
|
|
518
|
-
onPublish(cb) {
|
|
519
|
-
this.#onPublish.push(cb);
|
|
520
|
-
}
|
|
557
|
+
// -- Observability ----------------------------------------------------------
|
|
521
558
|
|
|
522
559
|
/**
|
|
523
|
-
*
|
|
560
|
+
* Subscribe to exactly one event name: `'marketplace:listing-published'`
|
|
561
|
+
* (data: the `ServiceListing`), `'marketplace:listing-unpublished'`
|
|
562
|
+
* (data: the `listingId` string), or `'marketplace:review-added'`
|
|
563
|
+
* (data: the `ServiceReview`) -- the same payloads the old
|
|
564
|
+
* `onPublish`/`onUnpublish`/`onReview` callbacks received, now delivered
|
|
565
|
+
* through `mesh-service.mjs`'s generic bus.
|
|
566
|
+
* @param {string} event
|
|
567
|
+
* @param {(data: object, event: string) => void} cb
|
|
568
|
+
* @returns {() => void} unsubscribe
|
|
524
569
|
*/
|
|
525
|
-
|
|
526
|
-
this.#
|
|
570
|
+
on(event, cb) {
|
|
571
|
+
return this.#events.on(event, cb);
|
|
527
572
|
}
|
|
528
573
|
|
|
529
574
|
/**
|
|
530
|
-
*
|
|
575
|
+
* Subscribe to every `marketplace:*` event, regardless of name.
|
|
576
|
+
* @param {(event: string, data: object) => void} cb
|
|
577
|
+
* @returns {() => void} unsubscribe
|
|
531
578
|
*/
|
|
532
|
-
|
|
533
|
-
this.#
|
|
579
|
+
onEvent(cb) {
|
|
580
|
+
return this.#events.onEvent(cb);
|
|
534
581
|
}
|
|
535
582
|
|
|
536
583
|
// -- Stats ----------------------------------------------------------------
|
|
@@ -752,3 +799,220 @@ export class MarketplaceIndex {
|
|
|
752
799
|
return [...matched];
|
|
753
800
|
}
|
|
754
801
|
}
|
|
802
|
+
|
|
803
|
+
// ---------------------------------------------------------------------------
|
|
804
|
+
// Marketplace network search
|
|
805
|
+
// ---------------------------------------------------------------------------
|
|
806
|
+
|
|
807
|
+
/** Default `envelope.type` for a marketplace's mesh-rpc attach -- see module doc comment. */
|
|
808
|
+
export const DEFAULT_MARKETPLACE_ENVELOPE_TYPE = 'mesh-marketplace';
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* @param {Marketplace} marketplace
|
|
812
|
+
* @returns {(req: {method: string, body?: object}) => Promise<{status: number, body: object}>}
|
|
813
|
+
*/
|
|
814
|
+
function createMarketplaceRequestHandler(marketplace) {
|
|
815
|
+
return async function onRequest({ method, body }) {
|
|
816
|
+
if (method === 'SEARCH') {
|
|
817
|
+
return { status: 200, body: { listings: marketplace.search(body || {}).map((l) => l.toJSON()) } };
|
|
818
|
+
}
|
|
819
|
+
if (method === 'REVIEWS') {
|
|
820
|
+
const listingId = body && body.listingId;
|
|
821
|
+
if (!listingId) return { status: 400, body: { error: 'listingId is required' } };
|
|
822
|
+
return { status: 200, body: { reviews: marketplace.getReviews(listingId).map((r) => r.toJSON()) } };
|
|
823
|
+
}
|
|
824
|
+
return { status: 404, body: { error: `unknown marketplace method: ${method}` } };
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/**
|
|
829
|
+
* Build a `MeshService` descriptor (`mesh-service.mjs`) that answers
|
|
830
|
+
* incoming `SEARCH`/`REVIEWS` requests against `marketplace`'s own local
|
|
831
|
+
* listings, over a dedicated `envelopeType` so it never collides with a
|
|
832
|
+
* pod's general-purpose `mesh-rpc` service. Thin wrapper around
|
|
833
|
+
* `createMeshRpcService()` -- see module doc comment.
|
|
834
|
+
*
|
|
835
|
+
* @param {object} opts
|
|
836
|
+
* @param {Marketplace} opts.marketplace
|
|
837
|
+
* @param {string} [opts.envelopeType='mesh-marketplace']
|
|
838
|
+
* @param {number} [opts.requestTimeoutMs]
|
|
839
|
+
* @param {Function} [opts.onLog]
|
|
840
|
+
* @returns {import('./mesh-service.mjs').MeshService}
|
|
841
|
+
*/
|
|
842
|
+
export function createMarketplaceNetworkService({
|
|
843
|
+
marketplace,
|
|
844
|
+
envelopeType = DEFAULT_MARKETPLACE_ENVELOPE_TYPE,
|
|
845
|
+
requestTimeoutMs,
|
|
846
|
+
onLog,
|
|
847
|
+
} = {}) {
|
|
848
|
+
if (!marketplace || typeof marketplace.search !== 'function') {
|
|
849
|
+
throw new Error('createMarketplaceNetworkService: opts.marketplace (a Marketplace instance) is required');
|
|
850
|
+
}
|
|
851
|
+
const rpcService = createMeshRpcService({
|
|
852
|
+
onRequest: createMarketplaceRequestHandler(marketplace),
|
|
853
|
+
envelopeType,
|
|
854
|
+
requestTimeoutMs,
|
|
855
|
+
onLog,
|
|
856
|
+
});
|
|
857
|
+
return { ...rpcService, name: 'marketplace-network' };
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* @param {Promise} promise
|
|
862
|
+
* @param {number} [timeoutMs]
|
|
863
|
+
* @returns {Promise}
|
|
864
|
+
*/
|
|
865
|
+
function withTimeout(promise, timeoutMs) {
|
|
866
|
+
if (timeoutMs === undefined) return promise;
|
|
867
|
+
return Promise.race([
|
|
868
|
+
promise,
|
|
869
|
+
new Promise((_, reject) => {
|
|
870
|
+
setTimeout(() => reject(new Error(`marketplace network request timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
871
|
+
}),
|
|
872
|
+
]);
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* Ergonomic wrapper composing a local `Marketplace` with
|
|
877
|
+
* `createMarketplaceNetworkService()` -- the same two-layer split
|
|
878
|
+
* `mesh-kv.mjs` established: `Marketplace` itself never gains a
|
|
879
|
+
* `PeerNode` reference, only `MeshMarketplace` does.
|
|
880
|
+
*/
|
|
881
|
+
export class MeshMarketplace {
|
|
882
|
+
/** @type {Marketplace} */
|
|
883
|
+
#marketplace;
|
|
884
|
+
/** @type {import('./peer-node.mjs').PeerNode} */
|
|
885
|
+
#node;
|
|
886
|
+
/** @type {ReturnType<import('./mesh-service.mjs').attachService>} */
|
|
887
|
+
#handle;
|
|
888
|
+
/** @type {import('./mesh-service.mjs').EventBus} */
|
|
889
|
+
#events = createEventBus();
|
|
890
|
+
/** @type {() => void} */
|
|
891
|
+
#unsubscribeForwardedEvents;
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* @param {object} opts
|
|
895
|
+
* @param {import('./peer-node.mjs').PeerNode} opts.node - duck-typed: needs `podId` and `registry.listPeers()`.
|
|
896
|
+
* @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [opts.network] - unused today (the network service declares no `createBackend`), accepted for forward compatibility with `attachService()`'s own signature.
|
|
897
|
+
* @param {string} [opts.localPodId] - defaults to `node.podId`.
|
|
898
|
+
* @param {string} [opts.envelopeType]
|
|
899
|
+
* @param {number} [opts.requestTimeoutMs]
|
|
900
|
+
* @param {Function} [opts.onLog]
|
|
901
|
+
*/
|
|
902
|
+
constructor({ node, network, localPodId, envelopeType, requestTimeoutMs, onLog } = {}) {
|
|
903
|
+
if (!node || typeof node.podId !== 'string') {
|
|
904
|
+
throw new Error('MeshMarketplace: opts.node (a PeerNode-like object with a podId) is required');
|
|
905
|
+
}
|
|
906
|
+
this.#node = node;
|
|
907
|
+
this.#marketplace = new Marketplace({ localPodId: localPodId ?? node.podId });
|
|
908
|
+
this.#handle = attachService(node, network, createMarketplaceNetworkService({
|
|
909
|
+
marketplace: this.#marketplace,
|
|
910
|
+
envelopeType,
|
|
911
|
+
requestTimeoutMs,
|
|
912
|
+
onLog,
|
|
913
|
+
}));
|
|
914
|
+
// Forward Marketplace's own local events verbatim onto this class's own
|
|
915
|
+
// bus -- same convention MeshKv already uses for its own composed
|
|
916
|
+
// service, not a second, differently-named vocabulary.
|
|
917
|
+
this.#unsubscribeForwardedEvents = this.#marketplace.onEvent((event, data) => this.#events.emit(event, data));
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/** @returns {string} */
|
|
921
|
+
get localPodId() {
|
|
922
|
+
return this.#marketplace.localPodId;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
// -- Local pass-throughs (delegate to the composed Marketplace) -----------
|
|
926
|
+
|
|
927
|
+
publish(listing) { return this.#marketplace.publish(listing); }
|
|
928
|
+
unpublish(listingId) { return this.#marketplace.unpublish(listingId); }
|
|
929
|
+
update(listingId, updates) { return this.#marketplace.update(listingId, updates); }
|
|
930
|
+
search(query) { return this.#marketplace.search(query); }
|
|
931
|
+
getListingById(id) { return this.#marketplace.getListingById(id); }
|
|
932
|
+
getListingsByProvider(podId) { return this.#marketplace.getListingsByProvider(podId); }
|
|
933
|
+
addReview(review) { return this.#marketplace.addReview(review); }
|
|
934
|
+
getReviews(listingId) { return this.#marketplace.getReviews(listingId); }
|
|
935
|
+
getAverageRating(listingId) { return this.#marketplace.getAverageRating(listingId); }
|
|
936
|
+
getCategories() { return this.#marketplace.getCategories(); }
|
|
937
|
+
getFeatured(limit) { return this.#marketplace.getFeatured(limit); }
|
|
938
|
+
getStats() { return this.#marketplace.getStats(); }
|
|
939
|
+
|
|
940
|
+
/** @returns {string[]} */
|
|
941
|
+
#connectedPeerIds() {
|
|
942
|
+
const peers = this.#node.registry && typeof this.#node.registry.listPeers === 'function'
|
|
943
|
+
? this.#node.registry.listPeers({ status: 'connected' })
|
|
944
|
+
: [];
|
|
945
|
+
return peers.map((p) => p.fingerprint);
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/**
|
|
949
|
+
* Search connected peers' own marketplaces, not just this one. A peer
|
|
950
|
+
* that times out or errors is silently excluded from the result rather
|
|
951
|
+
* than rejecting the whole call -- partial results, matching
|
|
952
|
+
* `chunk-replication.mjs`'s "best responder wins, nobody home is not a
|
|
953
|
+
* hard error" posture.
|
|
954
|
+
*
|
|
955
|
+
* @param {object} [query] - `Marketplace#search()`'s own query shape.
|
|
956
|
+
* @param {object} [opts]
|
|
957
|
+
* @param {string[]} [opts.peerIds] - defaults to currently-connected peers.
|
|
958
|
+
* @param {number} [opts.timeoutMs] - per-call override; omit to use the service's own `requestTimeoutMs`.
|
|
959
|
+
* @returns {Promise<ServiceListing[]>} deduped by listing id across all responding peers.
|
|
960
|
+
*/
|
|
961
|
+
async searchNetwork(query = {}, { peerIds, timeoutMs } = {}) {
|
|
962
|
+
const targets = peerIds ?? this.#connectedPeerIds();
|
|
963
|
+
const settled = await Promise.allSettled(
|
|
964
|
+
targets.map((peerId) => withTimeout(this.#handle.api.request(peerId, { method: 'SEARCH', body: query }), timeoutMs)),
|
|
965
|
+
);
|
|
966
|
+
const byId = new Map();
|
|
967
|
+
for (const result of settled) {
|
|
968
|
+
if (result.status !== 'fulfilled') continue;
|
|
969
|
+
const res = result.value;
|
|
970
|
+
if (res.status !== 200 || !res.body || !res.body.listings) continue;
|
|
971
|
+
for (const raw of res.body.listings) {
|
|
972
|
+
const listing = ServiceListing.fromJSON(raw);
|
|
973
|
+
if (!byId.has(listing.id)) byId.set(listing.id, listing);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return [...byId.values()];
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/**
|
|
980
|
+
* Fetch reviews for `listingId` from connected peers, same partial-results
|
|
981
|
+
* posture as `searchNetwork()`.
|
|
982
|
+
*
|
|
983
|
+
* @param {string} listingId
|
|
984
|
+
* @param {object} [opts]
|
|
985
|
+
* @param {string[]} [opts.peerIds]
|
|
986
|
+
* @param {number} [opts.timeoutMs]
|
|
987
|
+
* @returns {Promise<ServiceReview[]>} deduped by review id.
|
|
988
|
+
*/
|
|
989
|
+
async getReviewsNetwork(listingId, { peerIds, timeoutMs } = {}) {
|
|
990
|
+
const targets = peerIds ?? this.#connectedPeerIds();
|
|
991
|
+
const settled = await Promise.allSettled(
|
|
992
|
+
targets.map((peerId) => withTimeout(this.#handle.api.request(peerId, { method: 'REVIEWS', body: { listingId } }), timeoutMs)),
|
|
993
|
+
);
|
|
994
|
+
const byId = new Map();
|
|
995
|
+
for (const result of settled) {
|
|
996
|
+
if (result.status !== 'fulfilled') continue;
|
|
997
|
+
const res = result.value;
|
|
998
|
+
if (res.status !== 200 || !res.body || !res.body.reviews) continue;
|
|
999
|
+
for (const raw of res.body.reviews) {
|
|
1000
|
+
const review = ServiceReview.fromJSON(raw);
|
|
1001
|
+
if (!byId.has(review.id)) byId.set(review.id, review);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
return [...byId.values()];
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// -- Observability (forwards Marketplace's own events, see constructor) --
|
|
1008
|
+
|
|
1009
|
+
on(event, cb) { return this.#events.on(event, cb); }
|
|
1010
|
+
onEvent(cb) { return this.#events.onEvent(cb); }
|
|
1011
|
+
|
|
1012
|
+
/** Tears down the composed network service and stops event forwarding. */
|
|
1013
|
+
async close() {
|
|
1014
|
+
this.#unsubscribeForwardedEvents();
|
|
1015
|
+
await this.#handle.teardown();
|
|
1016
|
+
this.#events.closeAll();
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
@@ -362,7 +362,7 @@ export class EncryptedBlobStore {
|
|
|
362
362
|
|
|
363
363
|
// Upload ciphertext to peer
|
|
364
364
|
const path = `.encrypted-blobs/${cid}`
|
|
365
|
-
await this.#fileClient.writeFile(path, ciphertext)
|
|
365
|
+
await this.#fileClient.writeFile(peerId, path, ciphertext)
|
|
366
366
|
|
|
367
367
|
this.#onLog(2, `Uploaded encrypted blob ${cid} to peer ${peerId}`)
|
|
368
368
|
|
|
@@ -405,7 +405,7 @@ export class EncryptedBlobStore {
|
|
|
405
405
|
|
|
406
406
|
// Download ciphertext from peer
|
|
407
407
|
const path = `.encrypted-blobs/${cid}`
|
|
408
|
-
const result = await this.#fileClient.readFile(path)
|
|
408
|
+
const result = await this.#fileClient.readFile(peerId, path)
|
|
409
409
|
const ciphertext = result.data instanceof Uint8Array
|
|
410
410
|
? result.data
|
|
411
411
|
: new TextEncoder().encode(result.data)
|
|
@@ -440,7 +440,7 @@ export class EncryptedBlobStore {
|
|
|
440
440
|
this.#onLog(2, `Deleting blob ${cid} from peer ${peerId}`)
|
|
441
441
|
|
|
442
442
|
const path = `.encrypted-blobs/${cid}`
|
|
443
|
-
await this.#fileClient.deleteFile(path)
|
|
443
|
+
await this.#fileClient.deleteFile(peerId, path)
|
|
444
444
|
|
|
445
445
|
// Remove from manifest
|
|
446
446
|
const deleted = this.#manifest.delete(cid)
|
|
@@ -471,7 +471,7 @@ export class EncryptedBlobStore {
|
|
|
471
471
|
this.#onLog(2, `Verifying blob ${cid} on peer ${peerId}`)
|
|
472
472
|
|
|
473
473
|
const path = `.encrypted-blobs/${cid}`
|
|
474
|
-
const result = await this.#fileClient.readFile(path)
|
|
474
|
+
const result = await this.#fileClient.readFile(peerId, path)
|
|
475
475
|
const ciphertext = result.data instanceof Uint8Array
|
|
476
476
|
? result.data
|
|
477
477
|
: new TextEncoder().encode(result.data)
|
package/src/peer-escrow.mjs
CHANGED
|
@@ -282,8 +282,10 @@ export class EscrowManager {
|
|
|
282
282
|
create(opts) {
|
|
283
283
|
const { payerPodId, payeePodId, amount, description, conditions, timeoutMs } = opts
|
|
284
284
|
|
|
285
|
-
// Debit payer — throws on insufficient balance
|
|
286
|
-
|
|
285
|
+
// Debit payer — throws on insufficient balance. CreditLedger's real
|
|
286
|
+
// signature is debit(amount, toPodId, memo) -- no charge() method
|
|
287
|
+
// exists; amount comes first, not the podId.
|
|
288
|
+
this.#creditLedger.debit(amount, payerPodId, `escrow: ${description || 'contract'}`)
|
|
287
289
|
|
|
288
290
|
const contract = new EscrowContract({
|
|
289
291
|
payer: payerPodId,
|
|
@@ -331,8 +333,9 @@ export class EscrowManager {
|
|
|
331
333
|
}
|
|
332
334
|
}
|
|
333
335
|
|
|
334
|
-
// Credit payee
|
|
335
|
-
|
|
336
|
+
// Credit payee. CreditLedger's real signature is credit(amount,
|
|
337
|
+
// fromPodId, memo) -- amount first, not the podId.
|
|
338
|
+
this.#creditLedger.credit(contract.amount, contract.payee, `escrow release: ${contractId}`)
|
|
336
339
|
contract.status = 'released'
|
|
337
340
|
|
|
338
341
|
this.#onLog('info', `Escrow released: ${contractId} (${contract.amount} to ${contract.payee})`)
|
|
@@ -358,8 +361,8 @@ export class EscrowManager {
|
|
|
358
361
|
throw new Error(`Cannot refund contract ${contractId}: not funded (status: ${contract.status})`)
|
|
359
362
|
}
|
|
360
363
|
|
|
361
|
-
// Credit payer
|
|
362
|
-
this.#creditLedger.credit(contract.
|
|
364
|
+
// Credit payer. Same real signature as release() above: amount first.
|
|
365
|
+
this.#creditLedger.credit(contract.amount, contract.payer, `escrow refund: ${reason || contractId}`)
|
|
363
366
|
contract.status = 'refunded'
|
|
364
367
|
|
|
365
368
|
this.#onLog('info', `Escrow refunded: ${contractId} (${contract.amount} to ${contract.payer})`)
|
|
@@ -405,10 +408,11 @@ export class EscrowManager {
|
|
|
405
408
|
|
|
406
409
|
for (const contract of this.#contracts.values()) {
|
|
407
410
|
if (contract.status === 'funded' && contract.isExpired(ts)) {
|
|
408
|
-
// Auto-refund expired contracts
|
|
411
|
+
// Auto-refund expired contracts. Same real signature as release()/
|
|
412
|
+
// refund() above: credit(amount, fromPodId, memo), amount first.
|
|
409
413
|
this.#creditLedger.credit(
|
|
410
|
-
contract.payer,
|
|
411
414
|
contract.amount,
|
|
415
|
+
contract.payer,
|
|
412
416
|
`escrow expired: ${contract.id}`,
|
|
413
417
|
)
|
|
414
418
|
contract.status = 'expired'
|
package/src/quotas.mjs
CHANGED
|
@@ -1,18 +1,84 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* quotas.mjs -- Per-identity resource quotas with enforcement.
|
|
3
3
|
*
|
|
4
4
|
* Provides QuotaRule definitions, usage tracking (UsageRecord), a
|
|
5
5
|
* QuotaManager for CRUD on per-pod quota rules, and a QuotaEnforcer
|
|
6
6
|
* for recording usage, checking limits, and tracking violations.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
8
|
+
* ---------------------------------------------------------------------------
|
|
9
|
+
* `QuotaEnforcer` predated this package's `MeshService` convention
|
|
10
|
+
* (`mesh-service.mjs`) and, until now, stayed purely local: no
|
|
11
|
+
* `sendTo`/`onIncomingData`/`attachService()` anywhere, used by nothing
|
|
12
|
+
* else in this package. Its observability surface was a single
|
|
13
|
+
* constructor-injected `opts.onViolation` callback (one listener only,
|
|
14
|
+
* manually wrapped in `try/catch` + `silentCatch()` to swallow a throwing
|
|
15
|
+
* listener). Modernized to use `mesh-service.mjs`'s `createEventBus()`
|
|
16
|
+
* instead: `on(event, cb)`/`onEvent(cb)` support real multi-listener
|
|
17
|
+
* fan-out and get the bus's own swallow-on-throw guarantee for free,
|
|
18
|
+
* making the old manual `silentCatch()` call dead code (removed).
|
|
19
|
+
* `opts.onViolation` is kept as constructor sugar -- it subscribes the
|
|
20
|
+
* given function to the bus as listener #1, unchanged in payload shape --
|
|
21
|
+
* since existing callers already construct enforcers this way and it's
|
|
22
|
+
* genuinely additive, not a compatibility shim for anything removed.
|
|
23
|
+
*
|
|
24
|
+
* The `QUOTA_*`/`USAGE_REPORT` constants below are `browsermesh-primitives`
|
|
25
|
+
* wire-registry codes, re-exported but never used as an `envelope.type` --
|
|
26
|
+
* `MeshService`'s `ctx.onIncomingData()` filters on a plain string, which
|
|
27
|
+
* this numeric registry is structurally incompatible with.
|
|
28
|
+
* `createQuotaReportingService()` mints its own string envelope type
|
|
29
|
+
* (`'quota-reporting'`) instead of repurposing them, matching
|
|
30
|
+
* `mesh-swarm.mjs`'s identical precedent for the same situation. They stay
|
|
31
|
+
* exactly as they are: unused as routing.
|
|
32
|
+
*
|
|
33
|
+
* ---------------------------------------------------------------------------
|
|
34
|
+
* `createQuotaReportingService()` establishes a host/authority model: any
|
|
35
|
+
* peer running it accepts `USAGE_REPORT`s from other peers and enforces
|
|
36
|
+
* quotas on their behalf, replying `QUOTA_VIOLATION` when a report trips
|
|
37
|
+
* one. Built directly on `ctx.sendTo()`/`ctx.onIncomingData()`, NOT
|
|
38
|
+
* wrapped around `mesh-rpc.mjs` -- unlike `marketplace.mjs`'s network
|
|
39
|
+
* search (genuinely request/response-shaped), a usage report has no
|
|
40
|
+
* synchronous reply worth awaiting (a violation reply is async-maybe-
|
|
41
|
+
* never), so this is a push, matching `mesh-kv.mjs`'s broadcast shape,
|
|
42
|
+
* not `mesh-rpc.mjs`'s request/response shape.
|
|
43
|
+
*
|
|
44
|
+
* **Security-relevant, non-negotiable**: the wire shape for a usage report
|
|
45
|
+
* carries no `podId` field. The authority attributes usage to the
|
|
46
|
+
* connection-authenticated `fromPubKey` unconditionally, never to a self-
|
|
47
|
+
* declared identity in a payload -- without this, a peer could frame
|
|
48
|
+
* another peer (drive its usage over quota) or evade its own quota
|
|
49
|
+
* (attribute its usage to someone else). Same class of gap `mesh-kv.mjs`'s
|
|
50
|
+
* `attribution-mismatch` check and `chunk-replication.mjs`'s write-access
|
|
51
|
+
* gate already close elsewhere in this family; treated as baseline
|
|
52
|
+
* hygiene here too, not optional ACL.
|
|
53
|
+
*
|
|
54
|
+
* **No ACL on who may act as, or report to, a quota authority.** A peer
|
|
55
|
+
* decides who to trust as its authority (whose `QUOTA_VIOLATION`/
|
|
56
|
+
* `QUOTA_UPDATE` it listens to) entirely by its own wiring choices outside
|
|
57
|
+
* this service, mirroring `mesh-rpc.mjs`/`mesh-websocket.mjs`'s own
|
|
58
|
+
* explicit "authorization is the handler's job, not the transport's"
|
|
59
|
+
* stance. An authority accepts `USAGE_REPORT`s from any peer that can
|
|
60
|
+
* reach it; unknown senders fall back to `QuotaManager`'s existing
|
|
61
|
+
* `DEFAULT_LIMITS`, not to unlimited enforcement.
|
|
9
62
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
63
|
+
* **`quota-update` never self-applies to a receiving peer's own local
|
|
64
|
+
* `QuotaManager`.** Delivered as a notification event only
|
|
65
|
+
* (`quota:rule-update-received`); a caller that wants to actually trust a
|
|
66
|
+
* given authority's pushed rule changes must opt in explicitly at the
|
|
67
|
+
* call site (e.g. `meshQuotaEnforcer.on('quota:rule-update-received', rule
|
|
68
|
+
* => { if (trusted(rule)) manager.setQuota(...) })`). This is the one
|
|
69
|
+
* place a remote peer could otherwise silently mutate local enforcement
|
|
70
|
+
* state, and it stays closed by design, not by a forgettable check.
|
|
71
|
+
*
|
|
72
|
+
* `MeshQuotaEnforcer` is the ergonomic wrapper -- the same two-layer split
|
|
73
|
+
* `mesh-kv.mjs`/`marketplace.mjs`'s `MeshMarketplace` already established.
|
|
74
|
+
* `QuotaEnforcer`/`QuotaManager` never gain a `PeerNode` reference; only
|
|
75
|
+
* `MeshQuotaEnforcer` does.
|
|
76
|
+
*
|
|
77
|
+
* No browser-only imports at module level.
|
|
12
78
|
*/
|
|
13
79
|
|
|
14
80
|
import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
|
|
15
|
-
import {
|
|
81
|
+
import { createEventBus, attachService } from './mesh-service.mjs';
|
|
16
82
|
|
|
17
83
|
// ---------------------------------------------------------------------------
|
|
18
84
|
// Wire constants — imported from canonical registry
|
|
@@ -383,17 +449,19 @@ export class QuotaEnforcer {
|
|
|
383
449
|
/** @type {Array<{podId: string, resource: string, limit: number, actual: number, policy: string, timestamp: number}>} */
|
|
384
450
|
#violations = [];
|
|
385
451
|
|
|
386
|
-
/** @type {
|
|
387
|
-
#
|
|
452
|
+
/** @type {import('./mesh-service.mjs').EventBus} */
|
|
453
|
+
#events = createEventBus();
|
|
388
454
|
|
|
389
455
|
/**
|
|
390
456
|
* @param {QuotaManager} quotaManager
|
|
391
457
|
* @param {object} [opts]
|
|
392
|
-
* @param {Function} [opts.onViolation] -
|
|
458
|
+
* @param {Function} [opts.onViolation] - Sugar for `on('quota:violation-detected', onViolation)`; called with violation info on limit breach.
|
|
393
459
|
*/
|
|
394
460
|
constructor(quotaManager, opts = {}) {
|
|
395
461
|
this.#manager = quotaManager;
|
|
396
|
-
|
|
462
|
+
if (typeof opts.onViolation === 'function') {
|
|
463
|
+
this.#events.on('quota:violation-detected', opts.onViolation);
|
|
464
|
+
}
|
|
397
465
|
}
|
|
398
466
|
|
|
399
467
|
// -- Usage key helpers ----------------------------------------------------
|
|
@@ -455,9 +523,7 @@ export class QuotaEnforcer {
|
|
|
455
523
|
timestamp: Date.now(),
|
|
456
524
|
};
|
|
457
525
|
this.#violations.push(violation);
|
|
458
|
-
|
|
459
|
-
try { this.#onViolation(violation); } catch (e) { silentCatch('clawser-mesh-quotas', 'swallow-listener-errors', e) }
|
|
460
|
-
}
|
|
526
|
+
this.#events.emit('quota:violation-detected', violation);
|
|
461
527
|
}
|
|
462
528
|
}
|
|
463
529
|
|
|
@@ -541,6 +607,30 @@ export class QuotaEnforcer {
|
|
|
541
607
|
this.#usage.delete(key);
|
|
542
608
|
}
|
|
543
609
|
|
|
610
|
+
// -- Observability ----------------------------------------------------------
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Subscribe to exactly one event name -- currently only
|
|
614
|
+
* `'quota:violation-detected'` (data: `{podId, resource, limit, actual,
|
|
615
|
+
* policy, timestamp}`, the same shape the old constructor-only
|
|
616
|
+
* `onViolation` callback received).
|
|
617
|
+
* @param {string} event
|
|
618
|
+
* @param {(data: object, event: string) => void} cb
|
|
619
|
+
* @returns {() => void} unsubscribe
|
|
620
|
+
*/
|
|
621
|
+
on(event, cb) {
|
|
622
|
+
return this.#events.on(event, cb);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* Subscribe to every `quota:*` event this enforcer emits, regardless of name.
|
|
627
|
+
* @param {(event: string, data: object) => void} cb
|
|
628
|
+
* @returns {() => void} unsubscribe
|
|
629
|
+
*/
|
|
630
|
+
onEvent(cb) {
|
|
631
|
+
return this.#events.onEvent(cb);
|
|
632
|
+
}
|
|
633
|
+
|
|
544
634
|
// -- Violations -----------------------------------------------------------
|
|
545
635
|
|
|
546
636
|
/**
|
|
@@ -619,3 +709,212 @@ export class QuotaEnforcer {
|
|
|
619
709
|
return enforcer;
|
|
620
710
|
}
|
|
621
711
|
}
|
|
712
|
+
|
|
713
|
+
// ---------------------------------------------------------------------------
|
|
714
|
+
// Quota network reporting
|
|
715
|
+
// ---------------------------------------------------------------------------
|
|
716
|
+
|
|
717
|
+
/** Default `envelope.type` for a quota authority's mesh attach -- see module doc comment. */
|
|
718
|
+
export const DEFAULT_QUOTA_ENVELOPE_TYPE = 'quota-reporting';
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Build a `MeshService` descriptor (`mesh-service.mjs`) implementing the
|
|
722
|
+
* host/authority side of cross-peer usage reporting -- see module doc
|
|
723
|
+
* comment for the full wire-protocol/security writeup (attribution via
|
|
724
|
+
* `fromPubKey`, no ACL on who may report, `quota-update` never self-
|
|
725
|
+
* applying).
|
|
726
|
+
*
|
|
727
|
+
* @param {object} opts
|
|
728
|
+
* @param {QuotaEnforcer} opts.enforcer
|
|
729
|
+
* @param {string} [opts.envelopeType='quota-reporting']
|
|
730
|
+
* @param {Function} [opts.onLog]
|
|
731
|
+
* @returns {import('./mesh-service.mjs').MeshService}
|
|
732
|
+
*/
|
|
733
|
+
export function createQuotaReportingService({ enforcer, envelopeType = DEFAULT_QUOTA_ENVELOPE_TYPE, onLog } = {}) {
|
|
734
|
+
if (!enforcer || typeof enforcer.recordUsage !== 'function') {
|
|
735
|
+
throw new Error('createQuotaReportingService: opts.enforcer (a QuotaEnforcer instance) is required');
|
|
736
|
+
}
|
|
737
|
+
const log = onLog || (() => {});
|
|
738
|
+
|
|
739
|
+
return {
|
|
740
|
+
name: 'quota-reporting',
|
|
741
|
+
|
|
742
|
+
attach(peerNode, ctx) {
|
|
743
|
+
/** @param {string} fromPubKey @param {{resource: string, amount: number}} msg */
|
|
744
|
+
async function handleUsageReport(fromPubKey, msg) {
|
|
745
|
+
const { resource, amount } = msg;
|
|
746
|
+
|
|
747
|
+
// recordUsage() emits 'quota:violation-detected' synchronously
|
|
748
|
+
// (before returning) if -- and only if -- THIS call trips a
|
|
749
|
+
// violation, so a temporary listener scoped tightly around the
|
|
750
|
+
// call captures exactly that outcome, deterministically, with no
|
|
751
|
+
// timestamp heuristics or races against concurrent reports.
|
|
752
|
+
let triggeredViolation = null;
|
|
753
|
+
const unsubscribeOnce = enforcer.on('quota:violation-detected', (v) => {
|
|
754
|
+
triggeredViolation = v;
|
|
755
|
+
});
|
|
756
|
+
try {
|
|
757
|
+
// Attribution: always the connection-authenticated sender, never
|
|
758
|
+
// a self-declared identity in the payload -- see module doc
|
|
759
|
+
// comment's "Security-relevant, non-negotiable" section.
|
|
760
|
+
enforcer.recordUsage(fromPubKey, resource, amount);
|
|
761
|
+
} finally {
|
|
762
|
+
unsubscribeOnce();
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
ctx.emit('quota:usage-report-received', { from: fromPubKey, resource, amount });
|
|
766
|
+
|
|
767
|
+
if (triggeredViolation) {
|
|
768
|
+
try {
|
|
769
|
+
await ctx.sendTo(fromPubKey, envelopeType, { kind: 'quota-violation', violation: triggeredViolation });
|
|
770
|
+
} catch (err) {
|
|
771
|
+
log('quota-reporting:violation-send-failed', { to: fromPubKey, error: err?.message || String(err) });
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
|
|
777
|
+
if (!msg || typeof msg.kind !== 'string') return;
|
|
778
|
+
if (msg.kind === 'usage-report') {
|
|
779
|
+
handleUsageReport(fromPubKey, msg).catch((err) => {
|
|
780
|
+
log('quota-reporting:usage-report-handling-failed', { from: fromPubKey, error: err?.message || String(err) });
|
|
781
|
+
});
|
|
782
|
+
} else if (msg.kind === 'quota-violation') {
|
|
783
|
+
ctx.emit('quota:violation-notified', { from: fromPubKey, violation: msg.violation });
|
|
784
|
+
} else if (msg.kind === 'quota-update') {
|
|
785
|
+
// Informational only -- never self-applies to this peer's own
|
|
786
|
+
// QuotaManager. See module doc comment.
|
|
787
|
+
ctx.emit('quota:rule-update-received', { from: fromPubKey, rule: msg.rule });
|
|
788
|
+
}
|
|
789
|
+
});
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* Report this peer's own usage to a remote quota authority.
|
|
793
|
+
* Fire-and-forget: does not await a reply, since the only possible
|
|
794
|
+
* reply (a `quota-violation`) is async-maybe-never, not a
|
|
795
|
+
* synchronous ack -- see module doc comment.
|
|
796
|
+
* @param {string} authorityPodId
|
|
797
|
+
* @param {string} resource
|
|
798
|
+
* @param {number} amount
|
|
799
|
+
*/
|
|
800
|
+
async function reportUsage(authorityPodId, resource, amount) {
|
|
801
|
+
await ctx.sendTo(authorityPodId, envelopeType, { kind: 'usage-report', resource, amount });
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* Push a `QuotaRule` change to a specific peer as a notification --
|
|
806
|
+
* the receiving side never self-applies it (see module doc comment).
|
|
807
|
+
* @param {string} peerId
|
|
808
|
+
* @param {QuotaRule} rule
|
|
809
|
+
*/
|
|
810
|
+
async function pushQuotaUpdate(peerId, rule) {
|
|
811
|
+
await ctx.sendTo(peerId, envelopeType, { kind: 'quota-update', rule: rule.toJSON ? rule.toJSON() : rule });
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
return {
|
|
815
|
+
api: { reportUsage, pushQuotaUpdate },
|
|
816
|
+
teardown() {
|
|
817
|
+
unsubscribe();
|
|
818
|
+
},
|
|
819
|
+
};
|
|
820
|
+
},
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* Ergonomic wrapper composing a `QuotaEnforcer` with
|
|
826
|
+
* `createQuotaReportingService()` -- the same two-layer split `mesh-kv.mjs`/
|
|
827
|
+
* `marketplace.mjs`'s `MeshMarketplace` already established:
|
|
828
|
+
* `QuotaEnforcer`/`QuotaManager` never gain a `PeerNode` reference, only
|
|
829
|
+
* `MeshQuotaEnforcer` does.
|
|
830
|
+
*/
|
|
831
|
+
export class MeshQuotaEnforcer {
|
|
832
|
+
/** @type {QuotaManager} */
|
|
833
|
+
#manager;
|
|
834
|
+
/** @type {QuotaEnforcer} */
|
|
835
|
+
#enforcer;
|
|
836
|
+
/** @type {ReturnType<import('./mesh-service.mjs').attachService>} */
|
|
837
|
+
#handle;
|
|
838
|
+
/** @type {import('./mesh-service.mjs').EventBus} */
|
|
839
|
+
#events = createEventBus();
|
|
840
|
+
/** @type {() => void} */
|
|
841
|
+
#unsubscribeEnforcerEvents;
|
|
842
|
+
/** @type {() => void} */
|
|
843
|
+
#unsubscribeServiceEvents;
|
|
844
|
+
|
|
845
|
+
/**
|
|
846
|
+
* @param {object} opts
|
|
847
|
+
* @param {import('./peer-node.mjs').PeerNode} opts.node - duck-typed: needs `podId`.
|
|
848
|
+
* @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [opts.network] - unused today, accepted for forward compatibility with `attachService()`'s own signature.
|
|
849
|
+
* @param {QuotaManager} [opts.manager] - defaults to a fresh `new QuotaManager()`.
|
|
850
|
+
* @param {QuotaEnforcer} [opts.enforcer] - defaults to a fresh `new QuotaEnforcer(manager)`.
|
|
851
|
+
* @param {string} [opts.envelopeType]
|
|
852
|
+
* @param {Function} [opts.onLog]
|
|
853
|
+
*/
|
|
854
|
+
constructor({ node, network, manager, enforcer, envelopeType, onLog } = {}) {
|
|
855
|
+
if (!node || typeof node.podId !== 'string') {
|
|
856
|
+
throw new Error('MeshQuotaEnforcer: opts.node (a PeerNode-like object with a podId) is required');
|
|
857
|
+
}
|
|
858
|
+
this.#manager = manager ?? new QuotaManager();
|
|
859
|
+
this.#enforcer = enforcer ?? new QuotaEnforcer(this.#manager);
|
|
860
|
+
this.#handle = attachService(node, network, createQuotaReportingService({
|
|
861
|
+
enforcer: this.#enforcer,
|
|
862
|
+
envelopeType,
|
|
863
|
+
onLog,
|
|
864
|
+
}));
|
|
865
|
+
// Two independent sources forward onto this class's own bus: the
|
|
866
|
+
// enforcer's own local 'quota:violation-detected' (fired by
|
|
867
|
+
// recordUsage() itself, whether called locally or via an inbound
|
|
868
|
+
// usage-report), and the network service's own ctx.emit()'d events
|
|
869
|
+
// ('quota:usage-report-received'/'quota:violation-notified'/
|
|
870
|
+
// 'quota:rule-update-received') -- same forwarding convention
|
|
871
|
+
// MeshMarketplace/MeshKv use, just two emitters instead of one since
|
|
872
|
+
// this phase's own service has events the composed local class does not.
|
|
873
|
+
this.#unsubscribeEnforcerEvents = this.#enforcer.onEvent((event, data) => this.#events.emit(event, data));
|
|
874
|
+
this.#unsubscribeServiceEvents = this.#handle.onEvent((event, data) => this.#events.emit(event, data));
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** @returns {QuotaManager} */
|
|
878
|
+
get manager() { return this.#manager; }
|
|
879
|
+
|
|
880
|
+
/** @returns {QuotaEnforcer} */
|
|
881
|
+
get enforcer() { return this.#enforcer; }
|
|
882
|
+
|
|
883
|
+
// -- Local pass-throughs (delegate to the composed QuotaEnforcer) --------
|
|
884
|
+
|
|
885
|
+
recordUsage(podId, resource, amount) { return this.#enforcer.recordUsage(podId, resource, amount); }
|
|
886
|
+
checkQuota(podId, resource, requestedAmount) { return this.#enforcer.checkQuota(podId, resource, requestedAmount); }
|
|
887
|
+
listViolations(podId) { return this.#enforcer.listViolations(podId); }
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* @param {string} authorityPodId
|
|
891
|
+
* @param {string} resource
|
|
892
|
+
* @param {number} amount
|
|
893
|
+
*/
|
|
894
|
+
async reportUsage(authorityPodId, resource, amount) {
|
|
895
|
+
return this.#handle.api.reportUsage(authorityPodId, resource, amount);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* Push a `QuotaRule` change to a specific peer as a notification -- the
|
|
900
|
+
* receiving side never self-applies it. See module doc comment.
|
|
901
|
+
* @param {string} peerId
|
|
902
|
+
* @param {QuotaRule} rule
|
|
903
|
+
*/
|
|
904
|
+
async pushQuotaUpdate(peerId, rule) {
|
|
905
|
+
return this.#handle.api.pushQuotaUpdate(peerId, rule);
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// -- Observability (forwards the enforcer's events, plus this phase's own) --
|
|
909
|
+
|
|
910
|
+
on(event, cb) { return this.#events.on(event, cb); }
|
|
911
|
+
onEvent(cb) { return this.#events.onEvent(cb); }
|
|
912
|
+
|
|
913
|
+
/** Tears down the composed network service and stops event forwarding. */
|
|
914
|
+
async close() {
|
|
915
|
+
this.#unsubscribeEnforcerEvents();
|
|
916
|
+
this.#unsubscribeServiceEvents();
|
|
917
|
+
await this.#handle.teardown();
|
|
918
|
+
this.#events.closeAll();
|
|
919
|
+
}
|
|
920
|
+
}
|
|
@@ -88,12 +88,17 @@
|
|
|
88
88
|
* this monorepo's own `npm install`/CI regardless of the "optional" marking
|
|
89
89
|
* -- that marking only matters for a standalone external consumer.
|
|
90
90
|
* `@johnhenry/andbox` is a genuinely separate repo/package, not a workspace
|
|
91
|
-
* sibling, and
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
91
|
+
* sibling, and is declared as an OPTIONAL peer dependency
|
|
92
|
+
* (`peerDependenciesMeta`), so npm never attempts to install it
|
|
93
|
+
* automatically for anyone -- present only for a consumer that explicitly
|
|
94
|
+
* installs it themselves. (It's been published to npm since 0.0.1; that was
|
|
95
|
+
* never what made this lazy -- the optional-peer marking is what matters,
|
|
96
|
+
* and that hasn't changed.) A static top-level import here would make
|
|
97
|
+
* `index.mjs`'s eager `export *` chain fail for the ENTIRE package the
|
|
98
|
+
* moment `@johnhenry/andbox` is absent, breaking every consumer/test, not
|
|
99
|
+
* just ones using this specific executor. A dynamic `import()` inside the
|
|
100
|
+
* executor defers that requirement to "only if this specific executor is
|
|
101
|
+
* actually invoked."
|
|
97
102
|
*
|
|
98
103
|
* @module serverless-executor-andbox
|
|
99
104
|
*/
|