@johnhenry/browsermesh-apps 0.3.0 → 0.4.1
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 +7 -2
- package/src/cloud-storage.mjs +73 -13
- package/src/index.mjs +9 -0
- package/src/marketplace.mjs +290 -26
- package/src/peer-escrow.mjs +12 -8
- package/src/quotas.mjs +311 -12
- package/src/serverless-executor-andbox.mjs +141 -0
- package/src/serverless-fetch.mjs +70 -0
- package/src/serverless-functions.mjs +67 -0
- package/src/serverless-peer-select.mjs +69 -0
- package/src/serverless-proxy.mjs +127 -0
- package/src/serverless-router.mjs +115 -0
- package/src/serverless-sites.mjs +116 -0
- package/src/serverless-static.mjs +202 -0
- package/src/serverless-wire.mjs +87 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-apps",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
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",
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
"@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
|
|
27
27
|
"@johnhenry/browsermesh-discovery": ">=0.0.1 <1.0.0",
|
|
28
28
|
"@johnhenry/browsermesh-kernel": ">=0.0.0 <1.0.0",
|
|
29
|
-
"@johnhenry/browsermesh-netway": ">=0.0.0 <1.0.0"
|
|
29
|
+
"@johnhenry/browsermesh-netway": ">=0.0.0 <1.0.0",
|
|
30
|
+
"@johnhenry/andbox": ">=0.0.1 <1.0.0"
|
|
30
31
|
},
|
|
31
32
|
"peerDependenciesMeta": {
|
|
32
33
|
"@johnhenry/browsermesh-transport": {
|
|
@@ -43,9 +44,13 @@
|
|
|
43
44
|
},
|
|
44
45
|
"@johnhenry/browsermesh-netway": {
|
|
45
46
|
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"@johnhenry/andbox": {
|
|
49
|
+
"optional": true
|
|
46
50
|
}
|
|
47
51
|
},
|
|
48
52
|
"devDependencies": {
|
|
53
|
+
"@johnhenry/andbox": ">=0.0.1 <1.0.0",
|
|
49
54
|
"node-datachannel": "^0.33.4",
|
|
50
55
|
"fake-indexeddb": "^6.2.5",
|
|
51
56
|
"webgpu": "^0.6.1"
|
package/src/cloud-storage.mjs
CHANGED
|
@@ -587,22 +587,17 @@ export class CloudStorage {
|
|
|
587
587
|
}
|
|
588
588
|
|
|
589
589
|
/**
|
|
590
|
-
*
|
|
591
|
-
*
|
|
592
|
-
*
|
|
593
|
-
*
|
|
590
|
+
* Wait (up to `waitMs`) for `key`'s manifest entry to be present, per the
|
|
591
|
+
* module doc comment's point 2 ("the manifest entry itself isn't here
|
|
592
|
+
* yet"). Shared by `getObject()` and `stat()` so both honor the same
|
|
593
|
+
* manifest-sync-wait/tombstone contract as each other.
|
|
594
594
|
*
|
|
595
595
|
* @param {string} key
|
|
596
|
-
* @param {
|
|
597
|
-
* @
|
|
598
|
-
* @returns {Promise<Uint8Array>}
|
|
596
|
+
* @param {number} waitMs
|
|
597
|
+
* @returns {Promise<object>} the manifest registration entry
|
|
599
598
|
* @throws {CloudStorageNotFoundError}
|
|
600
599
|
*/
|
|
601
|
-
async
|
|
602
|
-
if (!key || typeof key !== 'string') {
|
|
603
|
-
throw new Error('CloudStorage.get: key is required and must be a non-empty string')
|
|
604
|
-
}
|
|
605
|
-
const waitMs = opts.manifestWaitMs ?? this.#manifestWaitMs
|
|
600
|
+
async #awaitManifestEntry(key, waitMs) {
|
|
606
601
|
const deadline = Date.now() + waitMs
|
|
607
602
|
|
|
608
603
|
let reg = null
|
|
@@ -620,6 +615,29 @@ export class CloudStorage {
|
|
|
620
615
|
if (reg.tombstone) {
|
|
621
616
|
throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
|
|
622
617
|
}
|
|
618
|
+
return reg
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Read `key`'s content plus the `contentType`/`metadata` it was `put()`
|
|
623
|
+
* with. The backend's `get` op already returns these fields
|
|
624
|
+
* (`cloud-storage-backend.mjs`'s `#opGet()`) -- `get()` below is a thin
|
|
625
|
+
* wrapper around this that returns only `data`, for callers that don't
|
|
626
|
+
* need the rest. Falls back to a remote peer request (Phase G's lazy
|
|
627
|
+
* pull/read-repair) for any chunk not already held locally.
|
|
628
|
+
*
|
|
629
|
+
* @param {string} key
|
|
630
|
+
* @param {object} [opts]
|
|
631
|
+
* @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
|
|
632
|
+
* @returns {Promise<{data: Uint8Array, contentType: (string|undefined), metadata: (object|undefined)}>}
|
|
633
|
+
* @throws {CloudStorageNotFoundError}
|
|
634
|
+
*/
|
|
635
|
+
async getObject(key, opts = {}) {
|
|
636
|
+
if (!key || typeof key !== 'string') {
|
|
637
|
+
throw new Error('CloudStorage.getObject: key is required and must be a non-empty string')
|
|
638
|
+
}
|
|
639
|
+
const waitMs = opts.manifestWaitMs ?? this.#manifestWaitMs
|
|
640
|
+
const reg = await this.#awaitManifestEntry(key, waitMs)
|
|
623
641
|
|
|
624
642
|
// Ensure every chunk this entry references is present locally BEFORE
|
|
625
643
|
// asking the backend to decrypt+assemble it -- the backend itself has
|
|
@@ -640,7 +658,49 @@ export class CloudStorage {
|
|
|
640
658
|
throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
|
|
641
659
|
}
|
|
642
660
|
this.#events.emit('cloud-storage:get-completed', { bucket: this.#bucket, key })
|
|
643
|
-
return fromBase64(res.data)
|
|
661
|
+
return { data: fromBase64(res.data), contentType: res.contentType, metadata: res.metadata }
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* Read `key`'s content. See `getObject()` for the `contentType`/`metadata`-
|
|
666
|
+
* preserving variant this delegates to.
|
|
667
|
+
*
|
|
668
|
+
* @param {string} key
|
|
669
|
+
* @param {object} [opts]
|
|
670
|
+
* @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
|
|
671
|
+
* @returns {Promise<Uint8Array>}
|
|
672
|
+
* @throws {CloudStorageNotFoundError}
|
|
673
|
+
*/
|
|
674
|
+
async get(key, opts = {}) {
|
|
675
|
+
const { data } = await this.getObject(key, opts)
|
|
676
|
+
return data
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Return `key`'s metadata (`size`, `contentType`, `metadata`, `updatedAt`,
|
|
681
|
+
* `version`) without reading or decrypting its content. Thin wrapper
|
|
682
|
+
* around the backend's existing `head` op (`cloud-storage-backend.mjs`'s
|
|
683
|
+
* `#opHead()`), which was already implemented but never called from this
|
|
684
|
+
* class.
|
|
685
|
+
*
|
|
686
|
+
* @param {string} key
|
|
687
|
+
* @param {object} [opts]
|
|
688
|
+
* @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
|
|
689
|
+
* @returns {Promise<{size: number, contentType: (string|undefined), metadata: (object|undefined), updatedAt: number, version: number}>}
|
|
690
|
+
* @throws {CloudStorageNotFoundError}
|
|
691
|
+
*/
|
|
692
|
+
async stat(key, opts = {}) {
|
|
693
|
+
if (!key || typeof key !== 'string') {
|
|
694
|
+
throw new Error('CloudStorage.stat: key is required and must be a non-empty string')
|
|
695
|
+
}
|
|
696
|
+
const waitMs = opts.manifestWaitMs ?? this.#manifestWaitMs
|
|
697
|
+
await this.#awaitManifestEntry(key, waitMs)
|
|
698
|
+
|
|
699
|
+
const res = await this.#sendCommand({ op: 'head', key })
|
|
700
|
+
if (res.error) {
|
|
701
|
+
throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
|
|
702
|
+
}
|
|
703
|
+
return { size: res.size, contentType: res.contentType, metadata: res.metadata, updatedAt: res.updatedAt, version: res.version }
|
|
644
704
|
}
|
|
645
705
|
|
|
646
706
|
/**
|
package/src/index.mjs
CHANGED
|
@@ -50,6 +50,15 @@ export * from './mesh-keepalive.mjs';
|
|
|
50
50
|
export * from './mesh-fetch.mjs';
|
|
51
51
|
export * from './mesh-websocket.mjs';
|
|
52
52
|
export * from './cloud-storage.mjs';
|
|
53
|
+
export * from './serverless-wire.mjs';
|
|
54
|
+
export * from './serverless-static.mjs';
|
|
55
|
+
export * from './serverless-router.mjs';
|
|
56
|
+
export * from './serverless-fetch.mjs';
|
|
57
|
+
export * from './serverless-proxy.mjs';
|
|
58
|
+
export * from './serverless-functions.mjs';
|
|
59
|
+
export * from './serverless-executor-andbox.mjs';
|
|
60
|
+
export * from './serverless-peer-select.mjs';
|
|
61
|
+
export * from './serverless-sites.mjs';
|
|
53
62
|
export * from './observability-bridge.mjs';
|
|
54
63
|
export * from './mesh-kv.mjs';
|
|
55
64
|
export * from './peer-payments.mjs';
|
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
|
+
}
|
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'
|