Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
39 changes: 39 additions & 0 deletions tensorboard/components/plugin_util/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package(default_visibility = ["//tensorboard:internal"])

load("//tensorboard/defs:web.bzl", "tf_web_library")

licenses(["notice"]) # Apache 2.0

tf_web_library(
name = "plugin_host",
srcs = [
"plugin-host.html",
"plugin-host.ts",
],
path = "/tf-plugin",
deps = [
":plugin_lib",
"//tensorboard/components/tf_backend",
],
)

tf_web_library(
name = "plugin_lib",
srcs = [
"message.ts",
],
path = "/tf-plugin",
)

tf_web_library(
name = "plugin_guest",
srcs = [
"plugin-guest.html",
"plugin-guest.ts",
],
path = "/tf-plugin",
visibility = ["//visibility:public"],
deps = [
":plugin_lib",
],
)
123 changes: 123 additions & 0 deletions tensorboard/components/plugin_util/message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed 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 type PayloadType =
| null
| undefined
| string
| string[]
| boolean
| boolean[]
| number
| number[]
| object
| object[];

export interface Message {
type: string;
id: string;
payload: PayloadType;
error: string | null;
}

export type MessageType = string;
export type MessageCallback = (payload: any) => any;

interface PromiseResolver {
resolve: (data: any) => void;
reject: (error: Error) => void;
}

export abstract class IPC {
private idPrefix: string;
private id = 0;
private readonly responseWaits = new Map<string, PromiseResolver>();
private readonly listeners = new Map<MessageType, MessageCallback>();

constructor() {
window.addEventListener('message', this.onMessage.bind(this));

// TODO(tensorboard-team): remove this by using MessageChannel.
const randomArray = new Uint8Array(16);
window.crypto.getRandomValues(randomArray);
Copy link
Contributor

Choose a reason for hiding this comment

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

This is creative!

Our API is good, so let's continue with this. In a followup, it would be neat to try using MessageChannels to replace the crypto-prefixing.
[1] https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel

this.idPrefix = Array.from(randomArray)
.map((int: number) => int.toString(16))
.join('');
}

listen(type: MessageType, callback: MessageCallback) {
this.listeners.set(type, callback);
}

unlisten(type: MessageType) {
this.listeners.delete(type);
}

private async onMessage(event: MessageEvent) {
// There are instances where random browser extensions send messages.
if (typeof event.data !== 'string') return;

const message = JSON.parse(event.data) as Message;
const callback = this.listeners.get(message.type);

if (this.responseWaits.has(message.id)) {
const {id, payload, error} = message;
const {resolve, reject} = this.responseWaits.get(id);
this.responseWaits.delete(id);
if (error) {
reject(new Error(error));
} else {
resolve(payload);
}
return;
}

let payload = null;
let error = null;
if (this.listeners.has(message.type)) {
const callback = this.listeners.get(message.type);
try {
const result = await callback(message.payload);
payload = result;
} catch (e) {
error = e;
}
}
const replyMessage: Message = {
type: message.type,
id: message.id,
payload,
error,
};
this.postMessage(event.source, JSON.stringify(replyMessage));
}

private postMessage(targetWindow: Window, message: string) {
targetWindow.postMessage(message, '*');
}

protected sendMessageToWindow(
targetWindow: Window,
type: MessageType,
payload: PayloadType
): Promise<PayloadType> {
const id = `${this.idPrefix}_${this.id++}`;
const message: Message = {type, id, payload, error: null};
this.postMessage(targetWindow, JSON.stringify(message));
return new Promise((resolve, reject) => {
this.responseWaits.set(id, {resolve, reject});
});
}
}
18 changes: 18 additions & 0 deletions tensorboard/components/plugin_util/plugin-guest.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!--
@license
Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed 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.
-->
<script src="plugin-guest.js"></script>
<script src="message.js"></script>
47 changes: 47 additions & 0 deletions tensorboard/components/plugin_util/plugin-guest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed 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 {IPC, Message, MessageType, PayloadType} from './message.js';

class GuestIPC extends IPC {
/**
* payload must be JSON serializable.
*/
sendMessage(type: MessageType, payload: PayloadType): Promise<PayloadType> {
return this.sendMessageToWindow(window.parent, type, payload);
}
}

