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

feat(cloudflare-module): expose all handlers as hooks #2795

Merged
merged 6 commits into from
Oct 15, 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
16 changes: 16 additions & 0 deletions docs/2.deploy/20.providers/cloudflare.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,22 @@ rules = [
bucket = ".output/public"
```

## Runtime hooks

You can use [runtime hooks](/guide/plugins#nitro-runtime-hooks) bellow in order to extend [worker handlers](https://developers.cloudflare.com/workers/runtime-apis/handlers/).

:read-more{to="/guide/plugins#nitro-runtime-hooks"}

> [!NOTE]
> This feature is currently available in [nightly channel](https://nitro.unjs.io/guide/nightly) only.

- [`cloudflare:scheduled`](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/)
- [`cloudflare:email`](https://developers.cloudflare.com/email-routing/email-workers/runtime-api/)
- [`cloudflare:queue`](https://developers.cloudflare.com/queues/configuration/javascript-apis/#consumer)
- [`cloudflare:tail`](https://developers.cloudflare.com/workers/runtime-apis/handlers/tail/)
- `cloudflare:trace`


### Preview your app locally

You can use [wrangler](https://github.com/cloudflare/workers-sdk/tree/main/packages/wrangler), to preview your app locally:
Expand Down
78 changes: 55 additions & 23 deletions src/presets/cloudflare/runtime/cloudflare-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ import {
getAssetFromKV,
mapRequestToAsset,
} from "@cloudflare/kv-asset-handler";
import type {
ExecutionContext,
ForwardableEmailMessage,
MessageBatch,
} from "@cloudflare/workers-types";
import type { ExportedHandler } from "@cloudflare/workers-types";
import wsAdapter from "crossws/adapters/cloudflare";
import { withoutBase } from "ufo";

Expand All @@ -25,12 +21,12 @@ const ws = import.meta._websocket
? wsAdapter(nitroApp.h3App.websocket)
: undefined;

interface CFModuleEnv {
[key: string]: any;
interface Env {
__STATIC_CONTENT?: any;
}

export default {
async fetch(request: Request, env: CFModuleEnv, context: ExecutionContext) {
export default <ExportedHandler<Env>>{
async fetch(request, env, context) {
// Websocket upgrade
// https://crossws.unjs.io/adapters/cloudflare
if (
Expand All @@ -44,7 +40,7 @@ export default {
// https://github.com/cloudflare/kv-asset-handler#es-modules
return await getAssetFromKV(
{
request,
request: request as unknown as Request,
waitUntil(promise) {
return context.waitUntil(promise);
},
Expand All @@ -62,7 +58,7 @@ export default {

const url = new URL(request.url);
let body;
if (requestHasBody(request)) {
if (requestHasBody(request as unknown as Request)) {
body = Buffer.from(await request.arrayBuffer());
}

Expand All @@ -82,15 +78,23 @@ export default {
host: url.hostname,
protocol: url.protocol,
method: request.method,
headers: request.headers,
headers: request.headers as unknown as Headers,
body,
});
},
scheduled(event: any, env: CFModuleEnv, context: ExecutionContext) {

scheduled(controller, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:scheduled", {
controller,
env,
context,
})
);
if (import.meta._tasks) {
(globalThis as any).__env__ = env;
context.waitUntil(
runCronTasks(event.cron, {
runCronTasks(controller.cron, {
context: {
cloudflare: {
env,
Expand All @@ -103,21 +107,49 @@ export default {
}
},

email(
event: ForwardableEmailMessage,
env: CFModuleEnv,
context: ExecutionContext
) {
email(message, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:email", {
message,
event: message, // backward compat
env,
context,
})
);
},

queue(batch, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:queue", {
batch,
event: batch,
env,
context,
})
);
},

tail(traces, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:email", { event, env, context })
nitroApp.hooks.callHook("cloudflare:tail", {
traces,
env,
context,
})
);
},

queue(event: MessageBatch, env: CFModuleEnv, context: ExecutionContext) {
trace(traces, env, context) {
(globalThis as any).__env__ = env;
context.waitUntil(
nitroApp.hooks.callHook("cloudflare:queue", { event, env, context })
nitroApp.hooks.callHook("cloudflare:trace", {
traces,
env,
context,
})
);
},
};
Expand Down
29 changes: 27 additions & 2 deletions src/presets/cloudflare/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import type {
ExecutionContext,
ForwardableEmailMessage,
MessageBatch,
ScheduledController,
TraceItem,
} from "@cloudflare/workers-types";
import type { Config as WranglerConfig } from "./types.wrangler";

Expand Down Expand Up @@ -58,14 +60,37 @@ export interface CloudflareOptions {

declare module "nitropack/types" {
export interface NitroRuntimeHooks {
// https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/
"cloudflare:scheduled": (_: {
controller: ScheduledController;
env: unknown;
context: ExecutionContext;
}) => void;
// https://developers.cloudflare.com/email-routing/email-workers/runtime-api
"cloudflare:email": (_: {
message: ForwardableEmailMessage;
/** @deprecated please use `message` */
event: ForwardableEmailMessage;
env: any;
env: unknown;
context: ExecutionContext;
}) => void;
// https://developers.cloudflare.com/queues/configuration/javascript-apis/#consumer
"cloudflare:queue": (_: {
batch: MessageBatch;
/** @deprecated please use `batch` */
event: MessageBatch;
env: any;
env: unknown;
context: ExecutionContext;
}) => void;
// https://developers.cloudflare.com/workers/runtime-apis/handlers/tail/
"cloudflare:tail": (_: {
traces: TraceItem[];
env: unknown;
context: ExecutionContext;
}) => void;
"cloudflare:trace": (_: {
traces: TraceItem[];
env: unknown;
context: ExecutionContext;
}) => void;
}
Expand Down