Restify for Laravel for Rust

Docs / Building

Actions and getters

operations beyond list, show, create, update and delete, such as publishing a post.

Introduction #

A repository's endpoints list, show, create, update and delete. Some operations are none of those, such as "publish these posts" or "count the posts". Write them as actions and getters. Restify serves each one at the same URLs as Restify for PHP, and as an MCP tool, with the same rules.

  • An action may write. It answers POST, and the client names it with ?action=.
  • A getter only reads. It takes no input. It answers GET, and its name is the last part of the path.
On the listOn one model
ActionPOST /api/restify/posts/actions?action=publish-posts-actionPOST /api/restify/posts/{id}/actions?action=publish-post-action
GetterGET /api/restify/posts/getters/statsGET /api/restify/posts/{id}/getters/word-count

/action works as well as /actions for running an action, as in PHP. GET /api/restify/posts/actions and its siblings list what a client may run: see The listings.

Both are written with one trait, restify::CustomAction<Post>, where Post is the repository's model. A repository serves none until it lists them, and each one refuses to run until its can_run method allows it.

Writing an action #

An action is a type that implements CustomAction. This one publishes the post in the URL:

use laravel::model::update;
use laravel::prelude::*;
use restify::{CustomAction, NoInput, Reply};

/// Publishes the post in the URL.
pub struct PublishPostAction;

impl CustomAction<Post> for PublishPostAction {
    const NAME: &'static str = "Publish Post Action";
    type Target = Post;
    type Input = NoInput;

    async fn can_run(_request: &Request, _post: Option<&Post>) -> laravel::Result<bool> {
        Ok(true)
    }

    async fn handle(_input: NoInput, _request: &Request, mut post: Post) -> laravel::Result<Reply> {
        update!(post { published_at: laravel::now() }).await?;

        Ok(Reply::message("Post published."))
    }
}

POST /api/restify/posts/2/actions?action=publish-post-action answers { "message": "Post published." }.

ItemRequiredDoes
const NAMEYesThe name the listings show, such as Publish Post Action. PHP writes the class name in words, so use the PHP class name when you port an action
const DESCRIPTIONNoWhat it does, for the listings and for AI agents. Write one: it's all an agent knows about the tool
const DESTRUCTIVENotrue for an action that destroys data, such as deleting. PHP's DestructiveAction
type TargetYesWhat handle gets: Post for an action on one model, Builder<Post> for one on the list or a standalone one
type InputYesThe input: a #[laravel::input] struct that derives Schema, or NoInput
fn uri_keyNoThe name in ?action=. Defaults to NAME in kebab-case: publish-post-action
fn can_seeNoWho sees it at all. Everyone by default
fn can_runIn practiceWho may run it. Refuses everyone by default
fn handleYesDoes the work and returns the answer

An input struct is written like a repository's Store struct: see Writing. It doesn't need fills, because handle decides what to write. It does need #[validate(authenticated)] or #[validate(anyone)], like every input. This one takes a format:

use restify::Schema;

/// What a client sends to export the posts.
#[laravel::input]
#[validate(authenticated)]
#[derive(Schema)]
pub struct Export {
    /// The file format: `csv` or `json`.
    #[validate(required, one_of("csv", "json"))]
    pub format: String,
}

Restify validates the input before it calls handle. A PHP action only validates when its handle calls $request->validate(..), so a PHP action that never does accepts anything.

Actions on the list #

An action on the list has type Target = Builder<Post>. The client sends the ids to run it on as repositories, or "all":

{ "repositories": [3, 5] }

handle gets the repository's query narrowed to those posts, newest key first, as PHP's ActionRequest::builder builds it. The query also has the request's own list parameters, such as ?search= or a filter, next to ?action=. Restify first asks can_run about each of those posts, and one refusal answers 403 before anything runs. The posts are read 200 at a time, like PHP's Action::$chunkCount, so "all" on a large table doesn't load the whole table into memory. Before any row is read, can_see is asked, so a hidden action loads nothing. can_run is never asked with None for an action on the list, because many actions refuse None, as this one does. To refuse a request before any row is read, use can_see. This one publishes the posts the user may update:

use laravel::db::Builder;
use serde_json::json;

/// Publishes the posts listed in `repositories`. Each must be one the user may update.
pub struct PublishPostsAction;

impl CustomAction<Post> for PublishPostsAction {
    const NAME: &'static str = "Publish Posts Action";
    type Target = Builder<Post>;
    type Input = NoInput;

    async fn can_run(request: &Request, post: Option<&Post>) -> laravel::Result<bool> {
        match post {
            Some(post) => request.can(PostPolicy::update, post).await,
            None => Ok(false),
        }
    }

    async fn handle(_input: NoInput, _request: &Request, posts: Builder<Post>) -> laravel::Result<Reply> {
        let ids = posts.pluck(Post::id).await?;
        update!(Post::query().filter(Post::id.is_in(ids.clone())) {
            published_at: laravel::now(),
        })
        .await?;

        Ok(Reply::data(json!({ "published": ids })))
    }
}

