Skip to content

POC of container with OpenNext on cloudflare #3383

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

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 50 additions & 41 deletions .github/composite/deploy-cloudflare/action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ runs:
GITBOOK_ASSETS_PREFIX: ${{ inputs.opItem }}/GITBOOK_ASSETS_PREFIX
GITBOOK_FONTS_URL: ${{ inputs.opItem }}/GITBOOK_FONTS_URL
- name: Build worker
run: bun run turbo build:v2:cloudflare
run: bun run turbo build:v2:container
env:
GITBOOK_RUNTIME: cloudflare
shell: bash
Expand All @@ -70,32 +70,42 @@ runs:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.10.0'
wranglerVersion: '4.21.1'
environment: ${{ inputs.environment }}
command: deploy --config ./packages/gitbook-v2/openNext/customWorkers/doWrangler.jsonc

- id: upload_server
name: Upload server to Cloudflare
# - id: upload_server
# name: Upload server to Cloudflare
# uses: cloudflare/[email protected]
# with:
# apiToken: ${{ inputs.apiToken }}
# accountId: ${{ inputs.accountId }}
# workingDirectory: ./
# wranglerVersion: '4.10.0'
# environment: ${{ inputs.environment }}
# command: ${{ format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook-v2/openNext/customWorkers/defaultWrangler.jsonc

# - name: Extract server version worker ID
# shell: bash
# id: extract_server_version_id
# run: |
# version_id=$(echo '${{ steps.upload_server.outputs.command-output }}' | grep "Worker Version ID" | awk '{print $4}')
# echo "version_id=$version_id" >> $GITHUB_OUTPUT

# - name: Run updateWrangler scripts
# shell: bash
# run: |
# bun run ./packages/gitbook-v2/openNext/customWorkers/script/updateWrangler.ts ${{ steps.extract_server_version_id.outputs.version_id }}

