Skip to content

Commit 5e84261

Browse files
committed
feat: allow dsg/ssr renders without access to datastore if it's not required (#38974)
* fix: generate lmdb cdn path after state was reloaded from cache restoration * feat: make lmdb datastore optional and lazy in engines * use datastore exlucde and skip deploy cleanup temporarily * fix lint * build engines after page configs were prepared * tmp: workaround local deploy problems with datastore exclussion * set rawUrl on request and use it to extract origin for engine download in case url passed at build doesn't work * no unhandled promise rejections, actually pass rawUrl * make one of e2e variants use datastore exclussion, so base case is still tested * revert adapters e2e test cleanup * scripts rename * findPageByPath renaming * getGraphqlEngine renaming (cherry picked from commit 884ecaf)
1 parent 0f9ad54 commit 5e84261

File tree

13 files changed

+305
-153
lines changed

13 files changed

+305
-153
lines changed

e2e-tests/adapters/package.json

+4-4
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@
1414
"develop:debug": "start-server-and-test develop http://localhost:8000 'npm run cy:open -- --config baseUrl=http://localhost:8000'",
1515
"ssat:debug": "start-server-and-test serve http://localhost:9000 cy:open",
1616
"test:template": "cross-env-shell CYPRESS_GROUP_NAME=\"adapter:$ADAPTER / trailingSlash:${TRAILING_SLASH:-always} / pathPrefix:${PATH_PREFIX:--}\" TRAILING_SLASH=$TRAILING_SLASH PATH_PREFIX=$PATH_PREFIX node ../../scripts/cypress-run-with-conditional-record-flag.js --browser chrome --e2e --config-file \"cypress/configs/$ADAPTER.ts\" --env TRAILING_SLASH=$TRAILING_SLASH,PATH_PREFIX=$PATH_PREFIX",
17-
"test:template:debug": "cross-env-shell CYPRESS_GROUP_NAME=\"adapter:$ADAPTER / trailingSlash:${TRAILING_SLASH:-always} / pathPrefix:${PATH_PREFIX:--}\" TRAILING_SLASH=$TRAILING_SLASH PATH_PREFIX=$PATH_PREFIX npm run cy:open -- --config-file \"cypress/configs/$ADAPTER.ts\" --env TRAILING_SLASH=$TRAILING_SLASH,PATH_PREFIX=$PATH_PREFIX",
17+
"test:template:debug": "cross-env-shell CYPRESS_GROUP_NAME=\"adapter:$ADAPTER / trailingSlash:${TRAILING_SLASH:-always} / pathPrefix:${PATH_PREFIX:--} / excludeDatastoreFromBundle:${GATSBY_EXCLUDE_DATASTORE_FROM_BUNDLE:-false}\" TRAILING_SLASH=$TRAILING_SLASH PATH_PREFIX=$PATH_PREFIX npm run cy:open -- --config-file \"cypress/configs/$ADAPTER.ts\" --env TRAILING_SLASH=$TRAILING_SLASH,PATH_PREFIX=$PATH_PREFIX",
1818
"test:debug": "npm-run-all -s build:debug ssat:debug",
1919
"test:netlify": "cross-env TRAILING_SLASH=always node scripts/deploy-and-run/netlify.mjs test:template",
2020
"test:smoke": "node smoke-test.mjs",
2121
"test:netlify:debug": "cross-env TRAILING_SLASH=always node scripts/deploy-and-run/netlify.mjs test:template:debug",
22-
"test:netlify:prefix-never": "cross-env TRAILING_SLASH=never PATH_PREFIX=/prefix node scripts/deploy-and-run/netlify.mjs test:template",
23-
"test:netlify:prefix-never:debug": "cross-env TRAILING_SLASH=never PATH_PREFIX=/prefix node scripts/deploy-and-run/netlify.mjs test:template:debug",
24-
"test": "npm-run-all -c -s test:netlify test:netlify:prefix-never"
22+
"test:netlify:non-defaults-variant": "cross-env TRAILING_SLASH=never PATH_PREFIX=/prefix GATSBY_EXCLUDE_DATASTORE_FROM_BUNDLE=true node scripts/deploy-and-run/netlify.mjs test:template",
23+
"test:netlify:non-defaults-variant:debug": "cross-env TRAILING_SLASH=never PATH_PREFIX=/prefix GATSBY_EXCLUDE_DATASTORE_FROM_BUNDLE=true node scripts/deploy-and-run/netlify.mjs test:template:debug",
24+
"test": "npm-run-all -c -s test:netlify test:netlify:non-defaults-variant"
2525
},
2626
"dependencies": {
2727
"gatsby": "next",

packages/gatsby-adapter-netlify/src/lambda-handler.ts

+2
Original file line numberDiff line numberDiff line change
@@ -176,11 +176,13 @@ const createRequestObject = ({ event, context }) => {
176176
multiValueHeaders = {},
177177
body,
178178
isBase64Encoded,
179+
rawUrl
179180
} = event
180181
const newStream = new Stream.Readable()
181182
const req = Object.assign(newStream, http.IncomingMessage.prototype)
182183
req.url = path
183184
req.originalUrl = req.url
185+
req.rawUrl = rawUrl
184186
req.query = queryStringParameters
185187
req.multiValueQuery = multiValueQueryStringParameters
186188
req.method = httpMethod

packages/gatsby/index.d.ts

+4
Original file line numberDiff line numberDiff line change
@@ -1869,6 +1869,10 @@ export interface GatsbyFunctionRequest<ReqBody = any> extends IncomingMessage {
18691869
* Object of `cookies` from header
18701870
*/
18711871
cookies: Record<string, string>
1872+
/**
1873+
* Optional field to store the full raw URL by adapters
1874+
*/
1875+
rawUrl?: string
18721876
}
18731877

18741878
export interface GatsbyFunctionBodyParserCommonMiddlewareConfig {

packages/gatsby/src/commands/build.ts

+29-31
Original file line numberDiff line numberDiff line change
@@ -191,37 +191,6 @@ module.exports = async function build(
191191
buildActivityTimer.end()
192192
}
193193

194-
if (shouldGenerateEngines()) {
195-
const state = store.getState()
196-
const buildActivityTimer = report.activityTimer(
197-
`Building Rendering Engines`,
198-
{ parentSpan: buildSpan }
199-
)
200-
try {
201-
buildActivityTimer.start()
202-
// bundle graphql-engine
203-
engineBundlingPromises.push(
204-
createGraphqlEngineBundle(program.directory, report, program.verbose)
205-
)
206-
207-
engineBundlingPromises.push(
208-
createPageSSRBundle({
209-
rootDir: program.directory,
210-
components: state.components,
211-
staticQueriesByTemplate: state.staticQueriesByTemplate,
212-
webpackCompilationHash: webpackCompilationHash as string, // we set webpackCompilationHash above
213-
reporter: report,
214-
isVerbose: program.verbose,
215-
})
216-
)
217-
await Promise.all(engineBundlingPromises)
218-
} catch (err) {
219-
reporter.panic(err)
220-
} finally {
221-
buildActivityTimer.end()
222-
}
223-
}
224-
225194
const buildSSRBundleActivityProgress = report.activityTimer(
226195
`Building HTML renderer`,
227196
{ parentSpan: buildSpan }
@@ -295,6 +264,35 @@ module.exports = async function build(
295264
}
296265

297266
if (shouldGenerateEngines()) {
267+
const state = store.getState()
268+
const buildActivityTimer = report.activityTimer(
269+
`Building Rendering Engines`,
270+
{ parentSpan: buildSpan }
271+
)
272+
try {
273+
buildActivityTimer.start()
274+
// bundle graphql-engine
275+
engineBundlingPromises.push(
276+
createGraphqlEngineBundle(program.directory, report, program.verbose)
277+
)
278+
279+
engineBundlingPromises.push(
280+
createPageSSRBundle({
281+
rootDir: program.directory,
282+
components: state.components,
283+
staticQueriesByTemplate: state.staticQueriesByTemplate,
284+
webpackCompilationHash: webpackCompilationHash as string, // we set webpackCompilationHash above
285+
reporter: report,
286+
isVerbose: program.verbose,
287+
})
288+
)
289+
await Promise.all(engineBundlingPromises)
290+
} catch (err) {
291+
reporter.panic(err)
292+
} finally {
293+
buildActivityTimer.end()
294+
}
295+
298296
await validateEnginesWithActivity(program.directory, buildSpan)
299297
}
300298

packages/gatsby/src/commands/serve.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ module.exports = async (program: IServeProgram): Promise<void> => {
202202
try {
203203
const { GraphQLEngine } =
204204
require(graphqlEnginePath) as typeof import("../schema/graphql-engine/entry")
205-
const { getData, renderPageData, renderHTML } =
205+
const { getData, renderPageData, renderHTML, findEnginePageByPath } =
206206
require(pageSSRModule) as typeof import("../utils/page-ssr-module/entry")
207207
const graphqlEngine = new GraphQLEngine({
208208
dbPath: path.posix.join(
@@ -222,7 +222,7 @@ module.exports = async (program: IServeProgram): Promise<void> => {
222222
}
223223

224224
const potentialPagePath = reverseFixedPagePath(requestedPagePath)
225-
const page = graphqlEngine.findPageByPath(potentialPagePath)
225+
const page = findEnginePageByPath(potentialPagePath)
226226

227227
if (page && (page.mode === `DSG` || page.mode === `SSR`)) {
228228
const requestActivity = report.phantomActivity(
@@ -272,7 +272,7 @@ module.exports = async (program: IServeProgram): Promise<void> => {
272272
router.use(async (req, res, next) => {
273273
if (req.accepts(`html`)) {
274274
const potentialPagePath = req.path
275-
const page = graphqlEngine.findPageByPath(potentialPagePath)
275+
const page = findEnginePageByPath(potentialPagePath)
276276
if (page && (page.mode === `DSG` || page.mode === `SSR`)) {
277277
const requestActivity = report.phantomActivity(
278278
`request for "${req.path}"`

packages/gatsby/src/schema/graphql-engine/entry.ts

+3
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,9 @@ export class GraphQLEngine {
195195
}
196196
}
197197

198+
/**
199+
* @deprecated use findEnginePageByPath exported from page-ssr module instead
200+
*/
198201
public findPageByPath(pathName: string): IGatsbyPage | undefined {
199202
// adapter so `findPageByPath` use SitePage nodes in datastore
200203
// instead of `pages` redux slice

packages/gatsby/src/utils/adapter/get-route-path.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ function maybeDropNamedPartOfWildcard(
1111
return path.replace(/\*.+$/, `*`)
1212
}
1313

14-
export function getRoutePathFromPage(page: IGatsbyPage): string {
14+
export function getRoutePathFromPage(
15+
page: Pick<IGatsbyPage, "path" | "matchPath">
16+
): string {
1517
return maybeDropNamedPartOfWildcard(page.matchPath) ?? page.path
1618
}
1719

packages/gatsby/src/utils/adapter/manager.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import { getPageMode } from "../page-mode"
2626
import { getStaticQueryPath } from "../static-query-utils"
2727
import { getAdapterInit } from "./init"
2828
import {
29-
LmdbOnCdnPath,
29+
getLmdbOnCdnPath,
3030
shouldBundleDatastore,
3131
shouldGenerateEngines,
3232
} from "../engines-helpers"
@@ -192,7 +192,7 @@ export async function initAdapterManager(): Promise<IAdapterManager> {
192192
}
193193

194194
// handle lmdb file
195-
const mdbInPublicPath = `public/${LmdbOnCdnPath}`
195+
const mdbInPublicPath = `public/${getLmdbOnCdnPath()}`
196196
if (!shouldBundleDatastore()) {
197197
const mdbPath = getDefaultDbPath() + `/data.mdb`
198198
copy(mdbPath, mdbInPublicPath)

packages/gatsby/src/utils/engines-helpers.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ function getCDNObfuscatedPath(path: string): string {
3232
return `${store.getState().status.cdnObfuscatedPrefix}-${path}`
3333
}
3434

35-
export const LmdbOnCdnPath = getCDNObfuscatedPath(`data.mdb`)
35+
export const getLmdbOnCdnPath = (): string => getCDNObfuscatedPath(`data.mdb`)
3636

3737
export interface IPlatformAndArch {
3838
platform: string

packages/gatsby/src/utils/get-server-data.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ export async function getServerData(
2323
req:
2424
| Partial<Pick<Request, "query" | "method" | "url" | "headers">>
2525
| undefined,
26-
page: IGatsbyPage,
26+
page: Pick<IGatsbyPage, "path" | "matchPath" | "context">,
2727
pagePath: string,
2828
mod: IModuleWithServerData | undefined
2929
): Promise<IServerData> {

packages/gatsby/src/utils/page-ssr-module/bundle-webpack.ts

+28-5
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,16 @@ import webpack from "webpack"
44
import mod from "module"
55
import { WebpackLoggingPlugin } from "../../utils/webpack/plugins/webpack-logging"
66
import reporter from "gatsby-cli/lib/reporter"
7-
import type { ITemplateDetails } from "./entry"
7+
import type { EnginePage, ITemplateDetails } from "./entry"
88

99
import {
1010
getScriptsAndStylesForTemplate,
1111
readWebpackStats,
1212
} from "../client-assets-for-template"
1313
import { IGatsbyState } from "../../redux/types"
1414
import { store } from "../../redux"
15-
import { LmdbOnCdnPath, shouldBundleDatastore } from "../engines-helpers"
15+
import { getLmdbOnCdnPath, shouldBundleDatastore } from "../engines-helpers"
16+
import { getPageMode } from "../page-mode"
1617

1718
type Reporter = typeof reporter
1819

@@ -112,6 +113,25 @@ export async function createPageSSRBundle({
112113
}
113114
}
114115

116+
const pagesIterable: Array<[string, EnginePage]> = []
117+
for (const [pagePath, page] of state.pages) {
118+
const mode = getPageMode(page, state)
119+
if (mode !== `SSG`) {
120+
pagesIterable.push([
121+
pagePath,
122+
{
123+
componentChunkName: page.componentChunkName,
124+
componentPath: page.componentPath,
125+
context: page.context,
126+
matchPath: page.matchPath,
127+
mode,
128+
path: page.path,
129+
slices: page.slices,
130+
},
131+
])
132+
}
133+
}
134+
115135
const compiler = webpack({
116136
name: `Page Engine`,
117137
mode: `none`,
@@ -193,6 +213,7 @@ export async function createPageSSRBundle({
193213
INLINED_TEMPLATE_TO_DETAILS: JSON.stringify(toInline),
194214
INLINED_HEADERS_CONFIG: JSON.stringify(state.config.headers),
195215
WEBPACK_COMPILATION_HASH: JSON.stringify(webpackCompilationHash),
216+
GATSBY_PAGES: JSON.stringify(pagesIterable),
196217
GATSBY_SLICES: JSON.stringify(slicesStateObject),
197218
GATSBY_SLICES_BY_TEMPLATE: JSON.stringify(slicesByTemplateStateObject),
198219
GATSBY_SLICES_SCRIPT: JSON.stringify(
@@ -248,9 +269,11 @@ export async function createPageSSRBundle({
248269
functionCode = functionCode
249270
.replaceAll(
250271
`%CDN_DATASTORE_PATH%`,
251-
shouldBundleDatastore()
252-
? ``
253-
: `${state.adapter.config.deployURL ?? ``}/${LmdbOnCdnPath}`
272+
shouldBundleDatastore() ? `` : getLmdbOnCdnPath()
273+
)
274+
.replaceAll(
275+
`%CDN_DATASTORE_ORIGIN%`,
276+
shouldBundleDatastore() ? `` : state.adapter.config.deployURL ?? ``
254277
)
255278
.replaceAll(`%PATH_PREFIX%`, pathPrefix)
256279
.replaceAll(

0 commit comments

Comments
 (0)