Skip to content

Commit

Permalink
feat: bidirectional loopback with makeNear
Browse files Browse the repository at this point in the history
  • Loading branch information
dtribble committed Sep 7, 2020
1 parent 0f722c0 commit 4e29d20
Showing 1 changed file with 25 additions and 15 deletions.
40 changes: 25 additions & 15 deletions packages/captp/lib/captp.js
Original file line number Diff line number Diff line change
Expand Up @@ -370,42 +370,52 @@ export function makeCapTP(ourId, rawSend, bootstrapObj = undefined, opts = {}) {
* Create an async-isolated channel to an object.
*
* @param {string} ourId
* @returns {{ makeFar<T>(x: T): ERef<T> }}
zcf * @returns {{ makeFar<T>(x: T): ERef<T>, makeNear<T>(x: T): ERef<T> }}
*/
export function makeLoopback(ourId) {
let nextNonce = 0;
const nonceToRef = new Map();

const bootstrap = harden({
refGetter: {
getRef(nonce) {
// Find the local ref for the specified nonce.
const xFar = nonceToRef.get(nonce);
nonceToRef.delete(nonce);
return xFar;
},
},
});

// Create the tunnel.
let remoteDispatch;
const { dispatch: localDispatch, getBootstrap } = makeCapTP(
const { dispatch: localDispatch, getBootstrap: getFarBootstrap } = makeCapTP(
`local-${ourId}`,
o => remoteDispatch(o),
bootstrap,
);
const { dispatch } = makeCapTP(
const { dispatch, getBootstrap: getNearBootstrap } = makeCapTP(
`remote-${ourId}`,
localDispatch,
harden({
farGetter: {
getRef(nonce) {
// Find the local ref for the specified nonce.
const xNear = nonceToRef.get(nonce);
nonceToRef.delete(nonce);
return xNear;
},
},
}),
bootstrap,
);
remoteDispatch = dispatch;

const farGetter = E.G(getBootstrap()).farGetter;
const farGetter = E.G(getFarBootstrap()).refGetter;
const nearGetter = E.G(getNearBootstrap()).refGetter;

async function makeFar(xNear) {
const myNonce = nextNonce;
nextNonce += 1;
nonceToRef.set(myNonce, harden(xNear));
return E(farGetter).getRef(myNonce);
}
async function makeNear(xFar) {
const myNonce = nextNonce;
nextNonce += 1;
nonceToRef.set(myNonce, harden(xFar));
return E(nearGetter).getRef(myNonce);
}

return { makeFar };
return { makeFar, makeNear };
}

0 comments on commit 4e29d20

Please sign in to comment.