Skip to content
프로젝트

소개

Infrastructure as Effects

시스템 및 인프라

이 수치를 측정하는 방법

측정된 스타 증가

in 24h
+36
in 7 days
+168
in 15 days
+285
in 1 month
+452

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original
Alchemy — build, verify and deploy production-ready software

npm license discord

Build, verify and deploy production-ready software.

Model your business as a verifiable domain model, the work as AI processes, and your infrastructure as code, in one typed Effect program.

Docs · Getting Started · Domain · AI · Examples · Discord

The model, a story that specifies it, an AI process that works on it, and the infrastructure that serves it, in one typed program:

// the model: what the business is, and the rules it keeps
export class Bank extends Domain.Model("Bank", {
  aggregates: [Account, Customer],
  views: [AccountSummary],
}) {}

// a story: a rule in the business's words, run in memory in milliseconds
it.effect("an overdraft is rejected with the evidence", () =>
  story(
    Story.given(
      account,
      new AccountOpened({ owner: "sam" }),
      new MoneyDeposited({ amount: 50, balanceAfter: 50 }),
    ),
    Story.when(account, new WithdrawMoney({ amount: 80 })),
    Story.rejected(new InsufficientFunds({ balance: 50, requested: 80 })),
  ),
);

// an AI process: it can read and send only what its prose mentions
export class FraudReview extends AI.Process("FraudReview")`
  Read ${Bank.AccountSummary}. If it looks
  stolen, send ${Bank.FreezeAccount}.
` {}

// the infrastructure: a Worker serving the API, its ledger in D1
export default Cloudflare.Worker(
  "Api", { main: import.meta.url },
  CustomerApi.pipe(Effect.provide(BankD1)),
);

Stories and proofs verify the rules, the type checker verifies the infrastructure, and Layers ground it in any platform. Swap Cloudflare.Worker and BankD1 for AWS.Lambda.Function and BankDynamoDB and the same program runs on AWS.

Declare the model

Alchemy Domain gives the words your business already uses a place in the code. A command declares what it asks for and every way it can end, an aggregate decides it in a pure function, and an event records what happened.

export class WithdrawMoney extends Domain.Command("WithdrawMoney", {
  target: AccountId,
  input: { amount: Schema.Int },
  events: [MoneyWithdrawn],
  rejects: [NotOpen, InsufficientFunds],
  reply: { balance: Schema.Int },
}) {}

Specify it as stories

A story is a test in the model's own terms: given this history, when this command, then these events. It reads like the requirement it came from, and fails if anything happens that it doesn't account for. It runs the real model in memory, policies and sagas included:

it.effect("a risky withdrawal freezes the account", () =>
  story(
    Story.given(
      account,
      new AccountOpened({ owner: "sam" }),
      new MoneyDeposited({ amount: 90_000, balanceAfter: 90_000 }),
    ),
    Story.when(account, new WithdrawMoney({ amount: 60_000 })),
    Story.then(
      account,
      new MoneyWithdrawn({ amount: 60_000, balanceAfter: 30_000 }),
    ),
    // the fraud policy asks the scoring service; the story answers
    Story.call(FraudCheck.score, { accountId: account.id, amount: 60_000 }),
    Story.succeed(FraudCheck.score, { risk: 0.95 }),
    Story.then(
      account,
      new AccountFrozen({ reason: "fraud risk 0.95", by: system("FraudReview") }),
    ),
  ),
);

Prove it

A story tests the cases you thought of. An invariant is a predicate that must hold in every case. One test proves each aggregate's invariants for every state and every input, then explores every short sequence of commands for one that breaks a rule.

// rules sit on the aggregate, beside decide
invariants: {
  NeverOverdrawn: (account) =>
    account._tag !== "Open" || account.balance >= 0,
},

// one test verifies every rule in the model
it.effect("the bank keeps its promises", () =>
  Verify.model(Bank, { apis: [CustomerApi, SupportApi], story }),
);
Proved: for every state and every input, after any number of commands
  ✓ Account.NeverOverdrawn
  ✓ Account.AClosedAccountStaysClosed

Checked: every sequence of up to 2 commands (19,641 sequences, 10,648 states)
  ✓ Bank.TransfersLoseNoMoney

A broken invariant fails with the shortest sequence that breaks it, written as a story. An AI process sends the same commands as anyone else, so every rule you proved holds whatever the agent does.

Ground it in a real platform

A proved model still knows nothing about the cloud. A Layer answers each of its contracts with a real platform: Durable Objects for the aggregates, a database for the ledger, a vendor for payments. Swap a Layer and the same program runs in memory, on your machine, or on another platform.

const BankLive = Bank.layer(BankHandlers).pipe(
  // the ledger projection writes to a D1 database
  Layer.provideMerge(D1LedgerStore),
  Layer.provide(
    Layer.mergeAll(
      // one Durable Object per aggregate
      DomainCloudflare.layerDurableObjects(),
      // Payments and FraudCheck, answered by vendors
      StripePayments,
      SiftFraudCheck,
      Cloudflare.D1.QueryDatabaseBinding,
    ),
  ),
);

Deploy it on a Worker

The Worker that serves the model is declared in the same program, so deploying it deploys the model:

export default class BankWorker extends Cloudflare.Worker<BankWorker>()(
  "BankWorker",
  { main: import.meta.url },
  Effect.gen(function* () {
    const customerApi = yield* CustomerApi;
    return { fetch: customerApi.fetch };
  }).pipe(Effect.provide(BankLive)),
) {}
pnpm alchemy deploy

There are no Durable Object classes, bindings or IAM policies to write. Each Layer owns the resources and the access it needs, and the type checker rejects a Worker that leaves one of the model's contracts unanswered.

Every step proves it works

  • Types, stories and proofs answer in milliseconds.
  • alchemy dev runs the whole system on your machine: Workers, Durable Objects, queues and buckets on emulated services.
  • The same tests run emulated in seconds, then against a live deployment in a stage of their own in about 20 seconds.
  • Every pull request gets its own deployment and a comment linking to it. Merging deploys to production.
  • Production traces speak the model's language: every command, event, policy and view is an OpenTelemetry span.
  • Many platforms, one program. AWS, Cloudflare, GCP, Fly, Hetzner, Kubernetes, Railway, Neon, PlanetScale, Stripe, and more.
pnpm add alchemy@latest @alchemy.run/cloudflare@latest effect @effect/platform-bun @effect/platform-node

Learn more

  • What is Alchemy? — the framework in 2 minutes
  • Getting Started — your first Stack
  • Domain — model your business as commands, aggregates and events
  • Verifying a model — state invariants and have them proved
  • AI — describe work as AI processes
  • Tutorial — build, test, and deploy a Cloudflare app step by step
  • Examples — runnable projects on AWS and Cloudflare
  • llms.txt — agent-ready documentation index

alchemy v2 is in beta. Expect breaking changes. Come hang in our Discord.

Credits

Blacksmith

Thanks to Blacksmith for sponsoring our CI runners. Their fast Linux, macOS, and Windows runners help us test our packages across platforms and deploy our content-heavy website in mere minutes.

License

Licensed under the Apache License 2.0. See Third-Party Licenses for code incorporated from upstream projects.

관련 프로젝트 살펴보기

불러오는 중…