toa

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Building Applications on Toa

在 Toa 上构建应用

How to turn business requirements into a working application on Toa: what to write, which files to create, how to run and test it. Why the runtime behaves the way it does, and what it guarantees, is in the mental model.
Every article answers "how do I do X?", stands on its own, and links to what it relies on. Find the one the task needs by its summary below and read that file. Every example comes from the same application — a small shop with orders and customer accounts.
如何将业务需求转化为 Toa 上可运行的应用:需要编写什么、创建哪些文件,以及如何运行和测试。运行时为何会表现出当前行为、又能提供哪些保证,请参阅 mental model。
每篇文章都回答“如何完成 X?”,可独立阅读,并链接至其依赖的内容。根据下方摘要找到任务所需的那篇文章并阅读对应文件。每个示例均来自同一个应用——一个包含订单和客户账户的小型商店。

Chapter I. First Steps

第一章。入门

From one command to a tested, configured component behind an HTTP API, one small step at a time.
  1. Create an Application — summary: what the machine needs; creating an application with one command; starting it; the two processes; the first requests; running its tests; the commands of every day; what was created and where each file is explained.
  2. Run It and Make a Change — summary: an operation and its file; restarting after a change; calling an operation from the command line; the manifest; an entity and the operations a component inherits; adding a property; what a restart generates.
  3. Create a Component — summary: a manifest with an entity; creating objects by forwarding to
    transit
    ; an operation with a business rule; returning and declaring an error; calling it; what a reply, an error and an exception look like.
  4. Expose It over HTTP — summary: the smallest exposition for listing, reading, creating and approving; where routes are mounted; the gateway; requests with curl; how a returned error and other failures are answered.
  5. Write a Test — summary: a scenario that sends http requests and matches responses; the steps the application came with; what a scenario runs against; running scenarios; calling an operation directly; the stage api; the agent's request text, captures, pipelines and matching.
  6. Add Configuration — summary: declaring a configuration schema and defaults; reading
    context.configuration
    ; setting values in the context; one value per environment with the
    @environment
    suffix; where secrets and runtime changes are described.
从一条命令到 HTTP API 背后一个经过测试和配置的组件,每次前进一小步。
  1. 创建应用 — 摘要:机器需要什么;用一条命令创建应用;启动应用;两个进程;最初的请求;运行测试;日常使用的命令;创建了哪些内容,以及每个文件在哪里得到说明。
  2. 运行应用并进行修改 — 摘要:operation 及其对应文件;修改后重启;从命令行调用 operation;manifest;entity 以及组件继承的 operation;添加属性;重启时生成的内容。
  3. 创建组件 — 摘要:包含 entity 的 manifest;通过转发到
    transit
    创建 object;包含业务规则的 operation;返回并声明 error;调用 operation;reply、error 和 exception 分别是什么样子。
  4. 通过 HTTP 暴露服务 — 摘要:用于列出、读取、创建和批准的最简 HTTP 暴露方式;route 的挂载位置;gateway;使用 curl 发起请求;如何响应返回的 error 和其他失败。
  5. 编写测试 — 摘要:发送 HTTP 请求并匹配响应的 scenario;应用自带的步骤;scenario 实际针对什么运行;运行 scenario;直接调用 operation;stage API;
    agent
    的请求文本、捕获内容、流水线和匹配机制。
  6. 添加配置 — 摘要:声明 configuration schema 和默认值;读取
    context.configuration
    ;在 context 中设置值;使用
    @environment
    后缀为每个 environment 设置一个值;secret 和运行时变更的说明位置。

Chapter II. Business Logic

第二章。业务逻辑

What a component is made of, one requirement at a time: state, operations, refusals, calls, events, and what follows from them.
  1. Describe State — summary: the entity schema, required properties and blank; system properties; associated entities and identifiers of your own; moments; storage; every manifest key.
  2. Write Operations — summary: a file is an operation; choosing a type and a scope; declaring input, output, concurrency and query; classes and factories; shared code; rules for operation code.
  3. Refuse a Request — summary: returning and declaring an error; handling an error from a call; exceptions and their http statuses; deciding not to write with discard; the four outcomes.
  4. Call Operations and Select State — summary: local and remote calls; input and query; criteria, sorting and paging; creating an object; versions; deleted objects; trimming the reply; every request property.
  5. Use the Inherited Operations — summary: transit, observe, enumerate, assign, terminate and the rest; narrowing and forwarding them; replacing one; inherited events; a prototype of your own.
  6. Protect an Invariant — summary: a guard file that every write must pass; what a refused write looks like; choosing between a guard, the schema and an operation.
  7. Announce a Change — summary: an event file with a condition; a payload of your own; trailers; inherited events; naming events for consumers outside the application; rules for conditions.
  8. React to an Event — summary: binding an event to an operation; building the request; skipping events; shared operations with arguments; own events; events from other systems; what the operation must expect.
  9. Do Work in the Background — summary: handing a call over with
    task: true
    ; tasks to your own component; getting the result; what a task's operation must handle; calls that cannot be tasks.
  10. Handle Repeated Calls — summary: why an operation can run again; setting instead of adding; skipping by
    VERSION
    ; keying a change by what it is for; declaring
    once
    , how long a call is remembered and why a transition that retries does not call it; the
    idempotency-key
    header; keys for external services.
  11. Call an External Service — summary: requests with
    context.fetch
    ; address and key from configuration; stubbing the provider locally and in tests; retries and timeouts; what a repeated operation means for a provider; traces and metrics.
  12. Write a Multi-Step Workflow — summary: an effect under
    continuity
    that goes on from the step that failed; starting it as a task or from a receiver; what counts as a step; time, randomness and ids from the context; what can still repeat; what it needs to run.
  13. Run Work on a Schedule — summary: pulses at a regular interval and cron schedules under
    cadence
    ; what must be configured and run; writing for missed and repeated calls; spreading work over a cycle; per- replica pulses; several entries; regions.
  14. Do Something Later — summary: arming a call with
    context.delay
    and cancelling it; choosing
    overdue
    ; timing and discreteness; calls that re-arm themselves; where a delay is refused; the
    cadence
    settings of the Context.
  15. Read a Large Collection — summary: reading a collection as a stream of parts; operations with the
    stream
    scope; tokens and reading only what changed; windows, order and
    stop
    ; what a reader handles; turning changes on with images.
  16. Stream a Reply or an Input — summary: answering with a generator or a
    Readable
    and reading it; operations that take a stream with
    stream
    and the
    http
    binding; how to call them; what such a call lacks; addresses for a local run.
  17. Keep Something in a Process — summary: run commands in
    rc/
    ;
    context.state
    ; releasing in
    dispose
    ;
    pause
    and
    resume
    ; stateful operations called by process name, their failures, timeouts and limits.
  18. Loops and Read-Only Calls — summary: reading and fixing a
    LoopException
    ;
    unchained
    operations and delays; the trail limits;
    SafetyException
    from a safe operation and under
    GET
    and
    HEAD
    ;
    io:readonly
    .
  19. Use TypeScript — summary: operations in typescript without a build step; generating types from manifests; type checking with tsc; the three rules of erased types.
  20. Indexes and Data Migrations — summary: declaring indexes, unique values and expiry; changing stored data; the rules a migration must follow.
  21. The Operation Context — summary: everything on the context argument and the article that teaches each member: calls, ids and time, where it runs, what extensions add.
