scripts: build: iii call sandbox::build worker=link run: iii call sandbox::start worker=link sandbox-libkrun: worker: package://api.workers.iii.dev/sandbox-libkrun version: "0.5.0" ``` The `engine:` section is where the engine can be configured, this is useful for when starting a compose project and the engine with `iii compose --up`. `containers` store one entry for each worker. Workers can exist as remote packages or local paths. For example `http` comes from a remote package, while `link` ...
18,978 stars
0 votes
0 copies
3 views
Added September 3, 2026
developmenttypescriptgobashnodedockerapidatabase
Works with
terminal
api
Security analysis
A92/100
mediumUses curl or wget to download content
mediumInstalls packages at runtime which could introduce malicious dependencies
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Linkly?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/iii-hq-linkly-29216103)
<!-- generated by iii-skill-render. DO NOT EDIT (changes here are overwritten on the next render). Edit docs/next/tutorials/linkly/foundations.mdx. -->
In this chapter you will build the core of Linkly: a worker that creates short codes and resolves
them back to URLs, callable first from the command line and then over HTTP. By the end you will have
a working web service where `POST /links` mints a short code and `GET /s/:code` redirects to the
original URL.
## Create the project
A iii project is a directory with a `worker-compose.yaml` file that describes your system. Create
one:
```bash
iii project init linkly --template linkly
cd linkly
```
<Note>
This project ships with all you need already contained within the project folder. Cases where you
need to add code will be accomplished by uncommenting the correct block of code.
</Note>
## Take a look at `worker-compose.yaml`
The project ships with a prebuilt worker-compose.yaml so at this point you don't need to make any
edits to it. When you do make edits they will largely be programmatic and use `compose::*`
functions.
Later in this chapter you'll serve the `link` worker over HTTP (provided by `http`) and stash
short-code → URL mappings in a key-value store (provided by `state`). `worker-compose.yaml` declares
both, along with the `link` worker you write next:
```yaml worker-compose.yaml
namespace: default
engine:
url: ws://127.0.0.1:49134
containers:
http:
worker: package://http
version: "latest"
config_name: http
state:
worker: package://state
version: "latest"
config_name: state
config_override:
adapter:
name: kv
config:
store_method: in_memory
link:
worker: path://./link
start_after:
- sandbox-libkrun
# Ch. 3: the schema is created at startup, after database is up.
# - database
scripts:
build: iii call sandbox::build worker=link
run: iii call sandbox::start worker=link
# The sandbox adapter: it builds and boots each VM worker's image.
# added by compose::add
sandbox-libkrun:
worker: package://api.workers.iii.dev/sandbox-libkrun
version: "0.5.0"
```
The `engine:` section is where the engine can be configured, this is useful for when starting a
compose project and the engine with `iii compose --up`.
`containers` store one entry for each worker. Workers can exist as remote packages or local paths.
For example `http` comes from a remote package, while `link` will be a path from your project
directory to the local worker.
`link` runs in a microVM, and its `scripts` say so. `iii call sandbox::build worker=link` builds the
worker's image into `.iii/build/link/` on its first start, and `iii call sandbox::start worker=link`
boots that image. `worker=` is the container's own key. `sandbox-libkrun` is the adapter that does
both, so `link` names it in `start_after`. After you change the worker's dependencies, rebuild it
with `iii call compose::build worker=link`, wait for the build to finish in
`iii compose logs link --follow`, then restart it with `iii call compose::restart worker=link`. See
[Compose / VM workers](../../using-iii/compose#vm-workers).
`state` uses an in-memory store by default, so every restart starts clean. That's what we want for
this chapter. The `config_override` block declares that default explicitly.
[Ch. 3: Persist everything](./persistence) will swap this approach for durable storage.
## Explore the link worker
The `link` directory holds the worker that stores and retrieves short links.
### The worker entrypoints
A worker is a self-contained service. Here, the `link` worker is a Node package but it could be any
language or runtime.
`link/iii.worker.yaml` is the manifest that describes how the worker runs itself:
```yaml iii.worker.yaml
name: link
runtime:
# Base OCI image used as the worker rootfs. Override to pin a version.
base_image: docker.io/iiidev/node:latest
scripts:
install: 'npm install'
start: 'npm run start'
```
<Info>
Compose runs the worker from `scripts.start`, but a worker can also be an ordinary service. Any
process that uses a iii SDK and calls `registerWorker()` is a worker.
<p>
Learn more about the [`iii.worker.yaml`
manifest](../../creating-workers/workers#worker-manifest).
</p>
</Info>
`link/package.json` declares the dependencies. Its `start` script uses `tsx watch`, which runs the
TypeScript source directly and reloads the worker whenever you save a change.
```json package.json
{
"name": "link",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"start": "tsx watch src/index.ts"
},
"dependencies": {
"iii-sdk": "0.27.0",
"@iii-dev/helpers": "0.27.0",
"tsx": "^4.22.3"
},
"devDependencies": {
"typescript": "^5.9.3",
"@types/node": "^24.10.1"
}
}
```
### The worker entry point
`link/src/index.ts` is the worker's entry point. You'll build it up in a few small steps. All of the
code below is contained within `index.ts`, you can uncomment it rather than copy and pasting.
<Info>
Pay attention to code blocks that note they will be replaced by future codeblocks. We are building
this application in much the same way you would in the real world and will be revising prior code
to add features and functionality as we go.
</Info>
#### Opening a connection to the engine
`registerWorker` opens the connection to the engine. Add the connection setup and a small helper
that generates random short codes to `index.ts`:
```typescript src/index.ts
import { registerWorker } from "iii-sdk";
import { Logger } from "@iii-dev/helpers/observability";
const worker = registerWorker(process.env.III_URL ?? "ws://localhost:49134", {
workerName: "link",
});
const logger = new Logger();
const CHARS = "abcdefghijklmnopqrstuvwxyz0123456789";
function makeCode(): string {
let s = "";
for (let i = 0; i < 6; i++) s += CHARS[Math.floor(Math.random() * CHARS.length)];
return s;
}
```
#### Add `link::create`
`registerFunction` publishes a function under a name like `link::create` that anything else on the
engine can call. This one stores the mapping by calling `state::set` on the `state` worker with
`worker.call`. Worker-to-worker calls always flow through the engine, so the `link` worker doesn't
import anything from `state`; it knows the function name. Append it:
```typescript src/index.ts
worker.registerFunction("link::create", async (payload: { url: string; code?: string }) => {
// Store an absolute URL so the redirect's Location header is absolute, not
// resolved relative to /s/:code.
const url = /^https?:\/\//i.test(payload.url) ? payload.url : `https://${payload.url}`;
const taken = async (c: string) =>
Boolean(await worker.call({ function_id: "state::get", payload: { scope: "links", key: c } }));
let code = payload.code;
if (code) {
// A requested code must be free; creating never overwrites an existing link.
if (await taken(code)) throw new Error(`code \`${code}\` is already taken`);
} else {
// A generated code retries until it finds a free one.
do {
code = makeCode();
} while (await taken(code));
}
await worker.call({
function_id: "state::set",
payload: { scope: "links", key: code, value: { url } },
});
logger.info("link created", { code, url });
return { code, url };
});
```
#### Add `link::resolve`
`link::resolve` looks the mapping back up with `state::get`, returning the URL or `null` when the
code is unknown. Append it, with a final log line so you can see the worker come up:
```typescript src/index.ts
worker.registerFunction("link::resolve", async (payload: { code: string }) => {
const stored = await worker.call<{ scope: string; key: string }, { url: string } | null>({
function_id: "state::get",
payload: { scope: "links", key: payload.code },
});
logger.info("link resolved", { code: payload.code, found: !!stored?.url });
return { url: stored?.url ?? null };
});
logger.info("link worker ready");
```
The `state::set` / `state::get` calls pass a `scope` (`links`) and a `key` (the short code). Scopes
keep different kinds of data in `state` from colliding; later chapters add more.
## Start the project
From the project root, start the engine and Compose project. The workers register their functions
with the engine. `--up` is a `iii compose` flag that starts the engine along with the workers:
```bash
iii compose --up
```
The first start builds `link`'s image first, so it takes longer than the next ones.
<Note>
`iii compose --up` stays in the foreground. Press Ctrl+C in that terminal to stop the engine and
every worker. From another terminal, `iii kill --compose <project folder>` stops the same project:
its Compose daemon, its engine and its workers.
</Note>
## Register the worker
`worker-compose.yaml` declares `link` as a `path://` container, so Compose starts it with the rest
of the project. On the Compose/engine output you will see the `link` worker register `link::create`
and `link::resolve`. You can see engine logs by tailing the engine log file. Compose keeps it inside
the project, under `.iii/compose/<namespace>/engine.log`, and `iii compose --up` prints its exact
path when it starts. From the project root:
```bash
tail -30 .iii/compose/default/engine.log
```
The output will look something like this:
```bash
[11:54:47.597 AM] [INFO] iii::worker_connections Worker registered
├ worker_id: adf46954-461e-450c-961f-ed6fe0cc1e31
└ ip_address: Some("127.0.0.1")
[11:54:47.609 AM] [INFO] iii::function [REGISTERED] Function link::create
[11:54:47.609 AM] [INFO] iii::function [REGISTERED] Function link::resolve
[11:54:47.697 AM] [INFO] iii-node link worker ready
```
## Call the functions
`iii call` invokes a function on the running engine. Create a link with a custom code:
```bash
iii call link::create url=https://iii.dev code=iii
```
```json
{
"code": "iii",
"url": "https://iii.dev"
}
```
Resolve it back:
```bash
iii call link::resolve code=iii
```
```json
{
"url": "https://iii.dev"
}
```
An unknown code resolves to `null`:
```bash
iii call link::resolve code=nope
```
```json
{
"url": null
}
```
<Check>
You have a working domain worker. `link::create` and `link::resolve` are registered with the
engine and callable from anywhere within your iii system. Next let's put them behind HTTP so that
external 3rd party systems could use them.
</Check>
<Info>
As you'll see later, unless you're supporting 3rd party systems it isn't necessary to expose
services over http since iii can even run browser tabs as workers.
</Info>
## Expose your functions over HTTP
The `http` worker you added at the start of the chapter serves HTTP through one function,
`http::on-request`: every request it receives is a call of that function. To serve a route, observe
`http::on-request` with the route in `args` and name the function that handles it as the target. The
`http` worker runs the target for each request on that route and sends back its return value as the
response.
### Create a function to handle new links
Add `http::create` to `link/src/index.ts`. It answers `400` when the request body has no `url`,
calls `link::create` through the engine with `worker.call`, and returns the new link with `201`, or
`409` when the requested code is already taken.
An error thrown by `link::create` reaches `http::create` as an `InvocationError` from `iii-sdk`. Its
`code` is `invocation_failed`, and its `message` is that code, a colon, and the message
`link::create` threw. The handler cuts the prefix off, so the response carries `link::create`'s
exact words. Add `InvocationError` to the `iii-sdk` import at the top of the file:
```typescript {1} src/index.ts
import { InvocationError, registerWorker } from "iii-sdk";
```
Then append `http::create`:
```typescript src/index.ts
worker.registerFunction("http::create", async (req) => {
const { url, code } = req.body ?? {};
if (!url) {
return {
status_code: 400,
body: { error: 'missing "url"' },
headers: { "Content-Type": "application/json" },
};
}
try {
const link = await worker.call<{ url: string; code?: string }, { code: string; url: string }>({
function_id: "link::create",
payload: { url, code },
});
return {
status_code: 201,
body: link,
headers: { "Content-Type": "application/json" },
};
} catch (err) {
// The SDK hands link::create's error back as an InvocationError whose
// message is `<err.code>: <what link::create threw>`; drop that prefix.
const error =
err instanceof InvocationError ? err.message.slice(err.code.length + 2) : String(err);
// Only link::create's own "is already taken" message means the code is in
// use (409). Anything else failed on the server's side (500).
if (error.endsWith("is already taken")) {
return {
status_code: 409,
body: { error },
headers: { "Content-Type": "application/json" },
};
}
logger.error("link create failed", { error });
return {
status_code: 500,
body: { error: "could not create the link" },
headers: { "Content-Type": "application/json" },
};
}
});
```
`link::create` always ends its message for a taken code with `is already taken`, so that message,
and nothing else, decides `409`; any other failure, such as a worker that does not answer, is logged
and answers `500`.
### Route `POST /links` to your create function
At the end of the same file (`link/src/index.ts`), observe `http::on-request` for `POST /links`. The
`http` worker reads the `args` and adds the route; for each `POST` request to `/links` it runs the
target, `http::create`, with the request.
```typescript src/index.ts
worker.observe(
{ function_id: "http::on-request", args: { method: "POST", path: "/links" } },
"http::create",
);
```
<Check>
This is the first observer you've added yourself. In iii every function is observable, and
`worker.observe(a, b)` means that when `a` runs, `b` runs. Here `a` is `http::on-request`, which
runs once per HTTP request, and its `args` tell the `http` worker which requests are yours. Learn
more about [Observers](../../using-iii/observers).
</Check>
<Info>
`worker.call` and `worker.observe` are the two ways functions work together: a call runs a
function now and returns its result, and an observer runs a function each time another one runs.
</Info>
### Mint a link over HTTP
Save the file and the worker reloads with the new route registered. The `http` container listens on
`127.0.0.1:3111` and serves the route below. Now try out your new route:
```bash
curl -i -X POST http://127.0.0.1:3111/links \
-H 'Content-Type: application/json' \
-d '{"url":"https://example.com","code":"demo"}'
```
```http
HTTP/1.1 201 Created
content-type: application/json
{"code":"demo","url":"https://example.com"}
```
Send the same request again. `demo` is taken now, so `link::create` refuses it and the route answers
`409` with its message:
```http
HTTP/1.1 409 Conflict
content-type: application/json
{"error":"code `demo` is already taken"}
```
A body without `url` never reaches `link::create`: the route answers `400` with
`{"error":"missing \"url\""}`.
The link sits in `state` now, but `GET /s/demo` has nowhere to go yet. There's no handler; add one
next.
### Create a function to handle redirects
Add `http::redirect` to the bottom of `link/src/index.ts`. It looks up the short code via
`link::resolve`, returns a 404 when there's no match, and a 302 to the original URL otherwise:
```typescript src/index.ts
worker.registerFunction("http::redirect", async (req) => {
const code = req.path_params.code;
const { url } = await worker.call<{ code: string }, { url: string | null }>({
function_id: "link::resolve",
payload: { code },
});
if (!url) {
return {
status_code: 404,
body: { error: "link not found" },
headers: { "Content-Type": "application/json" },
};
}
return { status_code: 302, headers: { Location: url } };
});
```
`req.path_params` holds the segments of the route's path that start with `:`, so `/s/abc` arrives
with `path_params.code` set to `abc`.
### Route `GET /s/:code` to your redirect function
Like before, observe `http::on-request`, this time for `GET /s/:code`:
```typescript src/index.ts
worker.observe(
{ function_id: "http::on-request", args: { method: "GET", path: "/s/:code" } },
"http::redirect",
);
```
### Follow the short code
`state` is in-memory in this chapter, so each time the engine restarts the previous link is gone.
Chapter 3 swaps in durable storage. For now create a fresh link and try it out:
```bash
curl -i -X POST http://127.0.0.1:3111/links \
-H 'Content-Type: application/json' \
-d '{"url":"http://iii.dev/docs/understanding-iii","code":"learn-iii"}'
```
```bash
curl -i http://127.0.0.1:3111/s/learn-iii
```
```http
HTTP/1.1 302 Found
location: http://iii.dev/docs/understanding-iii
```
An unknown code returns `404`:
```bash
curl -i http://127.0.0.1:3111/s/missing
```
```http
HTTP/1.1 404 Not Found
{"error":"link not found"}
```
## Conclusion
You have built a real link shortener: a domain worker exposed over HTTP, where the same
`link::create` and `link::resolve` functions serve both the command line and the web. Restarting the
engine still clears every link, though: `state` is in-memory until Chapter 3 swaps it for durable
storage.
Next, in [Ch. 2: Observe everything](./observability), you will add logs and traces and watch
invocations flow through the engine in the console.