@palettelab/cli 0.3.60 → 0.3.61

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/README.md CHANGED
@@ -11,7 +11,7 @@ Use the right helper for the runtime you are coding in:
11
11
  | Runtime | Package/helper | Use it for |
12
12
  |---|---|---|
13
13
  | Frontend TypeScript/React | `@palettelab/sdk`, `createPaletteClient(...)`, `palette.*` | UI code, current-user OS APIs, frontend broker clients, Data Room browsing/upload from the browser, toasts, and current-user OS notifications |
14
- | Backend Python/FastAPI | `palette_sdk`, `PluginContext`, `ctx.*`, `services(ctx)` | Backend routes, permission gates, app-owned data, migrations, cross-user notifications, server-side Data Rooms, managed services, app-to-app service handlers, and lifecycle hooks |
14
+ | Backend Python/FastAPI | `palette_sdk`, `PluginContext`, `ctx.*`, `services(ctx)` | Backend routes, permission gates, app-owned data, durable jobs, migrations, cross-user notifications, server-side Data Rooms, managed services, app-to-app service handlers, and lifecycle hooks |
15
15
  | CLI tooling | `pltt ...` | Scaffolding, local dev, testing, packaging, publishing, hosted sandbox previews, and generating frontend/backend typed service clients |
16
16
 
17
17
  The CLI bundles `palette_sdk` for local backend simulation, but backend app