组件由什么构成:每次满足一项需求,逐步加入 state、operation、拒绝、call、event,以及由它们引发的一切。
  1. 描述 State — 摘要:entity schema、必需属性和 blank;系统属性;关联 entity 及自定义 identifier;moment;storage;manifest 中的每个键。
  2. 编写 Operations — 摘要:一个文件就是一个 operation;选择 type 和 scope;声明 input、output、concurrency 和 query;class 与 factory;共享代码;operation 代码的规则。
  3. 拒绝请求 — 摘要:返回并声明 error;处理 call 中的 error;exception 及其 HTTP status;使用 discard 决定不执行写入;四种结果。
  4. 调用 Operations 并选择 State — 摘要:本地和远程 call;input 和 query;criteria、sorting 和 paging;创建 object;version;已删除的 object;裁剪 reply;request 的每个属性。
  5. 使用继承的 Operations — 摘要:transit、observe、enumerate、assign、terminate 等 operation;收窄和转发它们;替换某个 operation;继承的 event;创建自己的 prototype。
  6. 保护不变量 — 摘要:每次 write 都必须通过的 guard 文件;被拒绝的 write 是什么样子;在 guard、schema 和 operation 之间如何选择。
  7. 宣告变更 — 摘要:带 condition 的 event 文件;自定义 payload;trailers;继承的 event;为 application 外部的消费者命名 event;condition 的规则。
  8. 响应 Event — 摘要:将 event 绑定到 operation;构建 request;跳过 event;带 arguments 的共享 operation;自有 event;来自其他系统的 event;operation 必须预期什么。
  9. 在后台执行工作 — 摘要:使用
    task: true
    移交 call;发送给自身组件的 task;获取结果;task 的 operation 必须处理什么;哪些 call 不能成为 task。
  10. 处理重复调用 — 摘要:operation 为何会再次运行;使用 setting 而非 adding;通过
    VERSION
    跳过;按照用途为 change 设置 key;声明
    once
    、call 被记忆的时长,以及重试中的 transition 为何不会调用它;
    idempotency-key
    header;外部服务使用的 key。
  11. 调用外部服务 — 摘要:使用
    context.fetch
    发起 request;从 configuration 读取 address 和 key;在本地及测试中 stub provider;retry 和 timeout;重复 operation 对 provider 意味着什么;trace 和 metric。
  12. 编写多步骤 Workflow — 摘要:
    continuity
    下的 effect 从失败步骤继续;将 workflow 作为 task 或从 receiver 启动;什么算作一个 step;从 context 获取 time、randomness 和 id;哪些内容仍可重复;运行 workflow 需要什么。
  13. 按计划运行工作 — 摘要:按固定间隔产生 pulse,以及
    cadence
    下的 cron schedule;必须配置和运行什么;如何处理错过及重复的 call;在一个周期内分散工作;每个副本分别产生 pulse;多个条目;region。
  14. 稍后执行 — 摘要:使用
    context.delay
    设置并取消 call;选择
    overdue
    ;计时与离散性;重新设置自身的 call;delay 在哪里会被拒绝;Context 的
    cadence
    设置。
  15. 读取大型 Collection — 摘要:将 collection 作为分段 stream 读取;使用
    stream
    scope 的 operation;token 以及仅读取发生变化的机制;window、order 和
    stop
    ;reader 会处理什么;通过 images 启用变更。
  16. 流式返回 Reply 或读取 Input — 摘要:使用 generator 或
    Readable
    返回内容并读取它;通过
    stream
    和
    http
    binding 接收 stream 的 operation;如何调用;此类 call 缺少什么;本地运行时的 address。
  17. 在 Process 中保留状态 — 摘要:在
    rc/
    中运行 command;
    context.state
    ;在
    dispose
    中释放;
    pause
    和
    resume
    ;按 process 名称调用的有状态 operation,以及它们的失败、timeout 和限制。
  18. 循环与只读调用 — 摘要:读取并修复
    LoopException
    ;
    unchained
    operation 和 delay;trail 限制;安全 operation 产生的
    SafetyException
    ,以及在
    GET
    和
    HEAD
    下产生的异常;
    io:readonly
    。
  19. 使用 TypeScript — 摘要:无需 build step 即可使用 TypeScript 编写 operation;从 manifest 生成类型;使用 tsc 进行类型检查;erased type 的三条规则。
  20. 索引与数据迁移 — 摘要:声明 index、唯一值和 expiry;修改已存储的数据;migration 必须遵循的规则。
  21. Operation Context — 摘要:context 参数上的所有内容,以及分别讲解每个成员的文章:call、id 和 time、运行位置,以及 extension 添加的内容。

