Skip to content
Changelog

Report a bug

Write Safely

A write changes something outside the run: a Slack message, a Linear issue, or a row in an API. Networks fail, and the same work can run again, for example when a later run starts from an old checkpoint. Plan each write so that a second attempt is safe.

Type does not replay a stage after its code starts. It retries a stage only when it can prove that the code did not start. A repeat comes from your own design: a checkpoint that did not advance, a person who runs the work again, or code that sends a request again after a timeout.

ctx.write.call() and ctx.write.request() require an effectKey. Type records the call as a write in the run history. Build the key from values that stay the same for the same logical change:

TriggerGood keyBad key
An event`issue:${input.id}``issue:${Date.now()}`
A schedule`report:${input.scheduledAt}``report:${Math.random()}`
An item in a list`notify:${order.id}``notify:${index}`

A key has 1 to 200 characters. It starts with a letter or a digit, and it can contain letters, digits, ., _, :, /, and -.

Use one or more of these methods:

  1. Use the provider’s idempotency key. Many APIs accept an Idempotency-Key header. Send the effect key as its value.
  2. Read before you write. Look for an item from an earlier attempt. For example, find an issue with the event ID in its title.
  3. Use update instead of create. An update with the same values has the same result each time.
  4. Save progress in a checkpoint. Record which items are done, so the next run skips them. See Keep State Between Runs.

This stage reads the destination first, sends the effect key as the provider’s idempotency key, and records the create as an action:

import { TypeApiError } from "@type-dot-com/sdk";
import {
automation,
code,
complete,
recurringEventSchema,
} from "@type-dot-com/sdk/automations";
import { err } from "neverthrow";
import { z } from "zod";
const report = z.looseObject({ id: z.string() });
export default automation({
output: z.object({ reportId: z.string(), created: z.boolean() }),
deployment: {
subscriptions: {
daily: {
title: "Daily report",
description: "Create one report in the reporting API each day",
source: {
kind: "recurring",
schedule: { kind: "interval", everySeconds: 86400 },
},
entry: "publish",
},
},
},
stages: {
publish: code({
input: recurringEventSchema,
transitions: [],
async run({ ctx, input }) {
const day = input.scheduledAt.slice(0, 10);
const effectKey = `daily-report:${day}`;
// An earlier attempt can have created the report already.
const existing = await ctx.read.request(
{
organizationIntegrationId: "orgint_example",
method: "GET",
path: "/v1/reports",
query: { day },
},
z.looseObject({ reports: z.array(report) }),
);
if (existing.isErr()) return err(existing.error);
const found = existing.value.reports[0];
if (found) return complete({ reportId: found.id, created: false });
const created = await ctx.mutativeAction(
() =>
ctx.write.request(
{
organizationIntegrationId: "orgint_example",
method: "POST",
path: "/v1/reports",
headers: { "Idempotency-Key": effectKey },
body: { day },
},
report,
{ effectKey },
),
{ id: "create-report", message: `Create the report for ${day}` },
(value) => ({
message: `Created report ${value.id}`,
data: { id: value.id },
}),
);
if (created.isErr())
return err(
new TypeApiError(
`Could not confirm the report for ${day}: ${created.error.message}. Check the reporting API before you enable the automation again.`,
created.error.code,
created.error.status,
),
);
return complete({ reportId: created.value.id, created: true });
},
}),
},
});

A timeout or a lost connection does not mean that the write failed. The provider can have done it.

  • Do not send the write again at once in the same stage.
  • Read the destination to find out what happened, as in the sample above.
  • If you cannot find out, fail the stage with a clear message that names what to check. Type pauses the automation, and a person can check the destination before enabling it again.

ctx.action() and ctx.mutativeAction() record a step in run history before and after it runs. Use ctx.mutativeAction() for a step that changes something.

  • The first argument runs the step. It returns a Result or a ResultAsync.
  • The second argument is the log before the step: an id and a message. Each id can be used one time in a stage run, and a stage can record up to 100 actions.
  • The third argument makes the log after a successful step from the result.
  • Check the provider response inside the step, so the log shows a real success.
  • If Type cannot save the first log, the step does not run.
  • Action logs do not retry, and they do not undo earlier steps.
  • If the log after the step fails to save, the error says “Do not repeat the action”. The write can be complete.

See ctx.action() and ctx.mutativeAction().

Each code stage commits on its own. Type saves a stage’s checkpoint, output, and transition when the stage returns. A write happens at the time that you call it. Thus:

  • A write that succeeds, followed by a failure later in the same stage, is not undone.
  • If a later stage fails, the earlier stages of the run stay committed, and Type does not run them again.
  • The next run starts from the last saved checkpoint, and can try the same write again.
  • Type does not replay a failed run after a repair. Before you enable the automation, check the repair result and the failed run’s writes; a diagnosis alone does not prove they are safe. See Reconcile before verification.

Put the most important write last, or make every write safe to repeat.

In fixtures, Type gives your code the responses that you supply. No real write happens. Fixtures prove how your code handles a response. They do not prove that the provider accepts the write. See Test Automations.