@johnhenry/browsermesh-apps 0.2.0 → 0.4.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/README.md +232 -1
- package/package.json +7 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +859 -0
- package/src/compat.mjs +98 -0
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +34 -2
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1131 -12
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +33 -2
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/serverless-executor-andbox.mjs +136 -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/src/peer-session.mjs +0 -937
package/src/peer-routing.mjs
CHANGED
|
@@ -1,19 +1,28 @@
|
|
|
1
1
|
/**
|
|
2
|
-
|
|
3
|
-
*
|
|
2
|
+
* peer-routing.mjs -- Multi-hop message routing and server sharing (issue
|
|
3
|
+
* #121, split from #84: originally, incorrectly, claimed to depend on
|
|
4
|
+
* `PeerSession` -- confirmed self-contained, no `PeerSession` import at all).
|
|
4
5
|
*
|
|
5
6
|
* Routes messages across the mesh via intermediary peers when direct
|
|
6
7
|
* connections are unavailable. Also enables HTTP server sharing via mesh.
|
|
7
8
|
*
|
|
8
|
-
* MeshRouter manages a route table and forwards messages through multi-hop
|
|
9
|
+
* `MeshRouter` manages a route table and forwards messages through multi-hop
|
|
9
10
|
* paths with TTL enforcement.
|
|
10
|
-
* ServerSharing exposes local HTTP servers to the mesh and proxies incoming
|
|
11
|
+
* `ServerSharing` exposes local HTTP servers to the mesh and proxies incoming
|
|
11
12
|
* requests from peers.
|
|
12
13
|
*
|
|
14
|
+
* Both classes are plain, dependency-injected (`forwardFn`/`fetchFn`) and
|
|
15
|
+
* have no `PeerNode`/mesh-transport awareness of their own -- see
|
|
16
|
+
* `createMeshRoutingService()` below (Phase C, `mesh-service.mjs`) for the
|
|
17
|
+
* `MeshService` wrapper that wires them onto a real `PeerNode`'s
|
|
18
|
+
* `ctx.sendTo()`/`ctx.onIncomingData()` dispatch bus. This closes a real
|
|
19
|
+
* capability gap: multi-hop message forwarding between peers that aren't
|
|
20
|
+
* directly connected -- nothing else in this repo does this.
|
|
21
|
+
*
|
|
13
22
|
* No browser-only imports at module level. All dependencies injected.
|
|
14
23
|
*
|
|
15
24
|
* Run tests:
|
|
16
|
-
* node --import ./
|
|
25
|
+
* node --import ./test/_setup-globals.mjs --test test/peer-routing.test.mjs
|
|
17
26
|
*/
|
|
18
27
|
|
|
19
28
|
// ---------------------------------------------------------------------------
|
|
@@ -553,3 +562,358 @@ export class ServerSharing {
|
|
|
553
562
|
}
|
|
554
563
|
}
|
|
555
564
|
}
|
|
565
|
+
|
|
566
|
+
// ---------------------------------------------------------------------------
|
|
567
|
+
// createMeshRoutingService -- MeshService wiring (Phase C consumer, issue #121)
|
|
568
|
+
// ---------------------------------------------------------------------------
|
|
569
|
+
|
|
570
|
+
/** Default `envelope.type` used to route `MeshRouter` envelopes on the shared `onIncomingData()` bus. */
|
|
571
|
+
const DEFAULT_ROUTING_ENVELOPE_TYPE = 'mesh-routing'
|
|
572
|
+
/** Default `envelope.type` used to route `ServerSharing` proxy request/response envelopes. */
|
|
573
|
+
const DEFAULT_SERVER_SHARE_ENVELOPE_TYPE = 'mesh-server-share'
|
|
574
|
+
/** How long `requestProxy()` waits for a matching proxy response before giving up. Mirrors `mesh-rpc.mjs`'s own default. */
|
|
575
|
+
const DEFAULT_PROXY_TIMEOUT_MS = 10000
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) that wires
|
|
579
|
+
* `MeshRouter` -- and, if `fetchFn` is supplied, `ServerSharing` too -- onto
|
|
580
|
+
* a real `PeerNode`. Single combined descriptor rather than two, because
|
|
581
|
+
* both classes come from this one file and share the same `localPodId`
|
|
582
|
+
* concept; `ServerSharing`'s wiring is entirely independent internally
|
|
583
|
+
* (different envelope type, own inbound dispatch) so splitting it out later
|
|
584
|
+
* would be a non-breaking change if ever needed.
|
|
585
|
+
*
|
|
586
|
+
* ---------------------------------------------------------------------------
|
|
587
|
+
* MULTI-HOP ROUTING DESIGN -- `forwardFn` -> `ctx.sendTo()`:
|
|
588
|
+
*
|
|
589
|
+
* `MeshRouter`'s only side effect on the network is calling
|
|
590
|
+
* `forwardFn(nextHop, envelope)` (see `route()`/`handleRoutedMessage()`
|
|
591
|
+
* above), where `envelope` is `{ from, to, ttl, message, path }` and
|
|
592
|
+
* `nextHop` is either the ultimate target (if it's a registered direct peer)
|
|
593
|
+
* or an intermediate pod from the route table. This file's `forwardFn` is
|
|
594
|
+
* simply:
|
|
595
|
+
*
|
|
596
|
+
* (nextHop, envelope) => ctx.sendTo(nextHop, envelopeType, envelope)
|
|
597
|
+
*
|
|
598
|
+
* `ctx.sendTo()` sends `{ type: envelopeType, ...envelope }` to `nextHop` --
|
|
599
|
+
* the envelope's own `to`/`ttl`/`message`/`path` fields pass through
|
|
600
|
+
* unchanged, so the receiving peer's `ctx.onIncomingData()` callback gets
|
|
601
|
+
* the exact same shape `handleRoutedMessage()` expects, plus the `type` tag
|
|
602
|
+
* (which `handleRoutedMessage()` ignores). `MeshRouter` calls `forwardFn`
|
|
603
|
+
* SYNCHRONOUSLY and does not await or check its return value (see
|
|
604
|
+
* `route()`/`handleRoutedMessage()`'s own bodies) -- `ctx.sendTo()` is
|
|
605
|
+
* async, so this wrapper fires it and attaches a `.catch()` for logging
|
|
606
|
+
* rather than letting a failed send become an unhandled rejection.
|
|
607
|
+
*
|
|
608
|
+
* The actual multi-hop mechanics -- genuinely different from a plain
|
|
609
|
+
* `ctx.sendTo()` request/response, per this phase's own brief -- happen
|
|
610
|
+
* entirely inside `MeshRouter.handleRoutedMessage()`, unmodified: an
|
|
611
|
+
* intermediate pod (say B, relaying from A to C) receives the envelope via
|
|
612
|
+
* this file's `ctx.onIncomingData()` subscription, calls
|
|
613
|
+
* `router.handleRoutedMessage(envelope)`, which sees `envelope.to !== B's
|
|
614
|
+
* own podId`, decrements `ttl`, appends B to `path`, and re-invokes
|
|
615
|
+
* `forwardFn` (this same wrapper) to send the decremented envelope onward
|
|
616
|
+
* to C -- recursing through as many pods as `maxTTL` allows. Each hop is an
|
|
617
|
+
* independent `ctx.sendTo()` call; there is no single long-lived connection
|
|
618
|
+
* or stream spanning the whole path. The topology itself (who is a "direct
|
|
619
|
+
* peer" vs. reachable only "via route") is intentionally NOT auto-discovered
|
|
620
|
+
* from `PeerNode`'s own connection events here -- `addDirectPeer()`/
|
|
621
|
+
* `addRoute()`/`removeRoute()` are exposed on `api` exactly as `MeshRouter`
|
|
622
|
+
* already defines them, so a caller (or a later phase) decides how routing
|
|
623
|
+
* topology gets populated, mirroring how `MeshRouter`'s own class never
|
|
624
|
+
* assumed a topology source either.
|
|
625
|
+
*
|
|
626
|
+
* ---------------------------------------------------------------------------
|
|
627
|
+
* SERVER SHARING DESIGN (opt-in via `fetchFn`) -- `ServerSharing` itself has
|
|
628
|
+
* no wire protocol or `PeerNode` awareness at all: `expose()`/`unexpose()`
|
|
629
|
+
* are purely local bookkeeping, and `handleRequest()` is a plain async
|
|
630
|
+
* function `{name, method, path, headers, body} -> {status, headers, body}`
|
|
631
|
+
* that proxies via the injected `fetchFn`. To let a REMOTE peer actually
|
|
632
|
+
* trigger that proxying (the whole point of "server sharing"), this file
|
|
633
|
+
* adds a small request/response wire protocol over a second envelope type
|
|
634
|
+
* (`serverShareEnvelopeType`, default `'mesh-server-share'`), modeled
|
|
635
|
+
* directly on `mesh-rpc.mjs`'s `requestId`-correlated request/response
|
|
636
|
+
* pattern (same reasoning: multiple concurrent `requestProxy()` calls must
|
|
637
|
+
* not cross-correlate):
|
|
638
|
+
*
|
|
639
|
+
* Proxy request (caller -> host): `{ type, kind: 'proxy-request', requestId, name, method, path, headers, body }`
|
|
640
|
+
* Proxy response (host -> caller): `{ type, kind: 'proxy-response', requestId, status, headers, body }`
|
|
641
|
+
*
|
|
642
|
+
* The HOST side (the peer with `expose()`d servers) answers a proxy request
|
|
643
|
+
* by calling its own `serverSharing.handleRequest()` directly -- no
|
|
644
|
+
* caller-supplied handler, unlike `mesh-rpc.mjs`'s `onRequest`, since
|
|
645
|
+
* `ServerSharing`'s whole job already IS "answer this proxy request". A
|
|
646
|
+
* `ServerSharing` attached with no `fetchFn` (or `fetchFn: null`, honoring
|
|
647
|
+
* that class's own `'fetchFn' in opts` distinction -- see its constructor)
|
|
648
|
+
* still answers proxy requests, just with `ServerSharing`'s own `503`
|
|
649
|
+
* ("Fetch not available") for every one, exactly like calling
|
|
650
|
+
* `handleRequest()` directly would.
|
|
651
|
+
*
|
|
652
|
+
* This half is entirely OPT-IN: `createMeshRoutingService()` only
|
|
653
|
+
* constructs a `ServerSharing` instance, attaches its proxy dispatch, and
|
|
654
|
+
* adds `expose`/`unexpose`/`handleRequest`/`listExposed`/`getExposed`/
|
|
655
|
+
* `requestProxy` to `api` when the caller's options object has an OWN
|
|
656
|
+
* `fetchFn` key at all (checked via `'fetchFn' in opts`, matching
|
|
657
|
+
* `ServerSharing`'s own constructor distinction between "omitted" and
|
|
658
|
+
* "explicitly null") -- a caller that only wants multi-hop routing and
|
|
659
|
+
* never mentions `fetchFn` gets no `ServerSharing` instance, no second
|
|
660
|
+
* `ctx.onIncomingData()` subscription, and no server-sharing methods on
|
|
661
|
+
* `api` at all.
|
|
662
|
+
*
|
|
663
|
+
* ---------------------------------------------------------------------------
|
|
664
|
+
* EVENTS (`ctx.emit()`, see `mesh-service.mjs`'s "Observability events"
|
|
665
|
+
* section for the full convention) -- `MeshRouter`'s own pre-existing
|
|
666
|
+
* `on`/`off` surface (`'message'`/`'forward'`/`'route:add'`/`'route:remove'`)
|
|
667
|
+
* is bridged through verbatim, prefixed `mesh-routing:`:
|
|
668
|
+
*
|
|
669
|
+
* - `mesh-routing:message` -- the routed envelope, whenever `envelope.to`
|
|
670
|
+
* was this pod (`MeshRouter`'s own `'message'` event payload, unchanged).
|
|
671
|
+
* - `mesh-routing:forward` -- the (possibly TTL-decremented) envelope
|
|
672
|
+
* this pod just forwarded onward (`MeshRouter`'s own `'forward'` payload).
|
|
673
|
+
* - `mesh-routing:route-add` -- the new/updated `RouteEntry` (`MeshRouter`'s
|
|
674
|
+
* own `'route:add'` payload).
|
|
675
|
+
* - `mesh-routing:route-remove` -- `{ target }`, wrapping `MeshRouter`'s own
|
|
676
|
+
* `'route:remove'` payload (a bare targetPodId string) in an object, to
|
|
677
|
+
* match this file's other events and the family's general "emit an
|
|
678
|
+
* object" convention.
|
|
679
|
+
*
|
|
680
|
+
* Plus this file's own, for the `ServerSharing` half:
|
|
681
|
+
*
|
|
682
|
+
* - `mesh-routing:server-share-served` `{from, name, status}` -- a proxy
|
|
683
|
+
* request was answered (whatever the status).
|
|
684
|
+
* - `mesh-routing:server-share-timeout` `{to, name, method, path}` -- the
|
|
685
|
+
* CALLING side's `requestProxy()` gave up waiting.
|
|
686
|
+
*
|
|
687
|
+
* ---------------------------------------------------------------------------
|
|
688
|
+
* `ServerSharing` HAS NO `on`/`off` OF ITS OWN (confirmed by reading the
|
|
689
|
+
* class above -- unlike `MeshRouter`, it has no `#listeners`/`#emit()` at
|
|
690
|
+
* all). This is treated as intentional, not a gap to backfill here:
|
|
691
|
+
* `expose()`/`unexpose()`/`handleRequest()` are synchronous-ish local
|
|
692
|
+
* bookkeeping and request/response calls respectively, each with an
|
|
693
|
+
* immediately-observable return value at the call site -- there is no
|
|
694
|
+
* asynchronous background state transition (unlike `MeshRouter`'s routing
|
|
695
|
+
* table expiring, or `TransportHealthCheck`'s liveness state machine) that
|
|
696
|
+
* a caller could otherwise only learn about via an event. This file's own
|
|
697
|
+
* `mesh-routing:server-share-served`/`-timeout` events above already cover
|
|
698
|
+
* the one genuinely async, fire-and-forget-shaped thing `ServerSharing`
|
|
699
|
+
* gains once it's wired to the network (a remote proxy request being
|
|
700
|
+
* answered, or timing out).
|
|
701
|
+
*
|
|
702
|
+
* No browser-only imports at module level.
|
|
703
|
+
*/
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* @param {object} [opts]
|
|
707
|
+
* @param {number} [opts.maxTTL] - Forwarded to `MeshRouter` (default 8, see `ROUTING_DEFAULTS`).
|
|
708
|
+
* @param {number} [opts.routeCacheMs] - Forwarded to `MeshRouter` (default 60000, see `ROUTING_DEFAULTS`).
|
|
709
|
+
* @param {string} [opts.envelopeType='mesh-routing'] - `envelope.type` used for `MeshRouter` traffic.
|
|
710
|
+
* @param {Function} [opts.fetchFn] - If this key is present at all (even
|
|
711
|
+
* `null`), a `ServerSharing` instance is also constructed and wired --
|
|
712
|
+
* see module doc comment's "SERVER SHARING DESIGN" section. Passed
|
|
713
|
+
* straight through to `new ServerSharing({ fetchFn })`.
|
|
714
|
+
* @param {string} [opts.serverShareEnvelopeType='mesh-server-share'] -
|
|
715
|
+
* `envelope.type` used for `ServerSharing` proxy request/response traffic.
|
|
716
|
+
* Only relevant when `fetchFn` is supplied.
|
|
717
|
+
* @param {number} [opts.proxyTimeoutMs=10000] - How long `requestProxy()`
|
|
718
|
+
* waits for a matching proxy response. Only relevant when `fetchFn` is supplied.
|
|
719
|
+
* @param {Function} [opts.onLog]
|
|
720
|
+
* @returns {import('./mesh-service.mjs').MeshService}
|
|
721
|
+
*/
|
|
722
|
+
export function createMeshRoutingService(opts = {}) {
|
|
723
|
+
const {
|
|
724
|
+
maxTTL,
|
|
725
|
+
routeCacheMs,
|
|
726
|
+
envelopeType = DEFAULT_ROUTING_ENVELOPE_TYPE,
|
|
727
|
+
fetchFn,
|
|
728
|
+
serverShareEnvelopeType = DEFAULT_SERVER_SHARE_ENVELOPE_TYPE,
|
|
729
|
+
proxyTimeoutMs = DEFAULT_PROXY_TIMEOUT_MS,
|
|
730
|
+
onLog,
|
|
731
|
+
} = opts
|
|
732
|
+
const wireServerSharing = 'fetchFn' in opts
|
|
733
|
+
const log = onLog || (() => {})
|
|
734
|
+
|
|
735
|
+
return {
|
|
736
|
+
name: 'mesh-routing',
|
|
737
|
+
|
|
738
|
+
attach(peerNode, ctx) {
|
|
739
|
+
const localPodId = peerNode.podId
|
|
740
|
+
|
|
741
|
+
// -----------------------------------------------------------------
|
|
742
|
+
// MeshRouter -- see module doc comment's "MULTI-HOP ROUTING DESIGN".
|
|
743
|
+
// -----------------------------------------------------------------
|
|
744
|
+
const router = new MeshRouter({
|
|
745
|
+
localPodId,
|
|
746
|
+
forwardFn: (nextHop, envelope) => {
|
|
747
|
+
ctx.sendTo(nextHop, envelopeType, envelope).catch((err) => {
|
|
748
|
+
log('mesh-routing:forward-send-failed', {
|
|
749
|
+
nextHop,
|
|
750
|
+
to: envelope?.to,
|
|
751
|
+
error: err?.message || String(err),
|
|
752
|
+
})
|
|
753
|
+
})
|
|
754
|
+
},
|
|
755
|
+
maxTTL,
|
|
756
|
+
routeCacheMs,
|
|
757
|
+
onLog: (msg) => log('mesh-routing:router-log', { message: msg }),
|
|
758
|
+
})
|
|
759
|
+
|
|
760
|
+
// Bridge MeshRouter's own pre-existing on()/off() events through
|
|
761
|
+
// ctx.emit() -- see module doc comment's "EVENTS" section.
|
|
762
|
+
const onRouterMessage = (envelope) => ctx.emit('mesh-routing:message', envelope)
|
|
763
|
+
const onRouterForward = (envelope) => ctx.emit('mesh-routing:forward', envelope)
|
|
764
|
+
const onRouterRouteAdd = (entry) => ctx.emit('mesh-routing:route-add', entry)
|
|
765
|
+
const onRouterRouteRemove = (target) => ctx.emit('mesh-routing:route-remove', { target })
|
|
766
|
+
router.on('message', onRouterMessage)
|
|
767
|
+
router.on('forward', onRouterForward)
|
|
768
|
+
router.on('route:add', onRouterRouteAdd)
|
|
769
|
+
router.on('route:remove', onRouterRouteRemove)
|
|
770
|
+
|
|
771
|
+
const unsubscribeRouting = ctx.onIncomingData(envelopeType, (fromPubKey, envelope) => {
|
|
772
|
+
router.handleRoutedMessage(envelope)
|
|
773
|
+
})
|
|
774
|
+
|
|
775
|
+
const api = {
|
|
776
|
+
route: (targetPodId, message) => router.route(targetPodId, message),
|
|
777
|
+
addRoute: (targetPodId, nextHop, hops, ttl) => router.addRoute(targetPodId, nextHop, hops, ttl),
|
|
778
|
+
removeRoute: (targetPodId) => router.removeRoute(targetPodId),
|
|
779
|
+
getRoute: (targetPodId) => router.getRoute(targetPodId),
|
|
780
|
+
addDirectPeer: (podId) => router.addDirectPeer(podId),
|
|
781
|
+
removeDirectPeer: (podId) => router.removeDirectPeer(podId),
|
|
782
|
+
listDirectPeers: () => router.listDirectPeers(),
|
|
783
|
+
listRoutes: () => router.listRoutes(),
|
|
784
|
+
pruneExpired: (now) => router.pruneExpired(now),
|
|
785
|
+
toJSON: () => router.toJSON(),
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// -----------------------------------------------------------------
|
|
789
|
+
// ServerSharing (opt-in) -- see module doc comment's "SERVER SHARING
|
|
790
|
+
// DESIGN" section.
|
|
791
|
+
// -----------------------------------------------------------------
|
|
792
|
+
let serverSharing = null
|
|
793
|
+
let unsubscribeServerShare = null
|
|
794
|
+
/** @type {Map<string, {resolve: Function, reject: Function, timer: ReturnType<typeof setTimeout>}>} */
|
|
795
|
+
const pendingProxyRequests = new Map()
|
|
796
|
+
|
|
797
|
+
if (wireServerSharing) {
|
|
798
|
+
serverSharing = new ServerSharing({
|
|
799
|
+
localPodId,
|
|
800
|
+
fetchFn,
|
|
801
|
+
onLog: (msg) => log('mesh-routing:server-share-log', { message: msg }),
|
|
802
|
+
})
|
|
803
|
+
|
|
804
|
+
let proxyReqSeq = 0
|
|
805
|
+
const nextProxyRequestId = () => `${localPodId}:${Date.now()}:${++proxyReqSeq}`
|
|
806
|
+
|
|
807
|
+
async function handleProxyRequest(fromPubKey, msg) {
|
|
808
|
+
const { requestId } = msg
|
|
809
|
+
let result
|
|
810
|
+
try {
|
|
811
|
+
result = await serverSharing.handleRequest({
|
|
812
|
+
name: msg.name,
|
|
813
|
+
method: msg.method,
|
|
814
|
+
path: msg.path,
|
|
815
|
+
headers: msg.headers,
|
|
816
|
+
body: msg.body,
|
|
817
|
+
})
|
|
818
|
+
} catch (err) {
|
|
819
|
+
// handleRequest() already catches its own fetchFn errors (see
|
|
820
|
+
// ServerSharing.handleRequest()'s 502 path) -- reaching here
|
|
821
|
+
// would mean something else entirely went wrong; still never
|
|
822
|
+
// let it become an unhandled rejection or crash the shared
|
|
823
|
+
// dispatch loop.
|
|
824
|
+
result = { status: 500, headers: {}, body: `Proxy handling error: ${err?.message || err}` }
|
|
825
|
+
}
|
|
826
|
+
const status = typeof result?.status === 'number' ? result.status : 200
|
|
827
|
+
const headers = result?.headers && typeof result.headers === 'object' ? result.headers : {}
|
|
828
|
+
const body = result && 'body' in result ? result.body : undefined
|
|
829
|
+
try {
|
|
830
|
+
await ctx.sendTo(fromPubKey, serverShareEnvelopeType, {
|
|
831
|
+
kind: 'proxy-response', requestId, status, headers, body,
|
|
832
|
+
})
|
|
833
|
+
ctx.emit('mesh-routing:server-share-served', { from: fromPubKey, name: msg.name, status })
|
|
834
|
+
} catch (err) {
|
|
835
|
+
log('mesh-routing:server-share-response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
function handleProxyResponse(msg) {
|
|
840
|
+
const pending = pendingProxyRequests.get(msg.requestId)
|
|
841
|
+
if (!pending) return // no longer waiting (already timed out, or not ours) -- ignore
|
|
842
|
+
pendingProxyRequests.delete(msg.requestId)
|
|
843
|
+
clearTimeout(pending.timer)
|
|
844
|
+
pending.resolve({ status: msg.status, headers: msg.headers || {}, body: msg.body })
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
unsubscribeServerShare = ctx.onIncomingData(serverShareEnvelopeType, (fromPubKey, msg) => {
|
|
848
|
+
if (!msg || typeof msg.kind !== 'string') return
|
|
849
|
+
if (msg.kind === 'proxy-request') {
|
|
850
|
+
handleProxyRequest(fromPubKey, msg).catch((err) => {
|
|
851
|
+
log('mesh-routing:server-share-request-handling-failed', { from: fromPubKey, requestId: msg.requestId, error: err?.message || String(err) })
|
|
852
|
+
})
|
|
853
|
+
} else if (msg.kind === 'proxy-response') {
|
|
854
|
+
handleProxyResponse(msg)
|
|
855
|
+
}
|
|
856
|
+
})
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* Ask `podId` (a peer that has `expose()`d `name`) to proxy an HTTP
|
|
860
|
+
* request to its locally exposed server, and await the response.
|
|
861
|
+
* @param {string} podId
|
|
862
|
+
* @param {{name: string, method?: string, path?: string, headers?: object, body?: *}} req
|
|
863
|
+
* @returns {Promise<{status: number, headers: object, body: *}>}
|
|
864
|
+
*/
|
|
865
|
+
async function requestProxy(podId, { name, method = 'GET', path = '/', headers = {}, body } = {}) {
|
|
866
|
+
const requestId = nextProxyRequestId()
|
|
867
|
+
|
|
868
|
+
const promise = new Promise((resolve, reject) => {
|
|
869
|
+
const timer = setTimeout(() => {
|
|
870
|
+
pendingProxyRequests.delete(requestId)
|
|
871
|
+
ctx.emit('mesh-routing:server-share-timeout', { to: podId, name, method, path })
|
|
872
|
+
reject(new Error(`mesh-routing: proxy request ${method} ${path} (server "${name}") to ${podId} timed out after ${proxyTimeoutMs}ms`))
|
|
873
|
+
}, proxyTimeoutMs)
|
|
874
|
+
pendingProxyRequests.set(requestId, { resolve, reject, timer })
|
|
875
|
+
})
|
|
876
|
+
|
|
877
|
+
try {
|
|
878
|
+
await ctx.sendTo(podId, serverShareEnvelopeType, { kind: 'proxy-request', requestId, name, method, path, headers, body })
|
|
879
|
+
} catch (err) {
|
|
880
|
+
const pending = pendingProxyRequests.get(requestId)
|
|
881
|
+
if (pending) {
|
|
882
|
+
clearTimeout(pending.timer)
|
|
883
|
+
pendingProxyRequests.delete(requestId)
|
|
884
|
+
}
|
|
885
|
+
throw err
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
return promise
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
api.expose = (port, name, exposeOpts) => serverSharing.expose(port, name, exposeOpts)
|
|
892
|
+
api.unexpose = (name) => serverSharing.unexpose(name)
|
|
893
|
+
api.handleRequest = (request) => serverSharing.handleRequest(request)
|
|
894
|
+
api.listExposed = () => serverSharing.listExposed()
|
|
895
|
+
api.getExposed = (name) => serverSharing.getExposed(name)
|
|
896
|
+
api.requestProxy = requestProxy
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
return {
|
|
900
|
+
api,
|
|
901
|
+
teardown() {
|
|
902
|
+
router.off('message', onRouterMessage)
|
|
903
|
+
router.off('forward', onRouterForward)
|
|
904
|
+
router.off('route:add', onRouterRouteAdd)
|
|
905
|
+
router.off('route:remove', onRouterRouteRemove)
|
|
906
|
+
unsubscribeRouting()
|
|
907
|
+
if (unsubscribeServerShare) unsubscribeServerShare()
|
|
908
|
+
for (const pending of pendingProxyRequests.values()) {
|
|
909
|
+
clearTimeout(pending.timer)
|
|
910
|
+
pending.reject(new Error('mesh-routing: service torn down while a proxy request was still in flight'))
|
|
911
|
+
}
|
|
912
|
+
pendingProxyRequests.clear()
|
|
913
|
+
},
|
|
914
|
+
}
|
|
915
|
+
},
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
export { DEFAULT_ROUTING_ENVELOPE_TYPE, DEFAULT_SERVER_SHARE_ENVELOPE_TYPE, DEFAULT_PROXY_TIMEOUT_MS }
|