Skip to content

Commit 0585bf0

Browse files
author
Nicolas Dorseuil
committed
use DO tag cache in the server
Fix NextRequest body being incorrect
1 parent 2c9431e commit 0585bf0

File tree

8 files changed

+109
-139
lines changed

8 files changed

+109
-139
lines changed

packages/gitbook-v2/open-next.config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export default {
88
proxyExternalRequest: 'fetch',
99
queue: () => import('./openNext/queue/server').then((m) => m.default),
1010
incrementalCache: () => import('./openNext/incrementalCache').then((m) => m.default),
11-
tagCache: () => import('./openNext/tagCache/server').then((m) => m.default),
11+
tagCache: () => import('./openNext/tagCache/middleware').then((m) => m.default),
1212
},
1313
},
1414
middleware: {

packages/gitbook-v2/openNext/customWorkers/default.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import { runWithCloudflareRequestContext } from '../../.open-next/cloudflare/init.js';
22

3-
import { handler } from '../../.open-next/server-functions/default/handler.mjs';
4-
53
export default {
64
async fetch(request, env, ctx) {
75
return runWithCloudflareRequestContext(request, env, ctx, async () => {
6+
// We can't move the handler import to the top level, otherwise the runtime will not be properly initialized
7+
const { handler } = await import(
8+
'../../.open-next/server-functions/default/handler.mjs'
9+
);
10+
811
// - `Request`s are handled by the Next server
912
return handler(request, env, ctx);
1013
});

packages/gitbook-v2/openNext/customWorkers/defaultWrangler.jsonc

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,14 @@
2828
{
2929
"binding": "WORKER_SELF_REFERENCE",
3030
"service": "gitbook-open-v2-server-dev"
31-
},
32-
{
33-
"binding": "MIDDLEWARE_REFERENCE",
34-
"service": "gitbook-open-v2-dev"
3531
}
3632
]
3733
},
3834
"preview": {
3935
"vars": {
40-
"STAGE": "preview"
36+
"STAGE": "preview",
37+
// Just as a test for the preview environment to check that everything works
38+
"NEXT_PRIVATE_DEBUG_CACHE": "true"
4139
},
4240
"r2_buckets": [
4341
{
@@ -49,10 +47,6 @@
4947
{
5048
"binding": "WORKER_SELF_REFERENCE",
5149
"service": "gitbook-open-v2-server-preview"
52-
},
53-
{
54-
"binding": "MIDDLEWARE_REFERENCE",
55-
"service": "gitbook-open-v2-preview"
5650
}
5751
]
5852
// No durable objects on preview, as they block the generation of preview URLs
@@ -69,10 +63,21 @@
6963
{
7064
"binding": "WORKER_SELF_REFERENCE",
7165
"service": "gitbook-open-v2-server-staging"
72-
},
66+
}
67+
],
68+
"durable_objects": {
69+
"bindings": [
70+
{
71+
"name": "NEXT_TAG_CACHE_DO_SHARDED",
72+
"class_name": "DOShardedTagCache",
73+
"script_name": "gitbook-open-v2-staging"
74+
}
75+
]
76+
},
77+
"migrations": [
7378
{
74-
"binding": "MIDDLEWARE_REFERENCE",
75-
"service": "gitbook-open-v2-staging"
79+
"tag": "v1",
80+
"new_sqlite_classes": ["DOShardedTagCache"]
7681
}
7782
],
7883
"tail_consumers": [
@@ -92,10 +97,21 @@
9297
{
9398
"binding": "WORKER_SELF_REFERENCE",
9499
"service": "gitbook-open-v2-server-production"
95-
},
100+
}
101+
],
102+
"durable_objects": {
103+
"bindings": [
104+
{
105+
"name": "NEXT_TAG_CACHE_DO_SHARDED",
106+
"class_name": "DOShardedTagCache",
107+
"script_name": "gitbook-open-v2-production"
108+
}
109+
]
110+
},
111+
"migrations": [
96112
{
97-
"binding": "MIDDLEWARE_REFERENCE",
98-
"service": "gitbook-open-v2-production"
113+
"tag": "v1",
114+
"new_sqlite_classes": ["DOShardedTagCache"]
99115
}
100116
],
101117
"tail_consumers": [
Lines changed: 4 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import { WorkerEntrypoint } from 'cloudflare:workers';
22
import { runWithCloudflareRequestContext } from '../../.open-next/cloudflare/init.js';
33

4-
import onConfig from '../../.open-next/middleware/open-next.config.mjs';
5-
64
import { handler as middlewareHandler } from '../../.open-next/middleware/handler.mjs';
75

86
export { DOQueueHandler } from '../../.open-next/.build/durable-objects/queue.js';
@@ -19,10 +17,11 @@ export default class extends WorkerEntrypoint {
1917
}
2018

2119
if (this.env.STAGE !== 'preview') {
20+
reqOrResp.headers.set(
21+
'Cloudflare-Workers-Version-Overrides',
22+
`gitbook-open-v2-${this.env.STAGE}="${this.env.WORKER_VERSION_ID}"`
23+
);
2224
return this.env.DEFAULT_WORKER?.fetch(reqOrResp, {
23-
headers: {
24-
'Cloudflare-Workers-Version-Overrides': `gitbook-open-v2-${this.env.STAGE}="${this.env.WORKER_VERSION_ID}"`,
25-
},
2625
cf: {
2726
cacheEverything: false,
2827
},
@@ -39,37 +38,4 @@ export default class extends WorkerEntrypoint {
3938
});
4039
});
4140
}
42-
43-
/**
44-
* All the functions below are used to interact with the tag cache.
45-
* They are needed for the server who wouldn't be able to access the tag cache directly.
46-
*/
47-
48-
async getLastRevalidated() {
49-
return runWithCloudflareRequestContext(
50-
new Request('http://local'),
51-
this.env,
52-
this.ctx,
53-
async () => {
54-
const tagCache = await onConfig.middleware.override.tagCache();
55-
if (tagCache) {
56-
return tagCache.getLastRevalidated();
57-
}
58-
}
59-
);
60-
}
61-
62-
async writeTags(tags) {
63-
return runWithCloudflareRequestContext(
64-
new Request('http://local'),
65-
this.env,
66-
this.ctx,
67-
async () => {
68-
const tagCache = await onConfig.middleware.override.tagCache();
69-
if (tagCache) {
70-
return tagCache.writeTags(tags);
71-
}
72-
}
73-
);
74-
}
7541
}

