Skip to content

Connect another service

An integration is a small program of the site that talks to another service: it reads an API on a schedule and keeps what it found in a table, sends something out when a row is added, or takes a call another service makes. It is two files of the site, written on a branch like any file and live once the branch is merged:

integrations/weather.ts what runs
integrations/weather.json what it may use, and what starts it: its manifest

Several jobs that share a manifest, tables and pages go in one folder, a package (“6. Several jobs in one package”).

Work the site does by itself is a workflow first (guide site-workflows). Write an integration for what a workflow’s steps can’t express, such as a login that hands back a token, paging through an API, or adding many rows, or only the new ones, in one run, and before you do, file what the workflow lacks with request_feature, tag workflows, as that guide’s “When a workflow can’t” says.

Guide vzk/integrations is the language the code is written in, with four whole integrations to start from (one keeps the site in step with a repository at another git host), and topic integrations is the exact list of triggers, verifiers and limits.

Integrations come with the plans that include them; on any other site the integration commands say so and change nothing. The commands run inside bash: list_integrations, run_integration and get_integration_run. There is no command that writes one: write its files with the file commands, run the site’s tests, and merge_branch puts them live.

The code exports any of three functions, and nothing else:

Export Runs Is given
sync() On the schedule that has no name, or when run by hand. Nothing.
on(event) When a row is added or a file is stored, on each schedule that has a name, or when run by hand. event.record with its id and data, event.file, event.schedule, the schedule’s name, or the event a run by hand gives it.
receive(request) When another service calls one of its paths. method, path, the headers the manifest names, and body where it is JSON or text otherwise.
integrations/weather.ts
export function sync() {
const was = state.get()
const answer = await fetch("https://api.example.com/forecast", {
query: { city: settings.city, after: was?.cursor },
headers: { authorization: `Bearer ${secrets.WEATHER_KEY}` }
})
if (!answer.ok) { fail("The weather service refused the key.") }
const days = answer.json.days.map(day => ({ day: day.date, high: day.high }))
const wrote = tables.forecasts.upsert(days, "day")
state.set({ cursor: answer.json.next })
log("Read " + days.length + " days")
return { continue: wrote.added == 500 }
}

What the code may call:

  • await fetch(url, options), over HTTPS, to a host the manifest names. Every text of the answer is treated as a stranger’s.
  • secrets.NAME, a secret the manifest names. It goes into a fetch and nowhere else: the code never reads its value.
  • tables.<handle>.upsert(rows, by) adds or changes rows matched by one field, and tables.<handle>.remove(by, keys) removes them, for a table in writes. A table in reads is read as a page reads one.
  • state.get() and state.set(value) keep one small value between runs, such as a cursor.
  • once(key) is true the first time it sees a key, so a delivery sent twice writes nothing twice.
  • log(text) keeps a line with the run, which a dry run answers. notify(text) tells the site’s members, in the site’s own words. fail(text) ends the run as failed.
  • settings.<name> reads the manifest’s settings.
  • random(n) is n letters and digits, from 1 to 256, drawn fresh for each run: a nonce, or a key a service asks the caller to make. It is plain text, so it may be kept in a row or state and sent anywhere.
  • site.addresses is every address the site answers at, read as a table is (filter, sortBy, slice, count), where the manifest says "addresses": true (in a package, at its top and in the job’s entry under jobs): address, the whole address, path, kind (page or row), file, the page that draws it, language, indexed, whether search engines are told of it, and changed_at, when it last changed (a row’s own page when the row was last saved, any other page when the site was last published). A page reads it too.

Returning { continue: true } runs the function again at once, up to 12 times, with state carrying the place. Read a large API a page at a time this way and never in one run.

fetch takes four more options here, each for a shape an API has:

  • A login, then a call. mint makes a token a login answers into a secret of the run, which the code never reads:

    await fetch("https://login.example.com/token", {
    method: "POST",
    form: { grant_type: "client_credentials", client_secret: secrets.KEY },
    mint: { SESSION: "json.access_token" }
    })
    const me = await fetch("https://api.example.com/me", {
    headers: { authorization: `Bearer ${secrets.SESSION}` }
    })

    A place is json.path.to.it, header.name or text. The manifest lists the minted name with "mint", the host it comes from, beside "host", the host it is sent to.

  • A form. form is an object sent as application/x-www-form-urlencoded; a fetch takes a body or a form.

  • A signature. crypto.hmac("sha256", secrets.KEY, message, "hex") and crypto.digest("sha1", text, "base64") sign what is sent (md5, sha1, sha256 or sha512; hex, base64 or base64url). What they answer is a secret too: it goes into a fetch and nowhere else.

  • The next page. await fetch(answer.json.next, { follow: true }) follows an address the service answered, held to hosts as any is.

