Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support MessageChannel in bridge.js #3566

Merged
merged 5 commits into from
Jul 21, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/annotator/cross-frame.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ export class CrossFrame {
};

// Initiate connection to the sidebar.
const onDiscoveryCallback = (source, origin, token) =>
bridge.createChannel(source, origin, token);
discovery.startDiscovery(onDiscoveryCallback);
discovery.startDiscovery((source, origin, token) =>
bridge.createChannel({ source, origin, token })
);
frameObserver.observe(injectIntoFrame, iframeUnloaded);

/**
Expand Down
6 changes: 5 additions & 1 deletion src/annotator/test/cross-frame-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,11 @@ describe('CrossFrame', () => {
createCrossFrame();
fakeDiscovery.startDiscovery.yield('SOURCE', 'ORIGIN', 'TOKEN');
assert.called(fakeBridge.createChannel);
assert.calledWith(fakeBridge.createChannel, 'SOURCE', 'ORIGIN', 'TOKEN');
assert.calledWith(fakeBridge.createChannel, {
source: 'SOURCE',
origin: 'ORIGIN',
token: 'TOKEN',
});
});
});

Expand Down
79 changes: 72 additions & 7 deletions src/shared/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default class Bridge {
this.links = [];
/** @type {Record<string, (...args: any[]) => void>} */
this.channelListeners = {};
/** @type {Array<(channel: RPC, window: Window) => void>} */
/** @type {Array<(channel: RPC, window?: Window) => void>} */
this.onConnectListeners = [];
}

Expand All @@ -27,18 +27,83 @@ export default class Bridge {
this.links.forEach(channel => channel.destroy());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Array.from usage here was probably a hangover from semi-automated CoffeeScript => JS conversion. The decaffeinate tool that we used for some of this conversion added Array.from in some places to be conservative.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I makes sense.

}

/**
* Deprecated - Remove after MessagePort conversion
* @typedef windowOptions
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* @typedef windowOptions
* @typedef WindowOptions

Type names should use PascalCase. I'd probably have gone for something without an Options suffix since that tends to imply optional parameters. In this case the object is really a combination of a Window + origin. Maybe something like WindowTarget (as in fields needed to send messages to a particular window target)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed a commit that keeps the name but just converts it to PascalCase.

* @prop {Window} source - The source window
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think using the term source is potentially a little confusing here because this window is both a source of messages that trigger on callbacks and a target of messages sent with call. Also when the RPC channel is constructed, the source is passed as the destFrameOrPort argument.

Naming this target would be misleading for the same reason and naming it window could cause it to be confused with the window global. So perhaps just revising the documentation to something like @prop {Window} source - The window to communicate with would be enough for now.

* @prop {string} origin - The origin of the document in `source`
* @prop {string} token - Shared token between the `source` and this window
* agreed during the discovery process
*/

/**
* Create a communication channel between frames using either `MessagePort` or
* `Window`.
*
* The created channel is added to the list of channels which `call`
* and `on` send and receive messages over.
*
* @param {windowOptions|MessagePort} options
* @return {RPC} - Channel for communicating with the window.
*/
createChannel(options) {
if (options instanceof MessagePort) {
return this._createChannelForPort(options);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR will result on a reduction in code coverage, which will be fix by #3598.

PR #3566 adds integration tests, but I don't see a reason not to add unit tests here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed a commit that adds a few extra tests to cover the new code paths.

} else {
// Deprecated - Remove after MessagePort conversion
return this._createChannelForWindow(options);
}
}

/**
* Create a communication channel using a `MessagePort`.
*
* The created channel is added to the list of channels which `call`
* and `on` send and receive messages over.
*
* @param {MessagePort} port
* @return {RPC} - Channel for communicating with the window.
*/
_createChannelForPort(port) {
const listeners = { connect: cb => cb(), ...this.channelListeners };

// Set up a channel
const channel = new RPC(
window /* dummy */,
port,
'*' /* dummy */,
listeners
);

let connected = false;
const ready = () => {
if (connected) {
return;
}
connected = true;
this.onConnectListeners.forEach(cb => cb(channel));
};

// Fire off a connection attempt
channel.call('connect', ready);

// Store the newly created channel in our collection
this.links.push(channel);

return channel;
}

