-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathSiteBaker.tsx
1208 lines (1082 loc) · 44.1 KB
/
SiteBaker.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This should be imported as early as possible so the global error handler is
// set up before any errors are thrown.
import "../serverUtils/instrument.js"
import fs from "fs-extra"
import path from "path"
import { glob } from "glob"
import { keyBy, without, uniq, mapValues, pick, chunk } from "lodash"
import ProgressBar from "progress"
import * as db from "../db/db.js"
import {
BLOG_POSTS_PER_PAGE,
BASE_DIR,
GDOCS_DETAILS_ON_DEMAND_ID,
FEATURE_FLAGS,
} from "../settings/serverSettings.js"
import {
renderFrontPage,
renderBlogByPageNum,
renderDataCatalogPage,
renderSearchPage,
renderDonatePage,
makeAtomFeed,
feedbackPage,
renderNotFoundPage,
renderCountryProfile,
flushCache as siteBakingFlushCache,
renderPost,
renderGdoc,
makeAtomFeedNoTopicPages,
renderDynamicCollectionPage,
renderTopChartsCollectionPage,
renderDataInsightsIndexPage,
renderThankYouPage,
makeDataInsightsAtomFeed,
renderGdocTombstone,
renderExplorerIndexPage,
} from "../baker/siteRenderers.js"
import {
bakeGrapherUrls,
getGrapherExportsByUrl,
GrapherExports,
} from "../baker/GrapherBakingUtils.js"
import { makeSitemap } from "../baker/sitemap.js"
import { bakeCountries } from "../baker/countryProfiles.js"
import {
countries,
FullPost,
LinkedAuthor,
LinkedChart,
LinkedIndicator,
extractDetailsFromSyntax,
OwidGdocErrorMessageType,
ImageMetadata,
OwidGdoc,
DATA_INSIGHTS_INDEX_PAGE_SIZE,
OwidGdocMinimalPostInterface,
excludeUndefined,
grabMetadataForGdocLinkedIndicator,
TombstonePageData,
gdocUrlRegex,
ChartViewInfo,
} from "@ourworldindata/utils"
import { execWrapper } from "../db/execWrapper.js"
import { countryProfileSpecs } from "../site/countryProfileProjects.js"
import {
getGrapherRedirectsMap,
getRedirects,
flushCache as redirectsFlushCache,
} from "./redirects.js"
import { bakeAllChangedGrapherPagesVariablesPngSvgAndDeleteRemovedGraphers } from "./GrapherBaker.js"
import { EXPLORERS_ROUTE_FOLDER } from "@ourworldindata/explorer"
import { GIT_CMS_DIR } from "../gitCms/GitCmsConstants.js"
import {
bakeAllExplorerRedirects,
bakeAllPublishedExplorers,
} from "./ExplorerBaker.js"
import { ExplorerAdminServer } from "../explorerAdminServer/ExplorerAdminServer.js"
import {
getBlogIndex,
getFullPost,
getPostsFromSnapshots,
postsFlushCache,
} from "../db/model/Post.js"
import { GdocPost } from "../db/model/Gdoc/GdocPost.js"
import { getAllImages } from "../db/model/Image.js"
import { generateEmbedSnippet } from "../site/viteUtils.js"
import { logErrorAndMaybeCaptureInSentry } from "../serverUtils/errorLog.js"
import {
getChartEmbedUrlsInPublishedWordpressPosts,
mapSlugsToConfigs,
} from "../db/model/Chart.js"
import { FeatureFlagFeature } from "../settings/clientSettings.js"
import pMap from "p-map"
import { GdocDataInsight } from "../db/model/Gdoc/GdocDataInsight.js"
import { calculateDataInsightIndexPageCount } from "../db/model/Gdoc/gdocUtils.js"
import { getVariableMetadata } from "../db/model/Variable.js"
import {
gdocFromJSON,
getAllMinimalGdocBaseObjects,
getLatestDataInsights,
} from "../db/model/Gdoc/GdocFactory.js"
import { getBakePath } from "@ourworldindata/components"
import { GdocAuthor, getMinimalAuthors } from "../db/model/Gdoc/GdocAuthor.js"
import {
makeExplorerLinkedChart,
makeGrapherLinkedChart,
makeMultiDimLinkedChart,
} from "../db/model/Gdoc/GdocBase.js"
import { DATA_INSIGHTS_ATOM_FEED_NAME } from "../site/SiteConstants.js"
import { getRedirectsFromDb } from "../db/model/Redirect.js"
import { getTombstones } from "../db/model/GdocTombstone.js"
import { bakeAllMultiDimDataPages } from "./MultiDimBaker.js"
import { getAllLinkedPublishedMultiDimDataPages } from "../db/model/MultiDimDataPage.js"
import { getPublicDonorNames } from "../db/model/Donor.js"
import { getChartViewsInfo } from "../db/model/ChartView.js"
type PrefetchedAttachments = {
donors: string[]
linkedAuthors: LinkedAuthor[]
linkedDocuments: Record<string, OwidGdocMinimalPostInterface>
imageMetadata: Record<string, ImageMetadata>
linkedCharts: {
graphers: Record<string, LinkedChart>
explorers: Record<string, LinkedChart>
}
linkedIndicators: Record<number, LinkedIndicator>
linkedChartViews: Record<string, ChartViewInfo>
}
// These aren't all "wordpress" steps
// But they're only run when you have the full stack available
const wordpressSteps = [
"assets",
"blogIndex",
"embeds",
"redirects",
"rss",
"wordpressPosts",
] as const
const nonWordpressSteps = [
"specialPages",
"countries",
"countryProfiles",
"explorers",
"charts",
"multiDimPages",
"gdocPosts",
"gdocTombstones",
"dods",
"dataInsights",
"authors",
] as const
const otherSteps = ["removeDeletedPosts"] as const
export const bakeSteps = [
...wordpressSteps,
...nonWordpressSteps,
...otherSteps,
]
export type BakeStep = (typeof bakeSteps)[number]
export type BakeStepConfig = Set<BakeStep>
const defaultSteps = new Set(bakeSteps)
function getProgressBarTotal(bakeSteps: BakeStepConfig): number {
// There are 2 non-optional steps: flushCache at the beginning and flushCache at the end (again)
const minimum = 2
let total = minimum + bakeSteps.size
// Redirects has two progress bar ticks
if (bakeSteps.has("redirects")) total++
// Add a tick for the validation step that occurs when these two steps run
if (bakeSteps.has("dods") && bakeSteps.has("charts")) total++
// Add ticks for prefetching attachments, which will only run if any of these steps are enabled
if (
bakeSteps.has("gdocPosts") ||
bakeSteps.has("gdocTombstones") ||
bakeSteps.has("dataInsights") ||
bakeSteps.has("authors") ||
bakeSteps.has("multiDimPages")
) {
total += 9
}
return total
}
export class SiteBaker {
private grapherExports!: GrapherExports
private bakedSiteDir: string
baseUrl: string
progressBar: ProgressBar
explorerAdminServer: ExplorerAdminServer
bakeSteps: BakeStepConfig
constructor(
bakedSiteDir: string,
baseUrl: string,
bakeSteps: BakeStepConfig = defaultSteps
) {
this.bakedSiteDir = bakedSiteDir
this.baseUrl = baseUrl
this.bakeSteps = bakeSteps
this.progressBar = new ProgressBar(
"--- BakeAll [:bar] :current/:total :elapseds :name\n",
{
total: getProgressBarTotal(bakeSteps),
renderThrottle: 0,
}
)
this.explorerAdminServer = new ExplorerAdminServer(GIT_CMS_DIR)
}
private async bakeEmbeds(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("embeds")) return
// Find all grapher urls used as embeds in all Wordpress posts on the site
const grapherUrls = uniq(
await getChartEmbedUrlsInPublishedWordpressPosts(knex)
)
await bakeGrapherUrls(knex, grapherUrls)
this.grapherExports = await getGrapherExportsByUrl()
this.progressBar.tick({ name: "✅ baked embeds" })
}
private async bakeCountryProfiles(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("countryProfiles")) return
await Promise.all(
countryProfileSpecs.map(async (spec) => {
// Delete all country profiles before regenerating them
await fs.remove(`${this.bakedSiteDir}/${spec.rootPath}`)
// Not necessary, as this is done by stageWrite already
// await this.ensureDir(profile.rootPath)
for (const country of countries) {
const html = await renderCountryProfile(
spec,
country,
knex,
this.grapherExports
).catch(() =>
console.error(
`${country.name} country profile not baked for project "${spec.project}". Check that both pages "${spec.landingPageSlug}" and "${spec.genericProfileSlug}" exist and are published.`
)
)
if (html) {
const outPath = path.join(
this.bakedSiteDir,
`${spec.rootPath}/${country.slug}.html`
)
await this.stageWrite(outPath, html)
}
}
})
)
this.progressBar.tick({ name: "✅ baked country profiles" })
}
// Bake an individual post/page
private async bakeOwidGdoc(gdoc: OwidGdoc) {
const html = renderGdoc(gdoc)
const outPath = `${getBakePath(this.bakedSiteDir, gdoc)}.html`
await fs.mkdirp(path.dirname(outPath))
await this.stageWrite(outPath, html)
}
private async bakeOwidGdocTombstone(
tombstone: TombstonePageData,
attachments: PrefetchedAttachments
) {
const html = renderGdocTombstone(tombstone, {
...attachments,
linkedCharts: {},
relatedCharts: [],
})
const outPath = path.join(
this.bakedSiteDir,
"deleted",
`${tombstone.slug}.html`
)
await this.stageWrite(outPath, html)
}
// Bake an individual post/page
private async bakePost(post: FullPost, knex: db.KnexReadonlyTransaction) {
const html = await renderPost(
post,
knex,
this.baseUrl,
this.grapherExports
)
const outPath = path.join(this.bakedSiteDir, `${post.slug}.html`)
await fs.mkdirp(path.dirname(outPath))
await this.stageWrite(outPath, html)
}
// Returns the slugs of posts which exist on the filesystem but are not in the DB anymore.
// This happens when posts have been saved in previous bakes but have been since then deleted, unpublished or renamed.
// Among all existing slugs on the filesystem, some are not coming from WP. They are baked independently and should not
// be deleted if WP does not list them (e.g. grapher/*).
private getPostSlugsToRemove(postSlugsFromDb: string[]) {
const existingSlugs = glob
.sync(`${this.bakedSiteDir}/**/*.html`)
.map((path) =>
path.replace(`${this.bakedSiteDir}/`, "").replace(".html", "")
)
.filter(
(path) =>
!path.startsWith("uploads") &&
!path.startsWith("grapher") &&
!path.startsWith("countries") &&
!path.startsWith("country") &&
!path.startsWith("latest") &&
!path.startsWith("explore") &&
!countryProfileSpecs.some((spec) =>
path.startsWith(spec.rootPath)
) &&
path !== "donate" &&
path !== "feedback" &&
path !== "charts" &&
path !== "search" &&
path !== "index" &&
path !== "identifyadmin" &&
path !== "404" &&
path !== "google8272294305985984"
)
return without(existingSlugs, ...postSlugsFromDb)
}
// Prefetches all linkedAuthors, linkedDocuments, imageMetadata,
// linkedCharts, and linkedIndicators instead of having to fetch them for
// each individual gdoc. Optionally takes a tuple of string arrays to pick
// from the prefetched dictionaries.
_prefetchedAttachmentsCache: PrefetchedAttachments | undefined = undefined
private async getPrefetchedGdocAttachments(
knex: db.KnexReadonlyTransaction,
picks?: [string[], string[], string[], string[], string[], string[]]
): Promise<PrefetchedAttachments> {
if (!this._prefetchedAttachmentsCache) {
console.log("Prefetching attachments...")
const donors = await getPublicDonorNames(knex)
this.progressBar.tick({
name: `✅ Prefetched donors`,
})
const publishedGdocs = await getAllMinimalGdocBaseObjects(knex)
const publishedGdocsDictionary = keyBy(publishedGdocs, "id")
this.progressBar.tick({
name: `✅ Prefetched ${publishedGdocs.length} gdocs`,
})
const imageMetadataDictionary = await getAllImages(knex).then(
(images) => keyBy(images, "filename")
)
this.progressBar.tick({
name: `✅ Prefetched ${Object.values(imageMetadataDictionary).length} images`,
})
const publishedExplorersBySlug = await this.explorerAdminServer
.getAllPublishedExplorersBySlugCached()
.then((results) =>
mapValues(results, (explorer) => {
return makeExplorerLinkedChart(explorer, explorer.slug)
})
)
this.progressBar.tick({
name: `✅ Prefetched ${Object.values(publishedExplorersBySlug).length} explorers`,
})
// Get all grapher links from the database so that we only prefetch the ones that are actually in use
// 2024-06-25 before/after: 6266/2194
const grapherLinks = await db
.getGrapherLinkTargets(knex)
.then((rows) => rows.map((row) => row.target))
.then((targets) => new Set(targets))
// Includes redirects
const publishedChartsRaw = await mapSlugsToConfigs(knex).then(
(configs) => {
return configs.filter((config) =>
grapherLinks.has(config.slug)
)
}
)
const publishedCharts: LinkedChart[] = []
for (const publishedChartsRawChunk of chunk(
publishedChartsRaw,
20
)) {
await Promise.all(
publishedChartsRawChunk.map(async (chart) => {
publishedCharts.push(
await makeGrapherLinkedChart(
chart.config,
chart.slug
)
)
})
)
}
const multiDims = await getAllLinkedPublishedMultiDimDataPages(knex)
for (const { slug, config } of multiDims) {
publishedCharts.push(makeMultiDimLinkedChart(config, slug))
}
const publishedChartsBySlug = keyBy(publishedCharts, "originalSlug")
this.progressBar.tick({
name: `✅ Prefetched ${publishedCharts.length} charts`,
})
// The only reason we need linkedIndicators is for the KeyIndicator+KeyIndicatorCollection components.
// The homepage is currently the only place that uses them (and it handles its data fetching separately)
// so all of this is kind of redundant, but it's here for completeness if we start using them elsewhere
const allLinkedIndicatorSlugs = await db.getLinkedIndicatorSlugs({
knex,
excludeHomepage: true,
})
const linkedIndicatorCharts = publishedCharts.filter(
(chart) =>
allLinkedIndicatorSlugs.has(chart.originalSlug) &&
chart.indicatorId
)
const linkedIndicators: LinkedIndicator[] = await Promise.all(
linkedIndicatorCharts.map(async (linkedChart) => {
const indicatorId = linkedChart.indicatorId as number
const metadata = await getVariableMetadata(indicatorId)
return {
id: indicatorId,
...grabMetadataForGdocLinkedIndicator(metadata, {
chartConfigTitle: linkedChart.title,
}),
}
})
)
this.progressBar.tick({
name: `✅ Prefetched ${linkedIndicators.length} linked indicators`,
})
const datapageIndicatorsById = keyBy(linkedIndicators, "id")
const publishedAuthors = await getMinimalAuthors(knex)
this.progressBar.tick({
name: `✅ Prefetched ${publishedAuthors.length} authors`,
})
const chartViewsInfo = await getChartViewsInfo(knex)
const chartViewsInfoByName = keyBy(chartViewsInfo, "name")
this.progressBar.tick({
name: `✅ Prefetched ${chartViewsInfo.length} chart views`,
})
const prefetchedAttachments = {
donors,
linkedAuthors: publishedAuthors,
linkedDocuments: publishedGdocsDictionary,
imageMetadata: imageMetadataDictionary,
linkedCharts: {
explorers: publishedExplorersBySlug,
graphers: publishedChartsBySlug,
},
linkedIndicators: datapageIndicatorsById,
linkedChartViews: chartViewsInfoByName,
}
this.progressBar.tick({ name: "✅ Prefetched attachments" })
this._prefetchedAttachmentsCache = prefetchedAttachments
}
if (picks) {
const [
authorNames,
linkedDocumentIds,
imageFilenames,
linkedGrapherSlugs,
linkedExplorerSlugs,
linkedChartViewNames,
] = picks
const linkedDocuments = pick(
this._prefetchedAttachmentsCache.linkedDocuments,
linkedDocumentIds
)
// Gdoc.linkedImageFilenames normally gets featuredImages, but it relies on linkedDocuments already being populated,
// which is isn't when we're prefetching attachments. So we have to do it manually here.
const featuredImages = Object.values(linkedDocuments)
.map((gdoc) => gdoc["featured-image"])
.filter((filename): filename is string => !!filename)
const linkedGrapherCharts = pick(
this._prefetchedAttachmentsCache.linkedCharts.graphers,
linkedGrapherSlugs
)
const linkedIndicatorIds = excludeUndefined(
Object.values(linkedGrapherCharts).map(
(chart) => chart.indicatorId
)
)
return {
donors: this._prefetchedAttachmentsCache.donors,
linkedDocuments,
imageMetadata: pick(
this._prefetchedAttachmentsCache.imageMetadata,
[...imageFilenames, ...featuredImages]
),
linkedCharts: {
graphers: {
...linkedGrapherCharts,
},
explorers: {
...pick(
this._prefetchedAttachmentsCache.linkedCharts
.explorers,
linkedExplorerSlugs
),
},
},
linkedIndicators: pick(
this._prefetchedAttachmentsCache.linkedIndicators,
linkedIndicatorIds
),
linkedAuthors:
this._prefetchedAttachmentsCache.linkedAuthors.filter(
(author) => authorNames.includes(author.name)
),
linkedChartViews: pick(
this._prefetchedAttachmentsCache.linkedChartViews,
linkedChartViewNames
),
}
}
return this._prefetchedAttachmentsCache
}
private async removeDeletedPosts(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("removeDeletedPosts")) return
const postsApi = await getPostsFromSnapshots(knex)
const postSlugs = []
for (const postApi of postsApi) {
const post = await getFullPost(knex, postApi)
postSlugs.push(post.slug)
}
const gdocPosts = await getAllMinimalGdocBaseObjects(knex)
for (const post of gdocPosts) {
postSlugs.push(post.slug)
}
// Delete any previously rendered posts that aren't in the database
for (const slug of this.getPostSlugsToRemove(postSlugs)) {
const outPath = `${this.bakedSiteDir}/${slug}.html`
await fs.unlink(outPath)
this.stage(outPath, `DELETING ${outPath}`)
}
this.progressBar.tick({ name: "✅ removed deleted posts" })
}
private async bakePosts(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("wordpressPosts")) return
const alreadyPublishedViaGdocsSlugsSet =
await db.getSlugsWithPublishedGdocsSuccessors(knex)
const redirects = await getRedirectsFromDb(knex)
const postsApi = await getPostsFromSnapshots(
knex,
undefined,
(postrow) =>
// Exclude posts that are already published via GDocs
!alreadyPublishedViaGdocsSlugsSet.has(postrow.slug) &&
// Exclude posts that are redirect sources
!redirects.some((row) => row.source.slice(1) === postrow.slug)
)
await pMap(
postsApi,
async (postApi) =>
getFullPost(knex, postApi).then((post) =>
this.bakePost(post, knex)
),
{ concurrency: 10 }
)
this.progressBar.tick({ name: "✅ baked posts" })
}
// Bake all GDoc posts, or a subset of them if slugs are provided
async bakeGDocPosts(knex: db.KnexReadonlyTransaction, slugs?: string[]) {
if (!this.bakeSteps.has("gdocPosts")) return
// We don't need to call `load` on these, because we prefetch all attachments
const publishedGdocs = await db
.getPublishedGdocPostsWithTags(knex)
.then((gdocs) => gdocs.map(gdocFromJSON))
const allParentTagArraysByChildName =
await db.getParentTagArraysByChildName(knex)
const gdocsToBake =
slugs !== undefined
? publishedGdocs.filter((gdoc) => slugs.includes(gdoc.slug))
: publishedGdocs
// Ensure we have a published gdoc for each slug given
if (slugs !== undefined && slugs.length !== gdocsToBake.length) {
const slugsNotFound = slugs.filter(
(slug) => !gdocsToBake.find((gdoc) => gdoc.slug === slug)
)
throw new Error(
`Some of the gdoc slugs were not found or are not published: ${slugsNotFound}`
)
}
for (const publishedGdoc of gdocsToBake) {
const attachments = await this.getPrefetchedGdocAttachments(knex, [
publishedGdoc.content.authors,
publishedGdoc.linkedDocumentIds,
publishedGdoc.linkedImageFilenames,
publishedGdoc.linkedChartSlugs.grapher,
publishedGdoc.linkedChartSlugs.explorer,
publishedGdoc.linkedChartViewNames,
])
publishedGdoc.donors = attachments.donors
publishedGdoc.linkedAuthors = attachments.linkedAuthors
publishedGdoc.linkedDocuments = attachments.linkedDocuments
publishedGdoc.imageMetadata = attachments.imageMetadata
publishedGdoc.linkedCharts = {
...attachments.linkedCharts.graphers,
...attachments.linkedCharts.explorers,
}
publishedGdoc.linkedIndicators = attachments.linkedIndicators
publishedGdoc.linkedChartViews = attachments.linkedChartViews
if (
!publishedGdoc.manualBreadcrumbs?.length &&
publishedGdoc.tags?.length
) {
publishedGdoc.breadcrumbs = db.getBestBreadcrumbs(
publishedGdoc.tags,
allParentTagArraysByChildName
)
}
// this is a no-op if the gdoc doesn't have an all-chart block
if ("loadRelatedCharts" in publishedGdoc) {
await publishedGdoc.loadRelatedCharts(knex)
}
await publishedGdoc.validate(knex)
try {
await this.bakeOwidGdoc(publishedGdoc)
} catch (e) {
await logErrorAndMaybeCaptureInSentry(
new Error(
`Error baking gdoc post with id "${publishedGdoc.id}" and slug "${publishedGdoc.slug}": ${e}`
)
)
}
}
this.progressBar.tick({ name: "✅ baked google doc posts" })
}
async bakeGDocTombstones(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("gdocTombstones")) return
const tombstones = await getTombstones(knex)
for (const tombstone of tombstones) {
const attachments = await this.getPrefetchedGdocAttachments(knex)
const linkedGdocId =
tombstone.relatedLinkUrl?.match(gdocUrlRegex)?.[1]
if (linkedGdocId) {
const linkedDocument = attachments.linkedDocuments[linkedGdocId]
if (!linkedDocument) {
await logErrorAndMaybeCaptureInSentry(
new Error(
`Tombstone with id "${tombstone.id}" references a gdoc with id "${linkedGdocId}" which was not found`
)
)
}
}
try {
await this.bakeOwidGdocTombstone(tombstone, attachments)
} catch (e) {
await logErrorAndMaybeCaptureInSentry(
new Error(
`Error baking gdoc tombstone with id "${tombstone.id}" and slug "${tombstone.slug}": ${e}`
)
)
}
}
this.progressBar.tick({ name: "✅ baked google doc tombstones" })
}
// Bake unique individual pages
private async bakeSpecialPages(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("specialPages")) return
await this.stageWrite(
`${this.bakedSiteDir}/index.html`,
await renderFrontPage(knex)
)
await this.stageWrite(
`${this.bakedSiteDir}/donate.html`,
await renderDonatePage(knex)
)
await this.stageWrite(
`${this.bakedSiteDir}/thank-you.html`,
await renderThankYouPage()
)
await this.stageWrite(
`${this.bakedSiteDir}/feedback.html`,
await feedbackPage()
)
await this.stageWrite(
`${this.bakedSiteDir}/search.html`,
await renderSearchPage()
)
await this.stageWrite(
`${this.bakedSiteDir}/explorers.html`,
await renderExplorerIndexPage(knex)
)
await this.stageWrite(
`${this.bakedSiteDir}/collection/custom.html`,
await renderDynamicCollectionPage()
)
await this.stageWrite(
`${this.bakedSiteDir}/collection/top-charts.html`,
await renderTopChartsCollectionPage(knex)
)
await this.stageWrite(
`${this.bakedSiteDir}/404.html`,
await renderNotFoundPage()
)
await this.stageWrite(
`${this.bakedSiteDir}/sitemap.xml`,
await makeSitemap(this.explorerAdminServer, knex)
)
await this.stageWrite(
`${this.bakedSiteDir}/data.html`,
await renderDataCatalogPage(knex)
)
this.progressBar.tick({ name: "✅ baked special pages" })
}
private async bakeExplorers(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("explorers")) return
await bakeAllExplorerRedirects(
this.bakedSiteDir,
this.explorerAdminServer,
knex
)
await bakeAllPublishedExplorers(
`${this.bakedSiteDir}/${EXPLORERS_ROUTE_FOLDER}`,
this.explorerAdminServer,
knex
)
this.progressBar.tick({ name: "✅ baked explorers" })
}
private async validateGrapherDodReferences(
knex: db.KnexReadonlyTransaction
) {
if (!this.bakeSteps.has("dods") || !this.bakeSteps.has("charts")) return
if (!GDOCS_DETAILS_ON_DEMAND_ID) {
console.error(
"GDOCS_DETAILS_ON_DEMAND_ID not set. Unable to validate dods."
)
return
}
const { details } = await GdocPost.getDetailsOnDemandGdoc(knex)
if (!details) {
this.progressBar.tick({
name: "✅ no details exist. skipping grapher dod validation step",
})
return
}
const charts: { slug: string; subtitle: string; note: string }[] =
await db.knexRaw<{ slug: string; subtitle: string; note: string }>(
knex,
`-- sql
SELECT
cc.slug,
cc.full ->> '$.subtitle' as subtitle,
cc.full ->> '$.note' as note
FROM
charts c
JOIN
chart_configs cc ON c.configId = cc.id
WHERE
JSON_EXTRACT(cc.full, "$.isPublished") = true
AND (
JSON_EXTRACT(cc.full, "$.subtitle") LIKE "%#dod:%"
OR JSON_EXTRACT(cc.full, "$.note") LIKE "%#dod:%"
)
ORDER BY
cc.slug ASC
`
)
for (const chart of charts) {
const detailIds = new Set(
extractDetailsFromSyntax(`${chart.note} ${chart.subtitle}`)
)
for (const detailId of detailIds) {
if (!details[detailId]) {
await logErrorAndMaybeCaptureInSentry(
new Error(
`Grapher with slug ${chart.slug} references dod "${detailId}" which does not exist`
)
)
}
}
}
this.progressBar.tick({ name: "✅ validated grapher dods" })
}
private async bakeMultiDimPages(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("multiDimPages")) return
if (!FEATURE_FLAGS.has(FeatureFlagFeature.MultiDimDataPage)) {
console.log(
"Skipping baking multi-dim pages because feature flag is not set"
)
return
}
const { imageMetadata } = await this.getPrefetchedGdocAttachments(knex)
await bakeAllMultiDimDataPages(knex, this.bakedSiteDir, imageMetadata)
this.progressBar.tick({ name: "✅ baked multi-dim pages" })
}
private async bakeDetailsOnDemand(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("dods")) return
if (!GDOCS_DETAILS_ON_DEMAND_ID) {
console.error(
"GDOCS_DETAILS_ON_DEMAND_ID not set. Unable to bake dods."
)
return
}
const { details, parseErrors } =
await GdocPost.getDetailsOnDemandGdoc(knex)
if (parseErrors.length) {
await logErrorAndMaybeCaptureInSentry(
new Error(
`Error(s) baking details: ${parseErrors
.map((e) => e.message)
.join(", ")}`
)
)
}
if (details) {
await this.stageWrite(
`${this.bakedSiteDir}/dods.json`,
JSON.stringify(details)
)
this.progressBar.tick({ name: "✅ baked dods.json" })
} else {
throw Error("Details on demand not found")
}
}
private async bakeDataInsights(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("dataInsights")) return
const {
dataInsights: latestDataInsights,
imageMetadata: latestDataInsightsImageMetadata,
} = await getLatestDataInsights(knex)
const publishedDataInsights =
await GdocDataInsight.getPublishedDataInsights(knex)
for (const dataInsight of publishedDataInsights) {
const attachments = await this.getPrefetchedGdocAttachments(knex, [
dataInsight.content.authors,
dataInsight.linkedDocumentIds,
dataInsight.linkedImageFilenames,
dataInsight.linkedChartSlugs.grapher,
dataInsight.linkedChartSlugs.explorer,
dataInsight.linkedChartViewNames,
])
dataInsight.linkedDocuments = attachments.linkedDocuments
dataInsight.imageMetadata = {
...attachments.imageMetadata,
...latestDataInsightsImageMetadata,
}
dataInsight.linkedCharts = {
...attachments.linkedCharts.graphers,
...attachments.linkedCharts.explorers,
}
dataInsight.latestDataInsights = latestDataInsights
await dataInsight.validate(knex)
try {
await this.bakeOwidGdoc(dataInsight)
} catch (e) {
await logErrorAndMaybeCaptureInSentry(
new Error(
`Error baking gdoc post with id "${dataInsight.id}" and slug "${dataInsight.slug}": ${e}`
)
)
}
// We don't need the latest data insights nor their images in the
// feed later, when we render the list of all data insights.
dataInsight.latestDataInsights = []
dataInsight.imageMetadata = attachments.imageMetadata
}
const totalPageCount = calculateDataInsightIndexPageCount(
publishedDataInsights.length
)
for (let pageNumber = 0; pageNumber < totalPageCount; pageNumber++) {
const html = renderDataInsightsIndexPage(
publishedDataInsights.slice(
pageNumber * DATA_INSIGHTS_INDEX_PAGE_SIZE,
(pageNumber + 1) * DATA_INSIGHTS_INDEX_PAGE_SIZE
),
pageNumber,
totalPageCount
)
// Page 0 is data-insights.html, page 1 is data-insights/2.html, etc.
const filename = pageNumber === 0 ? "" : `/${pageNumber + 1}`
const outPath = path.join(
this.bakedSiteDir,
`data-insights${filename}.html`
)
await fs.mkdirp(path.dirname(outPath))
await this.stageWrite(outPath, html)
}
}
private async bakeAuthors(knex: db.KnexReadonlyTransaction) {
if (!this.bakeSteps.has("authors")) return
const publishedAuthors = await GdocAuthor.getPublishedAuthors(knex)
for (const publishedAuthor of publishedAuthors) {
const attachments = await this.getPrefetchedGdocAttachments(knex, [
publishedAuthor.content.authors,
publishedAuthor.linkedDocumentIds,
publishedAuthor.linkedImageFilenames,
publishedAuthor.linkedChartSlugs.grapher,
publishedAuthor.linkedChartSlugs.explorer,
publishedAuthor.linkedChartViewNames,
])
// We don't need these to be attached to the gdoc in the current
// state of author pages. We'll keep them here as documentation
// of intent, until we need them.
// publishedAuthor.linkedCharts = {
// ...attachments.linkedCharts.graphers,
// ...attachments.linkedCharts.explorers,
// }
// publishedAuthor.linkedAuthors = attachments.linkedAuthors
// Attach documents metadata linked to in the "featured work" section
publishedAuthor.linkedDocuments = attachments.linkedDocuments
// Attach image metadata for the profile picture and the "featured work" images
publishedAuthor.imageMetadata = attachments.imageMetadata
// Attach image metadata for the “latest work" images
await publishedAuthor.loadLatestWorkImages(knex)
await publishedAuthor.validate(knex)
if (
publishedAuthor.errors.filter(
(e) => e.type === OwidGdocErrorMessageType.Error
).length
) {
await logErrorAndMaybeCaptureInSentry(
new Error(
`Error(s) baking "${
publishedAuthor.slug
}" :\n ${publishedAuthor.errors
.map((error) => error.message)