// Only export for testability.
export const _guestIPC = new GuestIPC();

/**
* Sends a message to the parent frame.
* @return Promise that resolves with a payload from parent in response to this message.
*
* @example
* const someList = await sendMessage('v1.some.type.parent.understands');
* // do fun things with someList.
*/
export const sendMessage = _guestIPC.sendMessage.bind(_guestIPC);

/**
* Subscribes a callback to a message with particular type.
*/
export const listen = _guestIPC.listen.bind(_guestIPC);

/**
* Unsubscribes a callback to a message.
*/
export const unlisten = _guestIPC.unlisten.bind(_guestIPC);
20 changes: 20 additions & 0 deletions tensorboard/components/plugin_util/plugin-host.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!--
@license
Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed 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.
-->
<link rel="import" href="../tf-backend/tf-backend.html" />

<script src="message.js"></script>
<script src="plugin-host.js"></script>
57 changes: 57 additions & 0 deletions tensorboard/components/plugin_util/plugin-host.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed 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 {IPC, Message, MessageType, PayloadType} from './message.js';

class HostIPC extends IPC {
sendMessage(
iframe: HTMLIFrameElement,
type: MessageType,
payload: PayloadType
): Promise<PayloadType> {
return this.sendMessageToWindow(iframe.contentWindow, type, payload);
}
}

const hostIPC = new HostIPC();
const _listen = hostIPC.listen.bind(hostIPC);
const _unlisten = hostIPC.unlisten.bind(hostIPC);
const _sendMessage = hostIPC.sendMessage.bind(hostIPC);

export const sendMessage = _sendMessage;
export const listen = _listen;
export const unlisten = _unlisten;

// Export for testability.
export const _hostIPC = hostIPC;

namespace tf_plugin {
/**
* Sends a message to the frame specified.
* @return Promise that resolves with a payload from frame in response to the message.
*
* @example
* const someList = await sendMessage('v1.some.type.guest.understands');
* // do fun things with someList.
*/
export const sendMessage = _sendMessage;
/**
* Subscribes to messages from specified frame of a type specified.
*/
export const listen = _listen;
/**
* Unsubscribes to messages from specified frame of a type specified.
*/
export const unlisten = _unlisten;
} // namespace tf_plugin
60 changes: 60 additions & 0 deletions tensorboard/components/plugin_util/test/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package(
default_testonly = True,
default_visibility = ["//tensorboard:internal"],
)

load("//tensorboard/defs:web.bzl", "tf_web_library", "tf_web_test")
load("//tensorboard/defs:vulcanize.bzl", "tensorboard_html_binary")

licenses(["notice"]) # Apache 2.0

tf_web_test(
name = "test",
web_library = ":test_web_library",
src = "/tf-plugin/test/test_binary.html"
)

# HACK: specifying tensorboard_html_binary on tf_web_test causes certain
# environment to throw exception but wrapping tensorbard_html_binary with
# tf_web_library seems to be okay.
tf_web_library(
name = "test_web_library",
srcs = [
":test_binary.html",
],
path = "/tf-plugin/test",
deps = [
":test_lib",
"//tensorboard/components/tf_imports:web_component_tester",
],
)

tensorboard_html_binary(
name = "test_binary",
# Disable advanced optimization to prevent check for WebComponentTester
# gobals.
compilation_level = "SIMPLE",
# Requires for compiling `import`s away.
compile = True,
input_path = "/tf-plugin/test/tests.html",
output_path = "/tf-plugin/test/test_binary.html",
deps = [
":test_lib",
],
)

tf_web_library(
name = "test_lib",
srcs = [
"iframe.html",
"iframe.ts",
"plugin-test.ts",
"tests.html",
],
path = "/tf-plugin/test",
deps = [
"//tensorboard/components/plugin_util:plugin_host",
"//tensorboard/components/plugin_util:plugin_guest",
"//tensorboard/components/tf_imports:web_component_tester",
],
)
20 changes: 20 additions & 0 deletions tensorboard/components/plugin_util/test/iframe.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<!--
@license
Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed 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.
-->
<head>
<script src="./iframe.js" type="module"></script>
</head>
Loading