ReferencePeople and webhooks

Language specification

Runtime

Guides

Background

The Flow Book

People and webhooks

On this page

Your program needs a person's approval before it refunds an order, and the answer may take hours. To Flow, asking a person is a Tool call like any other that takes a while to answer. Below, a library asks a finance team on Slack to approve a refund. A webhook brings the answer back, and a check every ten minutes catches an answer the webhook missed.

Ask, with a deadline

The program calls the Tool like any other. When it must not wait forever, it races the call against a timer. The program sets the deadline; the library and the host don't (concurrency):

// finance/contract/lib.flow declares://   pub type Refund { pub order: Text, pub cents: Int }//   pub type Approval { Approved, Rejected { note: Text } }//   pub flow approve(refund: Refund) -> Approvaluse "std@v1/task"use "std@v1/time"use "std@v1/duration"use "./finance"type Waited { Answered(Result<finance.Approval, ToolProblem>), Expired(Result<Unit, ToolProblem>) }flow approved(refund: finance.Refund) -> Bool = {    let answer = task.spawn(flow() = Answered(finance.approve(refund)))    let timer = task.spawn(flow() = Expired(time.sleep(duration.seconds(48 * 3600))))    match task.first([answer, timer]) {        Answered(Ok(Approved)) => true,        _ => false,    }}
Open snippet in Playground (new tab) ↗

When the timer wins, approved returns false. Flow stops the losing task and closes its call to finance.approve, and nobody can answer that call afterwards.

Hold the call in the library

The Tool posts the question and holds, which promises an answer later. The program sees nothing yet, and the call stays open (history).

from datetime import datetime, timedelta, timezonefrom flow_toolkit import tool, context, Hold@tooldef approve(refund: Refund) -> Approval:    """Ask the finance team to approve a refund."""    ctx = context()    key = str(ctx.key)                     # the call's key as text    if ctx.cancelled:                      # the program stopped waiting        slack.mark_expired(key)        return Rejected("expired")         # discarded; the call is closed    decision = decisions.get(key)          # written by the webhook receiver    if decision is not None:        return decision    if not slack.posted(key):        slack.post(f"Approve a refund of {refund.cents} on {refund.order}?",                   callback_id=key)    raise Hold(retry_at=datetime.now(timezone.utc) + timedelta(minutes=10))
  • The key is the address. context().key names this one call and never changes; str(context().key) is its text form (abi). The question carries it as its callback id, so the answer can find its way back.
  • Expect to be asked again. A hold tells the host that asking again is safe, and every re-ask carries the same key. The host asks at the retry_at you give and once each time the run is resumed, so checking slack.posted(key) before posting keeps a re-ask from posting the question twice.
  • Let the webhook answer first. A webhook's reply answers the call at any time. Hold(retry_at=...) has the host call approve again at that time, which catches a webhook that was lost, for example because the laptop running the host was asleep. With Hold() and no time, the call is asked again only when the run is resumed.
  • Withdraw the question. When the program closes the call, by a deadline or a stopped task, the host calls the function once more with context().cancelled set and the original arguments, so the library can mark the question expired. The host discards what it returns then.

Reply from the webhook

The receiver that Slack calls answers the call by its key, with the toolkit's reply, from any process on the machine that runs the host:

from flow_toolkit import replydef on_click(payload):    answer = Approved() if payload["action"] == "approve" else Rejected(payload["note"])    decisions.put(payload["callback_id"], answer)     # for the re-ask, too    result = reply(payload["callback_id"], answer)    if result.already_answered and not result.same:        return "This request has expired."    return "Thanks."

A reply is ok, already answered, or a type error (history). Slack retries a receiver, so on_click treats an answer it already gave (same) as success and tells the person anything else has expired. A waiting run continues on ok; a stopped run gets the answer at the next flow resume (execution).

A run the host doesn't know, or a host it can't reach, raises an error instead. The run keeps the first answer it records, whether that is the webhook's reply or the library's own answer at a re-ask, so the two never conflict.

reply goes to the socket in the receiver's FLOW_REPLY_SOCKET, or to the one you pass it (reply(key, value, socket=path) in Python, reply_at(path, key, value) in Rust), and looks nowhere else: with neither it raises an error naming FLOW_REPLY_SOCKET. A Tool the host started already has the variable set. A receiver you start yourself takes the daemon's socket from flow daemon status, run with the same FLOW_HOME:

export FLOW_REPLY_SOCKET="$(flow daemon status --json | jq -r .data.socket)"

The daemon answers only the runs its home keeps, in FLOW_HOME/runs: a run kept under another FLOW_HOME is one it does not hold. When a reply gets no result, the daemon's reason is in FLOW_HOME/daemon.log.

Reply from another machine

reply reaches the host on the same machine. A receiver that lives elsewhere, such as an always-on web server, writes the decision by key to a store the library can read, and the next re-ask finds it and answers. That is why approve checks decisions before it posts. The key is the only thing the two share.

Ask a person at this machine

Every answer from outside a run comes in through the Tool that asked; the flow command has no way to answer a call. When the person sits at the machine that runs the host, the first-party people library is the channel, and needs no service:

use "github.com/buttercrab/flow@v1/libraries/people/people"flow approve(refund: Refund) -> Result<Approval, ToolProblem> =    people.ask(people.Person("finance"), "Approve a refund of ${refund.cents} on ${refund.order}?")
Open snippet in Playground (new tab) ↗

people.ask<T> writes the question, its call's key and the JSON Schema of the T the program chose into an inbox, FLOW_QUESTIONS or questions in FLOW_HOME, and holds the call. The person answers with the library's own command, outside flow. flow-people is built from the library's own crate and is not part of a release. Install it with Cargo, from a checkout with cargo install --path libraries/people --bin flow-people or without one with cargo install --git https://github.com/buttercrab/flow flow-lib-people --bin flow-people:

flow-people listflow-people answer 7f3a91c04be2d5e6f708192a3b4c5d6e/root/1#1 'Rejected { note: "over the monthly limit" }'flow resume 7f3a91c04be2

Set FLOW_REPLY_SOCKET to the socket flow daemon status --json reports. flow-people answer sends Flow notation with reply_text, and the host reads it at the call's type. A Text answer is raw text, quotes included. It replies by the key, as the webhook above does, so it gets the same three results: an answer that is not an Approval is refused and the question stays in the inbox, and a call already answered or closed takes nothing. Like any toolkit reply it reaches only the runs FLOW_HOME/runs keeps. flow runs lists each run's open calls, whether each is held, and when it will next be asked (the flow command).

Add a channel

Slack, email or a web form is a channel of your application, not of Flow. Add one by writing a Tool the way finance.approve is written above: post the question with the call's key, hold, and have the receiver reply by the key. To move a program that asks through people.ask onto your channel, bind your implementation to people.ask (embedding); the program and its types stay as they are. A receiver on another machine stores the answer by key for the next re-ask instead, as Reply from another machine describes.

Test the deadline

In a test, a fake stands in for finance.approve. A fake that calls test.hold() leaves its call open, as Hold() does, and the test's virtual clock lets the timer win at once. So the test covers the deadline branch without waiting 48 hours (execution).

Exact rules: open calls, holds and replies, asking again and replies, the toolkit's Hold, context() and reply.