/**
* Create a communication channel between this window and `source`.
*
* The created channel is added to the list of channels which `call`
* and `on` send and receive messages over.
*
* @param {Window} source - The source window.
* @param {string} origin - The origin of the document in `source`.
* @param {string} token
* @param {windowOptions} options
* @return {RPC} - Channel for communicating with the window.
* @deprecated
*/
createChannel(source, origin, token) {
_createChannelForWindow({ source, origin, token }) {
let channel = null;
let connected = false;

Expand All @@ -53,7 +118,7 @@ export default class Bridge {
const connect = (_token, cb) => {
if (_token === token) {
cb();
ready();
ready(); // This is necessary for testing only.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This raised eyebrows. Why do we have testing-only code in this callback? Since there is a callback being invoked here it seems to me that the tests should try to leverage that.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed a commit that reworks the tests to avoid the need for the ready() callback here. This means that the MessagePort and Window code paths are now the same except that the Window code path checks the token before invoking the callback.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left the code as it was originally (since it will be removed anyway), but I added the comment, because like you said, it didn't look right.

}
};

Expand Down Expand Up @@ -162,7 +227,7 @@ export default class Bridge {
/**
* Add a listener to be called upon a new connection.
*
* @param {(channel: RPC, window: Window) => void} listener
* @param {(channel: RPC, window?: Window) => void} listener
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at the callers of onConnect, none of them make use of the window argument, so we can just drop it.

  • The Guest class invokes onConnect indirectly (via CrossFrame) with no arguments
  • The FrameSync service invokes onConnect but only uses the first argument

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed a commit that removes the window argument.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏼

*/
onConnect(listener) {
this.onConnectListeners.push(listener);
Expand Down
46 changes: 25 additions & 21 deletions src/shared/test/bridge-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ describe('shared/bridge', () => {
bridge = new Bridge();

createChannel = () =>
bridge.createChannel(fakeWindow, 'http://example.com', 'TOKEN');
bridge.createChannel({
source: fakeWindow,
origin: 'http://example.com',
token: 'TOKEN',
});

fakeWindow = {
postMessage: sandbox.stub(),
Expand Down Expand Up @@ -85,11 +89,11 @@ describe('shared/bridge', () => {

it('calls a callback when all channels return successfully', done => {
const channel1 = createChannel();
const channel2 = bridge.createChannel(
fakeWindow,
'http://example.com',
'NEKOT'
);
const channel2 = bridge.createChannel({
source: fakeWindow,
origin: 'http://example.com',
token: 'NEKOT',
});
channel1.call.yields(null, 'result1');
channel2.call.yields(null, 'result2');

Expand All @@ -105,11 +109,11 @@ describe('shared/bridge', () => {
it('calls a callback with an error when a channels fails', done => {
const error = new Error('Uh oh');
const channel1 = createChannel();
const channel2 = bridge.createChannel(
fakeWindow,
'http://example.com',
'NEKOT'
);
const channel2 = bridge.createChannel({
source: fakeWindow,
origin: 'http://example.com',
token: 'NEKOT',
});
channel1.call.throws(error);
channel2.call.yields(null, 'result2');

Expand Down Expand Up @@ -260,16 +264,16 @@ describe('shared/bridge', () => {

describe('#destroy', () =>
it('destroys all opened channels', () => {
const channel1 = bridge.createChannel(
fakeWindow,
'http://example.com',
'foo'
);
const channel2 = bridge.createChannel(
fakeWindow,
'http://example.com',
'bar'
);
const channel1 = bridge.createChannel({
source: fakeWindow,
origin: 'http://example.com',
token: 'foo',
});
const channel2 = bridge.createChannel({
source: fakeWindow,
origin: 'http://example.com',
token: 'bar',
});

bridge.destroy();

Expand Down
4 changes: 3 additions & 1 deletion src/sidebar/services/frame-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,9 @@ export class FrameSyncService {
};

const discovery = new Discovery(window, { server: true });
discovery.startDiscovery(this._bridge.createChannel.bind(this._bridge));
discovery.startDiscovery((source, origin, token) =>
this._bridge.createChannel({ source, origin, token })
);
this._bridge.onConnect(addFrame);

this._setupSyncToFrame();
Expand Down