日本語

Actions

An action is a server endpoint a page calls with typed arguments. This page covers declaring one, calling it, and the request and the answer that go over the network.

Declaring an action

An Action<S, A = ()> is a server endpoint for the page whose signals are S, and it receives arguments of type A. Declare it on an action line of routes!, in the block that declares the pages, with its method, its path, and the handler that serves it: action LIKE: Action<Review> = post "/like" => like;. The method is post or get. The function the block generates registers each handler, so an action without a handler does not compile: routes! reports the form each line takes. A path that does not start with /, holds a {name} segment, or holds a byte the browser percent-encodes is a compile error too.

use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Review {
    likes: i32,
    stars: i32,
    comment: String,
}

hypersig::routes! {
    fn pages(Router<()>);
    // `Action<Review>` takes no arguments, because `A` defaults to `()`.
    action LIKE: Action<Review> = post "/like" => like;
    // Two values travel as a tuple.
    action RATE: Action<Review, (i32, String)> = post "/rate" => rate;
}

async fn like((): (), (): ()) -> Patches<Review> {
    Review::likes().patch(1).into()
}

async fn rate((): (), (stars, comment): (i32, String)) -> Patches<Review> {
    Review::stars()
        .patch(stars)
        .and(Review::comment().patch(comment))
        .into()
}

let app: axum::Router = pages(axum::Router::new());

A handler is async fn(state, args), or async fn(state, extractor, args) where the extractor implements axum's FromRequestParts for the router's state, such as a signed-in member read from a cookie. The arguments arrive deserialized into A. A handler that needs several values takes a tuple, which the page passes as a tuple of expressions. Extractors and headers covers the extractor.

Calling an action

call, fn call(&self) -> Call<S>, exists only on an Action<S, ()>. call_with, fn call_with(&self, args: impl IntoExpr<S, A>) -> Call<S>, takes the arguments as an expression, which the browser evaluates when the call runs. It can be a literal such as &id, a signal, or a tuple of either. The Call<S> it returns is a statement, so it goes wherever a statement goes: on_click, on_submit, on_load, or after then.

use hypersig::html::button;

let like = button::<Review>().on_click(LIKE.call()).text("Like");

// The browser reads both signals when the button is clicked.
let args = (Review::stars(), Review::comment());
let rate = button::<Review>().on_click(RATE.call_with(args)).text("Send");

The page never names the action's URL: the call takes its method and path from the Action constant, so the page and the router cannot disagree on them.

Arguments of the wrong type

An expression whose type is not A is a compile error, E0277. So is the call of an action declared for another page's signals, because a Call<Other> is not a statement on a page whose signals are Review. call() on an action that takes arguments is E0599, because the method does not exist there.

use hypersig::html::button;
use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Review {
    stars: i32,
    comment: String,
}

hypersig::routes! {
    fn pages(Router<()>);
    action RATE: Action<Review, (i32, String)> = post "/rate" => rate;
}

// error[E0277]: `Sig<Review, i32>` is not an expression of type `(i32, String)` on the page whose signals are `Review`
let send = button::<Review>().on_click(RATE.call_with(Review::stars()));

What the request carries

Each call is one fetch to the action's path, with the headers accept: text/event-stream and hypersig-call: 1. A POST sends the arguments as its JSON body with content-type: application/json, and an action without arguments sends the body null. A GET sends them as JSON in the args query parameter, and leaves the parameter out when there are none. A call made inside a component that is a Part adds the header hypersig-part. The browser's network tab shows these two requests for a rating and a search:

POST /rate
accept: text/event-stream
hypersig-call: 1
content-type: application/json

[5,"Lovely"]

GET /find?args=%22tea%22
accept: text/event-stream
hypersig-call: 1

Use get for a call that only reads, such as a search, and post for one that changes data. The two differ in the browser as well: only a POST marks its element aria-busy while it waits, and only for a POST are the late patches of an earlier call dropped, as Calls that overlap shows.

Action::request, fn request(&self, args: &A) -> Request<Body>, builds the request the browser sends, for a test that hands it to the router with oneshot, as on Testing handlers. It panics if args does not serialize to JSON.

use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Shop {
    results: Vec<String>,
    stars: i32,
}

hypersig::routes! {
    fn pages(Router<()>);
    action FIND: Action<Shop, String> = get "/find" => find;
    action RATE: Action<Shop, (i32, String)> = post "/rate" => rate;
}

// A `GET` carries the arguments as JSON in the `args` query parameter.
let find = FIND.request(&"tea".to_owned());
assert_eq!(find.method(), "GET");
assert_eq!(find.uri(), "/find?args=%22tea%22");
assert_eq!(find.headers()["accept"], "text/event-stream");
assert_eq!(find.headers()["hypersig-call"], "1");

// A `POST` carries them as its JSON body, here `[5,"Lovely"]`.
let rate = RATE.request(&(5, "Lovely".to_owned()));
assert_eq!(rate.method(), "POST");
assert_eq!(rate.uri(), "/rate");
assert_eq!(rate.headers()["content-type"], "application/json");

What the handler answers

A handler returns a type that implements IntoActionResponse<S>: Patches<S>, a SignalPatch<S>, a ListPatch<S>, a tuple of response parts and one of those, such as a header that sets a cookie, or a Result of one of those whose error implements IntoResponse. The answer is 200 with content-type: text/event-stream, and its body carries the patches in order. An Err answers with the error's own response, and a handler that panics answers 500 with an empty body. Patches covers the patches, and Errors and logging covers errors.

