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

feat: Introduce a library for embedded iframe <-> host communication #18652

Merged
merged 14 commits into from
Feb 12, 2022
2 changes: 1 addition & 1 deletion superset-embedded-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"module": "lib/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc & babel src --out-dir lib --extensions '.ts,.tsx' & webpack --mode production",
"build": "tsc ; babel src --out-dir lib --extensions '.ts,.tsx' ; webpack --mode production",
Copy link
Member Author

Choose a reason for hiding this comment

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

I didn't realize this before but & actually starts a process in the background instead of working like Promise.all

Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
"build": "tsc ; babel src --out-dir lib --extensions '.ts,.tsx' ; webpack --mode production",
"build": "tsc && babel src --out-dir lib --extensions '.ts,.tsx' && webpack --mode production",

I suggest use && to execute that in series only if the predecessor was successful. In other words, stop as soon as an error occurs.

Copy link
Member Author

@suddjian suddjian Feb 11, 2022

Choose a reason for hiding this comment

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

These aren't really dependent on each other's result. Running each of them regardless of the others' status can output more useful information in the case of an error. Ideally I'd like to run them in parallel and wait for all to complete before the command exits, but I am not familiar with a convenient way to do that without writing a script, and that seems like overkill since these all run in about a second.

"ci:release": "node ./release-if-necessary.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
Expand Down
27 changes: 21 additions & 6 deletions superset-embedded-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@

import { IFRAME_COMMS_MESSAGE_TYPE } from './const';

// We can swap this out for the actual switchboard package once it gets published
import { Switchboard } from '../../superset-frontend/packages/superset-ui-switchboard/src/switchboard';

