-
Notifications
You must be signed in to change notification settings - Fork 1.7k
lib: add a library for cross-frame communication #2309
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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", | ||
| ], | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| 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)) { | ||
stephanwlee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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}); | ||
| }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
stephanwlee marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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", | ||
| ], | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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