Skip to content

Latest commit

 

History

History

edge

Folders and files

README.md

@tupik/edge

Edge adapter for Tupik: exposes an app as a fetch handler for Cloudflare Workers, Deno and Fastly Compute. Worker env and ctx are forwarded to ctx.runtime. Verified on Cloudflare Workers (production), on Deno 2.9.6 and on Fastly Compute (Viceroy 0.23.0 with @fastly/js-compute 4.3.0); other fetch-based runtimes are not verified yet.

Install

npm install @tupik/edge @tupik/core

Usage

import { createApp, createModule } from '@tupik/core';
import { createEdgeWorker, getEnv } from '@tupik/edge';

const app = createApp().register(
  createModule().get('/', { access: 'public', handler: (ctx) => ({ greeting: getEnv<{ GREETING?: string }>(ctx).GREETING ?? 'hello' }) }),
);

// Cloudflare Workers: `export default worker;`
const worker = createEdgeWorker(app);

const response = await worker.fetch(new Request('https://example.com/'), { GREETING: 'hi from the edge' });
console.log(await response.json()); // { greeting: 'hi from the edge' }

Deno

import { createApp, createModule } from 'npm:@tupik/core';
import { toEdgeHandler } from 'npm:@tupik/edge';

const app = createApp().register(createModule().get('/', { access: 'public', handler: () => ({ hello: 'deno' }) }));

Deno.serve({ port: 8000 }, toEdgeHandler(app));

Deno.serve passes its ServeHandlerInfo (remoteAddr, completed) as the second argument, so on Deno ctx.runtime.env is that object, not Worker bindings. Read configuration with Deno.env instead of getEnv.

Verified on Deno 2.9.6 by a real smoke test (public and authenticated routes, 401, 404, 405, a validated JSON body and malformed JSON), with the official deno npm package, so nothing is downloaded by a shell script:

pnpm --filter @tupik/core --filter @tupik/edge build
pnpm --filter @tupik/edge smoke:deno   # npx -y deno@2.9.6 run ... scripts/smoke-deno.ts

Fastly Compute

/// <reference types="@fastly/js-compute" />
import { env } from 'fastly:env';
import { createApp, createModule } from '@tupik/core';
import { toEdgeHandler } from '@tupik/edge';

const app = createApp().register(
  createModule().get('/', { access: 'public', handler: () => ({ host: env('FASTLY_HOSTNAME') }) }),
);
const handler = toEdgeHandler(app);

addEventListener('fetch', (event) => event.respondWith(handler(event.request, undefined, event)));

Fastly's JavaScript runtime only dispatches the fetch event: export default { fetch } (or export default createEdgeWorker(app)) compiles but every request fails with a 500, so use addEventListener. Fastly passes no Worker-style bindings, so on Fastly ctx.runtime.env is undefined and getEnv throws: read configuration with env() from fastly:env, a Config Store or a Secret Store. Pass the FetchEvent as the third argument and it becomes ctx.runtime.executionCtx: its waitUntil keeps the instance alive after the response, and client/server carry the connection details.

Verified on Viceroy 0.23.0 (Fastly's local Compute runtime) by the same smoke test as Deno, with the official @fastly/js-compute 4.3.0 and @fastly/cli 17.2.0 npm packages run by npx at exact versions. It compiles the app to Wasm in a temp dir and serves it with fastly compute serve, locally: no Fastly account, login or deploy. On first use the CLI fetches the Viceroy release from github.com/fastly/viceroy.

pnpm --filter @tupik/core --filter @tupik/edge build
pnpm --filter @tupik/edge smoke:fastly   # node scripts/smoke-fastly.mjs

Cloudflare: cache, D1 replicas and placement

Three platform features that cut latency more than any per-request micro-optimization:

Edge cache for public reads. edgeCache from @tupik/middleware answers repeated public reads from caches.default without running the handler. It decides by what the route declares: only access: 'public' routes without authentication, without pii, health or secret response fields, and requests without authorization or cookie. The Cache API only works on a custom domain or route; on *.workers.dev it stores nothing.

import { edgeCache } from '@tupik/middleware';

const catalog = createModule('/catalog')
  .use(edgeCache({ maxAge: 300 }))
  .get('/products/:id', { access: 'public', handler: (ctx) => getProduct(ctx.params.id) });

D1 read replicas. With read replication enabled on the database (dashboard: D1, Settings, Enable Read Replication), queries run on a nearby replica only through the Sessions API. Keep the session's bookmark between requests (a header or cookie) so a user reads at least what they wrote:

const catalog = createModule('/catalog').get('/products', {
  access: 'public',
  handler: async (ctx) => {
    const env = getEnv<Env>(ctx);
    const session = env.DB.withSession(ctx.req.headers.get('x-d1-bookmark') ?? 'first-unconstrained');
    const { results } = await session.prepare('SELECT id, name FROM products').all();
    ctx.header('x-d1-bookmark', session.getBookmark() ?? '');
    return { products: results };
  },
});

Use withSession('first-primary') for writes and for reads that must see the latest data.

Smart Placement. A Worker that makes several round trips to one back end (D1, an external API) runs faster near that back end than near the user. Turn it on in the Wrangler file and Cloudflare moves the Worker after measuring (up to 15 minutes); it only affects fetch handlers:

{ "placement": { "mode": "smart" } }

When the back end is in a known cloud region, "placement": { "region": "aws:us-east-1" } places it directly.

Cron, queues and email

createEdgeWorker also takes the other Worker events. Only the handlers you pass are exported.

import { createEdgeWorker } from '@tupik/edge';

interface Env {
  readonly DB: D1Database;
}

interface EmailJob {
  readonly to: string;
  readonly template: string;
}

export default createEdgeWorker<Env>(app, {
  // Cron Triggers
  scheduled: async (controller, env) => {
    await env.DB.prepare('DELETE FROM sessions WHERE expires_at < ?').bind(controller.scheduledTime).run();
  },
  // One message at a time: acked when it resolves, retried when it throws.
  queue: {
    message: async (job: EmailJob, message, env) => {
      await sendEmail(env, job);
    },
    retryDelaySeconds: 60,
  },
  // Email Routing
  email: async (message) => {
    if (!message.from.endsWith('@example.com')) message.setReject('Unknown sender');
  },
});

A failed queue message is logged with the error name and message id only, never its body or error message, since those can carry personal data or tokens. Pass onError(error, { queue, messageId, attempts }) to report it elsewhere. To handle the whole batch yourself, pass a function instead: queue: (batch, env, ctx) => { ... }.

Key API

Export Purpose
createEdgeWorker(app, handlers?) Module worker with fetch and the scheduled, queue and email handlers you pass
QueueConsumer<Env, Body> Per-message queue consumer: message, retryDelaySeconds, onError
ScheduledControllerLike, MessageBatchLike, MessageLike, ForwardableEmailMessageLike Structural types of the Cloudflare event objects, no dependency on @cloudflare/workers-types
toEdgeHandler(app) Bare (request, env?, ctx?) => Promise<Response> handler
getEnv<TEnv>(ctx) Typed access to the runtime bindings inside a handler

License

MIT