Chapter III. The API

第三章。API

Serving the application over HTTP: routes, what they accept and return, files, live updates, and tools for AI assistants.
  1. Build an API for a Component — summary: more routes and methods; the two defaults, no body and no access; where a component is mounted and the trailing slash; a scenario that creates and reads; the host; routes of the context; the long form.
  2. Lay Out the Routes — summary: nested and flat routes; route variables and wildcards; which route answers; forwarding; intermediate nodes; how directives are inherited and how to avoid it; shortcuts; sharing declarations.
  3. Map Methods to Operations — summary: short and long form of a method; which operation suits which method; changing only some fields with patch; the body as input; route variables; read-only get; statuses of replies; retrying with an idempotency key.
  4. List with Filters, Sorting and Paging — summary: the standard parameters; criteria, fixed and open; sort; omit and limit with bounds; fixed queries; identifier; text search; projection; parameters of the operation; queries of collection streams.
  5. What a Client Sends and Receives — summary: formats and content negotiation; every status; the three kinds of failure; debug; headers on every reply and the ray; multipart responses; browsers on other origins; a halted deployment; a client's checklist.
  6. Choose What a Route Accepts and Returns — summary: naming the properties a route returns; narrowing the input; choosing the status from the output; throttling by address, route or identity; read-only calls.
  7. Pass Headers, Language and Host to an Operation — summary: headers, route variables, the language, the host, token claims and the raw body as input properties; requiring headers.
  8. Cache Replies and Prevent Lost Updates — summary: declaring how long a reply is kept; what authenticated requests get; an exact value; etag and not modified; writing only if unchanged with the version; a checklist.
  9. Stream Through the API — summary: reply streams; a collection read in windows, or its newest window with
    stop
    , and a token that continues with the next window or with changes; one value composed from a stream; request bodies streamed into an operation and bytes answered; calling one particular process; answering with content fetched elsewhere.
  10. Keep Files in a Storage — summary: declaring a storage and using it from an operation; entries; put, head, get and delete; providers and their options; a storage per environment; secrets; installing a provider's sdk.
  11. Upload and Download Files — summary: a file resource in three declarations; where a file is stored; accepted types and the size limit; naming and describing an upload; uploading by url; downloads, ranges and variants; the entry; deleting.
  12. Process an Uploaded File — summary: operations called with a reference to a stored file; parallel and sequential steps; the multipart reply and one composed reply; steps as tasks; workflows on delete and without storing; a scenario that uploads.
  13. Push Changes to the Browser — summary: routing events to keys; serving the stream of a key; an identity's own stream; literal keys; reading a stream and reconnecting with a token; rules for the client; a copy of a collection loaded with a stream and kept by events, never read for one: a list scrolled a window at a time, or the newest entries and what changed since the last launch; redis and expiry.
  14. Call the API as Procedures — summary: turning json-rpc on; how a route names a procedure; parameters and results; batches and notifications; errors; the rules shared with http.
  15. Let an AI Assistant Call the API — summary: turning mcp on and publishing a method as a tool; describing tools; what a tool takes and answers; hints; instructions; credentials, anonymous access and browser origins; a host of its own; icons; the protocol in brief.
  16. Describe the API — summary: asking a resource with options; the whole tree and its page; what a caller is shown; describing resources, methods and parameters; hiding a method.
  17. Run and Configure the Gateway — summary: running the gateway locally; ports; authorities; ingress, resources and http/2 in a deployment; readiness; the client address; the censor; stubs, delays and faults for development; every key of the context's exposition.
