Skip to content
estiiPublic

About

The structural core for replicated, capability-oriented actors

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

@opensurf/keel

The structural core for replicated, capability-oriented actors

Glue code for building actor-ish services whose state lives in a TinyBase mergeable store, syncs to clients over WebSockets, and exposes Cap’n Web RPC methods for mutations and queries.

Think: “a capability (RPC) + a replicated state (TinyBase) per actor instance”.


What you get

  • An actor URL scheme: ws://<host>:<port>/<actorType>/<instanceId>
  • A Bun WebSocket server (createCapnwebWsServer) that:
    • Hosts TinyBase sync “rooms” by path
    • Optionally wires in a per-room persister (TinyBase persister APIs)
    • Maintains a global actor directory so clients can listActors() and getActor(...)
  • Base classes to keep boilerplate low:
    • BaseApi: your RPC surface (Cap’n Web RpcTarget)
    • BaseActor: registers an API + joins sync
    • BaseClient: connects, syncs, and returns a typed remote API stub

Why this exists

When you build real-time apps, you usually end up with:

  • A state replication layer (OT/CRDT-ish or “mergeable”)
  • An RPC layer for explicit commands (“increment”, “setTitle”, “publish”)
  • A naming/discovery story (“which instance do I connect to?”)

capntinybase is an opinionated but tiny bridge between TinyBase (replicated/mergeable state) and Cap’n Web (capability-based RPC) that’s ergonomic in Bun.


Quickstart (runs the included examples)

Prereqs

  • Bun installed (bun --version)

Install & run

bun install
bun run start

You should see logs similar to:

  • page (initial title): ...
  • page (rpc getTitle): ...
  • page (synced title): ...
  • counter (rpc increment returned): ...
  • counter (synced): ...

The example entrypoint is example/index.ts.


Mental model

Actor key

An actor instance is identified by:

  • actorType: a string like "counter" or "page"
  • instanceId: a string like "main" or "default"

These combine into an actor key: actorType/instanceId, which is also the WebSocket path.

Two channels, one connection

Inside a single WebSocket connection to an actor path, you get both:

  • TinyBase sync messages (replicating the store)
  • Cap’n Web RPC (calling methods on capabilities)

The convention is:

  • RPC methods mutate/query the actor’s store
  • Clients observe results via synced TinyBase state (and/or via RPC return values)

The included examples

page

  • Store: a single title: string
  • RPC:
    • getTitle(): string
    • setTitle(title: string): void

Files:

  • example/page/store.ts
  • example/page/api.ts
  • example/page/actor.ts
  • example/page/client.ts

counter

  • Store: a single counter: number
  • RPC:
    • getCount(): number
    • increment(): number

Files:

  • example/counter/store.ts
  • example/counter/api.ts
  • example/counter/actor.ts
  • example/counter/client.ts

Create your own actor (template)

Below is the pattern used by the examples (names changed to be generic).

1) Define a typed store

import { createMergeableStore, type MergeableStore } from "tinybase";
import { createTypedStore, type TypedStore } from "tinybase-zod";
import z from "zod";

const schema = {
  tables: {},
  values: z.object({
    // your values here
    // e.g. title: z.string(),
  }),
} as const;

export type MyStore = TypedStore<typeof schema, MergeableStore>;

export function createMyStore(): MyStore {
  return createTypedStore(createMergeableStore(), schema);
}

2) Define your RPC API (capability)

import { BaseApi } from "./src/api";
import type { MyStore } from "./my-store";

export class MyApi extends BaseApi<MyStore> {
  // Methods can be sync or async; remote callers always `await`.
  hello(name: string) {
    return `hello, ${name}`;
  }

  // Typical pattern: mutate the store.
  setTitle(title: string) {
    this.store.setValue("title", title);
  }
}

3) Implement the actor (registers + syncs)

import { BaseActor, createAndRegister } from "./src/actor";
import type { SynchronizerOptions } from "./src/client";
import { MyApi } from "./my-api";
import { createMyStore, type MyStore } from "./my-store";

const actorType = "my-actor";

export class MyActor extends BaseActor<MyApi, MyStore> {
  private constructor(args: any) {
    super(args);
  }

  static async get(instanceId: string, options: SynchronizerOptions) {
    const store = createMyStore();
    const api = new MyApi(store);
    const { server, synchronizer } = await createAndRegister({
      actorType,
      instanceId,
      store,
      api,
      options,
    });

    return new MyActor({
      actorType,
      instanceId,
      store,
      api,
      server,
      synchronizer,
    });
  }
}

4) Implement the client (connects + syncs + returns remote API)

import { BaseClient, createAndConnect } from "./src/client";
import type { SynchronizerOptions } from "./src/client";
import { MyApi } from "./my-api";
import { createMyStore, type MyStore } from "./my-store";

const actorType = "my-actor";

export class MyClient extends BaseClient<MyApi, MyStore> {
  private constructor(args: any) {
    super(args);
  }

  static async get(instanceId: string, options: SynchronizerOptions) {
    const store = createMyStore();
    const connected = await createAndConnect({
      store,
      actorType,
      instanceId,
      options,
    });
    return new MyClient({
      actorType,
      instanceId,
      store,
      synchronizer: connected.synchronizer,
      server: connected.server,
      api: connected.api,
    });
  }
}

5) Start the server + wire things up

import { createCapnwebWsServer } from "./src/server";
import type { SynchronizerOptions } from "./src/client";
import { MyActor } from "./my-actor";
import { MyClient } from "./my-client";

const port = 8080;
createCapnwebWsServer({ port });

const options: SynchronizerOptions = { port, waitForActorMs: 2_000 };
await MyActor.get("default", options);

const client = await MyClient.get("default", options);
console.log(await client.api.hello("world"));

Server options

createCapnwebWsServer({ ... }) supports:

  • port: default 8080
  • hostname: optional bind hostname
  • requestTimeoutSeconds: Cap’n Web request timeout (default 1)
  • createPersisterForPath(pathId): optional per-room persister hook
  • onIgnoredError(error): best-effort error callback (transport, sync, persister cleanup)

The server creates one TinyBase “room” per path. Each room has a server-side TinyBase synchronizer, and any number of clients can connect.


Actor directory (global)

In addition to per-path sync, the server maintains a global directory keyed by actorType/instanceId so clients can:

  • listActors(): Array<{ actorType; instanceId }>
  • getActor(actorType, instanceId): unknown

Actors register themselves when they start (see createAndRegister).

This is intentionally cross-path: it’s a way to discover and fetch capabilities regardless of which sync room you’re currently in.


Development

bun run check

Status / notes

  • Experimental: the API surface is small, but expect changes.
  • Repository-only right now: package.json is marked "private": true.

About

The structural core for replicated, capability-oriented actors

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

⌂ Proxy