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: move RPC client response in a lazy way #80

Merged
merged 3 commits into from
Feb 10, 2024
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
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ declare global {
var BrisaRegistry: Map<string, number>;
var lastContextProviderId: number;
var __WEB_CONTEXT_PLUGINS__: boolean;
var __RPC_LAZY_FILE__: string;
}

export default constants;
10 changes: 6 additions & 4 deletions src/utils/compile-files/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,11 @@ describe("utils", () => {
`_500-${HASH}.js`,
`_500-${HASH}.js.gz`,
`_500.txt`,
`_action-${constants.VERSION_HASH}.js`,
`_action-${constants.VERSION_HASH}.js.gz`,
`_action.txt`,
`_rpc-${constants.VERSION_HASH}.js`,
`_rpc-${constants.VERSION_HASH}.js.gz`,
`_rpc-lazy-${constants.VERSION_HASH}.js`,
`_rpc-lazy-${constants.VERSION_HASH}.js.gz`,
`_rpc.txt`,
`_unsuspense-${constants.VERSION_HASH}.js`,
`_unsuspense-${constants.VERSION_HASH}.js.gz`,
`_unsuspense.txt`,
Expand Down Expand Up @@ -231,7 +233,7 @@ describe("utils", () => {
${info}λ /pages/page-with-web-component | 368 B | ${greenLog("4 kB")}
${info}λ /pages/somepage | 349 B | ${greenLog("0 B")}
${info}λ /pages/somepage-with-context | 335 B | ${greenLog("0 B")}
${info}λ /pages/index | 486 B | ${greenLog("971 B")}
${info}λ /pages/index | 486 B | ${greenLog("1 kB")}
${info}λ /pages/user/[username] | 183 B | ${greenLog("0 B")}
${info}ƒ /middleware | 738 B |
${info}λ /api/example | 283 B |
Expand Down
40 changes: 31 additions & 9 deletions src/utils/compile-files/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,15 @@ async function compileClientCodePage(

if (!pageCode) return null;

const { size, code, unsuspense, actionRPC, useI18n, i18nKeys } = pageCode;
const {
size,
code,
unsuspense,
actionRPC,
actionRPCLazy,
useI18n,
i18nKeys,
} = pageCode;

clientSizesPerPage[route] = size;

Expand All @@ -250,12 +258,19 @@ async function compileClientCodePage(
pagePath,
});

// create _action-[versionhash].js and _action.txt (list of pages with actions)
clientSizesPerPage[route] += addExtraChunk(actionRPC, "_action", {
// create _rpc-[versionhash].js and _rpc.txt (list of pages with actions)
clientSizesPerPage[route] += addExtraChunk(actionRPC, "_rpc", {
pagesClientPath,
pagePath,
});

// create _rpc-lazy-[versionhash].js
clientSizesPerPage[route] += addExtraChunk(actionRPCLazy, "_rpc-lazy", {
pagesClientPath,
pagePath,
skipList: true,
});

if (!code) continue;

// create i18n page content files
Expand Down Expand Up @@ -297,14 +312,18 @@ async function compileClientCodePage(
function addExtraChunk(
code: string,
filename: string,
{ pagesClientPath, pagePath }: { pagesClientPath: string; pagePath: string },
{
pagesClientPath,
pagePath,
skipList = false,
}: { pagesClientPath: string; pagePath: string; skipList?: boolean },
) {
const { BUILD_DIR, VERSION_HASH } = getConstants();
const jsFilename = `${filename}-${VERSION_HASH}.js`;

if (!code) return 0;

if (fs.existsSync(join(pagesClientPath, jsFilename))) {
if (!skipList && fs.existsSync(join(pagesClientPath, jsFilename))) {
const listPath = join(pagesClientPath, `${filename}.txt`);

Bun.write(
Expand All @@ -322,10 +341,13 @@ function addExtraChunk(

Bun.write(join(pagesClientPath, jsFilename), code);
Bun.write(join(pagesClientPath, `${jsFilename}.gz`), gzipUnsuspense);
Bun.write(
join(pagesClientPath, `${filename}.txt`),
pagePath.replace(BUILD_DIR, ""),
);

if (!skipList) {
Bun.write(
join(pagesClientPath, `${filename}.txt`),
pagePath.replace(BUILD_DIR, ""),
);
}

return gzipUnsuspense.length;
}
11 changes: 9 additions & 2 deletions src/utils/get-client-code-in-page/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ describe("utils", () => {
const expected = {
code: "",
actionRPC: "",
actionRPCLazy: "",
unsuspense: "",
size: 0,
useI18n: false,
Expand Down Expand Up @@ -78,11 +79,17 @@ describe("utils", () => {
const input = path.join(pages, "index.tsx");
const output = await getClientCodeInPage(input, allWebComponents);
const unsuspenseSize = 217;
const actionRPCSize = 1319;
const actionRPCSize = 1318;
const actionRPCLazySize = 307;

// actionRPCLazy is loaded after user interaction (action),
// so it's not included in the initial size
const initialSize = unsuspenseSize + actionRPCSize;

expect(output?.unsuspense.length).toBe(unsuspenseSize);
expect(output?.actionRPC.length).toBe(actionRPCSize);
expect(output?.size).toBe(unsuspenseSize + actionRPCSize);
expect(output?.actionRPCLazy.length).toBe(actionRPCLazySize);
expect(output?.size).toBe(initialSize);
expect(output?.code).toBeEmpty();
expect(output?.useI18n).toBeFalse();
expect(output?.i18nKeys).toBeEmpty();
Expand Down
9 changes: 8 additions & 1 deletion src/utils/get-client-code-in-page/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { join } from "node:path";

import { getConstants } from "@/constants";
import AST from "@/utils/ast";
import { injectActionRPCCode } from "@/utils/inject-action-rpc" with { type: "macro" };
import {
injectActionRPCCode,
injectActionRPCLazyCode,
} from "@/utils/inject-action-rpc" with { type: "macro" };
import { injectUnsuspenseCode } from "@/utils/inject-unsuspense-code" with { type: "macro" };
import { injectClientContextProviderCode } from "@/utils/context-provider/inject-client" with { type: "macro" };
import clientBuildPlugin from "@/utils/client-build-plugin";
Expand All @@ -20,6 +23,7 @@ type TransformOptions = {
const ASTUtil = AST("tsx");
const unsuspenseScriptCode = await injectUnsuspenseCode();
const actionRPCCode = await injectActionRPCCode();
const actionRPCLazyCode = await injectActionRPCLazyCode();
const ENV_VAR_PREFIX = "BRISA_PUBLIC_";

async function getAstFromPath(path: string) {
Expand Down Expand Up @@ -57,6 +61,7 @@ export default async function getClientCodeInPage(

const unsuspense = useSuspense ? unsuspenseScriptCode : "";
const actionRPC = useActions ? actionRPCCode : "";
const actionRPCLazy = useActions ? actionRPCLazyCode : "";

size += unsuspense.length;
size += actionRPC.length;
Expand All @@ -66,6 +71,7 @@ export default async function getClientCodeInPage(
code,
unsuspense,
actionRPC,
actionRPCLazy,
size,
useI18n: false,
i18nKeys: new Set<string>(),
Expand All @@ -86,6 +92,7 @@ export default async function getClientCodeInPage(
code,
unsuspense,
actionRPC,
actionRPCLazy,
size,
useI18n: transformedCode.useI18n,
i18nKeys: transformedCode.i18nKeys,
Expand Down
15 changes: 14 additions & 1 deletion src/utils/inject-action-rpc/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
import path from "node:path";
import constants from "@/constants";

// Should be used via macro
export async function injectActionRPCCode() {
return await buildRPC("rpc.ts");
}

// Should be used via macro
export async function injectActionRPCLazyCode() {
return await buildRPC("resolve-rpc.ts");
}

async function buildRPC(file: string) {
const { success, logs, outputs } = await Bun.build({
entrypoints: [path.join(import.meta.dir, "rpc.ts")],
entrypoints: [path.join(import.meta.dir, file)],
target: "browser",
minify: true,
define: {
__RPC_LAZY_FILE__: `'/_brisa/pages/_rpc-lazy-${constants.VERSION_HASH}.js'`,
},
});

if (!success) console.error(logs);
Expand Down
41 changes: 41 additions & 0 deletions src/utils/inject-action-rpc/resolve-rpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/// <reference lib="dom.iterable" />

async function resolveRPC(res: Response) {
const reader = res.body!.getReader();

/**
* The chunk is using Newline-delimited JSON (NDJSON) format.
* This format is used to parse JSON objects from a stream.
*
* Content-Type: application/x-ndjson
*
* https://en.wikipedia.org/wiki/JSON_streaming#Newline-delimited_JSON
*
* Example:
*
* {"action": "foo"} \n {"action": "bar"} \n {"action": "baz"}
*
* The difference between this format and JSON is that this format
* is not a valid JSON, but it is a valid JSON stream.
*
*/
while (true) {
const { done, value } = await reader.read();

if (done) break;

const text = new TextDecoder().decode(value);

for (const json of text.split("\n")) {
if (!json) continue;
const { action, params, selector } = JSON.parse(json);

// Redirect to a different page
if (action === "navigate") {
window.location.href = params[0];
}
}
}
}

window._rpc = resolveRPC;
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ import {
spyOn,
jest,
} from "bun:test";
import { injectActionRPCCode } from "." with { type: "macro" };
import {
injectActionRPCCode,
injectActionRPCLazyCode,
} from "." with { type: "macro" };
import { GlobalRegistrator } from "@happy-dom/global-registrator";

const actionRPCCode = await injectActionRPCCode();
const actionRPCLazyCode = await injectActionRPCLazyCode();

async function simulateRPC(
actions: any[],
Expand All @@ -30,6 +34,7 @@ async function simulateRPC(
document.body.appendChild(el);

// Inject RPC code
eval(actionRPCLazyCode);
eval(actionRPCCode);

// Mock fetch with the actions
Expand All @@ -54,7 +59,9 @@ async function simulateRPC(
);

// Simulate the event
el.dispatchEvent(new Event(eventName));
el.dispatchEvent(
eventName === "custom" ? new CustomEvent(eventName) : new Event(eventName),
);

// Wait the fetch to be processed
await Bun.sleep(0);
Expand All @@ -63,7 +70,7 @@ async function simulateRPC(
}

describe("utils", () => {
describe("inject-action-rpc", () => {
describe("rpc", () => {
beforeEach(() => {
GlobalRegistrator.register();
});
Expand Down Expand Up @@ -126,5 +133,15 @@ describe("utils", () => {

expect(mockFetch.mock.calls[0][1]?.body).toBeInstanceOf(FormData);
});

it("should send custom event serialized with _custom property", async () => {
const mockFetch = await simulateRPC(
[{ action: "navigate", params: ["http://localhost/some-page"] }],
{ eventName: "custom" },
);

const [event] = JSON.parse(mockFetch.mock.calls[0][1]?.body as any);
expect(event._custom).toBeTrue();
});
});
});
Loading
Loading