通过 HTTP 提供应用服务:route、接受的输入和返回的内容、文件、实时更新,以及供 AI 助手使用的工具。
  1. 为组件构建 API — 摘要:更多 route 和 method;两个默认值,即无 body 和无 access;组件的挂载位置及末尾斜杠;创建并读取数据的 scenario;host;context 的 route;long form。
  2. 设计 Route 布局 — 摘要:嵌套 route 和扁平 route;route variable 和 wildcard;由哪个 route 响应;转发;中间节点;directive 如何继承以及如何避免继承;快捷方式;共享声明。
  3. 将 Method 映射到 Operation — 摘要:method 的 short form 和 long form;哪种 operation 适合哪种 method;使用 patch 仅修改部分字段;将 body 作为 input;route variable;只读 get;reply 的 status;使用 idempotency key 重试。
  4. 使用过滤器、排序和分页列出数据 — 摘要:标准参数;固定和开放的 criteria;sort;带边界控制的 omit 和 limit;固定 query;identifier;文本搜索;projection;operation 的参数;collection stream 的 query。
  5. 客户端发送和接收的内容 — 摘要:格式和 content negotiation;所有 status;三类失败;debug;每个 reply 及 ray 上的 header;multipart response;来自其他 origin 的浏览器;已 halted 的 deployment;客户端检查清单。
  6. 选择 Route 接受和返回的内容 — 摘要:命名 route 返回的属性;收窄 input;根据 output 选择 status;按 address、route 或 identity 进行 throttling;只读 call。
  7. 将 Header、语言和 Host 传递给 Operation — 摘要:将 header、route variable、语言、host、token claim 和原始 body 作为 input 属性传入;要求提供 header。
  8. 缓存 Reply 并防止丢失更新 — 摘要:声明 reply 的保留时长;经过身份验证的请求会得到什么;精确值;etag 和 not modified;仅在未更改时使用 version 写入;检查清单。
  9. 通过 API 流式传输 — 摘要:reply stream;按 window 读取 collection,或使用
    stop
    读取最新 window,并通过 token 继续获取下一个 window 或变更;由 stream 组合出的单个值;将 request body 以流形式传入 operation 并以字节形式返回;调用特定 process;返回从其他位置获取的内容。
  10. 在 Storage 中保存文件 — 摘要:声明 storage 并从 operation 中使用;entry;put、head、get 和 delete;provider 及其选项;每个 environment 使用一个 storage;secret;安装 provider 的 SDK。
  11. 上传和下载文件 — 摘要:通过三种声明定义 file resource;文件存储在哪里;可接受的类型和大小限制;命名并描述 upload;通过 URL 上传;下载、range 和 variant;entry;删除。
  12. 处理已上传文件 — 摘要:使用存储文件引用调用的 operation;并行和串行步骤;multipart reply 和组合后的单个 reply;作为 task 的步骤;删除时以及不存储时执行的 workflow;执行 upload 的 scenario。
  13. 将变更推送到浏览器 — 摘要:将 event 路由到 key;提供 key 的 stream;identity 自身的 stream;字面量 key;读取 stream 并使用 token 重新连接;客户端规则;通过 stream 加载并由 event 保持最新、无需再次读取的 collection:用户滚动时每次读取一个 window 的无限列表,或读取最新的一百条记录,并在客户端启动时通过保留的 token 获取此后发生的变化;redis 和 expiry。
  14. 将 API 作为 Procedure 调用 — 摘要:启用 JSON-RPC;route 如何命名 procedure;参数和结果;batch 和 notification;error;HTTP 共享的规则。
  15. 让 AI 助手调用 API — 摘要:启用 MCP 并将 method 发布为 tool;描述 tool;tool 接受和返回什么;提示;说明;credential、匿名访问和浏览器 origin;独立 host;icon;协议简介。
  16. 描述 API — 摘要:使用 options 请求 resource;完整资源树及其页面;调用者会看到什么;描述 resource、method 和 parameter;隐藏 method。
  17. 运行和配置 Gateway — 摘要:在本地运行 gateway;port;authority;deployment 中的 ingress、resource 和 HTTP/2;readiness;客户端 address;censor;开发环境中的 stub、delay 和 fault;context 暴露部分的每个键。

Chapter IV. Users and Access

第四章。用户与访问控制

Signing users up and in, keeping them signed in, and deciding who may call what: owners, staff, other applications.
  1. Sign Users Up and In — summary: the token key; a sign-up route that creates an account and its identity; signing in with a username and password; reaching the caller's own account by path or by delegation; guests; sign in or up with one request; a scenario that signs up and in; where to go next; refusals of a sign-up.
  2. Manage Passwords — summary: rules for usernames and passwords; whether a username is free; changing, adding and removing a password; listing the ways to sign in; limiting password guessing; an identity without an account; the first administrator; hashing settings; the authentication schemes.
  3. Keep Users Signed In — summary: what a client does with the token; how long a sign-in lasts; signing a user out everywhere; token keys and replacing them; custom tokens for scripts limited to roles and paths; acting for another identity; listing and revoking custom tokens.
  4. Sign In with Google or Apple — summary: trusting a provider; signing in with its token; creating the account together with the identity; reading claims into the input; several client ids; exchanging an authorization code; adding, listing and removing providers of an account; a provider's account as the first administrator; why a token was refused.
  5. Sign In with an Emailed Code or a Passkey — summary: an operation that gets a code and emails it; signing in with the code; making an address a way into an account; moving a sign-in to another device; limits on codes; adding a passkey, signing up and signing in with one; listing and removing passkeys; passkey settings and refusals.
  6. Restrict Who Can Call a Route — summary: routes are closed until they say who; a customer reaches only their own orders; a scenario with the refusals; several ways in and why nesting cannot narrow; public routes; any signed-in user; roles; several conditions at once; who may send a property; asking for the password again; recording who called; admitting by a provider's token; access for the whole application; what a caller is shown; all directives.
  7. Give Staff Wider Access — summary: requiring a role on a route; the first administrator; granting a role; when a change reaches a signed-in user; a scenario with the principal; naming roles from general to specific; roles per resource; reading roles; letting staff pass roles on; revoking; banning a user; the system roles.
  8. Serve Several Domains and Screen Requests — summary: authorities and hosts per environment; users belong to an authority; telling an operation which domain was asked; the header that holds the client address; refusing requests by country; requiring a header; scenarios for the refusals.
  9. Let Another App Act for a User — summary: turning the authorization server on; which programs are known; the four steps of the consent page; what the program gets; limiting a token to roles and to one entry; connecting an AI assistant over MCP; showing and revoking what a user allowed; a scenario of the whole exchange; the requests a program makes; settings.
  10. Users and Access Reference — summary: every identity resource with its access; operations an application calls; directives; annotation keys; configuration of the identity components; secrets; statuses a client handles.