use axum::http::StatusCode;
use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Review {
    stars: i32,
}

hypersig::routes! {
    fn pages(Router<()>);
    action RATE: Action<Review, i32> = post "/rate" => rate;
}

// `Ok` answers 200 with the patches as an event stream, and `Err` answers
// its status with the text as a `text/plain` body.
async fn rate((): (), stars: i32) -> Result<Patches<Review>, (StatusCode, String)> {
    if !(1..=5).contains(&stars) {
        return Err((StatusCode::UNPROCESSABLE_ENTITY, "Pick 1 to 5 stars.".to_owned()));
    }
    Ok(Review::stars().patch(stars).into())
}

let answer = rate((), 4).await.ok().map(|patches| patches.value_of(Review::stars()));
assert_eq!(answer, Some(Some(4)));
assert!(rate((), 9).await.is_err());

A handler that returns anything else, such as the String it was given, is a compile error, E0277, at the routes! line that names it.

use hypersig::{Action, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Review {
    comment: String,
}

// error[E0277]: `String` is not a reply of an action on the page whose signals are `Review`
hypersig::routes! {
    fn pages(Router<()>);
    action EDIT: Action<Review, String> = post "/edit" => edit;
}

async fn edit((): (), comment: String) -> String {
    comment
}

Requests the router refuses

The router answers these requests itself, and the handler does not run. A request without Sec-Fetch-Site passes the check in the first row. Each body is one fixed sentence in text/plain, which the page receives as a failed call, as Busy and failed calls describes.

RequestStatusBody
Sec-Fetch-Site other than same-origin, so a page on another site, or on a sibling subdomain403the action was called from another site
A GET without hypersig-call, such as a link or an <img> pointed at the action403the call lacks the hypersig-call header the hypersig runtime adds
A POST whose content-type is not application/json, such as a plain HTML form415the action's body is not application/json
Arguments that do not deserialize into A400the action's arguments did not deserialize into its argument type
A hypersig-part header that is not a dotted field path400the call's part header is not a dotted field path

What actions leave unchecked

The type of A holds, and its values do not. The visitor's browser can send any value of A, whatever the page's expressions would compute, and anyone can call the action's URL without loading the page. A handler that guards the page does not guard its actions, so each handler checks that the visitor may act on the arguments it receives, such as the owner of an order whose id it takes. Security covers what the router checks for you.

The compiler checks that each action has a handler, and two mistakes stay unchecked. The first is a routes! block whose generated function the application never calls. Its pages answer 404, and each call to its actions, streams, and uploads gets a 404 with an empty body, which the browser writes to the console and error receives as a failed call. A call without error changes nothing on the page. rustc warns about a handler fn that only the uncalled function names, and not about a closure. The second is a page that calls an action of another block whose under names a different Base. The call goes to that block's prefix, which answers 404 unless the other block is served there too. Declaring every page and action in one block avoids both, because the application then calls one function and every line shares one base. A test that sends LIKE.request(&()) to the application's router with oneshot and expects a 200, as on Testing handlers, fails when the function is not called.

A complete example

This profile page saves a name with an argument and counts likes on the server. The save button is disabled while its call waits, the error text shows under the form, and the like count goes up before the server answers.

src/main.rs
use std::sync::Arc;
use std::sync::atomic::{AtomicI32, Ordering};

use axum::Router;
use hypersig::html::{attr, button, form, input, label, p, span};
use hypersig::{Action, Page, Patches, Route, RouterExt, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Profile {
    name: String,
    saving: bool,
    error: String,
    saved: String,
    likes: i32,
}

hypersig::routes! {
    fn pages(Router<Likes>);
    const INDEX: Route = "/" => index;
    action SAVE: Action<Profile, String> = post "/save" => save;
    action LIKE: Action<Profile> = post "/like" => like;
}

#[derive(Clone, Default)]
struct Likes(Arc<AtomicI32>);

async fn index(likes: Likes, (): ()) -> Page<Profile> {
    let name = Profile::name();
    let saving = Profile::saving();
    let count = Profile::likes();
    let initial = Profile {
        name: String::new(),
        saving: false,
        error: String::new(),
        saved: String::new(),
        likes: likes.0.load(Ordering::Relaxed),
    };
    Page::new("Profile", initial)
        .child(
            form()
                .on_submit(
                    SAVE.call_with(name)
                        .indicator(saving)
                        .error(Profile::error()),
                )
                .child(label().text("Name ").child(input().bind(name)))
                .child(
                    button()
                        .attr(attr::TYPE, "submit")
                        .attr_when(attr::DISABLED, saving)
                        .text("Save"),
                )
                .child(p().bind_text(Profile::error()))
                .child(p().bind_text(Profile::saved())),
        )
        .child(
            button()
                // The count goes up at once, and the request follows.
                .on_click(count.set(count + 1).then(LIKE.call()))
                .text("Like ")
                .child(span().bind_text(count.to_text())),
        )
}

async fn save(_: Likes, name: String) -> Patches<Profile> {
    Profile::saved().patch(format!("Saved as {name}.")).into()
}

async fn like(likes: Likes, (): ()) -> Patches<Profile> {
    let total = likes.0.fetch_add(1, Ordering::Relaxed) + 1;
    Profile::likes().patch(total).into()
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let app = pages(Router::new())
        .hypersig_runtime()
        .with_state(Likes::default());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app).await
}
This program needs a server, so this site shows it as code. It is built by cargo test from site/examples/ in the repository.

Next, Busy and failed calls covers indicator and error, Optimistic updates covers the change before the call, and Patches covers what the handler sends back.