{
"name": "Weather",
"state": "active",
"hosts": ["api.example.com"],
"writes": ["forecasts"],
"secrets": [{ "name": "WEATHER_KEY", "host": "api.example.com" }],
"settings": { "city": "Lviv" },
"triggers": [{ "kind": "schedule", "every": "1h" }]
}
  • name is what the owner sees. state is active or paused; a manifest that says neither is paused.
  • hosts are the names the code fetches from. A fetch to any other is refused.
  • reads and writes are the tables the code reads and writes. A table the code names and the manifest does not is refused.
  • secrets name what the owner saves, each with the host it is sent to (a name or a list). A secret is sent to no other host. A secret the code mints from a login is written { "name": "SESSION", "host": "api.example.com", "mint": "login.example.com" } and is never saved.
  • settings are plain values by name.
  • triggers say what starts a run, and each needs its export:
Trigger Starts Needs
{ "kind": "schedule", "every": "1h" } Every 15m, 30m, 1h, 6h or 1d. sync
{ "kind": "schedule", "every": "1d", "name": "catalogue" } A schedule with a name, of which there are as many as you want. on
{ "kind": "rows", "table": "enquiries" } When a row is added to a table in reads that the code does not write. on
{ "kind": "uploads" } When a file is stored. on
{ "kind": "inbound", "path": "stripe", ... } When another service calls /-/hooks/stripe on the site. receive
{ "kind": "dashboard", "name": "refresh", "label": "Refresh now" } When the owner presses its button in the Vizitka app. on

A row the site’s own workflows or integrations wrote starts nothing, so two of them cannot start each other forever.

A button for the owner. A dashboard trigger is an action the owner presses on the integration’s page in the Vizitka app, and nothing else starts it. Its name follows a named schedule’s rule and is one per integration, label is the button’s words (1 to 40 characters), confirm an optional question the app asks first (200 at most), and live: true asks it at once and shows what it returned on the screen, writing nothing, instead of making a run. on reads which one was pressed as event.dashboard, and is handed nothing else. A live action returns an object of at most 16 fields, each a short text, a number, a boolean or null, which the app draws as they are. No tool, dry run or workflow may hand on a dashboard event: play one in a scenario before it is live, on("<handle>", { dashboard: "refresh" }) (guide vzk/integrations, “Play it before it is live”), then tell the owner its label and they press it. list_integrations names each action.

A setting the owner picks or types. A dashboard trigger with a pick lists what the provider holds (a chat, an account) and sets the settings the code answers for the one the owner chooses in the app, and fields in the manifest are the settings the owner types, each with the pattern a value must fit. The value a choice sends comes back from the app, so the code reads it back from the provider before it sets anything. Guide vzk/integrations, “Settings the owner picks or types”, says how to declare both and what the code returns.

Several syncs and several services in one integration. A manifest lists as many schedules and as many inbound triggers as it wants, 32 triggers in all. One schedule may have no name and run sync; every other has a name of its own (1 to 32 small letters, digits, - and _, starting with a letter or a digit) and runs on, which reads the name as event.schedule. Every inbound trigger has a path of its own, with its own secret and verifier, and receive reads which one was called as request.path. Give each a function of its own:

export function on(event) {
if (event.schedule == "orders") { return orders() }
if (event.schedule == "catalogue") { return catalogue() }
}
function orders() { log("Read the orders") }
function catalogue() { log("Read the catalogue") }
export function receive(request) {
if (request.path == "/-/hooks/shop-orders") { return ordered(request) }
return stocked(request)
}
function ordered(request) { log("An order came") }
function stocked(request) { log("Stock moved") }
"triggers": [
{ "kind": "schedule", "every": "15m", "name": "orders" },
{ "kind": "schedule", "every": "1d", "name": "catalogue" },
{ "kind": "inbound", "path": "shop-orders", "secret": "ORDERS_SECRET", "verifier": { "kind": "token", "header": "X-Token" } },
{ "kind": "inbound", "path": "shop-stock", "secret": "STOCK_SECRET", "verifier": { "kind": "token", "header": "X-Token" } }
]

state is one value for the whole integration, so keep each sync’s place under its own key of it. run_integration runs one named sync by hand with entry: "on" and event: { "schedule": "orders" }. Every run a schedule starts counts toward the site’s 60 an hour, so four schedules at 15m are 16 of them, and a manifest whose schedules would come due more than 60 times an hour is refused. Five failed runs in a row stop the whole integration, every sync of it.