/**
* The function to fetch a guest token from your Host App's backend server.
* The Host App backend must supply an API endpoint
Expand All @@ -37,6 +40,15 @@ export type EmbedDashboardParams = {
fetchGuestToken: GuestTokenFetchFn
}

export type Size = {
width: number, height: number
}

export type EmbeddedDashboard = {
getScrollSize: () => Promise<Size>
unmount: () => void
}

/**
* Embeds a Superset dashboard into the page using an iframe.
*/
Expand All @@ -45,14 +57,14 @@ export async function embedDashboard({
supersetDomain,
mountPoint,
fetchGuestToken
}: EmbedDashboardParams) {
}: EmbedDashboardParams): Promise<EmbeddedDashboard> {
function log(...info: unknown[]) {
console.debug(`[superset-embedded-sdk][dashboard ${id}]`, ...info);
}

log('embedding');

async function mountIframe(): Promise<MessagePort> {
async function mountIframe(): Promise<Switchboard> {
return new Promise(resolve => {
const iframe = document.createElement('iframe');

Expand Down Expand Up @@ -83,7 +95,7 @@ export async function embedDashboard({
log('sent message channel to the iframe');

// return our port from the promise
resolve(ourPort);
resolve(new Switchboard(ourPort));
});

iframe.src = `${supersetDomain}/dashboard/${id}/embedded`;
Expand All @@ -94,18 +106,21 @@ export async function embedDashboard({

const [guestToken, ourPort] = await Promise.all([
fetchGuestToken(),
mountIframe()
mountIframe(),
]);

ourPort.postMessage({ guestToken });
ourPort.emit('guestToken', { guestToken });
log('sent guest token');

function unmount() {
log('unmounting');
mountPoint.replaceChildren();
}

const getScrollSize = () => ourPort.get<Size>('getScrollSize');

return {
unmount
getScrollSize,
unmount,
};
}
13 changes: 13 additions & 0 deletions superset-frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions superset-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"@superset-ui/plugin-chart-table": "file:./plugins/plugin-chart-table",
"@superset-ui/plugin-chart-word-cloud": "file:./plugins/plugin-chart-word-cloud",
"@superset-ui/preset-chart-xy": "file:./plugins/preset-chart-xy",
"@superset-ui/switchboard": "file:./packages/switchboard",
"@vx/responsive": "^0.0.195",
"abortcontroller-polyfill": "^1.1.9",
"antd": "^4.9.4",
Expand Down
33 changes: 33 additions & 0 deletions superset-frontend/packages/superset-ui-switchboard/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@superset-ui/switchboard",
"version": "0.18.25",
"description": "Switchboard is a library to make it easier to communicate across browser windows using the MessageChannel API",
"sideEffects": false,
"main": "lib/index.js",
"module": "esm/index.js",
"files": [
"esm",
"lib"
],
"repository": {
"type": "git",
"url": "git+https://github.com/apache/superset.git"
},
"keywords": [
"switchboard",
"iframe",
"communication",
"messagechannel",
"messageport",
"postmessage"
],
"author": "Superset",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/apache/superset/issues"
},
"homepage": "https://github.com/apache/superset#readme",
"publishConfig": {
"access": "public"
}
}
20 changes: 20 additions & 0 deletions superset-frontend/packages/superset-ui-switchboard/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

export * from './switchboard';
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { Switchboard } from './switchboard';

type EventHandler = (event: MessageEvent) => void;

// A note on these fakes:
//
// jsdom doesn't supply a MessageChannel or a MessagePort,
// so we have to build our own unless we want to unit test in-browser.
// Might want to open a PR in jsdom: https://github.com/jsdom/jsdom/issues/2448

/** Matches the MessagePort api as closely as necessary (it's a small api) */
class FakeMessagePort {
otherPort?: FakeMessagePort;
isStarted = false;
queue: MessageEvent[] = [];
listeners: Set<EventHandler> = new Set();

dispatchEvent(event: MessageEvent) {
if (this.isStarted) {
for (let listener of this.listeners) {
try {
listener(event);
} catch (err) {
// whatever browsers do here, idk
}
}
} else {
this.queue.push(event);
}
return true;
}

addEventListener(eventType: 'message', handler: EventHandler) {
this.listeners.add(handler);
}

removeEventListener(eventType: 'message', handler: EventHandler) {
this.listeners.delete(handler);
}

postMessage(data: any) {
this.otherPort!.dispatchEvent({ data } as MessageEvent);
}

start() {
if (this.isStarted) return;
this.isStarted = true;
for (let event of this.queue) {
this.dispatchEvent(event);
}
this.queue = [];
}

close() {
this.isStarted = false;
}

onmessage = null;
onmessageerror = null;
}

/** Matches the MessageChannel api as closely as necessary (an even smaller api than MessagePort) */
class FakeMessageChannel {
port1: MessagePort;
port2: MessagePort;

constructor() {
const port1 = new FakeMessagePort();
const port2 = new FakeMessagePort();
port1.otherPort = port2;
port2.otherPort = port1;
this.port1 = port1;
this.port2 = port2;
}
}

describe('comms', () => {
beforeAll(() => {
global.MessageChannel = FakeMessageChannel; // yolo
console.debug = () => {}; // silencio bruno
});

describe('emit', () => {
it('triggers the method', async () => {
const channel = new MessageChannel();
const ours = new Switchboard(channel.port1, 'ours');
const theirs = new Switchboard(channel.port2, 'theirs');
const handler = jest.fn();

theirs.defineMethod('someEvent', handler);
theirs.start();

ours.emit('someEvent', 42);

expect(handler).toHaveBeenCalledWith(42);
});
});

describe('get', () => {
it('returns the value', async () => {
const channel = new MessageChannel();
const ours = new Switchboard(channel.port1, 'ours');
const theirs = new Switchboard(channel.port2, 'theirs');
theirs.defineMethod('theirMethod', ({ x }: { x: number }) =>
Promise.resolve(x + 42),
);
theirs.start();

const value = await ours.get('theirMethod', { x: 1 });

expect(value).toEqual(43);
});

it('can handle one way concurrency', async () => {
const channel = new MessageChannel();
const ours = new Switchboard(channel.port1, 'ours');
const theirs = new Switchboard(channel.port2, 'theirs');
theirs.defineMethod('theirMethod', () => Promise.resolve(42));
theirs.defineMethod(
'theirMethod2',
() => new Promise(resolve => setImmediate(() => resolve(420))),
);
theirs.start();

const [value1, value2] = await Promise.all([
ours.get('theirMethod'),
ours.get('theirMethod2'),
]);

expect(value1).toEqual(42);
expect(value2).toEqual(420);
});

it('can handle two way concurrency', async () => {
const channel = new MessageChannel();
const ours = new Switchboard(channel.port1, 'ours');
const theirs = new Switchboard(channel.port2, 'theirs');
theirs.defineMethod('theirMethod', () => Promise.resolve(42));
ours.defineMethod(
'ourMethod',
() => new Promise(resolve => setImmediate(() => resolve(420))),
);
theirs.start();

const [value1, value2] = await Promise.all([
ours.get('theirMethod'),
theirs.get('ourMethod'),
]);

expect(value1).toEqual(42);
expect(value2).toEqual(420);
});
});
});