POST /api/restify/posts/actions?action=publish-posts-action with { "repositories": [3, 5] } answers { "data": { "published": [5, 3] } }. Without repositories, it answers 422 with "The repositories field is required."

An id that isn't a post's key, or one the repository's query leaves out, is skipped. PHP runs a long list in chunks of 200 and calls handle once for each chunk. Restify calls handle once with the whole query.

Every action runs in a database transaction, so an error in handle undoes what it wrote.

Standalone actions #

A standalone action runs on no post in particular, such as an export. It has type Target = Builder<Post> and is listed with Custom::standalone. It takes no repositories, and it shows up both on the list and on one model, as in PHP. handle gets the repository's query, narrowed only by Repository::query. can_run is asked once, with None:

/// Exports the titles of every post. It runs on no post in particular.
pub struct ExportPostsAction;

impl CustomAction<Post> for ExportPostsAction {
    const NAME: &'static str = "Export Posts Action";
    type Target = Builder<Post>;
    type Input = Export;

    async fn can_run(_request: &Request, _post: Option<&Post>) -> laravel::Result<bool> {
        Ok(true)
    }

    async fn handle(input: Export, _request: &Request, posts: Builder<Post>) -> laravel::Result<Reply> {
        let titles = posts.oldest(Post::id).pluck(Post::title).await?;

        Ok(Reply::data(json!({ "format": input.format, "titles": titles })))
    }
}

Who may see and run one #

Two methods decide, as PHP's canSee and canRun do:

  • can_see(request) decides whether the request sees the action at all. A hidden action is left out of the listings, and running it answers 403 with "You don't have permission to run this action." Everyone sees it by default.
  • can_run(request, model) decides whether the request may run it. The model is each post of repositories for an action on the list, the post in the URL for an action on one model, and None otherwise. A false answers 403 with "Not authorized to run this action." It refuses everyone by default, so write it for every action.

This destructive action is for admins only:

/// Deletes the posts listed in `repositories`. Only admins see it.
pub struct ArchivePostsAction;

impl CustomAction<Post> for ArchivePostsAction {
    const NAME: &'static str = "Archive Posts Action";
    const DESTRUCTIVE: bool = true;
    type Target = Builder<Post>;
    type Input = NoInput;

    async fn can_see(request: &Request) -> laravel::Result<bool> {
        is_admin(request).await
    }

    async fn can_run(_request: &Request, _post: Option<&Post>) -> laravel::Result<bool> {
        Ok(true)
    }

    // ...
}

Repository::authorize is asked for Action::AllowRestify first, as for every request to the repository. Nothing else of it is asked. In particular, the show policy of the post in the URL is not asked, as in PHP: a getter on one model also runs on a post the user can't see, if its can_run allows it. The post must still be in Repository::query for Action::Show. Safe setup: check the user in can_run, or keep the post out of query for that user.

What a handler answers #

handle returns a Reply: a status and a JSON body. Its constructors are PHP's helpers:

PHPRustBody
ok()Reply::ok()[]
ok('Post published.')Reply::message("Post published."){ "message": "Post published." }
data($value)Reply::data(value){ "data": value }
response()->json($body)Reply::json(body)body

Each answers 200. Add .status(StatusCode::ACCEPTED) for another status. A model goes in as serde_json::to_value(&post)?. It isn't a JSON:API resource then: a Post comes back as { "id": 1, "title": "..", ... }, without type and attributes.

Writing a getter #

A getter is written the same way, with type Input = NoInput. It only reads, so don't write in its handle. A getter on the list gets the repository's query, and can_run is asked with None. This one counts the posts:

/// Counts the posts, the published ones, and their votes.
pub struct PostStatsGetter;

impl CustomAction<Post> for PostStatsGetter {
    const NAME: &'static str = "Post Stats Getter";
    type Target = Builder<Post>;
    type Input = NoInput;

    fn uri_key() -> String {
        "stats".to_owned()
    }

    async fn can_run(_request: &Request, _post: Option<&Post>) -> laravel::Result<bool> {
        Ok(true)
    }

    async fn handle(_input: NoInput, _request: &Request, posts: Builder<Post>) -> laravel::Result<Reply> {
        let total = posts.count().await?;
        let published = posts.clone().filter(Post::published_at.is_not_null()).count().await?;
        let votes: Option<i64> = posts.sum(Post::votes).await?;

        Ok(Reply::json(json!({
            "data": { "total": total, "published": published, "votes": votes.unwrap_or(0) },
        })))
    }
}

GET /api/restify/posts/getters/stats answers { "data": { "total": 7, "published": 5, "votes": 95 } }. A getter ignores the list parameters, so ?featured=true changes nothing. A getter on one model has type Target = Post, like an action on one model.

A getter with an input other than NoInput stops the application from starting, because a GET request has no body to send it in. Make it an action instead.