packages/gitbook-v2/openNext/customWorkers/middlewareWrangler.jsonc

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
"env": {
2121
"dev": {
2222
"vars": {
23-
"STAGE": "dev"
23+
"STAGE": "dev",
24+
"NEXT_PRIVATE_DEBUG_CACHE": "true"
2425
},
2526
"r2_buckets": [
2627
{

packages/gitbook-v2/openNext/queue/middleware.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { trace } from '@/lib/tracing';
12
import type { Queue } from '@opennextjs/aws/types/overrides.js';
23
import { getCloudflareContext } from '@opennextjs/cloudflare';
34
import doQueue from '@opennextjs/cloudflare/overrides/queue/do-queue';
@@ -10,8 +11,11 @@ interface Env {
1011
export default {
1112
name: 'GitbookISRQueue',
1213
send: async (msg) => {
13-
const { ctx, env } = getCloudflareContext();
14-
const hasDurableObject = (env as Env).STAGE !== 'dev' && (env as Env).STAGE !== 'preview';
15-
ctx.waitUntil(hasDurableObject ? memoryQueue.send(msg) : doQueue.send(msg));
14+
return trace({ operation: 'gitbookISRQueueSend', name: msg.MessageBody.url }, async () => {
15+
const { ctx, env } = getCloudflareContext();
16+
const hasDurableObject =
17+
(env as Env).STAGE !== 'dev' && (env as Env).STAGE !== 'preview';
18+
ctx.waitUntil(hasDurableObject ? memoryQueue.send(msg) : doQueue.send(msg));
19+
});
1620
},
1721
} satisfies Queue;
Lines changed: 59 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,76 @@
1+
import { trace } from '@/lib/tracing';
12
import type { NextModeTagCache } from '@opennextjs/aws/types/overrides.js';
23
import doShardedTagCache from '@opennextjs/cloudflare/overrides/tag-cache/do-sharded-tag-cache';
3-
import {
4-
softTagFilter,
5-
withFilter,
6-
} from '@opennextjs/cloudflare/overrides/tag-cache/tag-cache-filter';
4+
import { softTagFilter } from '@opennextjs/cloudflare/overrides/tag-cache/tag-cache-filter';
75

8-
const filteredTagCache = withFilter({
9-
tagCache: doShardedTagCache({
10-
baseShardSize: 12,
11-
regionalCache: true,
12-
shardReplication: {
13-
numberOfSoftReplicas: 2,
14-
numberOfHardReplicas: 1,
15-
},
16-
}),
17-
// We don't use `revalidatePath`, so we filter out soft tags
18-
filterFn: softTagFilter,
6+
const originalTagCache = doShardedTagCache({
7+
baseShardSize: 12,
8+
regionalCache: true,
9+
shardReplication: {
10+
numberOfSoftReplicas: 2,
11+
numberOfHardReplicas: 1,
12+
},
1913
});
2014

2115
export default {
2216
name: 'GitbookTagCache',
2317
mode: 'nextMode',
2418
getLastRevalidated: async (tags: string[]) => {
25-
try {
26-
return await filteredTagCache.getLastRevalidated(tags);
27-
} catch (error) {
28-
console.error('Error getting last revalidated tags:', error);
29-
return 0; // Fallback to 0 if there's an error
19+
const tagsToCheck = tags.filter(softTagFilter);
20+
if (tagsToCheck.length === 0) {
21+
// If we reach here, it probably means that there is an issue that we'll need to address.
22+
console.warn(
23+
'getLastRevalidated - No valid tags to check for last revalidation, original tags:',
24+
tags
25+
);
26+
return 0; // If no tags to check, return 0
3027
}
28+
return trace(
29+
{
30+
operation: 'gitbookTagCacheGetLastRevalidated',
31+
name: tagsToCheck.join(', '),
32+
},
33+
async () => {
34+
return await originalTagCache.getLastRevalidated(tagsToCheck);
35+
}
36+
);
3137
},
3238
hasBeenRevalidated: async (tags: string[]) => {
33-
try {
34-
return await filteredTagCache.hasBeenRevalidated(tags);
35-
} catch (error) {
36-
console.error('Error checking if tags have been revalidated:', error);
37-
return false; // Fallback to false if there's an error
39+
const tagsToCheck = tags.filter(softTagFilter);
40+
if (tagsToCheck.length === 0) {
41+
// If we reach here, it probably means that there is an issue that we'll need to address.
42+
console.warn(
43+
'hasBeenRevalidated - No valid tags to check for revalidation, original tags:',
44+
tags
45+
);
46+
return false; // If no tags to check, return false
3847
}
48+
return trace(
49+
{
50+
operation: 'gitbookTagCacheHasBeenRevalidated',
51+
name: tagsToCheck.join(', '),
52+
},
53+
async () => {
54+
const result = await originalTagCache.hasBeenRevalidated(tagsToCheck);
55+
return result;
56+
}
57+
);
3958
},
4059
writeTags: async (tags: string[]) => {
41-
try {
42-
await filteredTagCache.writeTags(tags);
43-
} catch (error) {
44-
console.error('Error writing tags:', error);
45-
}
60+
return trace(
61+
{
62+
operation: 'gitbookTagCacheWriteTags',
63+
name: tags.join(', '),
64+
},
65+
async () => {
66+
const tagsToWrite = tags.filter(softTagFilter);
67+
if (tagsToWrite.length === 0) {
68+
console.warn('writeTags - No valid tags to write');
69+
return; // If no tags to write, exit early
70+
}
71+
// Write only the filtered tags
72+
await originalTagCache.writeTags(tagsToWrite);
73+
}
74+
);
4675
},
4776
} satisfies NextModeTagCache;

packages/gitbook-v2/openNext/tagCache/server.ts

Lines changed: 0 additions & 49 deletions
This file was deleted.

0 commit comments

Comments
 (0)