Skip to content

Fix memory leaks #102

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ export function Header({
}`}
placeholder="What needs to be done?"
autoFocus
// Spellcheck set to false to work around a memory leak issue in chrome:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1410394
spellCheck={false}
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you please add a comment with a reference to the chrome big we filed? Thanks

value={newTodoDetails.text}
onInput={(event: ChangeEvent<HTMLInputElement>) => {
const text = event.target.value;
Expand Down
2 changes: 1 addition & 1 deletion productivity-suite/app/legacy-app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@
}

body.show-seams #root > .layout,
body.show-seams piercing-fragment-host {
body.show-seams piercing-fragment-host:has(*) {
outline: 2px dashed var(--seams-color);
border-radius: 1px;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ export class GenericMessageBus implements MessageBus {
}

dispatch(eventName: string, value: JSONValue) {
// If the `value` here is an object that originates in a iframe, then it
// will hold a reference to the iframe Window through the `Object`'s
// prototype chain, causing a leak. Cloning it here avoids this
value = structuredClone(value);

this._state[eventName] = value;
const callbacksForEvent = this._callbacksMap.get(eventName) ?? [];
setTimeout(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,32 @@ export class PiercingFragmentOutlet extends HTMLElement {

disconnectedCallback() {
if (this.fragmentHost) {
unmountedFragmentIds.add(this.fragmentHost.fragmentId);
const fragmentId = this.fragmentHost.fragmentId;
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you add a comment before this block explaining what we are doing here? Thanks

unmountedFragmentIds.add(fragmentId);

// Loop through listeners created by the fragment and clean them up.
// fragmentRegistrationMap is initialized by `reframed-host` and then
// registered in reframed-client.
const fragmentFunctionConstructor =
fragmentRegistrationMap.get(fragmentId)!;

if (fragmentFunctionConstructor) {
fragmentRegistrationMap.delete(fragmentId);

const listenerRegistrations = fragmentListenerMap.get(
fragmentFunctionConstructor
)!;
fragmentListenerMap.delete(fragmentFunctionConstructor);

for (const listenerRegistration of listenerRegistrations) {
listenerRegistration.target.removeEventListener(
listenerRegistration.name,
listenerRegistration.listener,
listenerRegistration.options
);
}
}

this.fragmentHost = null;
}
}
Expand Down
60 changes: 45 additions & 15 deletions productivity-suite/piercing-library/src/piercing-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
// for debugging replace `qwikloader.js` with `qwikloader.debug.js` to have the code non-minified
import qwikloader from "@builder.io/qwik/qwikloader.js?raw";
import reframedClient from "./reframed-client?raw";
import reframedHost from "./reframed-host?raw";
import { MessageBusState } from "./message-bus/message-bus";
import { getMessageBusState } from "./message-bus/server-side-message-bus";

Expand Down Expand Up @@ -321,23 +322,19 @@ export class PiercingGateway<Env> {
const requestIsForHtml = request.headers
.get("Accept")
?.includes("text/html");

if (requestIsForHtml) {
const stateHeaderStr = request.headers.get("message-bus-state");
let indexBody = (await response.text()).replace(
"</head>",
`${getMessageBusInlineScript(stateHeaderStr ?? "{}")}\n` +
`${piercingFragmentHostInlineScript}\n` +
"</head>"
);
const isolateFragments = this.config.isolateFragments?.(env);

const postHead = `
${getMessageBusInlineScript(stateHeaderStr ?? "{}")}
${piercingFragmentHostInlineScript}
${isolateFragments ? getReframedHostCode() : qwikloaderScript}
</head>
`;
let indexBody = (await response.text()).replace("</head>", postHead);

if (!this.config.isolateFragments?.(env)) {
// We need to include the qwikLoader script here
// this is a temporary bugfix, see: https://jira.cfops.it/browse/DEVDASH-51
indexBody = indexBody.replace(
"</head>",
`\n${qwikloaderScript}</head>`
);
}
return new Response(indexBody, response);
}

Expand Down Expand Up @@ -372,12 +369,13 @@ export class PiercingGateway<Env> {
if (this.config.isolateFragments?.(env)) {
// Quotes must be escaped from srcdoc contents
template = `
${prePiercingStyles}
<piercing-fragment-host fragment-id=${fragmentConfig.fragmentId}>
</piercing-fragment-host>
${prePiercingStyles}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ahh... I see. This explains the FOUC

<iframe id="iframe_${fragmentId}" style="display: none" srcdoc="
<body>
--FRAGMENT_CONTENT--
${getEmbeddedStyleScript(fragmentId)}
${getEscapedReframedClientCode(fragmentId)}
${(framework === "qwik" && escapeQuotes(qwikloaderScript)) || ""}
</body>
Expand Down Expand Up @@ -463,6 +461,38 @@ function getEscapedReframedClientCode(fragmentId: string) {
</script>`;
}

// In order to avoid a FOUC when rendering fragments in an iframe, we need to
// resolve any linked css files into `style` tags which we inline. This is
// handled for non-isolated fragments inside `piercing-fragment-host`
function getEmbeddedStyleScript(fragmentId: string) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you please document the purpose of this fn. thank you

return `<script>
${escapeQuotes(
`
const stylesheets = document.querySelectorAll(
'link[href][rel="stylesheet"]'
);

stylesheets.forEach((styleLink) => {
if (styleLink.sheet) {
let rulesText = "";
for (const { cssText } of styleLink.sheet.cssRules) {
rulesText += cssText + "\\n";
}

const styleElement = document.createElement("style");
styleElement.textContent = rulesText;
styleLink.replaceWith(styleElement);
}
});
`
)}
</script>`;
}

function getReframedHostCode() {
return `<script id="reframedHost">${reframedHost}</script>`;
}

const escapeQuotes = (str: string) => str.replaceAll('"', `&quot;`);

const qwikloaderScript = `<script id="qwikloader">${qwikloader}</script>`;
15 changes: 13 additions & 2 deletions productivity-suite/piercing-library/src/reframed-client.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
const reframedContainer = window.parent.document.querySelector(
__FRAGMENT_SELECTOR__
);

if (!reframedContainer) {
console.error("Container element couldn't be found");
}

const fragmentId = reframedContainer.getAttribute("fragment-id");

const reframedDocument = reframedContainer.ownerDocument;
const reframedWindow = reframedDocument.defaultView;
const reframedRegistrationSymbol = Symbol.for("reframedRegistration");
const reframedRegistration = Reflect.get(
reframedWindow,
reframedRegistrationSymbol
);
reframedRegistration(fragmentId, Function);

const htmlToReframe = [];
const nodesToRemove = [];
Expand Down Expand Up @@ -42,6 +51,8 @@ document.body.childNodes.forEach((node) => {
});

nodesToRemove.forEach((node) => node.remove());

console.log("reframing iframe nodes");
reframedContainer.innerHTML = htmlToReframe.join("");

document.addEventListener("DOMContentLoaded", () => {
Expand Down Expand Up @@ -111,8 +122,8 @@ for (const listenerProperty of domListenerProperties) {
);
};

window[listenerProperty] = function reframedListenerFn(...args) {
return reframedWindow[listenerProperty].apply(reframedWindow, args);
window[listenerProperty] = function reframedListenerFn() {
return reframedWindow[listenerProperty].apply(reframedWindow, arguments);
};
}

Expand Down
52 changes: 52 additions & 0 deletions productivity-suite/piercing-library/src/reframed-host.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Maps that allow us to keep track of registered fragments and their listeners.
// We use FunctionConstructor as a way to identify the origin of a registered listener and map it back to its fragment.
const fragmentRegistrationMap = new Map();
const fragmentListenerMap = new Map();

// monkey patch global addEventListner on window and document so that we can automatically unregister
// any listeners created from within a registered fragment.
const addEventListenerTargets = [window, document];

for (const addEventListenerTarget of addEventListenerTargets) {
const originalDocumentAddEventListener =
addEventListenerTarget.addEventListener;
addEventListenerTarget.addEventListener =
function reframedHostAddEventListener(name, listener, options) {
let listenerFnConstructor;
if (listener.handleEvent) {
listenerFnConstructor = listener.handleEvent.constructor;
} else {
listenerFnConstructor = listener.constructor;
}

const listenerFns = fragmentListenerMap.get(listenerFnConstructor);

// if this listener comes from a registered fragment, then keep track of it so that we can unregister it
if (listenerFns) {
listenerFns.push({
target: addEventListenerTarget,
name,
listener,
options,
});
}

return originalDocumentAddEventListener.call(
addEventListenerTarget,
name,
listener,
options
);
};
}

const reframedRegistrationSymbol = Symbol.for("reframedRegistration");

Reflect.set(
window,
reframedRegistrationSymbol,
function reframedRegistration(fragmentId, clientFunctionConstructor) {
fragmentRegistrationMap.set(fragmentId, clientFunctionConstructor);
fragmentListenerMap.set(clientFunctionConstructor, []);
}
);