Skip to content
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

refactor: move to Workers Assets #101

Merged
merged 4 commits into from
Dec 22, 2024
Merged
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
39 changes: 39 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: Deploy
on:
push:
branches:
- master
- main
repository_dispatch:

env:
NODE_VERSION: 22
WRANGLER_VERSION: 3.99.0
jobs:
deploy:
runs-on: ubuntu-latest
timeout-minutes: 60
if: github.repository_owner == 'nodecraft'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- uses: dtolnay/rust-toolchain@stable
- uses: jetli/[email protected]
with:
version: latest
- uses: Swatinem/rust-cache@v2

- run: npm ci
- run: npm run build

- name: Publish
uses: cloudflare/[email protected]
with:
apiToken: ${{ secrets.CF_API_TOKEN }}
accountId: ${{ secrets.CF_ACCOUNT_ID }}
command: "deploy"
wranglerVersion: ${{ env.WRANGLER_VERSION }}

9 changes: 4 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
"test:dev": "vitest --watch"
},
"devDependencies": {
"@cloudflare/kv-asset-handler": "0.3.4",
"@cloudflare/vitest-pool-workers": "0.5.40",
"@cloudflare/workers-types": "4.20241218.0",
"@nodecraft/eslint-config": "44.3.0",
Expand Down
36 changes: 6 additions & 30 deletions src/worker/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import { getAssetFromKV } from '@cloudflare/kv-asset-handler';
import manifestJSON from '__STATIC_CONTENT_MANIFEST';

import { EMPTY } from './data';
import PromiseGatherer from './promise_gather';
import { RequestedKind, interpretRequest } from './request';
Expand All @@ -10,8 +7,6 @@
import { default as CACHE_BUST } from './util/cache-bust';
import { get_rendered_image } from '../../pkg/mcavatar';

const assetManifest = JSON.parse(manifestJSON);

import type { CraftheadRequest } from './request';
import type { Env } from './types';

Expand Down Expand Up @@ -126,47 +121,28 @@
}
}

async function handleRequest(request: Request, env: Env, ctx: ExecutionContext) {

Check warning on line 124 in src/worker/index.ts

View workflow job for this annotation

GitHub Actions / Node 22 Test

'ctx' is defined but never used
const startTime = new Date();
const interpreted = interpretRequest(request);
if (!interpreted) {
// We don't understand this request.
try {
const asset = await getAssetFromKV({
request,
waitUntil(promise) {
return ctx.waitUntil(promise);
},
}, {
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: assetManifest,
});
const asset = await env.ASSETS.fetch(request);
writeDataPoint(env.CRAFTHEAD_ANALYTICS, request, {
startTime,
kind: '_asset',
responseCode: 200,
});
return asset;
} catch {
} catch (err) {
try {
const notFoundResponse = await getAssetFromKV({
request,
waitUntil(promise) {
return ctx.waitUntil(promise);
},
}, {
mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
});
writeDataPoint(env.CRAFTHEAD_ANALYTICS, request, {
startTime,
kind: '_asset',
responseCode: 404,
});
return new Response(notFoundResponse.body, {
headers: notFoundResponse.headers,
status: 404,
statusText: 'Not found',
});
const probableError = err as Error;
return new Response(probableError?.message || probableError.toString(), { status: 500 });
} catch {
writeDataPoint(env.CRAFTHEAD_ANALYTICS, request, {
startTime,
Expand Down Expand Up @@ -222,7 +198,7 @@
}

export default {
fetch(request: Request, env: Env, ctx: ExecutionContext) {
fetch(request, env, ctx): Promise<Response> {
return handleRequest(request, env, ctx);
},
};
} satisfies ExportedHandler<Env>;
4 changes: 0 additions & 4 deletions src/worker/manifest.d.ts

This file was deleted.

3 changes: 1 addition & 2 deletions src/worker/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export interface Env {
__STATIC_CONTENT: KVNamespace;

ASSETS: Fetcher;
CRAFTHEAD_ANALYTICS?: AnalyticsEngineDataset;
PLAYERDB?: Fetcher;
}
27 changes: 25 additions & 2 deletions test/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,35 @@ describe('worker', () => {
expect(await response.headers.get('content-type')).toContain('image/png');
});

it('responds with data for profile', async () => {
type ProfileResponse = {
id: string;
name: string;
properties: {
name: string;
value: string;
signature?: string;
}[];
};
it('responds with data for profile on ID', async () => {
const request = new IncomingRequest('http://crafthead.net/profile/ef6134805b6244e4a4467fbe85d65513');
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
await waitOnExecutionContext(ctx);
const json = await response.json<any>();
const json = await response.json<ProfileResponse>();

expect(json.id).toBe('ef6134805b6244e4a4467fbe85d65513');
expect(json.name).toBe('CherryJimbo');
expect(json.properties).toBeDefined();
expect(json.properties).toBeInstanceOf(Array);
expect(json.properties[0].name).toBe('textures');
});

it('responds with data for profile on username', async () => {
const request = new IncomingRequest('http://crafthead.net/profile/CherryJimbo');
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
await waitOnExecutionContext(ctx);
const json = await response.json<ProfileResponse>();
expect(json.id).toBe('ef6134805b6244e4a4467fbe85d65513');
expect(json.name).toBe('CherryJimbo');
expect(json.properties).toBeDefined();
Expand Down
8 changes: 6 additions & 2 deletions wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ analytics_engine_datasets = [

compatibility_flags = ["nodejs_compat", "no_nodejs_compat_v2"]

[site]
bucket = "./src/website"
[assets]
directory = "./src/website"
binding = "ASSETS"
html_handling = "drop-trailing-slash"
not_found_handling = "404-page"
experimental_serve_directly = false

[build]
command = "npm run build" # required
Expand Down
Loading