Skip to content

Commit 49fd769

Browse files
MoocarKyleAMathews
authored andcommitted
Per page manifest (#14359)
* feat(gatsby): Page data without compilation hash (#13139) **Note: merges to `per-page-manifest`, not master. See #13004 for more info** ## Description This PR saves the `page-data.json` during query running. In order to minimize the size of PRs, my strategy is to save the page-data.json along with the normal query results, and then gradually shift functionality over to use `page-data.json` instead of `data.json`. Once all those PRs are merged, we'll be able to go back and delete the static query results, jsonNames, dataPaths, data.json etc. It does mean that we'll be storing double the amount of query results on disk. Hopefully that's ok in the interim. Compilation-hash will be added in future PRs. ## Related Issues - Sub-PR of #13004 * Websocket manager use page data (#13389) * add utils/page-data.read * read websocket page data from utils/page-data * Loader use page data (#13409) * page-data loader working for production-app * get new loader.getPage stuff working with gatsby develop * fix static-entry.js test * remove loadPageDataSync (will be in next PR) * use array of matchPaths * Deprecate various loader methods * remove console.log * document why fetchPageData needs to check that response is JSON * in offline, use prefetchedResources.push(...resourceUrls) * root.js remove else block * loader.js make* -> create* * loader drop else block * pass correct path/resourceUrls to onPostPrefetch * s/err => null/() => null/ * Extract loadComponent from loadPage * remove pageData from window object * update jest snapshots for static-entry (to use window.pagePath) * add loadPageOr404 * preload 404 page in background * normalize page paths * comment out resource-loading-resilience.js (will fix later) * Remove data json from guess (#13727) * remove data.json from plugin-guess * add test for plugin-guess * Gatsby serve use page data (#13728) * use match-paths.json for gatbsy serve * remove pages.json * move query/pages-writer to bootstrap/requires-writer (#13729) And delete data.json * fix(gatsby): refresh browser if webpack rebuild occurs (#13871) * move query running into build and develop * save build compilation hash * write compilationHash to page data * reload browser if rebuild occurs in background * add test to ensure that browser is reloaded if rebuild occurs * update page-datas when compilation hash changes * use worker pool to udpate page data compilation hash * update tests snapshot * reset plugin offline whitelist if compilation hash changes * prettier: remove global Cypress * separate page for testing compilation-hash * fix case typo * mock out static entry test webpackCompilationHash field * consolidate jest-worker calls into a central worker pool * page-data.json cleanup PR. Remove jsonName and dataPath (#14167) * remove json-name and don't save /static/d/ page query results * in loader.cleanAndFindPath, use __BASE_PATH__. Not __PATH_PREFIX__ * loader getPage -> loadPageSync (#14264) * Page data loading resilience (#14286) * fetchPageHtml if page resources aren't found * add page-data to production-runtime/resource-loading-resilience test Also use cypress tasks for blocking resources instead of npm run chunks * fetchPageHtml -> doesPageHtmlExist * remove loadPageOr404Sync * revert plugin-offline to master (#14385) * Misc per-page-manifest fixes (#14413) * use path.join for static-entry page-data path * add pathContext back to static-entry props (fix regression) * Remove jsonDataPaths from pre-existing redux state (#14501) * Add context to sentry xhr errors (#14577) * Add extra context to Sentry xhr errors * Don't define Sentry immediately as it'll always be undefined then * mv cpu-core-count.js test to utils/worker/__tests__ (fix bad merge) * remove sentry reporting
1 parent 3f11da3 commit 49fd769

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

71 files changed

+1455
-1440
lines changed

e2e-tests/production-runtime/cypress/integration/1-production.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
/* global Cypress, cy */
22

3+
// NOTE: This needs to be run before any other integration tests as it
4+
// sets up the service worker in offline mode. Therefore, if you want
5+
// to test an individual integration test, you must run this
6+
// first. E.g to run `compilation-hash.js` test, run
7+
//
8+
// cypress run -s \
9+
// "cypress/integration/1-production.js,cypress/integration/compilation-hash.js" \
10+
// -b chrome
11+
312
describe(`Production build tests`, () => {
413
it(`should render properly`, () => {
514
cy.visit(`/`).waitForRouteChange()
@@ -74,6 +83,13 @@ describe(`Production build tests`, () => {
7483
.should(`exist`)
7584
})
7685

86+
it(`should pass pathContext to props`, () => {
87+
cy.visit(`/path-context`).waitForRouteChange()
88+
89+
// `bar` is set in gatsby-node createPages
90+
cy.getTestElement(`path-context-foo`).contains(`bar`)
91+
})
92+
7793
it(`Uses env vars`, () => {
7894
cy.visit(`/env-vars`).waitForRouteChange()
7995

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/* global cy */
2+
3+
const getRandomInt = (min, max) => {
4+
min = Math.ceil(min)
5+
max = Math.floor(max)
6+
return Math.floor(Math.random() * (max - min)) + min
7+
}
8+
9+
const createMockCompilationHash = () =>
10+
[...Array(20)]
11+
.map(a => getRandomInt(0, 16))
12+
.map(k => k.toString(16))
13+
.join(``)
14+
15+
describe(`Webpack Compilation Hash tests`, () => {
16+
it(`should render properly`, () => {
17+
cy.visit(`/`).waitForRouteChange()
18+
})
19+
20+
// This covers the case where a user loads a gatsby site and then
21+
// the site is changed resulting in a webpack recompile and a
22+
// redeploy. This could result in a mismatch between the page-data
23+
// and the component. To protect against this, when gatsby loads a
24+
// new page-data.json, it refreshes the page if it's webpack
25+
// compilation hash differs from the one on on the window object
26+
// (which was set on initial page load)
27+
//
28+
// Since initial page load results in all links being prefetched, we
29+
// have to navigate to a non-prefetched page to test this. Thus the
30+
// `deep-link-page`.
31+
//
32+
// We simulate a rebuild by updating all page-data.jsons and page
33+
// htmls with the new hash. It's not pretty, but it's easier than
34+
// figuring out how to perform an actual rebuild while cypress is
35+
// running. See ../plugins/compilation-hash.js for the
36+
// implementation
37+
it(`should reload page if build occurs in background`, () => {
38+
cy.window().then(window => {
39+
const oldHash = window.___webpackCompilationHash
40+
expect(oldHash).to.not.eq(undefined)
41+
42+
const mockHash = createMockCompilationHash()
43+
44+
// Simulate a new webpack build
45+
cy.task(`overwriteWebpackCompilationHash`, mockHash).then(() => {
46+
cy.getTestElement(`compilation-hash`).click()
47+
cy.waitForAPIorTimeout(`onRouteUpdate`, { timeout: 3000 })
48+
49+
// Navigate into a non-prefetched page
50+
cy.getTestElement(`deep-link-page`).click()
51+
cy.waitForAPIorTimeout(`onRouteUpdate`, { timeout: 3000 })
52+
53+
// If the window compilation hash has changed, we know the
54+
// page was refreshed
55+
cy.window()
56+
.its(`___webpackCompilationHash`)
57+
.should(`equal`, mockHash)
58+
})
59+
60+
// Cleanup
61+
cy.task(`overwriteWebpackCompilationHash`, oldHash)
62+
})
63+
})
64+
})

e2e-tests/production-runtime/cypress/integration/resource-loading-resilience.js

Lines changed: 24 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -49,58 +49,52 @@ const runTests = () => {
4949

5050
describe(`Every resources available`, () => {
5151
it(`Restore resources`, () => {
52-
cy.exec(`npm run chunks -- restore`)
52+
cy.task(`restoreAllBlockedResources`)
5353
})
5454
runTests()
5555
})
5656

57-
describe(`Missing top level resources`, () => {
58-
describe(`Deleted pages manifest`, () => {
59-
it(`Block resources`, () => {
60-
cy.exec(`npm run chunks -- restore`)
61-
cy.exec(`npm run chunks -- block pages-manifest`)
57+
const runBlockedScenario = (scenario, args) => {
58+
it(`Block resources`, () => {
59+
cy.task(`restoreAllBlockedResources`).then(() => {
60+
cy.task(scenario, args).then(() => {
61+
runTests()
62+
})
6263
})
63-
runTests()
6464
})
65+
}
6566

67+
describe(`Missing top level resources`, () => {
6668
describe(`Deleted app chunk assets`, () => {
67-
it(`Block resources`, () => {
68-
cy.exec(`npm run chunks -- restore`)
69-
cy.exec(`npm run chunks -- block app`)
70-
})
71-
runTests()
69+
runBlockedScenario(`blockAssetsForChunk`, { chunk: `app` })
7270
})
7371
})
7472

75-
const runSuiteForPage = (label, path) => {
73+
const runSuiteForPage = (label, pagePath) => {
7674
describe(`Missing "${label}" resources`, () => {
7775
describe(`Missing "${label}" page query results`, () => {
78-
it(`Block resources`, () => {
79-
cy.exec(`npm run chunks -- restore`)
80-
cy.exec(`npm run chunks -- block-page ${path} query-result`)
76+
runBlockedScenario(`blockAssetsForPage`, {
77+
pagePath,
78+
filter: `page-data`,
8179
})
82-
runTests()
8380
})
8481
describe(`Missing "${label}" page page-template asset`, () => {
85-
it(`Block resources`, () => {
86-
cy.exec(`npm run chunks -- restore`)
87-
cy.exec(`npm run chunks -- block-page ${path} page-template`)
82+
runBlockedScenario(`blockAssetsForPage`, {
83+
pagePath,
84+
filter: `page-template`,
8885
})
89-
runTests()
9086
})
9187
describe(`Missing "${label}" page extra assets`, () => {
92-
it(`Block resources`, () => {
93-
cy.exec(`npm run chunks -- restore`)
94-
cy.exec(`npm run chunks -- block-page ${path} extra`)
88+
runBlockedScenario(`blockAssetsForPage`, {
89+
pagePath,
90+
filter: `extra`,
9591
})
96-
runTests()
9792
})
9893
describe(`Missing all "${label}" page assets`, () => {
99-
it(`Block resources`, () => {
100-
cy.exec(`npm run chunks -- restore`)
101-
cy.exec(`npm run chunks -- block-page ${path} all`)
94+
runBlockedScenario(`blockAssetsForPage`, {
95+
pagePath,
96+
filter: `all`,
10297
})
103-
runTests()
10498
})
10599
})
106100
}
@@ -111,6 +105,6 @@ runSuiteForPage(`404`, `/404.html`)
111105

112106
describe(`Cleanup`, () => {
113107
it(`Restore resources`, () => {
114-
cy.exec(`npm run chunks -- restore`)
108+
cy.task(`restoreAllBlockedResources`)
115109
})
116110
})
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
const fs = require(`fs-extra`)
2+
const path = require(`path`)
3+
const glob = require(`glob`)
4+
5+
const publicDir = path.join(__dirname, `..`, `..`, `public`)
6+
7+
const getAssetManifest = () => {
8+
const { assetsByChunkName } = require(`${publicDir}/webpack.stats.json`)
9+
return assetsByChunkName
10+
}
11+
12+
const moveAsset = (from, to) => {
13+
const fromExists = fs.existsSync(from)
14+
const toExists = fs.existsSync(to)
15+
16+
if (fromExists && !toExists) {
17+
fs.moveSync(from, to, {
18+
overwrite: true,
19+
})
20+
}
21+
}
22+
23+
const getAssetPath = assetFileName => path.join(publicDir, assetFileName)
24+
const getHiddenAssetPath = assetFileName => getAssetPath(`_${assetFileName}`)
25+
26+
const restoreAsset = assetFileName => {
27+
moveAsset(getHiddenAssetPath(assetFileName), getAssetPath(assetFileName))
28+
}
29+
30+
const blockAsset = assetFileName => {
31+
moveAsset(getAssetPath(assetFileName), getHiddenAssetPath(assetFileName))
32+
}
33+
34+
const blockAssetsForChunk = ({ chunk, filter }) => {
35+
const assetManifest = getAssetManifest()
36+
assetManifest[chunk].forEach(blockAsset)
37+
console.log(`Blocked assets for chunk "${chunk}"`)
38+
return null
39+
}
40+
41+
const restorePageData = hiddenPath => {
42+
if (path.basename(hiddenPath).charAt(0) !== `_`) {
43+
throw new Error(`hiddenPath should have _ prefix`)
44+
}
45+
const restoredPath = path.join(
46+
path.dirname(hiddenPath),
47+
path.basename(hiddenPath).slice(1)
48+
)
49+
moveAsset(hiddenPath, restoredPath)
50+
}
51+
52+
const getPageDataPath = pagePath => {
53+
const fixedPagePath = pagePath === `/` ? `index` : pagePath
54+
return path.join(publicDir, `page-data`, fixedPagePath, `page-data.json`)
55+
}
56+
57+
const getHiddenPageDataPath = pagePath => {
58+
const fixedPagePath = pagePath === `/` ? `index` : pagePath
59+
return path.join(publicDir, `page-data`, fixedPagePath, `_page-data.json`)
60+
}
61+
62+
const blockPageData = pagePath =>
63+
moveAsset(getPageDataPath(pagePath), getHiddenPageDataPath(pagePath))
64+
65+
const filterAssets = (assetsForPath, filter) =>
66+
assetsForPath.filter(asset => {
67+
if (filter === `all`) {
68+
return true
69+
} else if (filter === `page-data`) {
70+
return false
71+
}
72+
73+
const isMain = asset.startsWith(`component---`)
74+
if (filter === `page-template`) {
75+
return isMain
76+
} else if (filter === `extra`) {
77+
return !isMain
78+
}
79+
return false
80+
})
81+
82+
const blockAssetsForPage = ({ pagePath, filter }) => {
83+
const assetManifest = getAssetManifest()
84+
85+
const pageData = JSON.parse(fs.readFileSync(getPageDataPath(pagePath)))
86+
const { componentChunkName } = pageData
87+
const assetsForPath = assetManifest[componentChunkName]
88+
89+
const assets = filterAssets(assetsForPath, filter)
90+
assets.forEach(blockAsset)
91+
92+
if (filter === `all` || filter === `page-data`) {
93+
blockPageData(pagePath)
94+
}
95+
96+
console.log(`Blocked assets for path "${pagePath}" [${filter}]`)
97+
return null
98+
}
99+
100+
const restore = () => {
101+
const allAssets = Object.values(getAssetManifest()).reduce((acc, assets) => {
102+
assets.forEach(asset => acc.add(asset))
103+
return acc
104+
}, new Set())
105+
106+
allAssets.forEach(restoreAsset)
107+
108+
const globPattern = path.join(publicDir, `/page-data/**`, `_page-data.json`)
109+
const hiddenPageDatas = glob.sync(globPattern)
110+
hiddenPageDatas.forEach(restorePageData)
111+
112+
console.log(`Restored resources`)
113+
return null
114+
}
115+
116+
module.exports = {
117+
restoreAllBlockedResources: restore,
118+
blockAssetsForChunk,
119+
blockAssetsForPage,
120+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const fs = require(`fs-extra`)
2+
const path = require(`path`)
3+
const glob = require(`glob`)
4+
5+
const replaceHtmlCompilationHash = (filename, newHash) => {
6+
const html = fs.readFileSync(filename, `utf-8`)
7+
const regex = /window\.webpackCompilationHash="\w*"/
8+
const replace = `window.webpackCompilationHash="${newHash}"`
9+
fs.writeFileSync(filename, html.replace(regex, replace), `utf-8`)
10+
}
11+
12+
const replacePageDataCompilationHash = (filename, newHash) => {
13+
const pageData = JSON.parse(fs.readFileSync(filename, `utf-8`))
14+
pageData.webpackCompilationHash = newHash
15+
fs.writeFileSync(filename, JSON.stringify(pageData), `utf-8`)
16+
}
17+
18+
const overwriteWebpackCompilationHash = newHash => {
19+
glob
20+
.sync(path.join(__dirname, `../../public/page-data/**/page-data.json`))
21+
.forEach(filename => replacePageDataCompilationHash(filename, newHash))
22+
glob
23+
.sync(path.join(__dirname, `../../public/**/index.html`))
24+
.forEach(filename => replaceHtmlCompilationHash(filename, newHash))
25+
26+
// cypress requires that null be returned instead of undefined
27+
return null
28+
}
29+
30+
module.exports = {
31+
overwriteWebpackCompilationHash,
32+
}
Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,5 @@
1-
// ***********************************************************
2-
// This example plugins/index.js can be used to load plugins
3-
//
4-
// You can change the location of this file or turn off loading
5-
// the plugins file with the 'pluginsFile' configuration option.
6-
//
7-
// You can read more here:
8-
// https://on.cypress.io/plugins-guide
9-
// ***********************************************************
10-
11-
// This function is called when a project is opened or re-opened (e.g. due to
12-
// the project's config changing)
1+
const compilationHash = require(`./compilation-hash`)
2+
const blockResources = require(`./block-resources`)
133

144
module.exports = (on, config) => {
155
// `on` is used to hook into various events Cypress emits
@@ -27,4 +17,6 @@ module.exports = (on, config) => {
2717
return args
2818
})
2919
}
20+
21+
on(`task`, Object.assign({}, compilationHash, blockResources))
3022
}

0 commit comments

Comments
 (0)