An inbound trigger names the path, the secret the call is checked with, a verifier that says how the service signs its calls, the headers the code is handed, and optionally delivery, the header the service names each delivery in, so one sent twice runs once:

{ "kind": "inbound", "path": "stripe", "secret": "STRIPE_WEBHOOK_SECRET",
"verifier": { "kind": "hmac", "header": "Stripe-Signature", "key": "v1",
"timestamp": { "key": "t", "window": 300 }, "signed": "{timestamp}.{body}" } }

The site checks every call before any code runs, and the code never sees the signature. Three verifiers:

  • hmac: a signature of the body in a header. algorithm is sha256 (the default) or sha1, encoding is hex (the default) or base64. A prefix such as sha256= or a key in a k=v,k=v header says where the signature is; a timestamp (from a header, or a key of the same header, with a window in seconds) refuses an old call; signed is what is signed, written with {timestamp}, {body} and {path}, names {body} once, and is {body} when left out. A verifier that reads a timestamp names {timestamp} in signed too: a time the signature leaves out proves nothing, so the file is refused without it.
    • GitHub: { "kind": "hmac", "header": "X-Hub-Signature-256", "prefix": "sha256=" }, with "delivery": "X-GitHub-Delivery".
    • Shopify: { "kind": "hmac", "header": "X-Shopify-Hmac-Sha256", "encoding": "base64" }, with "delivery": "X-Shopify-Webhook-Id".
    • Slack: { "kind": "hmac", "header": "X-Slack-Signature", "prefix": "v0=", "timestamp": { "header": "X-Slack-Request-Timestamp" }, "signed": "v0:{timestamp}:{body}" }.
  • token: a shared secret in a header, as Telegram sends X-Telegram-Bot-Api-Secret-Token.
  • meta_hub: Meta’s subscription check and its signed calls. It takes two secrets: secret is the app secret its calls are signed with, and "verifier": { "kind": "meta_hub", "verify_token": "META_VERIFY_TOKEN" } names another, which the owner picks and types into Meta’s Verify Token field. List both in secrets, each with a host, such as { "name": "META_VERIFY_TOKEN", "host": "graph.facebook.com" }. They are never the same value: a site that saved one value under both is answered no check.

A service that signs its calls no other way cannot call the site yet: say so to the owner instead of leaving the door unchecked.

A signature proves who sent a call, not that it is new: only a verifier with a timestamp refuses an old one, and delivery only spares the site a service’s own retries. So write receive to take the same event twice: if (!once(request.body.id)) { return } with the event’s id from the body, before it writes anything.

list_integrations names each integration’s missing_secrets. A value is the owner’s to save, and the Vizitka app cannot save one yet: tell them so, and never ask for the value in the conversation. Nothing an agent can call reads a secret back.

Try it before the merge. run_integration with dry_run: true, the job’s handle and the branch as ref runs one function from the branch’s files and writes nothing: no row, no state, no once key, and nobody is told. Its requests are sent for real, with the secrets the owner switched on for dry runs filled in, so it is the way to see what a service answers. It answers the job’s log, how many rows its upsert and remove calls named, whether it set a state, what it would have told the members, and why it failed.

{ "dry_run": true, "handle": "weather", "ref": "agent/weather" }
{ "dry_run": true, "handle": "stripe", "ref": "agent/stripe", "entry": "receive",
"request": { "method": "POST", "path": "/-/hooks/stripe", "headers": {}, "body": { "id": "evt_1" } } }
  • Write log(...) lines for what you need to see: the log is all a dry run answers of what the job read. Keep a customer’s details and a service’s private answers out of them.
  • A dry run is a real call to each service, with the owner’s real keys: whatever the code asks a service to do is done. Try what you would be content to see run live.
  • A dry run is given a secret only where the owner switched it on for dry runs, and every secret starts off. list_integrations names the ones that are off as secrets_off_for_dry_runs. A request that names one is not sent, and answer.error says which secret it was. Nothing you can call switches one on, and the Vizitka app cannot yet: tell the owner which key and why.
  • A secret goes to the host the owner saved it with and no other, whatever the manifest on the branch says, and into one place of a request: a request that names the same secret twice is not sent in a dry run. A log line that repeats a secret stops the run, and an answer that repeats one fails.
  • A dry run judges no row, so a row the table would refuse still counts. A table the branch adds is not there until the merge, and reading it stops the run.
  • state.get() answers nothing: a dry run starts from no state, and once(key) is always true.
  • receive is tried by a dry run alone: a real one is run by a delivery the site checked.
  • 60 dry runs an hour for a site, one at a time.

run_integration with integration runs sync now, or on with an event you give, as the live site has it: it fetches and writes for real. A package’s job is named with job (“6. Several jobs in one package”).