注册和登录用户、保持登录状态,以及决定谁可以调用什么:owner、staff 和其他应用。
  1. 注册和登录用户 — 摘要:token key;创建账户及其 identity 的注册 route;使用用户名和密码登录;通过路径或 delegation 访问调用者自己的账户;guest;通过一次请求登录或注册;执行注册和登录的 scenario;后续阅读位置;注册被拒绝的情况。
  2. 管理密码 — 摘要:用户名和密码规则;判断用户名是否可用;更改、添加和移除密码;列出登录方式;限制密码猜测;没有账户的 identity;首位管理员;hash 设置;身份验证方案。
  3. 保持用户登录状态 — 摘要:客户端如何处理 token;一次登录持续多久;在所有位置退出登录;token key 及其替换;权限限定于 role 和 path 的自定义 token;代表其他 identity 行事;列出和撤销自定义 token。
  4. 使用 Google 或 Apple 登录 — 摘要:信任 provider;使用其 token 登录;同时创建账户和 identity;将 claim 读取到 input;多个 client ID;交换 authorization code;添加、列出和移除账户的 provider;将 provider 账户设为首位管理员;token 被拒绝的原因。
  5. 使用邮件验证码或 Passkey 登录 — 摘要:获取并通过电子邮件发送 code 的 operation;使用 code 登录;将某个地址作为进入账户的方式;将登录迁移到另一台设备;code 的限制;添加 passkey,并使用它注册和登录;列出和移除 passkey;passkey 设置和拒绝情况。
  6. 限制谁可以调用 Route — 摘要:route 在声明允许访问者之前默认关闭;customer 只能访问自己的订单;包含拒绝情况的 scenario;多种进入方式,以及为何嵌套无法进一步收窄;公开 route;任何已登录用户;role;多个条件同时生效;谁可以发送属性;再次要求密码;记录调用者;使用 provider 的 token 进行授权;整个 application 的访问控制;调用者会看到什么;所有 directive。
  7. 为 Staff 提供更广泛的访问权限 — 摘要:要求 route 具备某个 role;首位管理员;授予 role;变更何时对已登录用户生效;包含 principal 的 scenario;从通用到具体的 role 命名方式;每个 resource 的 role;读取 role;允许 staff 传递 role;撤销 role;封禁用户;系统 role。
  8. 服务多个域名并检查请求 — 摘要:每个 environment 的 authority 和 host;用户所属的 authority;告知 operation 请求的是哪个域名;保存客户端地址的 header;按国家拒绝请求;要求提供 header;执行拒绝的 scenario。
  9. 让另一个应用代表用户行事 — 摘要:启用 authorization server;已知哪些程序;consent page 的四个步骤;程序获得什么;将 token 限制到特定 role 和单个 entry;通过 MCP 连接 AI 助手;查看和撤销用户允许的内容;完整交换流程的 scenario;程序发出的请求;设置。
  10. 用户与访问控制参考 — 摘要:每个 identity resource 及其访问控制;application 调用的 operation;directive;annotation key;identity 组件的 configuration;secret;客户端需要处理的状态。

Chapter V. Platform Features

第五章。平台功能

Features the platform brings and a component switches on: settings, a cache, coordination, telemetry, a map of itself, a log to query.
  1. Turn On a Platform Feature — summary: declaring an extension in the manifest; setting it up in the context; values per environment; the full form; supplied extensions and connectors; ports that are taken.
  2. Keep Settings and Secrets out of the Code — summary: secret values and
    $NAME
    references;
    unwrap
    ; supplying secrets locally and to a deployment; schema, defaults, nested values, prototypes; values in the context; resources of the values service; trying a component with other values.
  3. Change a Setting without Redeploying — summary: creating, reading and resetting configuration over http; roles; the configuration page; changing values from an operation; the change event; what happens on the next deployment and after a schema change.
  4. Cache Something All Replicas Share — summary: turning the stash on; redis commands on
    context.stash
    ; storing objects; keys private to a component; a redis per component; behaviour when redis is away.
  5. Coordinate Replicas — summary: letting only one replica do something at a time; splitting work between replicas; limiting calls across replicas; the
    atomicity
    annotation; behaviour without redis.
  6. Write Logs — summary: writing entries with
    context.logs
    ; reading them on the console; finding everything about one request; levels per environment and per component; sending entries to a backend; finding why a process failed; writing good entries.
  7. Follow a Request through the Application — summary: seeing spans on the console; what is traced without code; adding spans with
    context.span
    ; sending traces to a backend; sampling; tracing the start of a process.
  8. Count Things and Alert on Them — summary: declaring and recording a counter; turning metrics on; labels; histograms and gauges; declaration reference; choosing intervals, buckets and labels; the metrics recorded for every application.
  9. Send Telemetry to Grafana — summary: wiring logs, traces and metrics to tempo, prometheus and loki; linking traces and logs; the whole
    telemetry
    annotation;
    otlp
    exporter options; loss and outages; resource attributes; the readiness probe.
  10. See What Is Deployed and How Components Talk — summary: the topology page and api; nodes and observed edges; leaving a component out; the
    introspection
    annotation; what to use the graph for.
  11. Change the Storage, the Transport or the Language — summary: the default storage and what it asks of you; storing nothing; the broker and brokers of other systems; the http binding for streamed calls; shell scripts as operations.
  12. Point the Application at Its Database, Broker and Cache — summary: one address for everything; addresses per environment, namespace and component; several addresses under one key; credentials locally and as deployed secrets; secret names.
  13. Write an Extension of Your Own — summary: an aspect of your own; declaring and calling it; annotations and deployment variables; validating declarations; tenants, services and residents; pausing; a storage of your own.
  14. Keep a Log of What Happens and Query It — summary: the store and its provider; the
    chronicles
    annotation and service; declaring what a component logs, typed and described; keeping personal data out;
    context.chronicles.send
    ; encounters from the storefront, visitors and sessions, and their documentation; the
    events
    ,
    states
    and
    encounters
    tables and the views of what is declared; the dialect; tools for an agent and their roles; views.
