Skip to content

Alchemy and domain models

@akterjs/alchemy provisions an Akter Cloud app as an Alchemy resource. @akterjs/domain runs an @alchemy.run/domain aggregate as one canonical Akter.make actor. Together they describe a domain, the actors that host it, and the Cloud environments that serve it, all in TypeScript.

Host an aggregate as an actor⁠

DomainAkter.make turns an aggregate into an actor contract. DomainAkter.toLayer builds the handlers for that contract.

  1. Declare the aggregate with @alchemy.run/domain. Its state must be a Schema.Union of Schema.TaggedStruct values.
  2. Declare the callers that may send its commands.
  3. Pass the aggregate, the callers, the parent, and the views to DomainAkter.make.
  4. Pass the actor to DomainAkter.toLayer, and serve the layer like any other actor layer.
account.actor.ts
import { Akter } from "@akterjs/effect/contract"
import { DomainAkter } from "@akterjs/domain"
import { Aggregate, Command, Event, Rejection, View } from "@alchemy.run/domain"
import { Match, Schema } from "effect"

export const AccountId = Schema.String.pipe(Schema.brand("AccountId"))

const AccountOpened = Event("AccountOpened", { owner: Schema.String })

const MoneyDeposited = Event("MoneyDeposited", { amount: Schema.Int, balanceAfter: Schema.Int })

const NotOpen = Rejection("NotOpen", {})

export const OpenAccount = Command("OpenAccount", {
  events: [AccountOpened],
  input: { owner: Schema.String },
  rejects: [],
  target: AccountId,
})

export const DepositMoney = Command("DepositMoney", {
  events: [MoneyDeposited],
  input: { amount: Schema.Int },
  rejects: [NotOpen],
  reply: { balance: Schema.Int },
  target: AccountId,
})

const Unopened = Schema.TaggedStruct("Unopened", {})

const Open = Schema.TaggedStruct("Open", { balance: Schema.Int, owner: Schema.String })

const AccountState = Schema.Union([Unopened, Open])

const balanceOf = (state: typeof AccountState.Type): number =>
  Match.valueTags(state, { Open: (open) => open.balance, Unopened: () => 0 })

const Account = Aggregate("Account", {
  commands: [OpenAccount, DepositMoney],
  decide: {
    DepositMoney: (state, { amount }) =>
      Match.valueTags(state, {
        Open: (open) => [MoneyDeposited.make({ amount, balanceAfter: open.balance + amount })],
        Unopened: () => new NotOpen(),
      }),
    OpenAccount: (_state, { owner }) => [AccountOpened.make({ owner })],
  },
  evolve: {
    AccountOpened: (_state, { owner }) => Open.make({ balance: 0, owner }),
    MoneyDeposited: (state, { balanceAfter }) =>
      Match.valueTags(state, {
        Open: (open) => Open.make({ ...open, balance: balanceAfter }),
        Unopened: (unopened) => unopened,
      }),
  },
  id: AccountId,
  initial: Unopened.make({}),
  reply: { DepositMoney: (state) => ({ balance: balanceOf(state) }) },
  state: AccountState,
})

const AccountLedger = View("AccountLedger", {
  evolve: { MoneyDeposited: (ledger, { amount }) => ({ deposits: ledger.deposits + amount }) },
  from: [Account],
  initial: { deposits: 0 },
  key: Account,
  state: Schema.Struct({ deposits: Schema.Int }),
})

const Teller = Akter.caller("teller", Schema.Struct({ id: Akter.PrincipalId }))

export const Accounts = DomainAkter.make(Account, { callers: [Teller], parent: Akter.Root, views: [AccountLedger] })

export const AccountsLive = DomainAkter.toLayer(Accounts)

The actor that DomainAkter.make declares⁠

Each part of the aggregate maps to one part of the actor.

Aggregate partActor part
Aggregate nameActor name
id schemakey
Members of the state unionstates, each one a Schema.TaggedStruct
initial stateinitial, created with the input {}
Each commandA command named by the command tag, from every state to every state
Rejections of a commanderrors of that command
reply of a commandoutput of that command, or Schema.Void without a reply
EventsRows of the domain_events table and events on the actor channel
Each viewA query named by the view name with a lowercase first letter

The actor also has two read-only queries. current returns the state. events takes { after, limit } and returns up to limit recorded events with a seq above after, in order. Each event comes with its seq, at, and commandId. limit is from 1 to 1000.

One command is one turn⁠

A command runs decide on the stored state. A rejection fails the call with the declared rejection, and the turn commits nothing. Accepted events then run through evolve, and the result becomes the next state.

The same turn writes each event to the domain_events table and folds each view into the domain_views table. A view starts from its initial state. A view handler that returns null removes the view, and the next event that has a handler starts it again from initial. A view query returns none until a handler first runs. The turn publishes each event on the actor channel and returns the reply. The state, the events, and the views commit together, or none of them commit.

The actor stores its state, so it never replays events to rebuild it. The domain_events table is an outbox that clients read and that jobs can forward. Views read only from the turn that changes them, so a view query never returns a state older than the actor state.

Definitions that DomainAkter.make refuses⁠

DomainAkter.make throws a DomainDefinitionError when it declares the actor. The reason field names the problem.

