@edgetime/cloudflare
Queue consumers, Cache API read-through, Turnstile, Access tokens and a strict Durable Object rate limiter.
npm install @edgetime/cloudflareAdapters and patterns for Cloudflare. This is the only edgetime package that names a platform.
The main entry point describes bindings by the methods it calls, so it also runs under Node with
stand-ins. @edgetime/cloudflare/durable is Workers-only.
Queues
Section titled “Queues”import { byQueue, consumeBatch } from '@edgetime/cloudflare';
export default { queue: (batch: MessageBatch, env: Env) => byQueue(batch, { 'emails': (b) => consumeBatch<Email>(b, (email) => send(env, email), { parse: parseEmail }), 'exports': (b) => consumeBatch(b, (job) => runExport(env, job), { concurrency: 4 }), }),};consumeBatch(batch, handle, options?) settles each message on its own: acknowledged when the
handler resolves, retried with a delay when it throws. One failing message does not redeliver the
rest. Delivery is at-least-once, so handlers must be idempotent.
| Option | Default | Purpose |
|---|---|---|
parse |
none | Validates the body. A throw retries the message, so it reaches the dead-letter queue. |
concurrency |
1 |
Messages handled at once. 1 keeps batch order. |
retryDelay |
backoff |
Seconds before redelivery, from the attempt count. Rounded down and capped at 43200 (12 hours). |
onError |
none | Called for each failure with the error, the message and the queue name. If it throws, the message is still retried. |
backoff comes from @edgetime/resilience and doubles from 30 seconds up to 15 minutes. byQueue
throws for a queue with no consumer, so a misconfigured binding shows up as retries.
import { cached, defaultCache } from '@edgetime/cloudflare';
const profile = await cached( { cache: defaultCache(), key: `profile/v1/${id}`, ttl: 60, waitUntil: (p) => ctx.waitUntil(p) }, () => loadProfile(env, id),);cached stores a JSON-serializable value in the Cache API and calls load on a miss. A load
that returns undefined stores nothing. The cache is per data center and best effort: a read or
write that fails is treated as a miss. With a cache, the value comes back as JSON carries it on
a miss as well as on a hit, so a Date is a string both times. ttl must be 1 second or more and key a non-empty
string; anything else throws. With
cache: undefined, as defaultCache() returns outside Workers, load is always called.
staleWhileRevalidate (seconds, 0 by default) keeps an entry for that long after ttl. During
that time a request gets the expired value at once and a fresh one is loaded and stored through
waitUntil; without waitUntil the request loads it in line. If that load fails, the expired
value is returned instead of the error. Requests are not merged: each that finds the entry
expired starts its own load, as each miss does, because a Worker cannot safely wait on work
started by another request.
Turnstile
Section titled “Turnstile”verifyTurnstile checks a Turnstile token with Siteverify. It never throws; every outcome other
than a confirmed token is a failure with a reason.
import { connectingIp, verifyTurnstile } from '@edgetime/cloudflare';import { HttpError, readForm } from '@edgetime/http';
const form = await readForm(request);const check = await verifyTurnstile({ secret: env.TURNSTILE_SECRET, token: form.get('cf-turnstile-response'), remoteIp: connectingIp(request), hostname: 'shop.example.com', action: 'checkout',});if (!check.success) { const fault = check.reason === 'not-configured' || check.reason === 'unavailable'; throw new HttpError(fault ? 503 : 403, 'Verification failed');}| Reason | Meaning |
|---|---|
not-configured |
No secret was given, or Siteverify refused it. |
missing-token |
No token, or one longer than 2048 characters. Siteverify is not called. |
rejected |
The token is invalid, expired or already used. errorCodes has the detail. |
hostname-mismatch, action-mismatch |
The token was issued for another host name or action. Checked only when you pass hostname or action. |
unavailable |
Siteverify did not answer within timeout (5000 ms by default) or returned an error. |
Pass idempotencyKey when you retry a verification, and url for widgets on China domains.
Turnstile’s test secret keys return example.com as the host name and no action, so leave
hostname and action unset when testing with them.
Access
Section titled “Access”@edgetime/cloudflare/access verifies Cloudflare Access application tokens. It builds on
@edgetime/auth/jwt, so it brings in jose.
import { jwtAuth } from '@edgetime/auth/jwt';import { accessSubject, accessToken, createAccessVerifier } from '@edgetime/cloudflare/access';import { perEnv } from '@edgetime/router';
const access = perEnv((env: Env) => createAccessVerifier({ teamDomain: env.ACCESS_TEAM_DOMAIN, audience: env.ACCESS_AUD }),);
router.use( jwtAuth<App>({ verifier: (c) => access(c.env), token: (c) => accessToken(c.req), subject: accessSubject, }),);teamDomain is https://<team>.cloudflareaccess.com and audience is the application’s AUD tag.
accessSubject identifies a user by sub and a service token, whose sub is empty, by
common_name. Without it, requests made with a service token are refused.
Request metadata
Section titled “Request metadata”connectingIp(request) returns the visitor’s address from CF-Connecting-IP, or undefined for
requests that did not come through Cloudflare’s edge, such as service-binding calls and local
runs. Use it as a rate-limit key: rateLimit({ limiter, key: (c) => connectingIp(c.req) }).
rateLimit refuses a request without an address unless told to skip it with
onMissingKey: 'skip'.
Strict rate limiter
Section titled “Strict rate limiter”@edgetime/cloudflare/durable exports RateLimiterObject, a Durable Object that counts a
fixed window for one key in one place, and durableRateLimiter(namespace, { limit, period }),
which adapts it to the limit({ key }) shape rateLimit() takes. A Rate Limiting binding is
cheaper and faster but counts per location; use this when a limit must hold exactly.
Counts are kept per key and per limit and period, so two limiters on one namespace do not
share a count when their keys coincide. Changing a limiter’s settings starts its counts afresh.
period is from 0.001 seconds to 366 days; anything else throws.
Export the class from the Worker entry and declare it with SQLite storage:
export { RateLimiterObject as StrictLimiter } from '@edgetime/cloudflare/durable';
// cloudflare.config.tsexports: { StrictLimiter: { type: 'durable-object', storage: 'sqlite' } },rateLimit<App>({ limiter: (c) => durableRateLimiter(c.ctx.exports.StrictLimiter, { limit: 5, period: 60 }), key: (c) => c.get('auth').subject,});Storage for a key is deleted when its window ends. limit and period must be positive numbers;
anything else throws, so an unset variable cannot create a window that never ends.
Source: packages/cloudflare on GitHub.