平台提供的功能,由组件选择启用:设置、缓存、协调、telemetry、自身拓扑图,以及可查询的日志。
  1. 启用平台功能 — 摘要:在 manifest 中声明 extension;在 context 中进行设置;每个 environment 的值;完整形式;平台提供的 extension 和 connector;已被占用的 port。
  2. 将设置和 Secret 保存在代码之外 — 摘要:secret 值和
    $NAME
    引用;
    unwrap
    ;在本地和 deployment 中提供 secret;schema、默认值、嵌套值和 prototype;context 中的值;values service 的 resource;使用其他值试用组件。
  3. 无需重新部署即可修改设置 — 摘要:通过 HTTP 创建、读取和重置 configuration;role;configuration 页面;从 operation 中修改变更值;change event;下次 deployment 以及 schema 变更后会发生什么。
  4. 缓存所有副本共享的内容 — 摘要:启用 stash;在
    context.stash
    上执行 redis command;存储 object;组件私有的 key;每个组件使用一个 redis;redis 不可用时的行为。
  5. 协调副本 — 摘要:确保同一时间只有一个副本执行某项操作;在副本之间拆分工作;限制跨副本 call;
    atomicity
    annotation;没有 redis 时的行为。
  6. 编写日志 — 摘要:使用
    context.logs
    写入 entry;在 console 中读取;查找一次请求的全部信息;每个 environment 和组件的 level;将 entry 发送到 backend;查找 process 失败原因;编写优质 entry。
  7. 在应用中跟踪请求 — 摘要:在 console 中查看 span;无需代码即可跟踪什么;使用
    context.span
    添加 span;将 trace 发送到 backend;sampling;跟踪 process 的启动过程。
  8. 对事物进行计数并设置警报 — 摘要:声明并记录 counter;启用 metric;label;histogram 和 gauge;声明参考;选择 interval、bucket 和 label;每个 application 自动记录的 metric。
  9. 将 Telemetry 发送到 Grafana — 摘要:将 log、trace 和 metric 接入 Tempo、Prometheus 和 Loki;关联 trace 与 log;完整的
    telemetry
    annotation;
    otlp
    exporter 选项;数据丢失和服务中断;resource attribute;readiness probe。
  10. 查看部署内容和组件交互关系 — 摘要:topology 页面及其 API;node 和观察到的 edge;排除某个组件;
    introspection
    annotation;图的用途。
  11. 更换 Storage、Transport 或 Language — 摘要:默认 storage 以及它对你的要求;不存储任何数据;broker 和其他系统的 broker;用于流式 call 的 HTTP binding;将 shell 脚本作为 operation。
  12. 将 Application 指向 Database、Broker 和 Cache — 摘要:为所有服务使用一个 address;按 environment、namespace 和组件划分的 address;一个 key 对应多个 address;本地 credential 和 deployment 中的 deployment secret;secret 名称。
  13. 编写自己的 Extension — 摘要:自定义 aspect;声明并调用它;annotation 和 deployment variable;验证声明;tenant、service 和 resident;pause;自定义 storage。
  14. 记录发生的事件并进行查询 — 摘要:store 及其 provider;
    chronicles
    annotation 和 service;声明组件记录的内容及其类型和说明;避免记录个人数据;
    context.chronicles.send
    ;来自 storefront、visitor 和 session 的 encounter 及其文档;
    events
    、
    states
    和
    encounters
    table,以及声明内容的 view;dialect;供 agent 使用的工具及其角色;view。

Chapter VI. Shipping

第六章。发布上线

From "it works on my machine" to production: describe the application, deploy it, release new versions safely and look after it.
  1. Describe the Application — summary: the context file; name and version; addresses of the broker and the database; keys of connectors and extensions; events another application reads; runtime settings; every top- level key.
  2. Give Each Environment Its Values — summary: the
    @environment
    suffix at any depth; the local environment and
    .env
    ; several local environments; derived environments as a chain; default environment of each command.
  3. Decide What Runs Together — summary: grouping components into compositions; replicas; cpu and memory; extension services inside a composition; ports; leaving components out of a deployment; one process for everything; how to group.
  4. Deploy — summary: what must exist before the first deploy; the keys a deploy needs;
    toa deploy
    and what you see; checking the result; options; what gets deployed; start and stop limits; ingress; single-image deployment; pipelines; running without kubernetes.
  5. Build Images — summary: the registry; building and pushing; tags; what goes into an image; platforms; private registries; base images; extra build steps and arguments; private npm registry; published service images; registry retention.
  6. Supply Secrets — summary: what is a secret; listing what a deployment needs; putting secrets in the cluster; the check before a deploy; changing a value; secrets for a local run; names of credential secrets; checklist for a new environment.
  7. Release a New Version — summary: what to do when you change code, add an operation, add a required input, remove or rename an input, change the entity, add a migration or change an event; changes that cannot be rolled; going back; the component map and versions.
  8. Run in More Than One Region — summary: declaring regions and ranks; requirements; concurrent writes in two regions; writing components for several regions; adding a region step by step; adding a component later; removing a region.
  9. Stop Everything for Maintenance — summary: turning halt on and its limits; requesting a halt over the gateway; what you and clients see;
    pause
    and
    resume
    run commands; choosing the numbers; deploying a release that cannot be rolled; rehearsing.
  10. Look After a Running Application — summary: what is running and at which version; a pod that does not become ready; a message that keeps failing and the parked queue; events that are not published and outbox settings; rolling back; changes without a release; an isolated second copy; alerts to have.
  11. The CLI — summary: installing; common options; every command with its arguments and options, grouped as preparing, running, inspecting, building and deploying, secrets and the cluster; variables the cli reads; exit codes.
