65155fe50c
Closes twentyhq/core-team-issues#2742 A logic function run is capped by its own `timeoutSeconds` (900s max), so anything that can't finish in one run — a full re-sync, a per-record fan-out, a rate-limited third-party API — had no way to continue. This adds a way to hand that work to the workers. ## What it looks like for an app author ```ts import { enqueueJob } from 'twenty-sdk/logic-function'; await enqueueJob({ logicFunctionUniversalIdentifier: '9f1c3d7e-51b8-4a29-8f0d-7c4e2a6b1d33', payload: { cursor: nextCursor }, retryLimit: 3, priority: 2, delayMs: 60_000, }); ``` The target runs in its own process with its own timeout budget. The classic shape is a function that enqueues *itself* with the next cursor until there is nothing left. ## Changes **twenty-shared** — `EnqueueJobInput` / `EnqueueJobOptions` / `EnqueueJobResult` in `application`. **twenty-server** — new `application-job` module under `core-modules/application`, following the `application-key-value` pattern: - `enqueueJob` mutation on the metadata API, `@AuthApplication`-scoped - the lookup is scoped to `applicationId` + `workspaceId` — that's the authorization boundary, an app can only enqueue its own logic functions, anything else is `LOGIC_FUNCTION_NOT_FOUND` - pushes a `LogicFunctionTriggerJob` onto the existing `logicFunctionQueue`, so the enqueued run goes through the same executor (and the same execution throttling) as every other trigger - the queued run inherits the caller's `userId`/`userWorkspaceId`, so its app access token carries the same permissions as the function that queued it **Job options** are range-checked via `ResolverValidationPipe`, since the values come from application code and an unbounded delay or retry count would let an app pin work in the shared queue: | Option | Default | Range | |--------|---------|-------| | `retryLimit` | `0` | `0`–`10` | | `priority` | queue default | `1`–`10` (lower first) | | `delayMs` | `0` | `0`–7 days | `retryLimit` defaults to `0` rather than inheriting the server-route path's `3`: retries re-run the whole handler, so opting in should be the author's explicit choice. **twenty-sdk** — `enqueueJob` in `twenty-sdk/logic-function`, same shape as `runAgent`/`kv`. **Docs** — new "Background Jobs" page under Extend → Apps → Logic, plus nav and overview entries. **Generated** — regenerated `twenty-front/src/generated-metadata` and `twenty-client-sdk/src/metadata/generated` for the new mutation. ## Tests - `application-job.service.spec.ts` — 5 unit tests: job options mapping, defaults, acting-user propagation, application-scoped lookup, not-found - `enqueue-job.integration-spec.ts` — 5 integration tests: rejects a non-`APPLICATION_ACCESS` token, enqueues a function the app owns, rejects a function owned by another application, rejects an unknown identifier, rejects out-of-range options All green locally, along with `typecheck` for `twenty-server`/`twenty-sdk` and oxlint/oxfmt on the touched files. ## Notes for review - The target is addressed by `universalIdentifier`, matching `runAgent({ agentUniversalIdentifier })` and `ServerRouteDispatchResult.targetLogicFunctionUniversalIdentifier`. Addressing by `name` would be friendlier, but logic function names aren't validated for uniqueness within an app — happy to add it as a convenience if you'd rather. - `enqueueJob` returns as soon as the job is accepted; it can't return the target's result, since the queue driver's `add` returns void. Documented, with a pointer to the KV store for handing results back. --- _Generated by [Claude Code](https://claude.ai/code/session_01QrYvGonS3HMdeuMAVjs5hR)_ <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23527?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --------- Co-authored-by: github-actions <github-actions@twenty.com>
62 lines
3.6 KiB
Plaintext
62 lines
3.6 KiB
Plaintext
---
|
|
title: Overview
|
|
description: Server-side TypeScript that runs inside Twenty — triggered by HTTP routes, cron schedules, database events, AI tools, or workflow actions.
|
|
icon: "bolt"
|
|
---
|
|
|
|
A Twenty app's **logic layer** is the code that *runs* — server-side TypeScript handlers reacting to HTTP requests, cron schedules, and record changes; AI skills and agents that live inside the workspace; and OAuth connections that let your functions act on a user's behalf in third-party services.
|
|
|
|
```text
|
|
┌─ HTTP route ──┐
|
|
│ Cron schedule │
|
|
│ Database event │ ┌────────────────────┐
|
|
triggers ─┤ AI tool call ├─────▶│ Logic function │
|
|
│ Workflow action │ │ (your handler) │
|
|
│ Manual exec │ └────────────────────┘
|
|
└────────────────────┘ │
|
|
▼
|
|
┌────────────────────────────┐
|
|
│ Twenty API (records) │
|
|
│ Third-party API │
|
|
│ (via Connection token) │
|
|
└────────────────────────────┘
|
|
```
|
|
|
|
## In this section
|
|
|
|
<CardGroup cols={2}>
|
|
<Card title="Logic Functions" icon="bolt" href="/developers/extend/apps/logic/logic-functions">
|
|
The core building block — trigger types, payloads, and the typed API client.
|
|
</Card>
|
|
<Card title="Skills & Agents" icon="robot" href="/developers/extend/apps/logic/skills-and-agents">
|
|
Reusable AI agent instructions and assistants with custom system prompts.
|
|
</Card>
|
|
<Card title="Connections" icon="plug" href="/developers/extend/apps/logic/connections">
|
|
OAuth credentials your app holds for third-party services — Linear, GitHub, Slack, and more.
|
|
</Card>
|
|
<Card title="Key-Value Store" icon="database" href="/developers/extend/apps/logic/key-value-store">
|
|
Persist state between logic function runs — caches, cursors, and cross-workspace claims.
|
|
</Card>
|
|
<Card title="Background Jobs" icon="layer-group" href="/developers/extend/apps/logic/background-jobs">
|
|
Enqueue a logic function run on the workers to get past the per-run timeout.
|
|
</Card>
|
|
</CardGroup>
|
|
|
|
## Trigger types at a glance
|
|
|
|
A logic function picks one or more triggers — every entry below is a separate field on `defineLogicFunction()`:
|
|
|
|
| Trigger | When it runs | Setting |
|
|
|---------|--------------|---------|
|
|
| **HTTP route** | A request hits your `/s/<path>` endpoint | `httpRouteTriggerSettings` |
|
|
| **Cron** | A CRON expression matches | `cronTriggerSettings` |
|
|
| **Database event** | A workspace record is created, updated, or deleted | `databaseEventTriggerSettings` |
|
|
| **AI tool** | A Twenty AI feature decides to call your function | `toolTriggerSettings` |
|
|
| **Workflow action** | A workflow step invokes your function | `workflowActionTriggerSettings` |
|
|
|
|
Functions run sandboxed in isolated Node.js processes and access the workspace through a typed API client scoped to the role declared on [`defineApplication()`](/developers/extend/apps/config/application).
|
|
|
|
<Note>
|
|
**Install-time hooks** — code that runs before or after the install — share this runtime but use their own define functions and live under [Config → Install Hooks](/developers/extend/apps/config/install-hooks).
|
|
</Note>
|