ReasonCause
CommandMiddlewareA command declares middleware. The actor checks callers instead.
StateNotTaggedThe initial state is not a member of the state union.
ViewKeyedElsewhereA view reads from or is keyed by something other than its aggregate.
ViewEmitsA view declares emit or keyOf.
ViewRoutedA view handler is a route map instead of a function.
ViewStatelessA view has no state schema to serve as a query.
ViewWithoutInitialA view has a state schema but no initial state to fold from.

Reach an actor through a Durable Object namespace⁠

AkterAlchemy.DurableObject gives an actor the namespace shape that Alchemy uses for Durable Objects. getByName returns the actor client for one key. states lists the tags of the actor states.

accounts.layer.ts
import { AkterAlchemy } from "@akterjs/alchemy"
import { Effect } from "effect"

import { AccountId, Accounts, DepositMoney } from "./account.actor.ts"

const accounts = AkterAlchemy.DurableObject(Accounts)

export const deposit = Effect.gen(function* () {
  const sam = yield* accounts.getByName(AccountId.make("sam"))

  return yield* sam.DepositMoney(DepositMoney.make({ amount: 100 }))
})

Each key is one actor on akterd. Cloudflare Durable Object limits, such as 128 MB of memory for each object, do not apply.

Provision the app with AkterAlchemy.CloudApp⁠

AkterAlchemy.CloudApp is an Alchemy resource. It converges one Akter Cloud app to its environments, secrets, custom domains, and backup bucket.

  1. Create an Akter Cloud API key for the organization.
  2. Store the API key in the AKTER_API_KEY environment variable.
  3. Add AkterAlchemy.providers to the stack with the key and the Cloud API URL.
  4. Declare the app with AkterAlchemy.CloudApp.
  5. Run alchemy deploy.
alchemy.run.ts
import { AkterAlchemy } from "@akterjs/alchemy"
import { Stack, localState } from "alchemy"
import { Config, Effect, Layer } from "effect"
import { FetchHttpClient } from "effect/http"

const providers = Layer.unwrap(
  Effect.map(Config.Redacted("AKTER_API_KEY"), (apiKey) =>
    AkterAlchemy.providers({ apiKey, url: "https://api.akter.dev" }),
  ),
).pipe(Layer.provide(FetchHttpClient.layer), Layer.orDie)

export default Stack(
  "bank",
  { providers, state: localState() },
  Effect.gen(function* () {
    const app = yield* AkterAlchemy.CloudApp("bank", {
      app: "bank",
      environments: [
        {
          backup: {
            bucket: "s3://acme-backups/bank",
            cadence: "15m",
            credentials: {
              accessKeyId: yield* Config.Redacted("BACKUP_ACCESS_KEY_ID"),
              secretAccessKey: yield* Config.Redacted("BACKUP_SECRET_ACCESS_KEY"),
            },
            region: "us-west-2",
          },
          domains: ["bank.example.com"],
          name: "prod",
          secrets: { LEDGER_KEY: yield* Config.Redacted("LEDGER_KEY") },
        },
      ],
      organization: "acme",
    })

    return { environments: app.environments }
  }),
)

The resource that AkterAlchemy.CloudApp manages⁠

PropertyMeaning
organizationThe Akter Cloud organization that owns the app.
appThe app name. A changed name deletes the old app before it creates the new one. The old app’s actor data is never reattached.
environments[].nameThe environment name. An environment that leaves the list is retired. A retired name cannot return.
environments[].domainsThe custom hostnames that the environment serves. A hostname moves between environments in one deploy, because the deploy waits until Akter Cloud releases the old claim.
environments[].secretsThe environment secrets, as Redacted values. A changed value writes a new secret version.
environments[].backupThe bucket that akter backup writes to.

The backup bucket is written as environment secrets that akter backup reads. bucket takes an s3:// or r2:// URL. cadence is continuous, 15m, hourly, or daily. An optional endpoint takes an https URL for an S3-compatible store.

Backup fieldSecret
bucketAKTER_BACKUP_BUCKET
cadenceAKTER_BACKUP_CADENCE
regionAKTER_BACKUP_REGION
endpointAKTER_BACKUP_ENDPOINT
credentials.accessKeyIdAKTER_BACKUP_ACCESS_KEY_ID
credentials.secretAccessKeyAKTER_BACKUP_SECRET_ACCESS_KEY
credentials.sessionTokenAKTER_BACKUP_SESSION_TOKEN

A deploy fails with the reason ReservedSecretName when secrets names an AKTER_BACKUP_ secret beside backup. A deploy that changes nothing writes nothing.

Deletes need a person’s approval⁠

Akter Cloud asks a person to approve each delete that an API key makes. This covers deleting an app, an environment, or a secret, and releasing a domain.

  • A deploy runs every delete before it creates or changes anything.
  • For each delete, the resource asks Akter Cloud for an approval. Akter Cloud emails a 6-digit code to the person who created the API key.
  • In an interactive terminal, alchemy deploy asks for that code and sends the approved delete.
  • Without an interactive terminal, the deploy fails with the reason ConfirmationRequired before it sends any request for approval. Nothing else in that deploy runs.

Keep the Alchemy state private⁠

Alchemy writes the value of each Redacted property into the stack state, including environment secrets and backup credentials. AkterAlchemy.CloudApp compares those stored values to decide which secrets to write. Store the state where only the people who deploy can read it.