- id: deploy_container
name: Deploy container to Cloudflare
uses: cloudflare/[email protected]
with:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.10.0'
environment: ${{ inputs.environment }}
command: ${{ format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook-v2/openNext/customWorkers/defaultWrangler.jsonc

- name: Extract server version worker ID
shell: bash
id: extract_server_version_id
run: |
version_id=$(echo '${{ steps.upload_server.outputs.command-output }}' | grep "Worker Version ID" | awk '{print $4}')
echo "version_id=$version_id" >> $GITHUB_OUTPUT

- name: Run updateWrangler scripts
shell: bash
run: |
bun run ./packages/gitbook-v2/openNext/customWorkers/script/updateWrangler.ts ${{ steps.extract_server_version_id.outputs.version_id }}
wranglerVersion: '4.21.1'
command: deploy --config ./packages/gitbook-v2/openNext/customWorkers/containerWrangler.jsonc

- id: upload_middleware
name: Upload middleware to Cloudflare
Expand All @@ -104,35 +114,34 @@ runs:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
workingDirectory: ./
wranglerVersion: '4.10.0'
wranglerVersion: '4.21.1'
environment: ${{ inputs.environment }}
command: ${{ format('versions upload --tag {0} --message "{1}"', inputs.commitTag, inputs.commitMessage) }} --config ./packages/gitbook-v2/openNext/customWorkers/middlewareWrangler.jsonc

- name: Extract middleware version worker ID
shell: bash
id: extract_middleware_version_id
run: |
version_id=$(echo '${{ steps.upload_middleware.outputs.command-output }}' | grep "Worker Version ID" | awk '{print $4}')
echo "version_id=$version_id" >> $GITHUB_OUTPUT

- name: Deploy server and middleware to Cloudflare
if: ${{ inputs.deploy == 'true' }}
uses: ./.github/actions/gradual-deploy-cloudflare
with:
apiToken: ${{ inputs.apiToken }}
accountId: ${{ inputs.accountId }}
opServiceAccount: ${{ inputs.opServiceAccount }}
opItem: ${{ inputs.opItem }}
environment: ${{ inputs.environment }}
serverVersionId: ${{ steps.extract_server_version_id.outputs.version_id }}
middlewareVersionId: ${{ steps.extract_middleware_version_id.outputs.version_id }}
deploy: ${{ inputs.deploy }}
# - name: Extract middleware version worker ID
# shell: bash
# id: extract_middleware_version_id
# run: |
# version_id=$(echo '${{ steps.upload_middleware.outputs.command-output }}' | grep "Worker Version ID" | awk '{print $4}')
# echo "version_id=$version_id" >> $GITHUB_OUTPUT

# - name: Deploy server and middleware to Cloudflare
# if: ${{ inputs.deploy == 'true' }}
# uses: ./.github/actions/gradual-deploy-cloudflare
# with:
# apiToken: ${{ inputs.apiToken }}
# accountId: ${{ inputs.accountId }}
# opServiceAccount: ${{ inputs.opServiceAccount }}
# opItem: ${{ inputs.opItem }}
# environment: ${{ inputs.environment }}
# serverVersionId: ${{ steps.extract_server_version_id.outputs.version_id }}
# middlewareVersionId: ${{ steps.extract_middleware_version_id.outputs.version_id }}
# deploy: ${{ inputs.deploy }}


- name: Outputs
shell: bash
env:
DEPLOYMENT_URL: ${{ steps.upload_middleware.outputs.deployment-url }}
run: |
echo "URL: ${{ steps.upload_middleware.outputs.deployment-url }}"
echo "Output server: ${{ steps.upload_server.outputs.command-output }}"
echo "URL: ${{ steps.upload_middleware.outputs.deployment-url }}"
5 changes: 5 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
FROM node:22-alpine
WORKDIR /app
COPY ./packages/gitbook-v2/.open-next/server-functions/default /app
EXPOSE 3000
CMD ["node", "index.mjs"]
7 changes: 6 additions & 1 deletion bun.lock
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@
"name": "gitbook-v2",
"version": "0.3.0",
"dependencies": {
"@cloudflare/containers": "^0.0.8",
"@cloudflare/workers-types": "^4.20250620.0",
"@gitbook/api": "catalog:",
"@gitbook/cache-tags": "workspace:*",
"@opennextjs/cloudflare": "1.2.1",
Expand Down Expand Up @@ -279,6 +281,7 @@
"patchedDependencies": {
"[email protected]": "patches/[email protected]",
"@vercel/[email protected]": "patches/@vercel%[email protected]",
"@opennextjs/[email protected]": "patches/@opennextjs%[email protected]",
},
"overrides": {
"@codemirror/state": "6.4.1",
Expand Down Expand Up @@ -495,6 +498,8 @@

"@changesets/write": ["@changesets/[email protected]", "", { "dependencies": { "@changesets/types": "^6.0.0", "fs-extra": "^7.0.1", "human-id": "^1.0.2", "prettier": "^2.7.1" } }, "sha512-kDxDrPNpUgsjDbWBvUo27PzKX4gqeKOlhibaOXDJA6kuBisGqNHv/HwGJrAu8U/dSf8ZEFIeHIPtvSlZI1kULw=="],

"@cloudflare/containers": ["@cloudflare/[email protected]", "", {}, "sha512-Uaw11AaUN0jVxRAd6PW33shAA4D4u0Yei3Xl/AOSijguYDhDGDMW4Dykx8vYUAl4tCbV9hGxvBgw9mAFCFXoJw=="],

"@cloudflare/kv-asset-handler": ["@cloudflare/[email protected]", "", { "dependencies": { "mime": "^3.0.0" } }, "sha512-+tv3z+SPp+gqTIcImN9o0hqE9xyfQjI1XD9pL6NuKjua9B1y7mNYv0S9cP+QEbA4ppVgGZEmKOvHX5G5Ei1CVA=="],

"@cloudflare/next-on-pages": ["@cloudflare/[email protected]", "", { "dependencies": { "acorn": "^8.8.0", "ast-types": "^0.14.2", "chalk": "^5.2.0", "chokidar": "^3.5.3", "commander": "^11.1.0", "cookie": "^0.5.0", "esbuild": "^0.15.3", "js-yaml": "^4.1.0", "miniflare": "^3.20231218.1", "package-manager-manager": "^0.2.0", "pcre-to-regexp": "^1.1.0", "semver": "^7.5.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20240208.0", "vercel": ">=30.0.0", "wrangler": "^3.28.2 || ^4.0.0" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "next-on-pages": "bin/index.js" } }, "sha512-rPy7x9c2+0RDDdJ5o0TeRUwXJ1b7N1epnqF6qKSp5Wz1r9KHOyvaZh1ACoOC6Vu5k9su5WZOgy+8fPLIyrldMQ=="],
Expand All @@ -511,7 +516,7 @@

"@cloudflare/workerd-windows-64": ["@cloudflare/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-dK9I8zBX5rR7MtaaP2AhICQTEw3PVzHcsltN8o46w7JsbYlMvFOj27FfYH5dhs3IahgmIfw2e572QXW2o/dbpg=="],

"@cloudflare/workers-types": ["@cloudflare/workers-types@4.20241230.0", "", {}, "sha512-dtLD4jY35Lb750cCVyO1i/eIfdZJg2Z0i+B1RYX6BVeRPlgaHx/H18ImKAkYmy0g09Ow8R2jZy3hIxMgXun0WQ=="],
"@cloudflare/workers-types": ["@cloudflare/workers-types@4.20250620.0", "", {}, "sha512-EVvRB/DJEm6jhdKg+A4Qm4y/ry1cIvylSgSO3/f/Bv161vldDRxaXM2YoQQWFhLOJOw0qtrHsKOD51KYxV1XCw=="],

"@codemirror/autocomplete": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-sFAphGQIqyQZfP2ZBsSHV7xQvo9Py0rV0dW7W3IMRdS+zDuNb2l3no78CvUaWKGfzFjI4FTrLdUSj86IGb2hRA=="],

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
},
"patchedDependencies": {
"[email protected]": "patches/[email protected]",
"@vercel/[email protected]": "patches/@vercel%[email protected]"
"@vercel/[email protected]": "patches/@vercel%[email protected]",
"@opennextjs/[email protected]": "patches/@opennextjs%[email protected]"
}
}
16 changes: 10 additions & 6 deletions packages/gitbook-v2/open-next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import type { OpenNextConfig } from '@opennextjs/cloudflare';
export default {
default: {
override: {
wrapper: 'cloudflare-node',
converter: 'edge',
proxyExternalRequest: 'fetch',
queue: () => import('./openNext/queue/middleware').then((m) => m.default),
incrementalCache: () => import('./openNext/incrementalCache').then((m) => m.default),
tagCache: () => import('./openNext/tagCache/middleware').then((m) => m.default),
wrapper: 'node',
converter: 'node',
proxyExternalRequest: 'node',
generateDockerfile: true,
queue: 'dummy',
incrementalCache: () => import('./openNext/serverCache').then((m) => m.default),
tagCache: 'dummy',
},
},
middleware: {
Expand All @@ -26,4 +27,7 @@ export default {
enableCacheInterception: true,
},
edgeExternals: ['node:crypto'],
cloudflare: {
dangerousDisableConfigValidation: true,
},
} satisfies OpenNextConfig;
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
globalThis.openNextDebug = false;globalThis.openNextVersion = "3.6.5";

// ../../node_modules/@opennextjs/cloudflare/dist/api/durable-objects/bucket-cache-purge.js
import { DurableObject } from "cloudflare:workers";

// ../../node_modules/@opennextjs/cloudflare/dist/api/cloudflare-context.js
var cloudflareContextSymbol = Symbol.for("__cloudflare-context__");

// ../../node_modules/@opennextjs/cloudflare/dist/api/overrides/internal.js
var debugCache = (name, ...args) => {
if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {
console.log(`[${name}] `, ...args);
}
};
async function internalPurgeCacheByTags(env, tags) {
if (!env.CACHE_PURGE_ZONE_ID && !env.CACHE_PURGE_API_TOKEN) {
debugCache("purgeCacheByTags", "No cache zone ID or API token provided. Skipping cache purge.");
return "missing-credentials";
}
try {
const response = await fetch(`https://api.cloudflare.com/client/v4/zones/${env.CACHE_PURGE_ZONE_ID}/purge_cache`, {
headers: {
Authorization: `Bearer ${env.CACHE_PURGE_API_TOKEN}`,
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify({
tags
})
});
if (response.status === 429) {
debugCache("purgeCacheByTags", "Rate limit exceeded. Skipping cache purge.");
return "rate-limit-exceeded";
}
const bodyResponse = await response.json();
if (!bodyResponse.success) {
debugCache("purgeCacheByTags", "Cache purge failed. Errors:", bodyResponse.errors.map((error) => `${error.code}: ${error.message}`));
return "purge-failed";
}
debugCache("purgeCacheByTags", "Cache purged successfully for tags:", tags);
return "purge-success";
} catch (error) {
console.error("Error purging cache by tags:", error);
return "purge-failed";
}
}

// ../../node_modules/@opennextjs/cloudflare/dist/api/durable-objects/bucket-cache-purge.js
var DEFAULT_BUFFER_TIME_IN_SECONDS = 5;
var MAX_NUMBER_OF_TAGS_PER_PURGE = 100;
var BucketCachePurge = class extends DurableObject {
bufferTimeInSeconds;
constructor(state, env) {
super(state, env);
this.bufferTimeInSeconds = env.NEXT_CACHE_DO_PURGE_BUFFER_TIME_IN_SECONDS ? parseInt(env.NEXT_CACHE_DO_PURGE_BUFFER_TIME_IN_SECONDS) : DEFAULT_BUFFER_TIME_IN_SECONDS;
state.blockConcurrencyWhile(async () => {
state.storage.sql.exec(`
CREATE TABLE IF NOT EXISTS cache_purge (
tag TEXT NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS tag_index ON cache_purge (tag);
`);
});
}
async purgeCacheByTags(tags) {
for (const tag of tags) {
this.ctx.storage.sql.exec(`
INSERT OR REPLACE INTO cache_purge (tag)
VALUES (?)`, [tag]);
}
const nextAlarm = await this.ctx.storage.getAlarm();
if (!nextAlarm) {
this.ctx.storage.setAlarm(Date.now() + this.bufferTimeInSeconds * 1e3);
}
}
async alarm() {
let tags = this.ctx.storage.sql.exec(`
SELECT * FROM cache_purge LIMIT ${MAX_NUMBER_OF_TAGS_PER_PURGE}
`).toArray();
do {
if (tags.length === 0) {
return;
}
const result = await internalPurgeCacheByTags(this.env, tags.map((row) => row.tag));
if (result === "rate-limit-exceeded") {
throw new Error("Rate limit exceeded");
}
this.ctx.storage.sql.exec(`
DELETE FROM cache_purge
WHERE tag IN (${tags.map(() => "?").join(",")})
`, tags.map((row) => row.tag));
if (tags.length < MAX_NUMBER_OF_TAGS_PER_PURGE) {
tags = [];
} else {
tags = this.ctx.storage.sql.exec(`
SELECT * FROM cache_purge LIMIT ${MAX_NUMBER_OF_TAGS_PER_PURGE}
`).toArray();
}
} while (tags.length >= 0);
}
};
export {
BucketCachePurge
};
Loading
Loading