从“在我的机器上可以运行”走向生产环境:描述应用、部署应用、安全发布新版本并持续维护。
  1. 描述 Application — 摘要:context 文件;名称和版本;broker 与 database 的 address;connector 和 extension 的 key;其他 application 读取的 event;运行时设置;所有顶层键。
  2. 为每个 Environment 提供值 — 摘要:任意深度使用
    @environment
    后缀;本地 environment 和
    .env
    ;多个本地 environment;以链式方式派生的 environment;每条 command 的默认 environment。
  3. 决定哪些内容一起运行 — 摘要:将组件分组为 composition;replica;CPU 和内存;composition 内的 extension service;port;将组件排除在 deployment 之外;所有内容运行在一个进程中;如何分组。
  4. 部署 — 摘要:首次部署前必须存在什么;deployment 需要的 key;
    toa deploy
    及其输出;检查结果;选项;部署了什么;启动和停止限制;ingress;单镜像 deployment;pipeline;不使用 Kubernetes 运行。
  5. 构建镜像 — 摘要:registry;构建和推送;tag;镜像中包含什么;平台;私有 registry;基础镜像;额外构建步骤和参数;私有 npm registry;已发布的 service image;registry 保留策略。
  6. 提供 Secret — 摘要:什么是 secret;列出 deployment 所需内容;将 secret 放入 cluster;部署前的检查;修改变更值;本地运行所需的 secret;credential secret 的名称;新 environment 的检查清单。
  7. 发布新版本 — 摘要:修改代码、添加 operation、添加必需 input、移除或重命名 input、修改 entity、添加 migration 或修改 event 时应做哪些处理;无法回滚的变更;回退;组件映射和版本。
  8. 在多个 Region 中运行 — 摘要:声明 region 和 rank;要求;在两个 region 中并发写入;为多个 region 编写组件;逐步添加 region;稍后添加组件;移除 region。
  9. 停止所有服务进行维护 — 摘要:启用 halt 及其限制;通过 gateway 请求 halt;你和客户端分别会看到什么;
    pause
    和
    resume
    command;如何选择数量;部署无法回滚的 release;进行演练。
  10. 维护正在运行的 Application — 摘要:正在运行的内容及其版本;无法进入 ready 状态的 pod;持续失败的消息及停放队列;未发布的 event 和 outbox 设置;回滚;不经过 release 的变更;隔离的第二个副本;应设置的警报。
  11. CLI — 摘要:安装;常用选项;每条 command 及其 arguments 和 options,并按准备、运行、检查、构建与部署、secret 和 cluster 分组;CLI 读取的变量;退出码。

Chapter VII. Patterns

第七章。设计模式

How typical problems are solved: when to call and when to announce, what repeats, races and late messages ask of the code, and how to say no.
  1. Call, Event, or Task — summary: the one rule for choosing; what goes wrong with calls only; what a call, an event and a task each give; a table of situations; the same operation called on one path and received on another.
  2. Reply Before the Work Is Done — summary: storing what is wanted and replying; an event of your own that starts the slow part; writing the result and the failure into state; telling the client; why not a task from the operation.
  3. Events Worth Subscribing To — summary: conditions that fire when a fact becomes true; trailers for what the states cannot say; payloads as contracts; receivers that filter and translate; why not subscribe to
    updated
    .
  4. The Same Message Twice — summary: why messages repeat; setting and looking before writing, by itself or under a key;
    once
    for what accumulates and how long it remembers; a record under the other system's id; deduplicating where the effect is.
  5. Two Writers at Once — summary: the read-check-write race; one transition with
    concurrency: retry
    ; keeping the fact in one object; what a second run repeats; forms edited by people; when a lock is the answer.
  6. Messages Out of Order — summary: why arrival order means nothing; carrying the version and skipping older messages; treating an event as a signal and asking the owner; values that only move forward; not creating the dependency.
  7. Saying No — summary: five ways to refuse and what each answers; schema and route, guard, returned error, success without a write, exception; refusals nobody hears; passing a refusal on; refusing before the work and settling after.
  8. Ask the Owner, or Keep a Copy — summary: using a fact another component owns; a call to the owner that keeps the rule; freezing an answer; a copy kept current by a receiver; entities that need no creation; a limit checked where its counter lives.
  9. Keep Data About a Customer without Creating It — summary: why records made at sign-up do not hold; an entity identified by the customer's id; a blank that says what is true before anything happened; what disappears; what a list and an assignment do not do; when existence means something.
  10. A Process Across Components — summary: a business process of several steps without a transaction; a status for every stage; steps that react to events and report back; the owner of the process decides; failure as one more step, with compensation; steps that repeat, race, refuse or never finish.
  11. Reservations — summary: setting money aside now and taking or releasing it later;
    hold
    ,
    settle
    and
    release
    keyed by the order; asking before the work and settling after it; the late hold; a guard for the sum; when a debit with a refund or charging afterwards is enough.
  12. Work on the Clock — summary: expiry as a stored moment compared on use; counters that renew at their next use; sweeps on a pulse that select by state; a delay per object; reconciling a copy with an outside truth; finding work that stopped.
  13. A Gateway to an External Service — summary: one entity-less component that alone holds a provider's keys; operations and errors in the application's words; an error for "ask again later"; a stub when the key is empty; a composition so secrets reach one process.
  14. Receiving Webhooks — summary: an anonymous route with the raw body; verifying the signature by a call; storing every notification and announcing it; one record per provider object under a derived id; why
    once
    is not enough; refusing so the provider sends again.
  15. Mirroring a Provider's Object — summary: a server-side copy of an object an outside service keeps, such as a subscription at a payment provider; when that service says the object changed, asking it for the object instead of trusting what it said; an associated mirror merged by a retried transition; signalling from the webhook, the customer's return and the shop's own change; announcing only what changed; a copy that refuses older reads; expiry as a date.
  16. A Wallet and Its Ledger — summary: a stored balance in an associated entity;
    credit
    as a
    once
    transition and
    debit
    keyed by what it is for, both with
    concurrency: retry
    ; a guard; trailers that say what moved; ledger lines derived from the wallet's event under
    id:VERSION
    ; a unique index; corrections as new lines.
  17. Taking a Payment, End to End — summary: a checkout started by a call; the result by webhook, by the customer's return and by a sweep, all ending in one record; consequences fanned out by events to the wallet, the ledger, the receipt and the page; which mechanism at each step; failures walked through; limits.
  18. A List That Stays Current — summary: a list in the client loaded with a collection stream and kept current by realtime events; never reading on an event, never asking a token on a timer; an endless list read a window at a time as the user scrolls; the newest hundred read with
    stop
    , and what changed since by the kept token when the client starts.
