# Local development

> Run your service on your own machine against a dev environment in Cairnflow Cloud, through an HTTPS tunnel whose URL does not change.

Source: https://cairnflow.dev/docs/develop/local-development

:::caution[Cloud is in waitlist]
This page is about developing against Cairnflow Cloud, which is not open yet —
[join the waitlist](/#pricing) for early access. Today you can run the runtime yourself: with a
node on your own machine, as in the [Quickstart](/docs/quickstart), you register
`http://127.0.0.1:<port>` and need no tunnel.
:::

Cairnflow Cloud does not run your code: it calls your service over HTTPS. While you develop, that
service can run on your own machine, as long as Cloud can reach it. This page covers that setup.
To run the runtime itself on your machine instead, install a release binary or run Docker: see
[Self-hosting](/docs/self-hosting).

## 1. Use a separate environment

Create an environment for development, for example `dev`, next to `prod`. Each environment has its
own endpoint, API keys, identity key and data, so nothing you register or run in `dev` touches
`prod`. How many environments an organization can have is in
[Account limits](/docs/cloud/limits#account-limits).

On the `dev` environment's page, copy its endpoint and identity key, and create an Admin API key:

```sh
export CAIRN_URL="<endpoint of the dev environment>"
export CAIRN_KEY="<Admin API key of the dev environment>"
export CAIRN_IDENTITY_KEY="<identity key of the dev environment>"
```

## 2. Run the service on your machine

```ts title="service.ts"

const greeter = service("Greeter", {
  greet: async (ctx, name: string) => {
    const upper = await ctx.run("upper", () => name.toUpperCase());
    return `Hello, ${upper}!`;
  },
});

await serve({
  services: [greeter],
  port: Number(process.env.PORT ?? 9080),
  identityKeys: [process.env.CAIRN_IDENTITY_KEY!],
});
```

Start it the way you run TypeScript in your project. `serve()` listens on `127.0.0.1` by default,
which is all a tunnel on the same machine needs, and nothing else on your network can reach it.
Keep `identityKeys`: the tunnel makes the service public, and the identity key is what refuses
requests that do not come from your environment. Cloud refuses to register an endpoint without
it.

## 3. Give it a public HTTPS URL that does not change

Cloud calls only `https://` endpoints on the public internet, so put a tunnel in front of the
service. Choose one whose URL stays the same every time you start it: a deployment remembers the
URL it was registered with, and invocations stay on the deployment they started on (see
[When the URL changes](#when-the-url-changes)).

### Cloudflare Tunnel, named, on your own domain

With a domain whose DNS is on Cloudflare, create a named tunnel once and give it a hostname:

```sh
cloudflared tunnel login
cloudflared tunnel create cairn-dev
cloudflared tunnel route dns cairn-dev cairn-dev.example.com
```

Point it at the service in `config.yml` in your `.cloudflared` directory:

```yaml title="config.yml"
tunnel: <tunnel UUID printed by cloudflared tunnel create>
credentials-file: <credentials file path printed by cloudflared tunnel create>
url: http://127.0.0.1:9080
```

Then run it whenever you work:

```sh
cloudflared tunnel run cairn-dev
```

The URL is `https://cairn-dev.example.com`, every time.

### ngrok with your dev domain

Every ngrok account, including a free one, has a dev domain that does not change when the agent
restarts, and `ngrok http` uses it unless you pass another domain with `--url`:

```sh
ngrok http 127.0.0.1:9080
```

The URL is your dev domain, shown when the agent starts.

### What to avoid

- **Tunnels that get a new URL every time**, such as Cloudflare's quick tunnels
  (`cloudflared tunnel --url …`, a new `trycloudflare.com` hostname on each start).
- **Long turns through a tunnel.** In request-response mode each turn is one HTTP request, and a
  tunnel or proxy can have its own limit on how long a request may take, on top of the
  [turn time limit](/docs/cloud/limits#turn-time-limit).

## 4. Register the tunnel URL

```sh
curl -X POST "$CAIRN_URL/deployments" \
  -H "authorization: Bearer $CAIRN_KEY" \
  -H "content-type: application/json" \
  -d '{"uri":"https://cairn-dev.example.com"}'
```

Leave `transport` out: Cloud then calls the tunnel URL in request-response mode, which works
through any tunnel. Invoke a handler to check the round trip:

```sh
curl -X POST "$CAIRN_URL/invoke/Greeter/greet" \
  -H "authorization: Bearer $CAIRN_KEY" \
  -H "content-type: application/json" \
  -d '"world"'
```

The console of the `dev` environment shows each invocation step by step.

## Day-to-day

- **Restart the service freely.** A turn cut by a restart is retried, and the invocation replays
  from its journal. While your machine sleeps or the tunnel is down, invocations that need your
  service are retried with backoff until it answers again, or until their retry policy gives up.
- **Changing code in place affects running invocations.** They replay against whatever code
  answers at the URL. Renaming, adding, removing or reordering steps, or changing a call's target
  or input, before the point an invocation reached pauses it with code `570`; see
  [Deploying new versions](/docs/develop/versioning).
- **Register again when you change services, handlers or their options** (retry policy,
  `inactivityTimeout`): they are read at registration. Each registration creates a new
  deployment, even for the same URL, and counts toward the environment's
  [deployment limit](/docs/cloud/limits) until you remove it. `DELETE /deployments/{id}` removes
  one that is no longer current and has no invocations left on it.

## When the URL changes

Every invocation stays on the deployment it started on, for its whole life, and a deployment always
calls the URL it was registered with. If the tunnel's URL changes (a quick tunnel, another ngrok
domain, a new hostname) and you register the new URL, new invocations go to the new deployment,
but the ones already running keep calling the old URL. They cannot reach it, so they are retried
with backoff, and without a [retry policy](/docs/develop/errors-retries#retry-policy) they keep
retrying until the old URL answers again.

:::caution
Do not leave invocations on a URL you no longer control. Every attempt sends the invocation's
journal (its input and step results) to that URL, so whoever answers there next receives them.
:::

Find them with `GET /deployments/{id}` of the old deployment (`pinnedInvocations` counts them), or
list them with SQL on the console's **Query** page or through [`POST /query`](/docs/query):

```sql
SELECT id, service, handler, class, last_failure_message
FROM sys_invocation
WHERE class IN ('active', 'paused') AND pinned_deployment = 'dp_…'
```

Then pick one way out for each:

- **Bring the old URL back.** Start a tunnel on the old hostname again; the invocations continue
  on their next retry. The code behind it must still match their journals.
- **Move them to the new deployment:**
  `POST /invocations/{id}/migrate?deployment=<new deployment id>`. Cloud first replays the
  invocation on the new deployment and refuses with `409` if the code there no longer matches its
  journal; `&force=true` skips that check. In the console: **Migrate…** on the invocation.
- **Run them again on the new deployment:**
  `POST /invocations/{id}/restart?deployment=<new deployment id>`. This starts a new invocation
  from the old one's input (add `&from=<n>` to keep the first `n` journal entries and their
  results); the old one ends, and callers waiting on it get the new one's result. A workflow's
  `run` cannot be restarted. In the console: **Restart from step…**.
- **End them:** a hard cancel, `POST /invocations/{id}/cancel`, does not need your service. In
  the console: **Cancel now**, also available as a bulk action.

Once no invocation is left on the old deployment, remove it with `DELETE /deployments/{id}`.

## Next

- [Deployments](/docs/cloud/deployments)
- [Deploying new versions](/docs/develop/versioning)
- [Beta limits](/docs/cloud/limits)