@@ -309,7 +309,7 @@ async def create_invoice(body: InvoiceIn, ctx: PluginContext = Depends(get_plugi
309
309
  Backend SDK features for app-owned data:
310
310
 
311
311
  - `PluginRouter`, `PluginContext`, and `get_plugin_context` provide the FastAPI route and request-context surface.
312
- - `PluginContext` exposes `user_id`, `organization_id`, `org_role`, `plugin_id`, `permissions`, `storage`, `ctx.db`, `ctx.data_rooms`, `ctx.connections`, `ctx.members`, `ctx.redis`, `ctx.vector`, `ctx.config`, and `ctx.logger`.
312
+ - `PluginContext` exposes `user_id`, `organization_id`, `org_role`, `plugin_id`, `permissions`, `storage`, `ctx.db`, `ctx.jobs`, `ctx.data_rooms`, `ctx.connections`, `ctx.members`, `ctx.redis`, `ctx.vector`, `ctx.config`, and `ctx.logger`.
313
313
  - `ctx.db` is the full scoped SQLAlchemy `AsyncSession` for app-owned database data.
314
314
  - `ctx.repo(Model)` gives org-safe CRUD helpers for app tables.
315
315
  - `ctx.data_rooms` gives backend access to Palette Data Rooms without importing platform internals.
@@ -323,6 +323,7 @@ Backend SDK features for app-owned data:
323
323
  - `ctx.redis` gives a Redis-backed, plugin/org-scoped Redis API when `"redis"` is declared in `platform_services`.
324
324
  - `ctx.vector` gives a Qdrant-backed, plugin/org-scoped vector API when `"vector"` is declared in `platform_services`.
325
325
  - `ctx.storage` gives app/org-scoped file upload helpers when `"storage"` is declared in `platform_services`.
326
+ - `@job(...)`, `JobExecution`, and `ctx.jobs` provide durable async work with retries, progress, status, and cancellation.
326
327
  - `LifecycleHooks` lets apps define install/update/enable/disable/uninstall hooks.
327
328
  - `OrgScopedTable` and `PluginBase` keep app data inside the plugin schema model set.
328
329
  - `plugin_safe_id(...)`, `plugin_schema(...)`, `plugin_table_prefix(...)`, and `ensure_org_rls(...)` keep database names and row-level security consistent.
@@ -333,6 +334,38 @@ Backend SDK features for app-owned data:
333
334
  - `SuccessResponse`, `ErrorResponse`, and `PaginatedResponse` are reusable response schemas.
334
335
  - `route_permission_issues(router, public_routes=None)` is the test helper for detecting ungated backend routes.
335
336
 
337
+ ## Durable Background Jobs
338
+
339
+ Declare `"background_jobs": true`, register an async handler with `@job`, and
340
+ enqueue a JSON payload from the request:
341
+
342
+ ```python
343
+ from palette_sdk import JobExecution, PluginContext, job
344
+
345
+ @job("reports.generate", timeout_seconds=1800, max_attempts=3)
346
+ async def generate_report(ctx: PluginContext, execution: JobExecution, payload: dict):
347
+ await execution.progress(10, "Starting")
348
+ # ctx and ctx.db are fresh, job-owned objects created by the worker.
349
+ return {"report_id": payload["report_id"]}
350
+
351
+ handle = await ctx.jobs.enqueue(
352
+ "reports.generate",
353
+ {"report_id": report_id},
354
+ idempotency_key=f"report:{report_id}",
355
+ )
356
+ return handle.accepted_response() # HTTP 202
357
+ ```
358
+
359
+ Never pass a request `ctx`, `ctx.db`, connection, ORM object, file handle, or
360
+ other live object into `ThreadPoolExecutor`, `asyncio.create_task`, or a
361
+ detached background callback. Request cleanup releases those resources, and
362
+ async database sessions are not thread-safe. The job payload must be JSON; the
363
+ worker creates fresh scoped context and database resources for every attempt.
364
+
365
+ See [Python Backend SDK Developer Guide](./docs/python-backend-sdk.md#4b-durable-background-jobs)
366
+ for status URLs, SSE progress, cancellation, retries, idempotency, hosted
367
+ execution, and `pltt dev` behavior.
368
+
336
369
  Python backend Data Room example:
337
370
 
338
371
  ```python
@@ -833,7 +866,7 @@ pltt test --json
833
866
  pltt test --publish-type preview
834
867
  ```
835
868
 
836
- Checks include manifest validity, SDK/platform compatibility, release semver bump detection, forbidden platform imports, frontend bundling and size limits, sandbox bridge smoke, backend dependency installation/import, route permission gates, route permission declarations, migration linting, frontend sandbox policy, and dependency policy for `package.json` / `pyproject.toml`. The semver bump check is skipped for `--publish-type preview` because hosted previews may reuse the current app version. The default frontend and backend bundle limits are 15 MiB; set `PALETTE_MAX_FRONTEND_BUNDLE_BYTES` or `PALETTE_MAX_BACKEND_BUNDLE_BYTES` for reviewed exceptions.
869
+ Checks include manifest validity, SDK/platform compatibility, release semver bump detection, forbidden platform imports, frontend bundling and size limits, sandbox bridge smoke, backend dependency installation/import, route permission gates, route permission declarations, migration linting, frontend sandbox policy, and dependency policy for `package.json` / `pyproject.toml`. The semver bump check is skipped for `--publish-type preview` because hosted previews may reuse the current app version. The default frontend and backend bundle limits are 50 MiB; set `PALETTE_MAX_FRONTEND_BUNDLE_BYTES` or `PALETTE_MAX_BACKEND_BUNDLE_BYTES` for reviewed exceptions.
837
870
 
838
871
  ### `pltt package`
839
872
 
@@ -16,6 +16,7 @@ from palette_sdk.platform_services import (
16
16
  )
17
17
  from palette_sdk.repository import OrgRepository
18
18
  from palette_sdk.lifecycle import LifecycleHooks
19
+ from palette_sdk.jobs import JobCancelledError, JobExecution, JobHandle, JobsClient, job
19
20
  from palette_sdk.tool_definition import ToolDefinition
20
21
  from palette_sdk.manifest import PluginManifest, load_manifest
21
22
  from palette_sdk.schemas import (
@@ -74,6 +75,11 @@ __all__ = [
74
75
  "UnavailablePlatformService",
75
76
  "OrgRepository",
76
77
  "LifecycleHooks",
78
+ "JobCancelledError",
79
+ "JobExecution",
80
+ "JobHandle",
81
+ "JobsClient",
82
+ "job",
77
83
  "ToolDefinition",
78
84
  "PluginManifest",
79
85
  "load_manifest",
@@ -112,4 +118,4 @@ __all__ = [
112
118
  "LocalStorageService",
113
119
  ]
114
120
 
115
- __version__ = "0.1.10"
121
+ __version__ = "0.1.11"
@@ -0,0 +1,177 @@
1
+ """Durable background jobs for Palette app backends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import Awaitable, Callable
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+
11
+ JobHandler = Callable[[Any, "JobExecution", dict[str, Any]], Awaitable[dict[str, Any] | None]]
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class JobDecl:
16
+ name: str
17
+ handler: JobHandler
18
+ timeout_seconds: int = 900
19
+ max_attempts: int = 3
20
+
21
+
22
+ _pending: list[JobDecl] = []
23
+
24
+
25
+ def job(
26
+ name: str,
27
+ *,
28
+ timeout_seconds: int = 900,
29
+ max_attempts: int = 3,
30
+ ) -> Callable[[JobHandler], JobHandler]:
31
+ """Register an async handler that runs in the OS durable job worker."""
32
+ if not name or len(name) > 128:
33
+ raise ValueError("job name must contain 1-128 characters")
34
+ if timeout_seconds < 1 or timeout_seconds > 7200:
35
+ raise ValueError("job timeout_seconds must be between 1 and 7200")
36
+ if max_attempts < 1 or max_attempts > 5:
37
+ raise ValueError("job max_attempts must be between 1 and 5")
38
+
39
+ def decorator(fn: JobHandler) -> JobHandler:
40
+ if not inspect.iscoroutinefunction(fn):
41
+ raise TypeError("@job handlers must be async functions")
42
+ _pending.append(
43
+ JobDecl(
44
+ name=name,
45
+ handler=fn,
46
+ timeout_seconds=timeout_seconds,
47
+ max_attempts=max_attempts,
48
+ )
49
+ )
50
+ return fn
51
+
52
+ return decorator
53
+
54
+
55
+ def drain_pending_jobs() -> list[JobDecl]:
56
+ """Platform-only: return and clear handlers registered during app import."""
57
+ out = list(_pending)
58
+ _pending.clear()
59
+ return out
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class JobHandle:
64
+ id: str
65
+ status: str
66
+ status_url: str
67
+ events_url: str
68
+ plugin_id: str = ""
69
+ handler: str = ""
70
+
71
+ @classmethod
72
+ def from_dict(cls, value: dict[str, Any]) -> "JobHandle":
73
+ job_id = str(value.get("job_id") or value.get("id") or "")
74
+ return cls(
75
+ id=job_id,
76
+ status=str(value.get("status") or "queued"),
77
+ status_url=str(value.get("status_url") or f"/api/v1/app-jobs/{job_id}"),
78
+ events_url=str(value.get("events_url") or f"/api/v1/app-jobs/{job_id}/events"),
79
+ plugin_id=str(value.get("plugin_id") or ""),
80
+ handler=str(value.get("handler") or ""),
81
+ )
82
+
83
+ def to_dict(self) -> dict[str, Any]:
84
+ return {
85
+ "job_id": self.id,
86
+ "status": self.status,
87
+ "status_url": self.status_url,
88
+ "events_url": self.events_url,
89
+ "plugin_id": self.plugin_id,
90
+ "handler": self.handler,
91
+ }
92
+
93
+ def accepted_response(self):
94
+ from fastapi.responses import JSONResponse
95
+
96
+ return JSONResponse(status_code=202, content=self.to_dict())
97
+
98
+
99
+ class JobsClient:
100
+ """Request-safe enqueue/status client injected as ``ctx.jobs``."""
101
+
102
+ def __init__(self, adapter: Any = None):
103
+ self._adapter = adapter
104
+
105
+ def _require_adapter(self) -> Any:
106
+ if self._adapter is None:
107
+ raise RuntimeError("Palette durable jobs are not available in this runtime")
108
+ return self._adapter
109
+
110
+ async def enqueue(
111
+ self,
112
+ name: str,
113
+ payload: dict[str, Any] | None = None,
114
+ *,
115
+ idempotency_key: str | None = None,
116
+ ) -> JobHandle:
117
+ if payload is not None and not isinstance(payload, dict):
118
+ raise TypeError("job payload must be a dict")
119
+ result = await self._require_adapter().enqueue(
120
+ name,
121
+ payload or {},
122
+ idempotency_key=idempotency_key,
123
+ )
124
+ return JobHandle.from_dict(result)
125
+
126
+ async def get(self, job_id: str) -> dict[str, Any]:
127
+ return await self._require_adapter().get(job_id)
128
+
129
+ async def cancel(self, job_id: str) -> dict[str, Any]:
130
+ return await self._require_adapter().cancel(job_id)
131
+
132
+
133
+ class JobExecution:
134
+ """Control surface passed to a running durable job handler."""
135
+
136
+ def __init__(
137
+ self,
138
+ adapter: Any,
139
+ *,
140
+ job_id: str,
141
+ attempt: int,
142
+ idempotency_key: str | None = None,
143
+ ) -> None:
144
+ self._adapter = adapter
145
+ self.id = job_id
146
+ self.attempt = attempt
147
+ self.idempotency_key = idempotency_key
148
+
149
+ async def progress(self, percent: int, message: str | None = None) -> None:
150
+ if percent < 0 or percent > 100:
151
+ raise ValueError("job progress must be between 0 and 100")
152
+ await self._adapter.progress(percent, message)
153
+
154
+ async def heartbeat(self) -> None:
155
+ await self._adapter.heartbeat()
156
+
157
+ async def cancelled(self) -> bool:
158
+ return bool(await self._adapter.cancelled())
159
+
160
+ async def check_cancelled(self) -> None:
161
+ if await self.cancelled():
162
+ raise JobCancelledError(f"job {self.id} was cancelled")
163
+
164
+
165
+ class JobCancelledError(Exception):
166
+ """Cooperative cancellation raised by ``JobExecution.check_cancelled``."""
167
+
168
+
169
+ __all__ = [
170
+ "JobCancelledError",
171
+ "JobDecl",
172
+ "JobExecution",
173
+ "JobHandle",
174
+ "JobsClient",
175
+ "drain_pending_jobs",
176
+ "job",
177
+ ]
@@ -18,6 +18,7 @@ from palette_sdk.notifications import NotificationsClient
18
18
  from palette_sdk.organization import OrganizationInfo
19
19
  from palette_sdk.platform_services import UnavailablePlatformService
20
20
  from palette_sdk.events import EventPublisher
21
+ from palette_sdk.jobs import JobsClient
21
22
 
22
23
 
23
24
  class MissingSecretError(KeyError):
@@ -64,6 +65,7 @@ class PluginContext:
64
65
  redis: Any = field(default_factory=lambda: UnavailablePlatformService("redis"))
65
66
  vector: Any = field(default_factory=lambda: UnavailablePlatformService("vector"))
66
67
  events: EventPublisher = field(default_factory=EventPublisher)
68
+ jobs: JobsClient = field(default_factory=JobsClient)
67
69
  config: dict[str, Any] = field(default_factory=dict)
68
70
  logger: logging.Logger = field(default_factory=lambda: logging.getLogger("palette_sdk.plugin"))
69
71
 
@@ -142,6 +144,7 @@ async def get_plugin_context(request: Request) -> PluginContext:
142
144
  redis=getattr(state, "redis", None) or UnavailablePlatformService("redis"),
143
145
  vector=getattr(state, "vector", None) or UnavailablePlatformService("vector"),
144
146
  events=EventPublisher(getattr(state, "plugin_events", None)),
147
+ jobs=JobsClient(getattr(state, "plugin_jobs", None)),
145
148
  config=getattr(state, "plugin_config", {}),
146
149
  logger=getattr(state, "plugin_logger", logging.getLogger(f"palette_sdk.plugin.{getattr(state, 'plugin_id', 'unknown')}")),
147
150
  )
@@ -117,6 +117,7 @@ Available context values:
117
117
  | `ctx.notifications` | Push OS notification-center notifications |
118
118
  | `ctx.apps` / `services(ctx)` | Governed app-to-app calls through declared `consumes` contracts |
119
119
  | `ctx.events` | Publish event topics declared in `provides.events` |
120
+ | `ctx.jobs` | Enqueue, inspect, and cancel durable background jobs |
120
121
  | `ctx.redis` | Plugin/org-scoped Redis-style service when `platform_services` includes `redis` |
121
122
  | `ctx.vector` | Plugin/org-scoped vector service when `platform_services` includes `vector` |
122
123
  | `ctx.config` | App install/config values |
@@ -155,12 +156,155 @@ These are the public Python helpers exported by `palette_sdk`.
155
156
  | `PlatformServiceUnavailable`, `UnavailablePlatformService` | Clear errors when an undeclared platform service is used |
156
157
  | `LifecycleHooks` | Install/update/enable/disable/uninstall callbacks |
157
158
  | `Event`, `EventPublisher`, `subscribe_event(...)` | In-process event subscriptions and declared app event publishing |
159
+ | `job(...)`, `JobExecution` | Register durable async job handlers and report progress, heartbeat, or cancellation |
160
+ | `JobHandle`, `JobsClient`, `ctx.jobs` | Enqueue jobs and inspect or cancel runs without retaining request state |
158
161
  | `sign_webhook(...)`, `verify_webhook_signature(...)` | HMAC-SHA256 webhook signing and verification |
159
162
  | `ToolDefinition` | Base class for custom agent tools |
160
163
  | `PluginManifest`, `load_manifest(...)` | Typed manifest parsing from `palette-plugin.json` |
161
164
  | `SuccessResponse`, `ErrorResponse`, `PaginatedResponse` | Common response schemas for plugin APIs |
162
165
  | `route_permission_issues(router, public_routes=None)` | Test helper that reports routes missing `require_permission(...)` |
163
166
 
167
+ ## 4b. Durable Background Jobs
168
+
169
+ Use Palette durable jobs for work that should continue after an HTTP response,
170
+ may take longer than normal request limits, or needs retries, progress, and
171
+ cancellation. Do not implement this by submitting an async function or request
172
+ context to `ThreadPoolExecutor`, `asyncio.create_task`, FastAPI
173
+ `BackgroundTasks`, or another process-local fire-and-forget mechanism.
174
+
175
+ Enable the capability in `palette-plugin.json`:
176
+
177
+ ```json
178
+ {
179
+ "capabilities": {
180
+ "backend": true,
181
+ "database": true,
182
+ "background_jobs": true
183
+ }
184
+ }
185
+ ```
186
+
187
+ Register the handler with `@job`, enqueue a JSON payload from the route, and
188
+ return the handle's `202 Accepted` response:
189
+
190
+ ```python
191
+ from fastapi import Depends
192
+ from palette_sdk import (
193
+ JobExecution,
194
+ PluginContext,
195
+ PluginRouter,
196
+ get_plugin_context,
197
+ job,
198
+ )
199
+ from models import Report
200
+
201
+ router = PluginRouter(tags=["reports"])
202
+
203
+
204
+ @job("reports.generate", timeout_seconds=1800, max_attempts=3)
205
+ async def generate_report(
206
+ ctx: PluginContext,
207
+ execution: JobExecution,
208
+ payload: dict,
209
+ ):
210
+ await execution.progress(10, "Loading rows")
211
+ report_id = payload["report_id"]
212
+
213
+ # This ctx and ctx.db belong to this job run, not to the HTTP request.
214
+ report = await ctx.repo(Report).get(report_id)
215
+ await execution.check_cancelled()
216
+
217
+ await execution.progress(80, "Writing report")
218
+ # Generate and store the report here.
219
+ return {"report_id": report.id}
220
+
221
+
222
+ @router.post("/reports/{report_id}/generate")
223
+ async def start_report(
224
+ report_id: int,
225
+ ctx: PluginContext = Depends(get_plugin_context),
226
+ ):
227
+ handle = await ctx.jobs.enqueue(
228
+ "reports.generate",
229
+ {"report_id": report_id},
230
+ idempotency_key=f"report:{report_id}",
231
+ )
232
+ return handle.accepted_response()
233
+ ```
234
+
235
+ `accepted_response()` returns HTTP `202`, because the request accepted the
236
+ work but did not complete it. Its JSON contains `job_id`, `status`,
237
+ `status_url`, and `events_url`. Returning `200` is technically possible, but
238
+ `202 Accepted` communicates the asynchronous contract correctly.
239
+
240
+ ### Request Context And Thread Safety
241
+
242
+ The request `PluginContext` is request-scoped. Once the route returns, FastAPI
243
+ dependency cleanup can close or release `ctx.db` and its underlying
244
+ connection. SQLAlchemy `AsyncSession` and async database drivers are also not
245
+ safe to move to a worker thread or another event loop. Therefore, never pass,
246
+ capture, or store any of these for later execution:
247
+
248
+ - `ctx`, `ctx.db`, an ORM model instance, database connection, or transaction
249
+ - `Request`, uploaded file handles, open streams, or response objects
250
+ - an SDK service client whose lifetime is tied to the request context
251
+
252
+ Pass only a JSON object containing durable identifiers and values. The job
253
+ worker loads the handler from the publish that accepted the job and creates a
254
+ fresh `PluginContext`, database session, and scoped services for that run. It
255
+ also closes the job-owned resources after the run finishes.
256
+
257
+ `asyncio.to_thread(sync_function, plain_data)` is appropriate only for a short
258
+ synchronous blocking function that the route still awaits. It is not a durable
259
+ background-job mechanism, and request context or database objects should not
260
+ be passed to it.
261
+
262
+ ### Progress, Status, And Cancellation
263
+
264
+ The `JobExecution` object exposes:
265
+
266
+ ```python
267
+ await execution.progress(50, "Halfway")
268
+ await execution.heartbeat()
269
+ cancel_requested = await execution.cancelled()
270
+ await execution.check_cancelled()
271
+ ```
272
+
273
+ Call `check_cancelled()` between meaningful units of work when the job can stop
274
+ cooperatively. A client can monitor or cancel a job through the returned URLs:
275
+
276
+ ```text
277
+ GET /api/v1/app-jobs/<job-id>
278
+ GET /api/v1/app-jobs/<job-id>/events
279
+ POST /api/v1/app-jobs/<job-id>/cancel
280
+ ```
281
+
282
+ The events URL is a server-sent event stream. Job states are `queued`,
283
+ `running`, `retrying`, `completed`, `failed`, and `cancelled`. Backend code can
284
+ also use `await ctx.jobs.get(job_id)` and `await ctx.jobs.cancel(job_id)` during
285
+ a normal request. Access remains scoped to the authenticated user,
286
+ organisation, and app.
287
+
288
+ ### Retries And Idempotency
289
+
290
+ Handlers must tolerate retries. `max_attempts` defaults to `3` and accepts
291
+ values from `1` to `5`; `timeout_seconds` defaults to `900` and accepts values
292
+ from `1` to `7200`. Use an enqueue `idempotency_key` when repeated HTTP requests
293
+ must resolve to the same job. Keys are scoped by organisation, user, app,
294
+ handler, and key value.
295
+
296
+ Keep external side effects idempotent too. For example, record a stable
297
+ operation key before charging a payment or sending a third-party request. A
298
+ job result must be a JSON object or `None`; store large files through
299
+ `ctx.storage` and return their identifiers.
300
+
301
+ In hosted Palette, PostgreSQL persists job state before the `202` response,
302
+ Redis wakes workers, and each attempt runs in an isolated subprocess with a
303
+ fresh context. `pltt dev` provides the same app-facing API using a local task
304
+ registry and a fresh local database session per run; local jobs do not survive
305
+ the development process exiting. App developers only declare and enqueue jobs;
306
+ they do not create or operate thread pools or worker processes.
307
+
164
308
  ## 5. Permissions
165
309
 
166
310
  Use route-level permission guards for normal APIs:
@@ -8,8 +8,8 @@ const { bundleFrontend, bundleBackend } = require("../bundler")
8
8
  const { declaredSecrets, loadLocalEnv, loadLocalEnvDetails } = require("../secrets")
9
9
  const buildCommand = require("./build")
10
10
 
11
- const DEFAULT_FRONTEND_BUNDLE_LIMIT = 15 * 1024 * 1024
12
- const DEFAULT_BACKEND_BUNDLE_LIMIT = 15 * 1024 * 1024
11
+ const DEFAULT_FRONTEND_BUNDLE_LIMIT = 50 * 1024 * 1024
12
+ const DEFAULT_BACKEND_BUNDLE_LIMIT = 50 * 1024 * 1024
13
13
 
14
14
  function reporter(json, results) {
15
15
  function printExtra(meta) {
@@ -172,17 +172,20 @@ function writeBackendRunner(cwd, devDir, manifest, backendEntry, backendPort) {
172
172
 
173
173
  import importlib
174
174
  import importlib.util
175
+ import asyncio
175
176
  import json
176
177
  import os
177
178
  import pathlib
178
179
  import re
179
180
  import sys
181
+ import traceback
180
182
  import uuid
181
183
  from datetime import datetime, timezone
182
184
  from types import SimpleNamespace
183
185
 
184
186
  from fastapi import FastAPI, HTTPException, Request, Response
185
187
  from fastapi.middleware.cors import CORSMiddleware
188
+ from fastapi.responses import StreamingResponse
186
189
  from starlette.middleware.base import BaseHTTPMiddleware
187
190
 
188
191
  ROOT = pathlib.Path(${JSON.stringify(cwd)}).resolve()
@@ -367,6 +370,12 @@ router = getattr(module, "router", None)
367
370
  if router is None:
368
371
  raise RuntimeError(f"backend entry has no router export: {ENTRY}")
369
372
 
373
+ from palette_sdk.jobs import JobCancelledError, JobExecution, JobsClient, drain_pending_jobs
374
+
375
+ LOCAL_JOB_HANDLERS = {decl.name: decl for decl in drain_pending_jobs()}
376
+ LOCAL_JOBS = {}
377
+ LOCAL_JOB_TASKS = set()
378
+
370
379
  engine = None
371
380
  SessionLocal = None
372
381
  if DATABASE_ENABLED:
@@ -380,6 +389,177 @@ if DATABASE_ENABLED:
380
389
  engine = create_async_engine(DATABASE_URL)
381
390
  SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
382
391
 
392
+ def _local_job_view(record):
393
+ job_id = record["id"]
394
+ return {
395
+ **{key: value for key, value in record.items() if key != "task"},
396
+ "job_id": job_id,
397
+ "status_url": f"/api/v1/app-jobs/{job_id}",
398
+ "events_url": f"/api/v1/app-jobs/{job_id}/events",
399
+ }
400
+
401
+ class LocalJobExecutionAdapter:
402
+ def __init__(self, record):
403
+ self.record = record
404
+
405
+ async def progress(self, percent, message=None):
406
+ self.record["progress"] = percent
407
+ self.record["message"] = message
408
+ self.record["updated_at"] = datetime.now(timezone.utc).isoformat()
409
+
410
+ async def heartbeat(self):
411
+ self.record["updated_at"] = datetime.now(timezone.utc).isoformat()
412
+
413
+ async def cancelled(self):
414
+ return bool(self.record.get("cancel_requested"))
415
+
416
+ class LocalJobsService:
417
+ async def enqueue(self, name, payload, *, idempotency_key=None):
418
+ declaration = LOCAL_JOB_HANDLERS.get(name)
419
+ if declaration is None:
420
+ raise HTTPException(status_code=422, detail=f"local job handler is not registered: {name}")
421
+ if not isinstance(payload, dict):
422
+ raise HTTPException(status_code=422, detail="job payload must be a JSON object")
423
+ try:
424
+ json.dumps(payload)
425
+ except (TypeError, ValueError) as exc:
426
+ raise HTTPException(status_code=422, detail=f"job payload is not JSON serializable: {exc}")
427
+ if idempotency_key:
428
+ for existing in LOCAL_JOBS.values():
429
+ if existing["handler"] == name and existing.get("idempotency_key") == idempotency_key:
430
+ return _local_job_view(existing)
431
+ job_id = str(uuid.uuid4())
432
+ now = datetime.now(timezone.utc).isoformat()
433
+ record = {
434
+ "id": job_id,
435
+ "plugin_id": MANIFEST.get("id", ""),
436
+ "handler": name,
437
+ "payload": payload or {},
438
+ "result": None,
439
+ "status": "queued",
440
+ "progress": 0,
441
+ "message": None,
442
+ "attempt_count": 0,
443
+ "max_attempts": declaration.max_attempts,
444
+ "cancel_requested": False,
445
+ "error_code": None,
446
+ "error_message": None,
447
+ "idempotency_key": idempotency_key,
448
+ "created_at": now,
449
+ "started_at": None,
450
+ "completed_at": None,
451
+ "updated_at": now,
452
+ }
453
+ LOCAL_JOBS[job_id] = record
454
+ task = asyncio.create_task(_run_local_job(record, declaration))
455
+ LOCAL_JOB_TASKS.add(task)
456
+ task.add_done_callback(LOCAL_JOB_TASKS.discard)
457
+ return _local_job_view(record)
458
+
459
+ async def get(self, job_id):
460
+ record = LOCAL_JOBS.get(str(job_id))
461
+ if record is None:
462
+ raise HTTPException(status_code=404, detail="Local job not found")
463
+ return _local_job_view(record)
464
+
465
+ async def cancel(self, job_id):
466
+ record = LOCAL_JOBS.get(str(job_id))
467
+ if record is None:
468
+ raise HTTPException(status_code=404, detail="Local job not found")
469
+ if record["status"] not in ("completed", "failed", "cancelled"):
470
+ record["cancel_requested"] = True
471
+ if record["status"] == "queued":
472
+ record["status"] = "cancelled"
473
+ record["completed_at"] = datetime.now(timezone.utc).isoformat()
474
+ return _local_job_view(record)
475
+
476
+ LOCAL_JOB_SERVICE = LocalJobsService()
477
+
478
+ def _local_job_context(session):
479
+ from palette_sdk import PluginContext
480
+ from palette_sdk.apps import AppInteropClient
481
+ from palette_sdk.connections import PluginConnectionsClient
482
+ from palette_sdk.events import EventPublisher
483
+ from palette_sdk.notifications import NotificationsClient
484
+ from palette_sdk.organization import OrganizationInfo
485
+ from palette_sdk.platform_services import UnavailablePlatformService
486
+
487
+ return PluginContext(
488
+ db=session,
489
+ user_id="dev-user",
490
+ organization_id=1,
491
+ organization=OrganizationInfo.from_dict(DEV_ORGANIZATION),
492
+ org_role="owner",
493
+ plugin_id=MANIFEST.get("id", ""),
494
+ permissions=MANIFEST.get("permissions", []),
495
+ storage=DEV_STORAGE or UnavailablePlatformService("storage"),
496
+ connections=PluginConnectionsClient(None, DEV_CONNECTIONS),
497
+ apps=AppInteropClient(LocalAppInteropService()),
498
+ notifications=NotificationsClient(NOTIFICATIONS),
499
+ redis=DEV_REDIS or UnavailablePlatformService("redis"),
500
+ vector=DEV_VECTOR or UnavailablePlatformService("vector"),
501
+ events=EventPublisher(LocalEventPublisher()),
502
+ jobs=JobsClient(LOCAL_JOB_SERVICE),
503
+ config={
504
+ "secrets": DEV_SECRETS,
505
+ "secret_specs": MANIFEST.get("secrets") or {},
506
+ "secret_scope": "dev",
507
+ },
508
+ )
509
+
510
+ async def _run_local_job(record, declaration):
511
+ record["status"] = "running"
512
+ record["attempt_count"] = 1
513
+ record["started_at"] = datetime.now(timezone.utc).isoformat()
514
+ record["updated_at"] = record["started_at"]
515
+ adapter = LocalJobExecutionAdapter(record)
516
+ execution = JobExecution(
517
+ adapter,
518
+ job_id=record["id"],
519
+ attempt=1,
520
+ idempotency_key=record.get("idempotency_key"),
521
+ )
522
+
523
+ async def invoke(session):
524
+ ctx = _local_job_context(session)
525
+ return await declaration.handler(ctx, execution, record["payload"])
526
+
527
+ try:
528
+ await execution.check_cancelled()
529
+ if SessionLocal is None:
530
+ result = await asyncio.wait_for(
531
+ invoke(None), timeout=declaration.timeout_seconds
532
+ )
533
+ else:
534
+ async with SessionLocal() as session:
535
+ result = await asyncio.wait_for(
536
+ invoke(session), timeout=declaration.timeout_seconds
537
+ )
538
+ await session.commit()
539
+ if result is not None and not isinstance(result, dict):
540
+ raise TypeError("job handler must return a dict or None")
541
+ json.dumps(result)
542
+ if record["cancel_requested"]:
543
+ record["status"] = "cancelled"
544
+ record["message"] = "Cancelled"
545
+ else:
546
+ record["status"] = "completed"
547
+ record["progress"] = 100
548
+ record["message"] = record["message"] or "Completed"
549
+ record["result"] = result
550
+ except JobCancelledError:
551
+ record["status"] = "cancelled"
552
+ record["message"] = "Cancelled"
553
+ except Exception as exc:
554
+ record["status"] = "failed"
555
+ record["message"] = "Job failed"
556
+ record["error_code"] = type(exc).__name__
557
+ record["error_message"] = str(exc)
558
+ traceback.print_exc()
559
+ finally:
560
+ record["completed_at"] = datetime.now(timezone.utc).isoformat()
561
+ record["updated_at"] = record["completed_at"]
562
+
383
563
  class DevPluginContextMiddleware(BaseHTTPMiddleware):
384
564
  async def dispatch(self, request: Request, call_next):
385
565
  request.state.user = SimpleNamespace(
@@ -400,6 +580,7 @@ class DevPluginContextMiddleware(BaseHTTPMiddleware):
400
580
  request.state.plugin_local_connections = DEV_CONNECTIONS
401
581
  request.state.plugin_apps = LocalAppInteropService()
402
582
  request.state.plugin_events = LocalEventPublisher()
583
+ request.state.plugin_jobs = LOCAL_JOB_SERVICE
403
584
  request.state.notifications = NOTIFICATIONS
404
585
  request.state.storage = DEV_STORAGE
405
586
  if DEV_REDIS is not None:
@@ -429,6 +610,32 @@ app.add_middleware(
429
610
  app.add_middleware(DevPluginContextMiddleware)
430
611
  app.include_router(router, prefix=f"/api/v1/plugins/{MANIFEST['id']}")
431
612
 
613
+ @app.get("/api/v1/app-jobs/{job_id}")
614
+ async def get_local_job(job_id: str):
615
+ return await LOCAL_JOB_SERVICE.get(job_id)
616
+
617
+ @app.post("/api/v1/app-jobs/{job_id}/cancel")
618
+ async def cancel_local_job(job_id: str):
619
+ return await LOCAL_JOB_SERVICE.cancel(job_id)
620
+
621
+ @app.get("/api/v1/app-jobs/{job_id}/events")
622
+ async def local_job_events(job_id: str):
623
+ await LOCAL_JOB_SERVICE.get(job_id)
624
+
625
+ async def stream():
626
+ last = None
627
+ while True:
628
+ current = await LOCAL_JOB_SERVICE.get(job_id)
629
+ marker = (current["status"], current["progress"], current["message"], current["updated_at"])
630
+ if marker != last:
631
+ yield "event: job\\ndata: " + json.dumps(current, default=str) + "\\n\\n"
632
+ last = marker
633
+ if current["status"] in ("completed", "failed", "cancelled"):
634
+ return
635
+ await asyncio.sleep(0.5)
636
+
637
+ return StreamingResponse(stream(), media_type="text/event-stream")
638
+
432
639
  @app.post("/api/v1/app-storage/{plugin_id}/uploads")
433
640
  async def create_local_app_storage_upload(plugin_id: str, request: Request):
434
641
  _require_local_storage(plugin_id)
@@ -887,4 +1094,4 @@ async function startSimulator({ cwd, frontendPort, backendPort }) {
887
1094
  await stop()
888
1095
  }
889
1096
 
890
- module.exports = { databaseDriverDependencies, resolveDevSecrets, startSimulator }
1097
+ module.exports = { databaseDriverDependencies, resolveDevSecrets, startSimulator, writeBackendRunner }
package/lib/manifest.js CHANGED
@@ -703,11 +703,11 @@ function validateManifest(m) {
703
703
  else {
704
704
  unknownKeys(
705
705
  m.capabilities,
706
- new Set(["frontend", "backend", "database", "webhooks", "scheduled_jobs", "file_uploads", "external_network"]),
706
+ new Set(["frontend", "backend", "database", "webhooks", "scheduled_jobs", "background_jobs", "file_uploads", "external_network"]),
707
707
  "capabilities",
708
708
  errors,
709
709
  )
710
- for (const key of ["frontend", "backend", "database", "webhooks", "scheduled_jobs", "file_uploads"]) {
710
+ for (const key of ["frontend", "backend", "database", "webhooks", "scheduled_jobs", "background_jobs", "file_uploads"]) {
711
711
  requireBoolean(m.capabilities, key, "capabilities", errors)
712
712
  }
713
713
  if (m.capabilities.external_network !== undefined) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@palettelab/cli",
3
- "version": "0.3.60",
3
+ "version": "0.3.61",
4
4
  "description": "Developer CLI for building Palette platform plugins — no platform source access required.",
5
5
  "bin": {
6
6
  "pltt": "bin/pltt.js"