An integration may run only when asked. With no triggers at all, its on runs when run_integration gives it an event, and at no other time: what it fetches is fetched on demand. Give the event keys of your own, and not schedule, which names a sync of the manifest.

get_integration_run says how the run went: its status, the rows it added, changed and removed, and why it failed. It does not say what a run was given, answered or logged; list_records shows a row it wrote.

Five failed runs in a row stop an integration and tell the owner. It starts again when a run by hand succeeds, or when it is paused and switched on again.

  • Ten seconds a run: one that takes longer ends failed.
  • 16 requests a run, five seconds and 256 KiB of answer each: a request past any of them fails, which the code reads with answer.ok, and the run goes on.
  • 500 rows in one upsert or remove.
  • 60 runs an hour for the whole site: past it a scheduled run or the next run of a chain is not made, and nothing fails.

When an integration grows into several jobs that share tables, settings or pages, put them in one folder, integrations/<name>/:

integrations/shop/integration.json what its jobs may use, and what starts each: its manifest
integrations/shop/jobs/orders.ts the job `orders`
integrations/shop/jobs/stock.ts the job `stock`
integrations/shop/tables/orders.json a table it owns, `shop_orders`
integrations/shop/tables/stock.json another, `shop_stock`
integrations/shop/pages/index.vzk its page at /-/integrations/shop

Name a package with small letters, digits, - and _: its pages and its calls from other services are addressed by that name. The two-file form stays as it is: integrations/weather.ts with integrations/weather.json is a package named weather with one job named weather. Two files and a folder of the same name are refused.

The names of the integrations Vizitka ships are taken. A site uses one of those once its owner sets it up in the Vizitka app, or through its entry in integrations.json, and never holds a copy, so an integration of the site’s own under one of those names, two files or a folder, is refused, and the refusal says which. Give yours another name.

The manifest’s top lists everything any job may use (hosts, reads, writes, secrets), and the package’s settings, which every job reads. jobs names each job with what that job uses and its triggers. A job is held to its own entry alone, an entry asks for nothing the top does not list, and a secret in an entry is its name alone. Each jobs/<job>.ts has an entry, and each entry a file; a job’s code is written as above and exports what its own triggers need.

{
"name": "Shop",
"state": "active",
"hosts": ["api.shop.example"],
"writes": ["orders", "stock"],
"secrets": [
{ "name": "SHOP_KEY", "host": "api.shop.example" },
{ "name": "STOCK_SECRET", "host": "api.shop.example" }
],
"settings": { "store": "main" },
"jobs": {
"orders": {
"hosts": ["api.shop.example"],
"writes": ["orders"],
"secrets": ["SHOP_KEY"],
"triggers": [{ "kind": "schedule", "every": "1h" }]
},
"stock": {
"writes": ["stock"],
"secrets": ["STOCK_SECRET"],
"triggers": [{ "kind": "inbound", "path": "stock", "secret": "STOCK_SECRET",
"verifier": { "kind": "token", "header": "X-Token" } }]
}
}
}
  • Its tables. tables/orders.json defines a table of the site named shop_orders, the package’s name and the file’s joined by _. In the package’s own files it is orders (tables.orders, "writes": ["orders"]); everywhere else, a page of the site included, it is shop_orders. A file may name its table with "handle".
  • Its pages. pages/index.vzk is drawn at /-/integrations/shop, and pages/settings.vzk at /-/integrations/shop/settings. They wear no layout. Write a link as the package sees it, <a href="/settings">, and it is written under /-/integrations/shop. A text page, such as pages/feed.xml.vzk, is drawn at /-/integrations/shop/feed.xml.
  • A call from another service reaches a job at /-/integrations/<name>/hooks/<path>, here /-/integrations/shop/hooks/stock, and request.path is that whole address. /-/hooks/<path> reaches the two-file integrations alone. A path is one integration’s on the site.
  • Running one job. run_integration takes job, the job to run: { "integration": "<uuid>", "job": "orders" }. Left out, the one job whose code exports the function runs; where two do, name one. A dry run names the package as handle and, where it has more than one job, the job as job: { "dry_run": true, "handle": "shop", "job": "stock", "ref": "agent/shop", "entry": "receive", "request": { "method": "POST", "path": "/-/integrations/shop/hooks/stock", "headers": {}, "body": {} } }. A workflow’s vizitka.ask_integration takes job the same way (guide site-workflows).
  • What a job keeps is its own. state and once are each job’s. Every run of every job counts toward the site’s 60 an hour, and five failed runs in a row, of any of its jobs, stop the whole package.