Listing them in the repository #

A repository serves the actions it lists in actions and the getters it lists in getters. Where each one is listed decides which URLs run it:

RustPHPRuns atTarget
Custom::index_and_show::<A>()Nothing: PHP's defaultThe list, where an action takes repositories, and one modelBuilder<Post>
Custom::index::<A>()->onlyOnIndex()The list. An action takes repositoriesBuilder<Post>
Custom::show::<A>()->onlyOnShow()One modelPost
Custom::standalone::<A>()->standalone()The list and one model. No repositoriesBuilder<Post>
use restify::Custom;

impl Repository for PostRepository {
    // ...

    fn actions() -> Vec<Custom<Post>> {
        vec![
            Custom::index::<PublishPostsAction>(),
            Custom::show::<PublishPostAction>(),
            Custom::standalone::<ExportPostsAction>(),
            Custom::index::<ArchivePostsAction>(),
        ]
    }

    fn getters() -> Vec<Custom<Post>> {
        vec![
            Custom::index::<PostStatsGetter>(),
            Custom::show::<PostWordCountGetter>(),
        ]
    }
}

Custom::show needs type Target = Post, and the others type Target = Builder<Post>. The compiler says so when they don't match.

A PHP action or getter that calls none of onlyOnIndex, onlyOnShow and standalone is offered on the list and on each model. Custom::index_and_show does the same with one type. On the list it works like Custom::index. On one model, such as POST /api/restify/posts/4/actions?action=publish, it asks can_run about that post, and handle gets the query narrowed to it. Its MCP tool takes repositories, as PHP's tool does. restify:import writes Custom::index_and_show for such a PHP action.

A getter in both places gets that narrowed query on one model too, such as GET /api/restify/posts/4/getters/stats. PHP's getter gets no query there, so when its handle counts with its own Post::query(), it counts every post on both URLs. To answer the same, start a new Post::query() in handle instead of counting with the query it gets.

Keep small actions in the model's file, next to the repository. When there are several, move them to a file of their own, such as src/models/post_actions.rs, and re-export them from src/models/mod.rs.

Each key must be kebab-case and unique among a repository's actions, and among its getters. Otherwise the application refuses to start and says which one to change.

The listings #

Four GET requests list what a request sees, without what can_see hides:

RequestLists
GET /api/restify/posts/actionsThe actions on the list, those on the list and one model, and the standalone ones
GET /api/restify/posts/{id}/actionsThe actions on one model, those on the list and one model, and the standalone ones
GET /api/restify/posts/gettersThe getters on the list, and those on the list and one model
GET /api/restify/posts/{id}/gettersThe getters on one model, and those on the list and one model

With an {id}, a missing model answers 404. An action is listed as PHP's Action::jsonSerialize writes it:

{ "data": [
    { "name": "Export Posts Action", "description": "", "destructive": false, "uriKey": "export-posts-action",
      "payload": { "format": ["required", "in:csv,json"] } }
] }

payload is the input's #[validate(..)] rules as Laravel writes them: one_of becomes in, max_length and max_value become max, min_length and min_value become min, and the others keep their names. A rule with its own message, such as required.message(".."), is listed by its name alone, required. It is [] when the input has no rules. A getter is listed as { "name": "Post Stats Getter", "uriKey": "stats" }.

Errors #

Restify runs the steps in PHP's order, and stops at the first that fails:

StatusMessageWhen
403The repository'sRepository::authorize refused Action::AllowRestify
404No query results for model ..The URL has an {id} and no post has it, or the repository's query leaves it out
404Action not found. or Getter not found.Nothing listed there has the key, or ?action= is missing
403You don't have permission to run this action. (or getter)can_see hides it
422The repositories field is required.An action on the list without repositories. null, "" and [] count as missing
403Not authorized to run this action. (or getter)can_run refused one of the posts, or refused with None
422The input'sThe input is invalid

The MCP tools #

When the repository's const MCP allows actions or getters, each one is a tool too. It is named after the repository, the key and the kind, as in Restify for PHP: posts-publish-posts-action-action-tool, posts-export-posts-action-action-tool, posts-stats-getter-tool and posts-word-count-getter-tool.

  • A tool on one model takes an id, next to the input's fields.
  • An action on the list takes the ids in repositories. Its schema asks for resources, as PHP's does, but the tool ignores that argument.
  • A getter's tool is marked readOnlyHint. An action's is marked openWorldHint, and destructiveHint is its DESTRUCTIVE: true or false. PHP leaves destructiveHint out, which agents read as true.
  • A user whose can_see refuses the action doesn't get its tool.

The tool runs the same code as the endpoint. It returns { "success": true, "action": "publish-posts-action", "result": { ... } }, with the body handle answered as result. When can_run refuses, it returns { "error": "...", "action": "publish-posts-action" } instead. See MCP. laravel restify:list shows each one with its endpoint and its tool.