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

stub worker wrapped in iframe #1016

Closed
wants to merge 1 commit into from
Closed
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
4 changes: 4 additions & 0 deletions demo/call-function/call-function.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Some comment
console.log('authorScript excuted');
function performComplexMath() {
return Math.random() * 1000;
}
Expand Down Expand Up @@ -37,3 +39,5 @@ function concat() {
// Manual test for .onerror, by scheduling an unhandled error
// 2s in via prompt which isn't valid in a Worker.
setTimeout(() => prompt(), 2000);

console.log('authorScript end');
7 changes: 4 additions & 3 deletions demo/call-function/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@
<meta charset="utf-8" />
<title>Call function</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="/dist/amp/main.mjs" type="module"></script>
<script src="/dist/amp-debug/" type="module"></script>
</head>
<body>
<div src="call-function.js" id="upgrade-me"></div>
<script type="module">
import { upgradeElement } from "/dist/amp/main.mjs";
import { upgradeElement } from "/dist/amp-debug/main.mjs";
upgradeElement(
document.getElementById("upgrade-me"),
"/dist/amp/worker/worker.nodom.mjs"
"/dist/amp-debug/worker/worker.nodom.mjs",
() => {}, () => {}, true
).then(async (worker) => {
worker
.callFunction("performComplexMath")
Expand Down
5 changes: 5 additions & 0 deletions src/main-thread/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ export interface InboundWorkerDOMConfiguration {
hydrateFilter?: HydrationFilterPredicate;
// Executor Filter, allow list
executorsAllowed?: Array<number>;
// Sandbox in iframe
// QQ: Do we want to expose the sandbox config to non AMP version? If not how to limit the support?
sandboxInIframe?: Boolean;

// ---- Optional Callbacks
// Called when worker consumes the page's initial DOM state.
Expand Down Expand Up @@ -74,6 +77,8 @@ export interface WorkerDOMConfiguration {
sanitizer?: Sanitizer;
// Hydration Filter Predicate
hydrateFilter?: HydrationFilterPredicate;
// Sandbox in iframe
sandboxInIframe?: Boolean;

// ---- Optional Callbacks
// Called when worker consumes the page's initial DOM state.
Expand Down
2 changes: 2 additions & 0 deletions src/main-thread/index.amp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export function upgradeElement(
domURL: string,
longTask?: LongTaskFunction,
sanitizer?: Sanitizer,
sandboxInIframe?: Boolean,
): Promise<ExportedWorker | null> {
const authorURL = baseElement.getAttribute('src');
if (authorURL) {
Expand All @@ -54,6 +55,7 @@ export function upgradeElement(
longTask,
hydrateFilter,
sanitizer,
sandboxInIframe,
});
}
return Promise.resolve(null);
Expand Down
130 changes: 130 additions & 0 deletions src/main-thread/worker-stub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/**
* Copyright 2020 The AMP HTML 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 { MessageToWorker } from '../transfer/Messages';

declare type MessageEventHandler = (event: MessageEvent) => void;
// const enum MessageToIframeType {
// INIT = 'init-worker',
// IFRAME_READY = 'iframe-ready',
// }

interface MessageToIframe {
data: {
type: string;
};
//source: Window,
}

/**
* A lightweight Document stub for the no-dom amp binary.
*/
export class IframeWorker {
// Internal variables.
private iframe: HTMLIFrameElement;
public onmessageerror: Function;
public terminate: Function;
public onerror: Function;
private handler?: MessageEventHandler;

/**
* @param workerDOMSrc
*/
constructor(workerDOMSrc: String) {
this.iframe = document.createElement('iframe');
this.iframe.setAttribute('sandbox', 'allow-scripts');
this.initWorkerInIframe(workerDOMSrc);
this.listenToWorker();
}

isSrcSupported() {
// Safari doesn't allow worker script from blobUrl, load iframe from cdn.ampproject.net
return true;
}

initWorkerInIframe(workerDOMSrc: String) {
if (!this.isSrcSupported()) {
console.error('Browser Not Supported Yet');
} else {
// TODO: Compile iframe srcdoc, and move out of the function
const iframeCode: string = `
parent.postMessage({
'type': 'iframe-ready',
}, '*');
window.addEventListener('message', event => {
const data = event.data;
const origin = event.origin;
if (data.type == 'init-worker') {
const src = data.workerDOMSrc;
const worker = new Worker(URL.createObjectURL(new Blob([src])));
}
});
`;
const iframeHtml: string = `
<html>
<!-- Heres a comment -->
<sxript>${iframeCode}</sxript>
</html>
`.replace(/sxript/g, 'script');
this.iframe.setAttribute('srcdoc', iframeHtml);
}

//
const listener = (event: MessageToIframe) => {
// TODO: Need to verify event.source
// How to declare event source in MessageToIframe?
if (this.iframe.contentWindow && event.data.type == 'iframe-ready') {
this.iframe.contentWindow.postMessage(
{
type: 'init-worker',
workerDOMSrc: workerDOMSrc,
},
'*',
);
}
};
window.addEventListener('message', listener);
document.body.appendChild(this.iframe);
}

listenToWorker() {
this.iframe.addEventListener('message', (event) => {
if (event.type == 'worker-response') {
if (this.handler) {
// Declare the event format
this.handler(new MessageEvent(event.type, {}));
}
}
});
}

public postMessage(message: MessageToWorker, transferables: Array<Transferable>) {
if (this.iframe.contentWindow) {
this.iframe.contentWindow.postMessage(
{
type: 'worker-msg',
message: message,
},
'*',
transferables,
);
}
}

set onmessage(handler: MessageEventHandler) {
this.handler = handler;
}
}
15 changes: 12 additions & 3 deletions src/main-thread/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@ import { readableHydrateableRootNode, readableMessageToWorker } from './debuggin
import { NodeContext } from './nodes';
import { TransferrableKeys } from '../transfer/TransferrableKeys';
import { StorageLocation } from '../transfer/TransferrableStorage';
import { IframeWorker } from './worker-stub';

// TODO: Sanitizer storage init is likely broken, since the code currently
// attempts to stringify a Promise.
export type StorageInit = { storage: Storage | Promise<StorageValue>; errorMsg: null } | { storage: null; errorMsg: string };
export class WorkerContext {
private [TransferrableKeys.worker]: Worker;
private [TransferrableKeys.worker]: Worker | IframeWorker;
private nodeContext: NodeContext;
private config: WorkerDOMConfiguration;

Expand Down Expand Up @@ -80,7 +81,15 @@ export class WorkerContext {
}).call(self);
${authorScript}
//# sourceURL=${encodeURI(config.authorURL)}`;
this[TransferrableKeys.worker] = new Worker(URL.createObjectURL(new Blob([code])));

// Wrap worker in sandbox iframe if config.sandboxInIframe is set
if (config.sandboxInIframe) {
// Wrap worker in iframe
this[TransferrableKeys.worker] = new IframeWorker(code);
} else {
this[TransferrableKeys.worker] = new Worker(URL.createObjectURL(new Blob([code])));
}

if (WORKER_DOM_DEBUG) {
console.info('debug', 'hydratedNode', readableHydrateableRootNode(baseElement, config, this));
}
Expand All @@ -92,7 +101,7 @@ export class WorkerContext {
/**
* Returns the private worker.
*/
get worker(): Worker {
get worker(): Worker | IframeWorker {
return this[TransferrableKeys.worker];
}

Expand Down