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.
- Declare the aggregate with
@alchemy.run/domain. Its state must be aSchema.UnionofSchema.TaggedStructvalues. - Declare the callers that may send its commands.
- Pass the aggregate, the callers, the parent, and the views to
DomainAkter.make. - Pass the actor to
DomainAkter.toLayer, and serve the layer like any other actor layer.
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 part | Actor part |
|---|---|
| Aggregate name | Actor name |
id schema | key |
Members of the state union | states, each one a Schema.TaggedStruct |
initial state | initial, created with the input {} |
| Each command | A command named by the command tag, from every state to every state |
| Rejections of a command | errors of that command |
reply of a command | output of that command, or Schema.Void without a reply |
| Events | Rows of the domain_events table and events on the actor channel |
| Each view | A 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.
| Reason | Cause |
|---|---|
CommandMiddleware | A command declares middleware. The actor checks callers instead. |
StateNotTagged | The initial state is not a member of the state union. |
ViewKeyedElsewhere | A view reads from or is keyed by something other than its aggregate. |
ViewEmits | A view declares emit or keyOf. |
ViewRouted | A view handler is a route map instead of a function. |
ViewStateless | A view has no state schema to serve as a query. |
ViewWithoutInitial | A 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.
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.
- Create an Akter Cloud API key for the organization.
- Store the API key in the
AKTER_API_KEYenvironment variable. - Add
AkterAlchemy.providersto the stack with the key and the Cloud API URL. - Declare the app with
AkterAlchemy.CloudApp. - Run
alchemy deploy.
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
| Property | Meaning |
|---|---|
organization | The Akter Cloud organization that owns the app. |
app | The 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[].name | The environment name. An environment that leaves the list is retired. A retired name cannot return. |
environments[].domains | The 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[].secrets | The environment secrets, as Redacted values. A changed value writes a new secret version. |
environments[].backup | The 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 field | Secret |
|---|---|
bucket | AKTER_BACKUP_BUCKET |
cadence | AKTER_BACKUP_CADENCE |
region | AKTER_BACKUP_REGION |
endpoint | AKTER_BACKUP_ENDPOINT |
credentials.accessKeyId | AKTER_BACKUP_ACCESS_KEY_ID |
credentials.secretAccessKey | AKTER_BACKUP_SECRET_ACCESS_KEY |
credentials.sessionToken | AKTER_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 deployasks for that code and sends the approved delete. - Without an interactive terminal, the deploy fails with the reason
ConfirmationRequiredbefore 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.