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

Increase memory for server function on Next.js with image optimization #7940

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
2 changes: 1 addition & 1 deletion src/firebaseConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export type HostingHeaders = HostingSource & {
// Allow only serializable options, since this is in firebase.json
// TODO(jamesdaniels) look into allowing serialized CEL expressions, params, and regexp
// and if we can build this interface automatically via Typescript silliness
interface FrameworksBackendOptions extends HttpsOptions {
export interface FrameworksBackendOptions extends HttpsOptions {
omit?: boolean;
cors?: string | boolean;
memory?: MemoryOption;
Expand Down
14 changes: 7 additions & 7 deletions src/frameworks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
/**
*
*/
export async function discover(dir: string, warn = true) {

Check warning on line 64 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
const allFrameworkTypes = [
...new Set(Object.values(WebFrameworks).map(({ type }) => type)),
].sort();
Expand Down Expand Up @@ -91,18 +91,18 @@
function memoizeBuild(
dir: string,
build: Framework["build"],
deps: any[],

Check warning on line 94 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
target: string,
context: FrameworkContext,
): ReturnType<Framework["build"]> {
const key = [dir, ...deps];

Check warning on line 98 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe spread of an `any` value in an array
for (const existingKey of BUILD_MEMO.keys()) {
if (isDeepStrictEqual(existingKey, key)) {
return BUILD_MEMO.get(existingKey) as ReturnType<Framework["build"]>;
}
}
const value = build(dir, target, context);
BUILD_MEMO.set(key, value);

Check warning on line 105 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any[]` assigned to a parameter of type `string[]`
return value;
}

Expand All @@ -110,7 +110,7 @@
* Use a function to ensure the same codebase name is used here and
* during hosting deploy.
*/
export function generateSSRCodebaseId(site: string) {

Check warning on line 113 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
return `firebase-frameworks-${site}`;
}

Expand Down Expand Up @@ -176,7 +176,7 @@
`Hosting config for site ${site} places server-side content in region ${ssrRegion} which is not known. Valid regions are ${validRegions}`,
);
}
const getProjectPath = (...args: string[]) => join(projectRoot, source, ...args);

Check warning on line 179 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
// Combined traffic tag (19 chars) and functionId cannot exceed 46 characters.
const functionId = `ssr${site.toLowerCase().replace(/-/g, "").substring(0, 20)}`;
const usesFirebaseAdminSdk = !!findDependency("firebase-admin", { cwd: getProjectPath() });
Expand Down Expand Up @@ -214,11 +214,11 @@
if (selectedSite) {
const { appId } = selectedSite;
if (appId) {
firebaseConfig = isDemoProject

Check warning on line 217 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
? constructDefaultWebSetup(project)
: await getAppConfig(appId, AppPlatform.WEB);
firebaseDefaults ||= {};
firebaseDefaults.config = firebaseConfig;

Check warning on line 221 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
} else {
const defaultConfig = await implicitInit(options);
if (defaultConfig.json) {
Expand All @@ -227,7 +227,7 @@
You can link a Web app to a Hosting site here https://console.firebase.google.com/project/${project}/settings/general/web`,
);
firebaseDefaults ||= {};
firebaseDefaults.config = JSON.parse(defaultConfig.json);

Check warning on line 230 in src/frameworks/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
} else {
// N.B. None of us know when this can ever happen and the deploy would
// still succeed. Maaaaybe if someone tried calling firebase serve
Expand Down Expand Up @@ -409,6 +409,7 @@
frameworksEntry = framework,
dotEnv = {},
rewriteSource,
frameworksBackend: functionsDirectoryFrameworksBackend,
} = await codegenFunctionsDirectory(
getProjectPath(),
functionsDist,
Expand Down Expand Up @@ -537,25 +538,24 @@
if (bootstrapScript) await writeFile(join(functionsDist, "bootstrap.js"), bootstrapScript);

// TODO move to templates
chalosalvador marked this conversation as resolved.
Show resolved Hide resolved

const mergedFrameworksBackend = {
...functionsDirectoryFrameworksBackend,
...frameworksBackend,
leoortizz marked this conversation as resolved.
Show resolved Hide resolved
};
if (packageJson.type === "module") {
await writeFile(
join(functionsDist, "server.js"),
`import { onRequest } from 'firebase-functions/v2/https';
const server = import('firebase-frameworks');
export const ${functionId} = onRequest(${JSON.stringify(
frameworksBackend || {},
)}, (req, res) => server.then(it => it.handle(req, res)));
export const ${functionId} = onRequest(${JSON.stringify(mergedFrameworksBackend)} || {}, (req, res) => server.then(it => it.handle(req, res)));
`,
);
} else {
await writeFile(
join(functionsDist, "server.js"),
`const { onRequest } = require('firebase-functions/v2/https');
const server = import('firebase-frameworks');
exports.${functionId} = onRequest(${JSON.stringify(
frameworksBackend || {},
)}, (req, res) => server.then(it => it.handle(req, res)));
exports.${functionId} = onRequest(${JSON.stringify(mergedFrameworksBackend)} || {}, (req, res) => server.then(it => it.handle(req, res)));
`,
);
}
Expand Down
24 changes: 16 additions & 8 deletions src/frameworks/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { IncomingMessage, ServerResponse } from "http";
import { EmulatorInfo } from "../emulator/types";
import { HostingHeaders, HostingRedirects, HostingRewrites } from "../firebaseConfig";
import {
FrameworksBackendOptions,
HostingHeaders,
HostingRedirects,
HostingRewrites,
} from "../firebaseConfig";
import { HostingOptions } from "../hosting/options";
import { Options } from "../options";

Expand Down Expand Up @@ -54,6 +59,15 @@ export type FrameworkContext = {
site?: string;
};

export type CodegenFunctionDirectoryResult = {
bootstrapScript?: string;
packageJson: any;
frameworksEntry?: string;
dotEnv?: Record<string, string>;
rewriteSource?: string;
frameworksBackend?: FrameworksBackendOptions;
};

export interface Framework {
supportedRange?: string;
discover: (dir: string) => Promise<Discovery | undefined>;
Expand Down Expand Up @@ -82,13 +96,7 @@ export interface Framework {
dest: string,
target: string,
context?: FrameworkContext,
) => Promise<{
bootstrapScript?: string;
packageJson: any;
frameworksEntry?: string;
dotEnv?: Record<string, string>;
rewriteSource?: string;
}>;
) => Promise<CodegenFunctionDirectoryResult>;
getValidBuildTargets?: (purpose: BUILD_TARGET_PURPOSE, dir: string) => Promise<string[]>;
shouldUseDevModeHandle?: (target: string, dir: string) => Promise<boolean>;
}
Expand Down
20 changes: 19 additions & 1 deletion src/frameworks/next/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from "../utils";
import {
BuildResult,
CodegenFunctionDirectoryResult,
Framework,
FrameworkContext,
FrameworkType,
Expand Down Expand Up @@ -83,6 +84,7 @@ import {
import { getAllSiteDomains, getDeploymentDomain } from "../../hosting/api";
import { logger } from "../../logger";
import { parseStrict } from "../../functions/env";
import { FrameworksBackendOptions } from "../../firebaseConfig";

const DEFAULT_BUILD_SCRIPT = ["next build"];
const PUBLIC_DIR = "public";
Expand Down Expand Up @@ -677,8 +679,14 @@ export async function ɵcodegenFunctionsDirectory(
}

// Add the `sharp` library if app is using image optimization

let frameworksBackend: FrameworksBackendOptions | undefined;
if (await isUsingImageOptimization(sourceDir, distDir)) {
packageJson.dependencies["sharp"] = SHARP_VERSION;
// TODO check if it is only for Next 15
frameworksBackend = {
memory: "512MiB",
chalosalvador marked this conversation as resolved.
Show resolved Hide resolved
};
}

const dotEnv: Record<string, string> = {};
Expand Down Expand Up @@ -710,7 +718,17 @@ export async function ɵcodegenFunctionsDirectory(
),
);

return { packageJson, frameworksEntry: "next.js", dotEnv };
const result: CodegenFunctionDirectoryResult = {
packageJson,
frameworksEntry: "next.js",
dotEnv,
};

if (frameworksBackend) {
result.frameworksBackend = frameworksBackend;
}

return result;
}

/**
Expand Down
Loading