如何解决典型问题:何时使用 call、何时使用 event;重复、竞态和延迟消息对代码提出什么要求;以及如何拒绝请求。
  1. Call、Event 还是 Task — 摘要:选择的唯一规则;只使用 call 会出现什么问题;call、event 和 task 各自提供什么;场景对照表;同一 operation 在一条路径上被调用、在另一条路径上被接收。
  2. 在工作完成前返回 Reply — 摘要:存储所需内容并返回 reply;通过自定义 event 启动耗时部分;将结果和失败写入 state;告知客户端;为何不从 operation 启动 task。
  3. 值得订阅的 Event — 摘要:当某个事实变为 true 时触发的 condition;用于表达 state 无法说明内容的 trailers;作为契约的 payload;过滤和转换的 receiver;为何不应订阅
    updated
    。
  4. 同一条消息出现两次 — 摘要:消息为何会重复;在写入前读取并检查,可以单独执行,也可以在 key 下执行;对累积内容使用
    once
    及其记忆时长;在其他系统的 ID 下保存记录;在产生副作用的位置进行去重。
  5. 两个 Writer 同时操作 — 摘要:读取、检查、写入之间的竞态;使用
    concurrency: retry
    的单一 transition;将事实保存在一个 object 中;第二次运行会重复什么;由人员编辑的表单;何时应使用 lock。
  6. 消息乱序到达 — 摘要:为何到达顺序没有意义;携带 version 并跳过较旧消息;将 event 视为 signal 并向所有者查询;只向前移动的值;不要创建依赖关系。
  7. 拒绝请求 — 摘要:拒绝请求的五种方式及各自返回的内容;schema 和 route、guard、返回的 error、不写入的成功结果、exception;无人听到的拒绝;转发拒绝;在工作前拒绝并在完成后结算。
  8. 询问所有者,或保留副本 — 摘要:使用其他组件拥有的事实;向所有者发起 call 并保留规则;冻结答案;通过 receiver 保持副本最新;无需创建的 entity;在 counter 所在位置检查限制。
  9. 保留客户数据但不创建客户 Entity — 摘要:为何注册时创建的记录无法长期保存信息;使用客户 ID 标识的 entity;在任何事情发生前表示当前事实的 blank;哪些内容会消失;list 和 assignment 不会做什么;何时“存在”本身具有意义。
  10. 跨组件的 Process — 摘要:没有 transaction 的多步骤业务流程;每个阶段都有 status;响应 event 并回报进度;由流程所有者决定;将失败视为又一个步骤并进行补偿;重复、竞态、拒绝或永不结束的步骤。
  11. 预留 — 摘要:现在预留资金,之后提取或释放;按照 order 设置 key 的
    hold
    、
    settle
    和
    release
    ;在工作前询问并在完成后结算;延迟到达的 hold;用于校验总额的 guard;何时只需扣款后退款或事后扣款。
  12. 按时间处理工作 — 摘要:将 expiry 保存为 moment,并在使用时比较;在下次使用时续期的 counter;通过 pulse 扫描并按 state 选择内容;每个 object 独立的 delay;将副本与外部事实进行核对;发现已经停止的工作。
  13. 通往外部服务的 Gateway — 摘要:一个没有 entity 的组件,单独持有 provider 的 key;使用 application 自己的语言表达 operation 和 error;为“稍后重试”返回 error;key 为空时使用 stub;使用 composition 将 secret 限制在一个进程内。
  14. 接收 Webhook — 摘要:使用原始 body 的匿名 route;通过 call 验证签名;存储每条通知并宣告它;在派生的 ID 下为每个 provider object 保存一条记录;为何
    once
    并不足够;拒绝请求以便 provider 再次发送。
  15. 镜像 Provider 的 Object — 摘要:在服务端复制外部服务保存的 object,例如支付 provider 中的 subscription;当该服务表示 object 已变更时,主动向其请求 object,而不是直接信任其通知;通过重试的 transition 合并关联 mirror;来自 webhook、客户返回和商店自身变更的 signal;只宣告发生变化的 content;拒绝旧读取的副本;将 expiry 作为日期。
  16. Wallet 与 Ledger — 摘要:在关联 entity 中保存余额;将
    credit
    作为
    once
    transition,将
    debit
    按用途设置 key,两者都使用
    concurrency: retry
    ;guard;说明发生变化的 trailers;根据 wallet 的 event 派生 ledger 行,并使用
    id:VERSION
    ;唯一 index;通过新增行进行更正。
  17. 端到端完成支付 — 摘要:通过 call 启动 checkout;通过 webhook、客户返回和 sweep 获得结果,最终都写入同一条记录;通过 event 将后果分发给 wallet、ledger、receipt 和页面;每一步采用哪种机制;逐步分析失败;限制。
  18. 保持最新状态的 List — 摘要:客户端加载 collection stream 的 list,并通过 realtime event 保持最新;不因 event 而读取,也不使用定时器请求 token;用户滚动时每次读取一个 window 的无限列表;使用
    stop
    读取最新的一百条记录,并在客户端启动时通过保留的 token 获取此后发生的变化。