@somewhere-cloud/cli 0.38.154 → 0.38.155
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/docs/adopt.md +39 -0
- package/dist/docs/analytics.md +161 -0
- package/dist/docs/api-reference.md +339 -0
- package/dist/docs/api-surface.md +2067 -0
- package/dist/docs/app-mcp.md +162 -0
- package/dist/docs/architecture-patterns.md +334 -0
- package/dist/docs/auth-client.md +531 -0
- package/dist/docs/billing.md +76 -0
- package/dist/docs/browser.md +639 -0
- package/dist/docs/calendar.md +298 -0
- package/dist/docs/changes.md +323 -0
- package/dist/docs/cli.md +407 -0
- package/dist/docs/common-mistakes.md +199 -0
- package/dist/docs/connect-agent.md +72 -0
- package/dist/docs/cors.md +114 -0
- package/dist/docs/cron.md +167 -0
- package/dist/docs/database-engine.md +167 -0
- package/dist/docs/declared-data.md +1656 -0
- package/dist/docs/declared-files.md +475 -0
- package/dist/docs/deploy-intelligence.md +188 -0
- package/dist/docs/deploy.md +733 -0
- package/dist/docs/design-system.md +273 -0
- package/dist/docs/dev-environments.md +496 -0
- package/dist/docs/domain-ownership.md +31 -0
- package/dist/docs/domains.md +370 -0
- package/dist/docs/feedback.md +88 -0
- package/dist/docs/file-tools.md +116 -0
- package/dist/docs/functions.md +489 -0
- package/dist/docs/getting-started.md +238 -0
- package/dist/docs/github.md +95 -0
- package/dist/docs/google-calendar.md +212 -0
- package/dist/docs/groups.md +836 -0
- package/dist/docs/guarantees.md +58 -0
- package/dist/docs/handled-for-you.md +224 -0
- package/dist/docs/inspect.md +171 -0
- package/dist/docs/limits.md +68 -0
- package/dist/docs/live-data.md +197 -0
- package/dist/docs/live.md +92 -0
- package/dist/docs/local-dev.md +30 -0
- package/dist/docs/migration-supabase.md +58 -0
- package/dist/docs/payments.md +1102 -0
- package/dist/docs/portability.md +194 -0
- package/dist/docs/postgres.md +301 -0
- package/dist/docs/pricing-comparison.md +42 -0
- package/dist/docs/pricing.md +39 -0
- package/dist/docs/project-groups.md +107 -0
- package/dist/docs/projects.md +380 -0
- package/dist/docs/recipe-ai-agent.md +112 -0
- package/dist/docs/recipe-ai-features.md +227 -0
- package/dist/docs/recipe-ai-receipts.md +783 -0
- package/dist/docs/recipe-background-jobs.md +369 -0
- package/dist/docs/recipe-booking.md +348 -0
- package/dist/docs/recipe-csv-import.md +390 -0
- package/dist/docs/recipe-ecommerce.md +127 -0
- package/dist/docs/recipe-email.md +282 -0
- package/dist/docs/recipe-escalation.md +133 -0
- package/dist/docs/recipe-file-uploads.md +159 -0
- package/dist/docs/recipe-import-app.md +110 -0
- package/dist/docs/recipe-login.md +457 -0
- package/dist/docs/recipe-multi-chat.md +198 -0
- package/dist/docs/recipe-paid-api.md +161 -0
- package/dist/docs/recipe-pdfs.md +205 -0
- package/dist/docs/recipe-push-notifications.md +107 -0
- package/dist/docs/recipe-seo.md +200 -0
- package/dist/docs/recipe-signed-in-app.md +330 -0
- package/dist/docs/render.md +99 -0
- package/dist/docs/rooms.md +554 -0
- package/dist/docs/sdk.md +287 -0
- package/dist/docs/sdks.md +24 -0
- package/dist/docs/search.md +199 -0
- package/dist/docs/security-model.md +168 -0
- package/dist/docs/setup.md +212 -0
- package/dist/docs/smoke.md +102 -0
- package/dist/docs/speed.md +298 -0
- package/dist/docs/sql-compatibility.md +96 -0
- package/dist/docs/sw.agent.md +248 -0
- package/dist/docs/sw.ai.md +1291 -0
- package/dist/docs/sw.auth.md +1811 -0
- package/dist/docs/sw.billing.md +171 -0
- package/dist/docs/sw.db.md +2128 -0
- package/dist/docs/sw.email.md +661 -0
- package/dist/docs/sw.endpoint.md +187 -0
- package/dist/docs/sw.env.md +303 -0
- package/dist/docs/sw.fetch.md +115 -0
- package/dist/docs/sw.fs.md +424 -0
- package/dist/docs/sw.groups.md +836 -0
- package/dist/docs/sw.image.md +69 -0
- package/dist/docs/sw.jobs.md +520 -0
- package/dist/docs/sw.logs.md +61 -0
- package/dist/docs/sw.mail.md +106 -0
- package/dist/docs/sw.notifications.md +78 -0
- package/dist/docs/sw.push.md +161 -0
- package/dist/docs/sw.rateLimit.md +67 -0
- package/dist/docs/sw.web.md +128 -0
- package/dist/docs/tasks.md +269 -0
- package/dist/docs/test.md +220 -0
- package/dist/docs/tool-reference-account.md +7 -0
- package/dist/docs/tool-reference-ai.md +121 -0
- package/dist/docs/tool-reference-analytics.md +37 -0
- package/dist/docs/tool-reference-api.md +19 -0
- package/dist/docs/tool-reference-artifacts.md +35 -0
- package/dist/docs/tool-reference-auth.md +163 -0
- package/dist/docs/tool-reference-browser.md +114 -0
- package/dist/docs/tool-reference-code.md +26 -0
- package/dist/docs/tool-reference-connect.md +21 -0
- package/dist/docs/tool-reference-cron.md +48 -0
- package/dist/docs/tool-reference-db.md +282 -0
- package/dist/docs/tool-reference-domains.md +107 -0
- package/dist/docs/tool-reference-email.md +55 -0
- package/dist/docs/tool-reference-env.md +19 -0
- package/dist/docs/tool-reference-feedback.md +56 -0
- package/dist/docs/tool-reference-fs.md +265 -0
- package/dist/docs/tool-reference-github.md +57 -0
- package/dist/docs/tool-reference-groups.md +85 -0
- package/dist/docs/tool-reference-help.md +29 -0
- package/dist/docs/tool-reference-jobs.md +39 -0
- package/dist/docs/tool-reference-live.md +48 -0
- package/dist/docs/tool-reference-logs.md +16 -0
- package/dist/docs/tool-reference-payments.md +44 -0
- package/dist/docs/tool-reference-project.md +706 -0
- package/dist/docs/tool-reference-push.md +78 -0
- package/dist/docs/tool-reference-rate-limit.md +18 -0
- package/dist/docs/tool-reference-search.md +68 -0
- package/dist/docs/tool-reference-security.md +42 -0
- package/dist/docs/tool-reference-smoke.md +17 -0
- package/dist/docs/tool-reference-stock-photos.md +20 -0
- package/dist/docs/tool-reference-tasks.md +73 -0
- package/dist/docs/tool-reference-telegram.md +32 -0
- package/dist/docs/tool-reference-usage.md +9 -0
- package/dist/docs/tool-reference-web.md +71 -0
- package/dist/docs/tool-reference-webhooks.md +9 -0
- package/dist/docs/troubleshooting.md +411 -0
- package/dist/docs/typed-functions.md +94 -0
- package/dist/docs/verify-before-deploy.md +67 -0
- package/dist/docs/vs-supabase.md +75 -0
- package/dist/docs/vs-vercel.md +103 -0
- package/dist/lib/bundle.js +303 -221
- package/dist/lib/bundle.js.map +3 -3
- package/dist/types/lib/test-session.d.ts +8 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -2
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# sw.image — Image transformations
|
|
2
|
+
|
|
3
|
+
Available inside any deployed function via the sw argument
|
|
4
|
+
provided to the handler.
|
|
5
|
+
|
|
6
|
+
sw.image.resize builds a transformation URL — it doesn't fetch the
|
|
7
|
+
image, it returns a URL that triggers transformation at the edge when
|
|
8
|
+
the browser (or your code) fetches it. Stick the URL in <img src>
|
|
9
|
+
for free, no extra hop.
|
|
10
|
+
|
|
11
|
+
## sw.image.resize(source, options)
|
|
12
|
+
Returns a string URL.
|
|
13
|
+
|
|
14
|
+
source:
|
|
15
|
+
'/uploads/foo.png' — relative path on this project's domain
|
|
16
|
+
'https://example.com/foo.png' — absolute URL (must be reachable
|
|
17
|
+
from the project's zone)
|
|
18
|
+
|
|
19
|
+
options (all optional):
|
|
20
|
+
width number pixel width
|
|
21
|
+
height number pixel height
|
|
22
|
+
fit 'cover' | 'contain' | 'scale-down' | 'crop' | 'pad'
|
|
23
|
+
format 'auto' | 'webp' | 'avif' | 'json' (default: format=auto)
|
|
24
|
+
quality 1–100 JPEG/WebP/AVIF quality
|
|
25
|
+
dpr number device-pixel ratio (1, 2, 3)
|
|
26
|
+
gravity 'auto' | 'left' | 'right' | 'top' | 'bottom' | 'face' | '0.5x0.5'
|
|
27
|
+
background '#ffffff' fill colour for pad/contain
|
|
28
|
+
blur 1–250
|
|
29
|
+
sharpen 1–10
|
|
30
|
+
rotate 90 | 180 | 270
|
|
31
|
+
trim '20;30;20;30' edge trim (top;right;bottom;left)
|
|
32
|
+
metadata 'keep' | 'copyright' | 'none'
|
|
33
|
+
anim true | false (animated GIF/WebP support)
|
|
34
|
+
|
|
35
|
+
Example:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
// api/photo.ts — a thumbnail and a larger WebP of /photo.jpg; nothing is fetched here
|
|
39
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
40
|
+
const thumb = sw.image.resize('/photo.jpg', { width: 200, height: 200, fit: 'cover' })
|
|
41
|
+
// → https://your-project.somewhere.site/cdn-cgi/image/width=200,height=200,fit=cover/photo.jpg
|
|
42
|
+
const webp = sw.image.resize('/photo.jpg', { width: 800, format: 'webp', quality: 80 })
|
|
43
|
+
return new Response(`<a href="${webp}"><img src="${thumb}" alt="Photo" /></a>`, { headers: { 'Content-Type': 'text/html' } })
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Billing
|
|
48
|
+
|
|
49
|
+
5,000 unique transformations / month free per project; usage beyond
|
|
50
|
+
that is at /v1/pricing. Repeated fetches of the same transformed URL are
|
|
51
|
+
cached at the edge — only the first fetch counts. Cached for 1 year
|
|
52
|
+
by default.
|
|
53
|
+
|
|
54
|
+
## Source restrictions
|
|
55
|
+
|
|
56
|
+
The source URL must be on the project's subdomain (default) or on a
|
|
57
|
+
verified custom domain attached to the project. Cross-origin external
|
|
58
|
+
URLs are blocked by default and return 403 — if you need to transform
|
|
59
|
+
images from a domain you don't own, file via the `feedback` tool.
|
|
60
|
+
|
|
61
|
+
For files in sw.fs, point at the project URL with the path:
|
|
62
|
+
sw.image.resize('/api/files/photo.jpg', { width: 400 })
|
|
63
|
+
where /api/files/photo.jpg is a function that does sw.fs.read.
|
|
64
|
+
|
|
65
|
+
## Errors
|
|
66
|
+
|
|
67
|
+
The transformed URL returns 4xx if Image Transformations isn't enabled
|
|
68
|
+
on the zone, or 415 if the source isn't an image. The helper itself
|
|
69
|
+
only validates the inputs and builds the URL — it does not pre-flight.
|
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
# Jobs and schedules
|
|
2
|
+
|
|
3
|
+
Work that shouldn't hold up a request runs in the background with no worker
|
|
4
|
+
or queue server to operate. A background handler is an ordinary function in
|
|
5
|
+
`api/`. The platform calls it with a signed request, and one call,
|
|
6
|
+
`sw.jobs.verifyInvocation(request)`, tells a real delivery apart from anyone
|
|
7
|
+
else calling that URL.
|
|
8
|
+
|
|
9
|
+
## Choose the kind of work
|
|
10
|
+
|
|
11
|
+
| You need | Use | You get |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| Work with a status the user can check, such as an export or a report | `sw.jobs.create` | A durable job id, `sw.jobs.status`, retries |
|
|
14
|
+
| A side effect nobody reads back, such as logging an event | `sw.jobs.create`, without checking its status | Retries, an optional later start, a status if you ever need it |
|
|
15
|
+
| Work on a clock, such as hourly cleanup | A schedule (`somewhere cron create`) | The handler called on a cron expression |
|
|
16
|
+
|
|
17
|
+
Every kind can run its handler more than once. Make each handler safe to
|
|
18
|
+
repeat.
|
|
19
|
+
|
|
20
|
+
## Run a job and report its status
|
|
21
|
+
|
|
22
|
+
This job counts a user's notes and stores a summary row. It uses the `notes`
|
|
23
|
+
table from **Data**:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// db/schema.ts
|
|
27
|
+
import { id, integer, owner, schema, table, text, timestamp } from 'somewhere/db';
|
|
28
|
+
|
|
29
|
+
export default schema({
|
|
30
|
+
notes: table(
|
|
31
|
+
{ id: id(), title: text(), body: text({ default: '' }), created_at: timestamp({ default: 'now' }) },
|
|
32
|
+
{ scope: owner(), client: { read: ['id', 'title', 'body', 'created_at'], create: ['title', 'body'], update: ['title', 'body'], delete: true } },
|
|
33
|
+
),
|
|
34
|
+
note_summaries: table(
|
|
35
|
+
{ id: id(), summary_id: text({ unique: true }), note_count: integer(), created_at: timestamp({ default: 'now' }) },
|
|
36
|
+
{ scope: owner(), client: { read: ['id', 'note_count', 'created_at'] } },
|
|
37
|
+
),
|
|
38
|
+
});
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
// api/summaries.ts — POST starts a summary job; GET ?id= reports it
|
|
43
|
+
export default async function summaries(
|
|
44
|
+
request: Request,
|
|
45
|
+
sw: SomewhereRuntimeContext,
|
|
46
|
+
): Promise<Response> {
|
|
47
|
+
const user = await sw.auth.fromRequest(request);
|
|
48
|
+
if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
|
|
49
|
+
|
|
50
|
+
if (request.method === 'GET') {
|
|
51
|
+
const id = new URL(request.url).searchParams.get('id');
|
|
52
|
+
if (!id) return Response.json({ error: 'Pass ?id=<job_id>.' }, { status: 400 });
|
|
53
|
+
const job = await sw.jobs.status(id);
|
|
54
|
+
return Response.json({ status: job.status });
|
|
55
|
+
}
|
|
56
|
+
if (request.method !== 'POST') {
|
|
57
|
+
return new Response('Use GET or POST.', { status: 405, headers: { Allow: 'GET, POST' } });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const input: unknown = await request.json().catch(() => null);
|
|
61
|
+
const operationId =
|
|
62
|
+
typeof input === 'object' && input !== null && 'operation_id' in input ? input.operation_id : undefined;
|
|
63
|
+
if (typeof operationId !== 'string' || !/^[A-Za-z0-9_-]{8,64}$/.test(operationId)) {
|
|
64
|
+
return Response.json({ error: 'Send an operation_id of 8–64 letters, digits, _ or -.' }, { status: 400 });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const allowance = await sw.rateLimit.check(`summaries:${user.id}`, 10, 3600);
|
|
68
|
+
if (!allowance.allowed) {
|
|
69
|
+
return Response.json({ error: 'Try again later.' }, { status: 429 });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// The same user and operation_id always produce the same key and arguments,
|
|
73
|
+
// so a retried request reaches the same job instead of creating another.
|
|
74
|
+
const job = await sw.jobs.create({
|
|
75
|
+
handler: '/api/jobs/summarize-notes',
|
|
76
|
+
idempotency_key: `summary:${user.id}:${operationId}`,
|
|
77
|
+
// user_id comes from the verified session, so the handler can trust it.
|
|
78
|
+
payload: { summary_id: `${user.id}:${operationId}`, user_id: user.id },
|
|
79
|
+
});
|
|
80
|
+
return Response.json({ job_id: job.job_id }, { status: 202 });
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
// api/jobs/summarize-notes.ts — runs only when the platform delivers the job
|
|
86
|
+
export default async function summarizeNotes(
|
|
87
|
+
request: Request,
|
|
88
|
+
sw: SomewhereRuntimeContext,
|
|
89
|
+
): Promise<Response> {
|
|
90
|
+
if (!(await sw.jobs.verifyInvocation(request))) {
|
|
91
|
+
return Response.json({ error: 'forbidden' }, { status: 403 });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const payload: unknown = await request.json().catch(() => null);
|
|
95
|
+
const fields = typeof payload === 'object' && payload !== null ? payload : {};
|
|
96
|
+
const summaryId = 'summary_id' in fields ? fields.summary_id : undefined;
|
|
97
|
+
const userId = 'user_id' in fields ? fields.user_id : undefined;
|
|
98
|
+
if (typeof summaryId !== 'string' || !summaryId || typeof userId !== 'string' || !userId) {
|
|
99
|
+
return Response.json({ error: 'Invalid payload.' }, { status: 400 });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Server authority, scoped by hand to the user your own code put in the payload.
|
|
103
|
+
const { data: noteCount } = await sw.db.server.count('notes', { where: { user_id: userId } });
|
|
104
|
+
// A repeated run inserts nothing: summary_id is unique.
|
|
105
|
+
await sw.db.server.insert(
|
|
106
|
+
'note_summaries',
|
|
107
|
+
{ summary_id: summaryId, note_count: noteCount, user_id: userId },
|
|
108
|
+
{ onConflict: 'ignore' },
|
|
109
|
+
);
|
|
110
|
+
return Response.json({ ok: true });
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The page creates one `operation_id` per user action, for example with
|
|
115
|
+
`crypto.randomUUID()`, and reuses it if it retries that request. It posts
|
|
116
|
+
`{ operation_id }` to `/api/summaries`, receives `job_id`, and checks
|
|
117
|
+
`GET /api/summaries?id=<job_id>` until the status is `complete`, `failed`
|
|
118
|
+
or `cancelled`. `indeterminate` is not final on its own: the job may still be
|
|
119
|
+
recovering, so check again, and read its `recovery` before starting new work.
|
|
120
|
+
When it's `complete`, the summary row is in the user's `note_summaries`.
|
|
121
|
+
|
|
122
|
+
- **Verify before reading the payload.** `verifyInvocation` checks that the
|
|
123
|
+
request is a platform-signed delivery for this project. Answer 403 when
|
|
124
|
+
verification fails, including when the platform cannot confirm the
|
|
125
|
+
signature. Validate the payload before using it.
|
|
126
|
+
- **Server authority, scoped by your code.** The handler writes with
|
|
127
|
+
`sw.db.server` and names `user_id` itself. That's safe here because the job
|
|
128
|
+
payload came from your own verified request, never from a browser.
|
|
129
|
+
- **Repeats are expected.** The platform retries a failed run, so the unique
|
|
130
|
+
`summary_id` turns a repeat into a no-op. How many times a run can repeat:
|
|
131
|
+
`sw.jobs` → `recovery-status-what-a-job-handle-can-tell-you`.
|
|
132
|
+
- **Status is per user.** `sw.jobs.status` serves a job only to the user who
|
|
133
|
+
created it. In a signed-in handler, `sw.jobs.cancel(jobId)` cancels that
|
|
134
|
+
user's job. An ordinary handler already running finishes; its side effects
|
|
135
|
+
remain. Until that execution ends, the cancelled job keeps its concurrency
|
|
136
|
+
slot and reports `completed_at: null`. A queued job releases its slot
|
|
137
|
+
immediately.
|
|
138
|
+
- **One key per user action.** `user_id` comes only from the session, and
|
|
139
|
+
the key is `summary:<user id>:<operation_id>`. If `sw.jobs.create` throws
|
|
140
|
+
`JOB_ADMISSION_UNCONFIRMED`, send the same request again with the same
|
|
141
|
+
`operation_id`. The same key and arguments reach the job that may already
|
|
142
|
+
exist instead of creating a second one. Never retry with a new
|
|
143
|
+
`operation_id` for the same action. A status of `indeterminate` carries
|
|
144
|
+
`recovery` details. Read them before submitting new work.
|
|
145
|
+
|
|
146
|
+
## Job limits
|
|
147
|
+
|
|
148
|
+
- **Creation rate.** 600 `sw.jobs.create` calls a minute per account
|
|
149
|
+
owner, counted across the account's projects. Above it the call throws
|
|
150
|
+
`RATE_LIMITED` (429) with a retry delay.
|
|
151
|
+
- **Jobs at once.** At most 100 jobs queued, scheduled or running at once
|
|
152
|
+
per account, on every plan. Above it the call throws
|
|
153
|
+
`JOB_QUOTA_EXCEEDED` (429); create more as earlier ones finish.
|
|
154
|
+
The two limits are separate: a job holds its slot from creation until it
|
|
155
|
+
finishes, so how many jobs you can run per minute also depends on how long
|
|
156
|
+
each one runs. Runs started by your cron schedules never use these slots;
|
|
157
|
+
your plan's schedule limits pace them instead.
|
|
158
|
+
- **Start time.** `run_at` can be any future time.
|
|
159
|
+
|
|
160
|
+
Fanning out many small messages, one per item, does not fit these limits. Put
|
|
161
|
+
a batch of items in one job's payload and loop over them in the handler: one
|
|
162
|
+
job per batch, with each item's result recorded in your own table. Each run of
|
|
163
|
+
the handler is one function request under the usual time limits (`limits`),
|
|
164
|
+
so size a batch to finish well inside one run.
|
|
165
|
+
|
|
166
|
+
## In a preview
|
|
167
|
+
|
|
168
|
+
`sw.jobs.create`, `sw.jobs.status`, `sw.jobs.cancel` and
|
|
169
|
+
`sw.jobs.verifyInvocation` work in preview code. The job runs the preview's
|
|
170
|
+
own code against the preview's data, files, users and mail, and never touches
|
|
171
|
+
your live app. A preview sees only its own jobs; production and other
|
|
172
|
+
previews never see them. Smaller than production, and said in the answer:
|
|
173
|
+
|
|
174
|
+
- **One attempt, no retries.** Status shows `attempts_allowed: 1`.
|
|
175
|
+
- **At most 270 seconds.** A longer `timeout_seconds` is accepted and capped;
|
|
176
|
+
the create answer says `preview_timeout_capped: true` with
|
|
177
|
+
`preview_timeout_cap_seconds`, and the job's `timeout_seconds` is the
|
|
178
|
+
effective one.
|
|
179
|
+
- **The handler is a path in this project**, such as `/api/report`; an
|
|
180
|
+
address is refused with `PREVIEW_HANDLER_NOT_PREVIEW_CODE`. Redirects are
|
|
181
|
+
not followed.
|
|
182
|
+
- **No result webhook** (`PREVIEW_WEBHOOK_UNSUPPORTED`), no row-bound jobs
|
|
183
|
+
(`PREVIEW_ROW_JOB_UNSUPPORTED`) and no agent jobs
|
|
184
|
+
(`PREVIEW_AGENT_UNSUPPORTED`).
|
|
185
|
+
- **At most 20 unfinished jobs per preview** (`PREVIEW_JOB_LIMIT`) and
|
|
186
|
+
60 creates a minute; they never count against your production limits.
|
|
187
|
+
- **A job created by a signed-in preview user acts for that user** only for
|
|
188
|
+
data, files and teams. It cannot use `sw.jobs` for that user (create, status
|
|
189
|
+
or cancel answer `PREVIEW_NESTED_JOB_UNSUPPORTED`); the preview's own
|
|
190
|
+
requests can. A run with no user (`preview run-job`, `cron run --preview`)
|
|
191
|
+
can create further preview jobs.
|
|
192
|
+
- **When the preview closes, expires, is promoted or is saved again**, its
|
|
193
|
+
unfinished jobs end with `PREVIEW_ENDED` within about a minute, delayed ones
|
|
194
|
+
too; no new handler starts for the old version. A preview saved before jobs
|
|
195
|
+
opened keeps `sw.jobs` refused until it is saved again.
|
|
196
|
+
|
|
197
|
+
`sw.cron` refuses in a preview (`PREVIEW_CRON_UNAVAILABLE`): a schedule is a
|
|
198
|
+
production setting. To test a job or scheduled handler from outside the app,
|
|
199
|
+
run it once in the preview with `somewhere preview run-job <handler-path>
|
|
200
|
+
[--payload <json>]`, or `somewhere cron run <name> --preview` for a
|
|
201
|
+
production schedule's handler and payload.
|
|
202
|
+
|
|
203
|
+
## Existing sw.queue code
|
|
204
|
+
|
|
205
|
+
Use `sw.jobs` for new background work. `sw.queue` is not recommended for new
|
|
206
|
+
code, but it keeps working unchanged for apps that already use it:
|
|
207
|
+
`sw.queue.push({ handler, payload, delay_seconds?, idempotency_key? })` is still
|
|
208
|
+
accepted, delivered with retries, and its terminal failures are listed at
|
|
209
|
+
`GET /v1/queue/dead-letters`. Its handler verifies with
|
|
210
|
+
`sw.queue.verifyInvocation(request)`, the same check as
|
|
211
|
+
`sw.jobs.verifyInvocation(request)`.
|
|
212
|
+
|
|
213
|
+
The two have different limits; jobs are not a higher-throughput replacement:
|
|
214
|
+
|
|
215
|
+
| | `sw.queue` (existing code) | `sw.jobs` (recommended) |
|
|
216
|
+
|---|---|---|
|
|
217
|
+
| Admission rate per account owner | 600 a minute | 600 a minute |
|
|
218
|
+
| Waiting or running at once | no limit | 100 on every plan (queued, scheduled or running) |
|
|
219
|
+
| Later start | up to 12 hours (`delay_seconds`) | any future `run_at` |
|
|
220
|
+
| Status, cancel, inspectable retries | none | yes |
|
|
221
|
+
|
|
222
|
+
When you move code from `sw.queue` to `sw.jobs`:
|
|
223
|
+
- `delay_seconds` becomes `run_at`, an ISO-8601 time with an explicit offset,
|
|
224
|
+
such as `new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()`.
|
|
225
|
+
- A burst that sent one message per item may exceed the job limits; put a
|
|
226
|
+
batch of items in one job's payload, sized to finish in one run.
|
|
227
|
+
- Queue keys and job keys are separate: nothing dedupes a job against a queue
|
|
228
|
+
message, and messages already sent are not moved or sent again. If both can
|
|
229
|
+
run for the same work, keep the effect idempotent in your handler, for
|
|
230
|
+
example a unique column for the work's own id.
|
|
231
|
+
|
|
232
|
+
## Run on a schedule
|
|
233
|
+
|
|
234
|
+
Deploy the handler first, then register the schedule:
|
|
235
|
+
|
|
236
|
+
```bash
|
|
237
|
+
somewhere cron create "0 * * * *" /api/jobs/cleanup --name cleanup
|
|
238
|
+
somewhere cron run cleanup --wait # run it once now and wait for the result
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
A scheduled handler verifies with `sw.jobs.verifyInvocation` like any job. A
|
|
242
|
+
fire missed while the platform was unavailable isn't replayed, so design for
|
|
243
|
+
an occasional skipped run. Schedules work on every plan; the plan sets how
|
|
244
|
+
many a project can hold and how often each can run. The `cron_list` tool
|
|
245
|
+
returns your plan's `policy.min_interval_minutes` and `max_per_project`. A
|
|
246
|
+
tighter schedule is refused with `CRON_SCHEDULE_TOO_FREQUENT`, and one past the
|
|
247
|
+
count with `CRON_QUOTA_EXCEEDED`. Times are UTC unless you pass `--timezone`.
|
|
248
|
+
|
|
249
|
+
## Start once at a future time
|
|
250
|
+
|
|
251
|
+
Pass `run_at` to `sw.jobs.create` or the `job_create` tool: an ISO-8601
|
|
252
|
+
instant with a time zone, such as `2026-10-05T09:00:00Z`. This schedules a
|
|
253
|
+
single job at any future time. Omit it to start immediately: `sw.jobs.create`
|
|
254
|
+
answers once the job is saved (`queued`) and the job starts right after. In the
|
|
255
|
+
rare case that start is lost, the minute-by-minute dispatcher starts it, so it
|
|
256
|
+
can stay `queued` for up to about 75 seconds.
|
|
257
|
+
The job reports `scheduled` until its earliest start time; the minute-by-minute
|
|
258
|
+
dispatcher starts due work, so a busy batch can start later.
|
|
259
|
+
|
|
260
|
+
A waiting job reserves a slot in the account's job limit. List jobs with
|
|
261
|
+
`job_get({ project_id, status: 'scheduled' })` and cancel one to free its slot.
|
|
262
|
+
Keep the same idempotency key and arguments after a lost response: even after
|
|
263
|
+
the time has passed, that retry returns the original job. A new job with a past
|
|
264
|
+
time gets `RUN_AT_NOT_IN_FUTURE`. Changing the time requires a new logical job. A
|
|
265
|
+
scheduled job whose creator loses project access stops with
|
|
266
|
+
`JOB_CREATOR_ACCESS_REVOKED` before it starts. Cancelling before dispatch
|
|
267
|
+
prevents the handler from running; cancellation after a handler starts is best effort.
|
|
268
|
+
|
|
269
|
+
## More on jobs and schedules
|
|
270
|
+
|
|
271
|
+
| Need | Where |
|
|
272
|
+
|---|---|
|
|
273
|
+
| Idempotency keys, admission and replay rules | `sw.jobs` → `idempotency-key-safe-retries` |
|
|
274
|
+
| Retries, `indeterminate`, recovery codes | `sw.jobs` → `recovery-status-what-a-job-handle-can-tell-you` |
|
|
275
|
+
| Handler and signature details | `sw.jobs` → `job-handler-function` |
|
|
276
|
+
| Creation rate, jobs at once, batching | `sw.jobs` → `job-limits` |
|
|
277
|
+
| Cron format, time zones, plan limits, run now | `cron` → `schedule-format`, `minimum-interval`, `run-once-now` |
|
|
278
|
+
| A complete scheduled cleanup | `cron` → `recipe-hourly-cleanup-of-stale-rows` |
|
|
279
|
+
| Agent runs that continue in the background | `sw.agent` |
|
|
280
|
+
| A job that acts on one row for the user who started it | `sw.jobs` → `act-on-one-row-for-the-signed-in-user` |
|
|
281
|
+
|
|
282
|
+
## Retries and timeouts
|
|
283
|
+
|
|
284
|
+
Run work that shouldn't block a user request in a job.
|
|
285
|
+
`timeout_seconds` is how long the platform waits for your handler: 300 seconds
|
|
286
|
+
by default, up to 1800. A deadline of up to 270 seconds is waited for exactly.
|
|
287
|
+
A deadline from 271 to 300 seconds, which includes the default, is waited for
|
|
288
|
+
at most 270 seconds. A deadline above 300 seconds is waited for in full,
|
|
289
|
+
except in a preview, where a run is waited for at most 270 seconds.
|
|
290
|
+
|
|
291
|
+
When the deadline passes, the platform stops waiting and the job fails with
|
|
292
|
+
`JOB_TIMEOUT`. The job is not sent again. Your handler is not stopped: it may
|
|
293
|
+
still be running at that moment and may finish some of its work, so write it so
|
|
294
|
+
that a later run can pick up safely.
|
|
295
|
+
|
|
296
|
+
Once a job has ended (timed out, cancelled, failed or complete), the platform
|
|
297
|
+
refuses further `sw.*` calls from its handler with `JOB_ENDED`, so a handler
|
|
298
|
+
that outlives its job can no longer write through `sw.fs`, `sw.email`,
|
|
299
|
+
`sw.payments`, `sw.jobs`, or `sw.db` in a managed-mode database. This
|
|
300
|
+
narrows what a late handler can change. It does not stop the handler, and these
|
|
301
|
+
can still happen after the deadline:
|
|
302
|
+
- Calls started before the job's status changes. A timeout is recorded a
|
|
303
|
+
moment after the deadline; until then calls still run.
|
|
304
|
+
- A call already accepted when the job ends. It completes.
|
|
305
|
+
- Outbound `fetch`, including requests to your own app's routes, which run as
|
|
306
|
+
new, ordinary requests.
|
|
307
|
+
- Work started or scheduled before the job ended: jobs it created, schedules,
|
|
308
|
+
queue messages, and calls already in progress.
|
|
309
|
+
- `sw.db` in a database that does not use managed mode. Its queries run
|
|
310
|
+
directly and are not checked.
|
|
311
|
+
- Effects outside the platform, such as a call your handler made to another
|
|
312
|
+
service. These cannot be refused or undone.
|
|
313
|
+
- Functions you last deployed before 17:18 UTC on October 18, 2026, until you
|
|
314
|
+
deploy again with `somewhere deploy`.
|
|
315
|
+
|
|
316
|
+
An error your handler returns is retried, one attempt at a time and inside the
|
|
317
|
+
same deadline. When the connection fails after the request may have reached your
|
|
318
|
+
handler, the job fails with `JOB_DELIVERY_UNCONFIRMED` instead of being sent
|
|
319
|
+
again. The platform never sends a job again while an earlier delivery of it may
|
|
320
|
+
still be running, but a handler can still run more than once in sequence — see
|
|
321
|
+
Recovery status below.
|
|
322
|
+
Make handlers idempotent — they may run more than once.
|
|
323
|
+
|
|
324
|
+
## Create a job
|
|
325
|
+
|
|
326
|
+
`sw.jobs.create({ handler, payload, idempotency_key, timeout_seconds, run_at })`
|
|
327
|
+
starts the work; `api/summaries.ts` in **Run a job and report its status**
|
|
328
|
+
above is the complete example. The handler must be a deployed function path,
|
|
329
|
+
such as `/api/jobs/summarize-notes`. The platform POSTs the payload to your
|
|
330
|
+
function when the job runs. The call resolves to
|
|
331
|
+
`{ job_id, status, duplicate, recovery }`: `duplicate` is `true` when the same
|
|
332
|
+
idempotency key and arguments returned an existing job, and an
|
|
333
|
+
`indeterminate` status means read `recovery` before retrying.
|
|
334
|
+
|
|
335
|
+
## Idempotency key — safe retries
|
|
336
|
+
|
|
337
|
+
Pass an optional `idempotency_key` (1–200 characters, no surrounding
|
|
338
|
+
whitespace) in the body, or the `Idempotency-Key` header; if both are sent
|
|
339
|
+
they must match. Inside a deployed function, `sw.jobs.create` and
|
|
340
|
+
`sw.agent.run` generate one key per invocation when you do not supply one,
|
|
341
|
+
and the CLI and MCP forward one per call — so a lost response on a single
|
|
342
|
+
call is safe to retry with the same key. A separate invocation is new work
|
|
343
|
+
unless you reuse your explicit key.
|
|
344
|
+
|
|
345
|
+
- Same key + same effective arguments, within the same project and caller →
|
|
346
|
+
the same job handle comes back; current authorization is always checked
|
|
347
|
+
first, and a sequential replay does not consume a new concurrent job slot.
|
|
348
|
+
- Same key + different arguments → `409 IDEMPOTENCY_KEY_REUSED`.
|
|
349
|
+
- Concurrent equal requests admit one job. Each request may still hit the
|
|
350
|
+
per-request rate limiter before admission deduplicates; rate accounting is
|
|
351
|
+
not part of admission.
|
|
352
|
+
- Unkeyed equal requests are independent jobs. A key lives as long as its
|
|
353
|
+
job and receipt, not beyond project or job deletion.
|
|
354
|
+
- If admission cannot be confirmed you get `503 JOB_ADMISSION_UNCONFIRMED`:
|
|
355
|
+
retry only with the same key. Concurrency caps return
|
|
356
|
+
`429 JOB_QUOTA_EXCEEDED` (`job-limits`).
|
|
357
|
+
|
|
358
|
+
## Recovery status — what a job handle can tell you
|
|
359
|
+
|
|
360
|
+
A job handle is durable. Your handler may run more than once for one job and
|
|
361
|
+
must be idempotent; there is no exactly-once guarantee, and there is also no
|
|
362
|
+
promise that every admitted job is invoked (see the fenced crash below). A
|
|
363
|
+
response may carry `status: 'indeterminate'` with
|
|
364
|
+
`recovery` diagnostics instead of a final answer — read them, do not blindly
|
|
365
|
+
replay:
|
|
366
|
+
|
|
367
|
+
- `JOB_RESULT_UNCONFIRMED` — the provider reports complete but no product
|
|
368
|
+
result was stored: unconfirmed, not success.
|
|
369
|
+
- `JOB_EXECUTION_STOPPED` — the run errored or was terminated without a
|
|
370
|
+
product result; partial effects may exist.
|
|
371
|
+
- `JOB_STATUS_UNCONFIRMED` — the job was admitted (the id is real) but its
|
|
372
|
+
status could not be read; poll it.
|
|
373
|
+
- A crash between the dispatch fence and invocation stays `unknown`; the
|
|
374
|
+
platform does not create a second run on your behalf. Decide with your own
|
|
375
|
+
records whether to submit new work.
|
|
376
|
+
|
|
377
|
+
The same rules apply to ingest jobs, which share this admission path.
|
|
378
|
+
|
|
379
|
+
## Job handler function
|
|
380
|
+
A job handler is an ordinary deployed function, so the database rules are the
|
|
381
|
+
same as for requests. Application tables are declared in db/schema.ts. sw.db.from reads them with caller-scoped access, and sw.db.server.from reads them once the caller is authorized for server access. The corresponding structured methods, such as sw.db.server.insert, change them. Raw query and batch go to the separate raw SQL database on current projects.
|
|
382
|
+
|
|
383
|
+
`api/jobs/summarize-notes.ts` in **Run a job and report its status** above
|
|
384
|
+
is the complete handler: it verifies with `sw.jobs.verifyInvocation` before
|
|
385
|
+
reading the body, answers 403 when that returns `false`, validates the
|
|
386
|
+
payload, scopes its server writes to the payload's user, and makes a repeated
|
|
387
|
+
run a no-op.
|
|
388
|
+
|
|
389
|
+
The platform signs each job delivery with X-Somewhere-Signature,
|
|
390
|
+
X-Somewhere-Invocation-Timestamp, and X-Somewhere-Body-SHA256.
|
|
391
|
+
Always verify before trusting the payload on public /api/jobs/*
|
|
392
|
+
handlers. This blocks a browser from calling the job handler directly
|
|
393
|
+
with forged payloads. `verifyInvocation` returns `false` whenever the
|
|
394
|
+
platform cannot confirm the signature, including when its database was
|
|
395
|
+
briefly unreachable; the REST check behind it answers that case
|
|
396
|
+
`503 INVOCATION_VERIFY_OUTCOME_UNKNOWN`, because the one-time signature may
|
|
397
|
+
already be recorded (the same signed request can then be refused as a
|
|
398
|
+
replay). Answer 403 and do not run the work.
|
|
399
|
+
|
|
400
|
+
To test redelivery, enqueue through the app in a test project. For a test-only
|
|
401
|
+
payload, have the handler record a durable first-attempt marker and return
|
|
402
|
+
503 once, after a write you expect to be safe to repeat. The platform retries a
|
|
403
|
+
retryable response within the job deadline with a newly signed delivery.
|
|
404
|
+
Poll its status and check the final rows for duplicates. To test repeat-safe
|
|
405
|
+
writes without waiting for a platform retry, invoke two jobs with the same
|
|
406
|
+
business operation ID and different enqueue keys. Reusing the enqueue key
|
|
407
|
+
only returns the original job.
|
|
408
|
+
|
|
409
|
+
## Look up a job's status
|
|
410
|
+
|
|
411
|
+
`sw.jobs.status(jobId)` returns the job. Its `status` is `queued`,
|
|
412
|
+
`scheduled`, `running`, `complete`, `failed`, `cancelled` or
|
|
413
|
+
`indeterminate`, alongside `attempts`, `error`, `error_code`,
|
|
414
|
+
`started_at`, `completed_at`, `run_at` and `recovery`. Poll it from another
|
|
415
|
+
request: the browser calls your function, which calls `sw.jobs.status` for the
|
|
416
|
+
signed-in user, as the `GET` branch of `api/summaries.ts` above does. A job
|
|
417
|
+
is served only to the user who created it.
|
|
418
|
+
|
|
419
|
+
### Result size
|
|
420
|
+
|
|
421
|
+
A job keeps its handler's answer as its `result`, within two limits.
|
|
422
|
+
|
|
423
|
+
- The result and the record that carries it from your handler are measured
|
|
424
|
+
together and must fit in 768 KiB (786,432 bytes). The measure is
|
|
425
|
+
conservative: characters that need escaping (quotes, backslashes, control
|
|
426
|
+
characters) count as their escaped form, and a result that contains any
|
|
427
|
+
character outside Latin-1 counts two bytes for every character.
|
|
428
|
+
- The job as a whole — its `payload`, its attempt history, its `result` and
|
|
429
|
+
its other fields — must fit in 1,999,000 bytes, measured when the result is
|
|
430
|
+
saved. A job with a large `payload` therefore has less room for its result.
|
|
431
|
+
|
|
432
|
+
A JSON answer is kept exactly as sent; an answer that is not JSON is kept as
|
|
433
|
+
`{ "text": … }` with its first 100,000 characters.
|
|
434
|
+
|
|
435
|
+
A larger answer ends the job as `failed` with `JOB_RESULT_TOO_LARGE`. The
|
|
436
|
+
handler ran and answered, but the result was discarded and the job was not run
|
|
437
|
+
again. Anything the handler did before answering was not undone. Return a
|
|
438
|
+
smaller result, or write large output with `sw.fs` and return a reference to
|
|
439
|
+
it.
|
|
440
|
+
|
|
441
|
+
## Act on one row for the signed-in user
|
|
442
|
+
|
|
443
|
+
A job can read or change one row as the user who started it, with only the
|
|
444
|
+
operations its binding declares. Declare the binding in the schema options,
|
|
445
|
+
beside the table it acts on:
|
|
446
|
+
|
|
447
|
+
```ts
|
|
448
|
+
schema(
|
|
449
|
+
{
|
|
450
|
+
expenses: table(
|
|
451
|
+
{ id: id(), group_id: text(), amount_cents: integer(), status: text({ default: 'open' }) },
|
|
452
|
+
{ scope: group(), client: { read: true, create: ['group_id', 'amount_cents'] } },
|
|
453
|
+
),
|
|
454
|
+
},
|
|
455
|
+
{ jobs: { settle_expense: { table: 'expenses', operations: ['read', 'update'], maxDurationSeconds: 900 } } },
|
|
456
|
+
);
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
Start it from the signed-in user's own request, naming the binding and the row:
|
|
460
|
+
|
|
461
|
+
```ts
|
|
462
|
+
// api/expenses/settle.ts — POST { id }: queue a settlement job for one expense
|
|
463
|
+
export default async function settleExpense(
|
|
464
|
+
request: Request,
|
|
465
|
+
sw: SomewhereRuntimeContext,
|
|
466
|
+
): Promise<Response> {
|
|
467
|
+
if (request.method !== 'POST') {
|
|
468
|
+
return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
469
|
+
}
|
|
470
|
+
if (!(await sw.auth.fromRequest(request))) {
|
|
471
|
+
return Response.json({ error: 'Sign in first.' }, { status: 401 });
|
|
472
|
+
}
|
|
473
|
+
const body = (await request.json().catch(() => null)) as { id?: unknown } | null;
|
|
474
|
+
if (typeof body?.id !== 'string' || body.id === '') {
|
|
475
|
+
return Response.json({ error: 'Send the expense ID as a non-empty string.' }, { status: 400 });
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const job = await sw.jobs.create({
|
|
479
|
+
handler: '/api/jobs/settle-expense',
|
|
480
|
+
row: { binding: 'settle_expense', id: body.id },
|
|
481
|
+
});
|
|
482
|
+
return Response.json({ job_id: job.job_id }, { status: 202 });
|
|
483
|
+
}
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
```ts
|
|
487
|
+
// api/jobs/settle-expense.ts — the job: reads and updates only its one row
|
|
488
|
+
export default async function settleExpenseJob(
|
|
489
|
+
request: Request,
|
|
490
|
+
sw: SomewhereRuntimeContext,
|
|
491
|
+
): Promise<Response> {
|
|
492
|
+
if (!(await sw.jobs.verifyInvocation(request))) return new Response('Forbidden', { status: 403 });
|
|
493
|
+
// Structured calls in a row-bound job reach only its row, as its user.
|
|
494
|
+
const { data } = await sw.db.from('expenses', { limit: 1 });
|
|
495
|
+
if (!data.length) return Response.json({ settled: false });
|
|
496
|
+
await sw.db.update('expenses', { set: { status: 'settled' }, where: { status: 'open' } });
|
|
497
|
+
return Response.json({ settled: true });
|
|
498
|
+
}
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
- **The row id is typed by its key.** `id()` keys take a string;
|
|
502
|
+
`id({ uuid: false })` keys take a whole number. `'42'` never names row `42`.
|
|
503
|
+
- If the row is missing or the caller cannot use it for the declared job operations,
|
|
504
|
+
job creation returns `403 FORBIDDEN`. Check the row ID and the caller's access.
|
|
505
|
+
- **The user's access still applies.** Each read and write runs with that user's
|
|
506
|
+
current access to the row, inside the binding's operations. If they lose
|
|
507
|
+
access, the job sees and changes nothing.
|
|
508
|
+
- **User authority for one row.** The job's structured `sw.db` calls on the
|
|
509
|
+
bound table run as that user and reach only that row, with the binding's
|
|
510
|
+
operations: no new rows, counts, aggregates, related rows or key changes. The
|
|
511
|
+
grant gives that user no authority over other rows or other tables, and no
|
|
512
|
+
file access: plain `sw.fs` is refused in the job, while `sw.fs.server`
|
|
513
|
+
stays your project authority that needs your own check. A row-bound job
|
|
514
|
+
can't use `sw.db.server` or a table's `publicRead` access; an ordinary
|
|
515
|
+
job started by a user can still call `sw.db.server` explicitly.
|
|
516
|
+
- **Bounded in time.** The grant starts at the job's start (`run_at` when set)
|
|
517
|
+
and ends `maxDurationSeconds` later; retries keep the same deadline. A
|
|
518
|
+
cancelled or finished job keeps no access.
|
|
519
|
+
- **Created by the user, on the deployed app.** Only a signed-in user's own
|
|
520
|
+
request starts one, never another job; a preview or local run can't.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# sw.logs — Application Logging (inside deployed functions)
|
|
2
|
+
|
|
3
|
+
Structured logs written to the project's log stream.
|
|
4
|
+
Readable via the `project_logs` MCP tool or dashboard Logs page.
|
|
5
|
+
|
|
6
|
+
For reading logs and errors while you debug, start with `browser` → `read-what-happened`.
|
|
7
|
+
|
|
8
|
+
## Write logs
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
// api/log-example.ts — one line at each level; await every write
|
|
12
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
13
|
+
const started = Date.now();
|
|
14
|
+
const config = { region: 'eu', retries: 3 };
|
|
15
|
+
await sw.logs.debug('loaded config', { keys: Object.keys(config) });
|
|
16
|
+
|
|
17
|
+
let body: unknown;
|
|
18
|
+
try {
|
|
19
|
+
body = await req.json();
|
|
20
|
+
} catch (err) {
|
|
21
|
+
await sw.logs.error('unreadable request body', { error: err instanceof Error ? err.message : String(err) });
|
|
22
|
+
return Response.json({ error: 'Send a JSON body.' }, { status: 400 });
|
|
23
|
+
}
|
|
24
|
+
await sw.logs.info('request received', { has_body: body !== null });
|
|
25
|
+
|
|
26
|
+
const ms = Date.now() - started;
|
|
27
|
+
if (ms > 500) await sw.logs.warn('slow request', { ms });
|
|
28
|
+
return Response.json({ ok: true });
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
All four levels accept (message: string, data?: object) and return a promise
|
|
33
|
+
that resolves once the platform has accepted the line. Await it: a log call
|
|
34
|
+
still pending when your function returns can be lost. Prefer `sw.logs` to
|
|
35
|
+
`console.*` for anything you need to read back. `data` is stored as JSON.
|
|
36
|
+
|
|
37
|
+
Each project has a daily log quota that resets at midnight UTC. Past it, the
|
|
38
|
+
write is refused with 429 `LOG_QUOTA_EXCEEDED`, the message names the daily
|
|
39
|
+
limit, and the awaited call throws an Error carrying that `.code` and
|
|
40
|
+
`.status`. When ingestion is saturated, the call throws 503
|
|
41
|
+
`LOG_INGEST_UNAVAILABLE`; retry shortly. Other ceilings: docs({ topic: 'limits' }).
|
|
42
|
+
|
|
43
|
+
## Retention
|
|
44
|
+
Application log retention follows the project owner’s plan:
|
|
45
|
+
- Free: 7 days.
|
|
46
|
+
- Builder: 30 days.
|
|
47
|
+
- Pro: 90 days.
|
|
48
|
+
- Scale: 365 days.
|
|
49
|
+
|
|
50
|
+
Hourly cleanup deletes expired entries in batches; a backlog continues on the next run.
|
|
51
|
+
Deleted entries have no archive.
|
|
52
|
+
|
|
53
|
+
## Reading logs
|
|
54
|
+
From a shell: `somewhere logs` (and `somewhere errors` for failures). Over MCP:
|
|
55
|
+
the project_logs tool with project_id. Inside a function:
|
|
56
|
+
`await sw.logs.tail({ level: 'error', search: 'payment', limit: 20 })`.
|
|
57
|
+
Both return newest first and take the same filters: `level`, `source`,
|
|
58
|
+
`search` (lines whose message contains the text; `data` is not searched),
|
|
59
|
+
`trace_id` (one request's lines) and `limit`. In a preview, `sw.logs.tail`
|
|
60
|
+
is refused with `DRAFT_PLATFORM_CAPABILITY_DENIED` (logs are not separated by
|
|
61
|
+
preview); read them with `somewhere logs` instead.
|