che-rest 0.3.4

Typed REST framework and project tooling for che-orm applications
Documentation

che-rest

Breaking v2 REST layer for che-orm applications. Current source version: 0.3.4.

The library targets che-orm 0.3. Database connection methods are async; REST viewsets and image actions support models with i64 or UUID primary keys.

The current v2 surface is the typed ORM2 CRUD router. A viewset builds its database-independent queryset in get_queryset; database access happens only when the queryset is materialized:

use che_rest::{CrudViewSet, Server};

let app = Server::new(state)
    .install(apps::installed_apps())
    .build()
    .await?;

The migration plan is documented in docs/ORM2_MIGRATION_PLAN.md.

The runnable CRUD example is available under examples/cli_fullstack. Apply its compiled migrations and create an administrator as described in its README, then start it:

cargo run --manifest-path examples/cli_fullstack/Cargo.toml

Offline synchronization

SyncViewSet and ModelSyncEndpoints add an authenticated journal per model. Writes use ordinary REST CRUD with conditional revisions and idempotency keys. ModelLogClient stores offline edits and immutable submitted requests in SQLite; RestModelTransport delivers them through HTTP. Run the two-device example:

cargo run --features sync-http --example model_sync

The example creates an offline record through ModelLogClient::save, then edits loaded models with client.database().save(&model).await?. The configured database captures those edits in the sync outbox. Database::save updates existing rows and returns Option<Model>; it never inserts a missing record. Use the returned model to retain refreshed managed fields. For a selected-field update of a stale object, use database.update::<Model>(id).set(...).execute().await? instead.

Applications can register a typed aggregate journal action and opt in with RestModelTransport::with_batched_changes() to download explicit per-model cursors in one request. Existing per-model endpoints and write identities remain unchanged; this does not create a global cursor or switch wire protocols.

See docs/model-sync.md for setup, migrations and access rules. The scoped pull/snapshot protocol and todo_sync example remain available for explicitly managed legacy clients.

For a desktop application, see the runnable Todo server and che-tauri client. It has a shared UUID model, separate frozen server/client migrations, offline SQLite edits, manual synchronization and conflict selection. Its independent Cargo workspace lives in che-tauri; root che-rest tests do not run it.

che-rest owns the protocol-2 HTTP transport and RestModelWrite DTO; che-sync owns durable state, outbox, receipts and merge through the generic ModelLogTransport interface. che-tauri/sync exposes that client as managed TauriSync and the che_model_sync invoke command. HTTP stays outside the ORM and sync crates. See Tauri setup and authentication.

Start a Project

Create a new runnable che-rest application:

cargo install che-rest --bin che-rest
che-rest startproject my_project --layout modular
cd my_project
cargo run --bin manage -- makemigrations --name initial
cargo run --bin manage -- migrate
cargo run

cargo-generate Template

The templates/project scaffold offers interactive project naming, optional authentication and single/modular layouts:

cargo install cargo-generate
cargo generate --path templates/project --no-workspace

See template setup and verification. This checkout prepares che-rest 0.3.4 with che-orm 0.3.3 and che-sync 0.1.3; select absolute local dependency paths until the new REST/sync versions are published. Empty paths select crates.io. When using local REST, select its matching local ORM too; mixing local and crates.io copies produces incompatible Model/ModelSerializer types.

When developing against local checkouts with the built-in project generator, point the generated project at them:

cargo run --bin manage -- startproject my_project \
  --che-rest-path /absolute/path/to/che-rest \
  --che-orm-path /absolute/path/to/che-orm --layout single
cd my_project
cargo run --bin manage -- makemigrations --name initial
cargo run --bin manage -- migrate
cargo run

The generated project includes app.toml, a server entrypoint, an apps::installed_apps() registry, and a local manage binary. Both layouts include a starter Task REST resource. single keeps its files in src/; modular puts them in src/apps/tasks/. Models use #[orm(app = super::APP_NAME)], sharing the prefix with AppModule::name(); Task's table is tasks_task. Create additional apps with:

cargo run --bin manage -- createapp users --model User
cargo run --bin manage -- makemigrations --name add_users
cargo run --bin manage -- migrate

Path overrides are useful for this repo layout:

../che-rest
../che-orm

Include the built-in auth module in the generated app registry:

cargo run --bin manage -- startproject my_project --with-auth

createapp and startapp are aliases. New modules are installed automatically and own an empty migration registry; the first migration is generated explicitly. The framework management backend is SQLite; changing the URL alone does not select PostgreSQL.

A complete runnable example with CRUD, authentication, WebSocket signals, internal channels, TypeScript generation, and Vue admin generation is available in examples/cli_fullstack.

For a minimal SQLite todo API, see the step-by-step Todo API From Scratch tutorial.

Management

Applications define one installed app list and use it for both the API server and management commands:

pub mod users;

use che_rest::InstalledApps;

pub fn installed_apps() -> InstalledApps {
    InstalledApps::new().add(users::module())
}

Common management commands:

cargo run --bin manage -- startapp tasks --model Task
cargo run --bin manage -- makemigrations
cargo run --bin manage -- migrate
cargo run --bin manage -- migrate status
cargo run --bin manage -- generate-ts
cargo run --bin manage -- generate-admin

OpenAPI is served by the running application at /api/openapi.json by default, and follows custom Server::api_prefix(...) values.

Server startup:

Server::build() prints a compact configuration banner by default: the configured server address, effective API/Swagger and OpenAPI URLs, installed apps, SQLite pool size, media root and session settings when auth is installed. Database URLs are omitted. The banner describes configuration; the application binds its own listener afterward. Disable it with .startup_banner(false) on Server.

let app = Server::new(state)
    .install(apps::installed_apps())
    .build()
    .await?;

Server startup does not create model tables. Generate and apply migrations before starting the server:

cargo run --bin manage -- makemigrations
cargo run --bin manage -- migrate

Image fields

Install che_rest::media::module() alongside auth to serve authenticated files under /api/media/{key} (or the configured API prefix). che_orm::ImageField is a TEXT-backed relative storage key, not a URL or a BLOB; Option<ImageField> is nullable. The field is always read-only in JSON writes, even without an explicit #[serializer(read_only)]. Register an image action once in the owning ViewSet; che-rest then creates the upload/replace and clear endpoints:

use che_orm::ImageField;
use che_rest::media::{ImageFieldEndpoint, ImagePolicy};

// In the model: pub avatar: Option<ImageField>,
// In the ViewSet's configure():
config.image_field(ImageFieldEndpoint::<Self>::new(
    "avatar", User::AVATAR, |user| user.avatar.as_ref(),
    ImagePolicy::new("avatars", 10 * 1024 * 1024, 8192),
))?;

For a ViewSet registered at /users, this adds PUT and DELETE at /api/users/{id}/images/avatar/. PUT takes a multipart file and replaces the image; DELETE clears it. Both operations appear in OpenAPI and the generated TypeScript client (userApi.avatar.replace(id, file) and userApi.avatar.clear(id)). By default, the handlers use the ViewSet's permissions and object queryset. authorize, before, and write callbacks allow field-specific rules: a self-only avatar, a scene-version check held through saving, or additional model metadata. Async authorize adds restrictions to the ViewSet permission and receives the committing PermissionContext for its final check. It does not replace the ViewSet policy.

ImageCreateEndpoint similarly adds a multipart POST /api/{resource}/upload/ for images that are new records, such as attachments. Its application callback validates extra form fields and creates domain links; on failure the framework removes the new file. The generated client sends optional extra fields as Record<string, string | Blob>. Neither form accepts a storage key from the client.

The media service's read_image_field limits multipart parts; ImageStorage::save checks the actual JPEG/PNG/GIF/WebP format, decodes the image and enforces byte and dimension limits. An ImagePolicy::thumbnail(max_dimension) re-encodes a bounded PNG. Without it, the validated original bytes are retained (including animated GIFs). replace writes a new file, compares the previously read image key with the current database key, then updates the model. A stale write returns 409 and discards its new file. The write callback can include related metadata such as the avatar URL, MIME type and size in that same conditional database update. clear uses the same check. Application callbacks remain responsible for domain-specific checks such as diagram revision matching; they do not implement the HTTP upload flow.

JSON responses serialize ImageField as its storage key. generate-ts emits string | null for nullable image fields, and generated admin metadata marks them as images. A browser can form an image URL using the configured API base plus /media/ and the returned key. A ViewSet can register ImageCleanup in configure() to remove the file after a direct ViewSet deletion. An async prepare_delete_async hook can collect keys before a parent record cascades; after_delete then removes them. Post-commit failures are queued in .pending-image-deletions and retried on startup or later uploads: a committed DELETE must not return 500 because file cleanup failed. Raw SQL deletes do not run ViewSet hooks and need separate orphan cleanup. With no [media] section, the storage root is uploads. To override it in app.toml:

[media]
root = "/var/lib/my-app/uploads"

Back up this directory separately from the SQLite database.

The generated app.toml also configures the listener and API prefix:

[server]
host = "127.0.0.1"
port = 3000
api_prefix = "/api"

The application entrypoint reads these values, so changing the bind address, port, or API prefix does not require editing Rust code.

Installed app routes are served under /api by default. A viewset registered as "/users" is exposed as /api/users. Swagger UI is exposed at /api/ and the OpenAPI JSON schema at /api/openapi.json.

Writable foreign-key fields can be exposed separately from nested read-only output. Use #[serializer(foreign_key = User, relation = TaskAssigneeRelation)] on a scalar Option<i64> field. The generated admin uses an async relation selector, while nested fields such as Task.author remain read-only response data.

Typed ViewSets

Generated and custom viewsets use associated types for their detail/write serializer, list serializer, queryset, filters, and permissions:

use che_rest::{AllowAny, Filter, FilterSetSpec, Model, ViewSet};

#[derive(che_orm::ModelSerializer, serde::Serialize)]
#[serializer(model = Task)]
pub struct TaskSerializer {
    pub id: i64,
    pub name: String,
    pub completed: bool,
}

#[derive(Clone, Copy, Default)]
pub struct TaskFilterSet;

impl FilterSetSpec for TaskFilterSet {
    type Model = Task;

    fn filters(&self) -> &'static [Filter] {
        TASK_FILTERS
    }
}

#[derive(Clone, Copy, Default)]
pub struct TaskViewSet;

#[che_rest::async_trait]
impl ViewSet for TaskViewSet {
    type Model = Task;
    type Serializer = TaskSerializer;
    type ListSerializer = Self::Serializer;
    type QuerySet = che_orm::DatabaseQuery<Task>;
    type FilterSet = TaskFilterSet;
    type Permission = AllowAny;

    fn get_queryset(&self) -> Self::QuerySet {
        che_orm::DatabaseQuery::new(Task::query())
    }

    fn path(&self) -> &'static str {
        "/tasks"
    }
}

Register a typed viewset with viewset_with; it uses ViewSet::path() for the router, model schema, and API metadata:

ctx.viewset_with(TaskViewSet);

ListSerializer is required on every ViewSet. Set it to Self::Serializer when list and detail responses have the same fields. To return fewer fields from the list, derive a separate ModelSerializer for the same model and use it instead:

#[derive(che_orm::ModelSerializer)]
#[serializer(model = Task)]
pub struct TaskListSerializer {
    #[serializer(read_only)]
    pub id: i64,
    #[serializer(read_only)]
    pub name: String,
}

impl ViewSet for TaskViewSet {
    type Model = Task;
    type Serializer = TaskSerializer;
    type ListSerializer = TaskListSerializer;
    // QuerySet, FilterSet, Permission, get_queryset, and path as above.
}

Both serializers must accept the queryset's item type. GET /tasks/ uses ListSerializer; GET /tasks/{id}/ and write responses use Serializer. OpenAPI describes separate list-item and detail schemas. generate-ts gives list() a distinct TaskListItem result type when the fields differ, while retrieve() retains Task. The generated admin uses list fields for table columns and detail fields for forms. Regenerate the clients after changing either serializer.

FilterSetSpec types must implement Default. Built-in permissions include AllowAny, IsAuthenticated, and IsAdminUser. Custom permissions are asynchronous and receive PermissionContext; scope restricts SQL before pagination, and write checks use the committing transaction.

For groups and typed per-object grants, use auth::access::Access<Model>. See access control and run cargo run --example object_permissions. Object ACLs support ordinary REST and image actions. Opt-in protocol 3 adds shared-object synchronization with grants, revocations and retained offline drafts: see object sync and the shared mode of the Todo example. Relation inheritance and recipient-aware signals remain future work.

The Model derive generates compile-time-safe field constants on the model type. Use those constants when declaring filters:

static TASK_FILTERS: &[Filter<Task>] = &[
    Filter::exact(Task::COMPLETED),
    Filter::contains(Task::NAME),
    Filter::gte(Task::CREATED_AT),
];

The model type is part of Filter<M>, so a filter for one model cannot be accidentally used in another model's FilterSet. Filter::exact_as("assignee", Task::ASSIGNEE_ID) can be used when the public query name should differ from the database field name. Query builders also accept typed fields directly:

Task::query()
    .filter(Task::COMPLETED.eq(false))
    .all(database)
    .await?;

Relations use serializer attributes with generated ORM2 relation markers:

#[serializer(one = User, relation = TaskAuthorRelation)]
pub author: UserSerializer,

Fields populated by the server should be read-only in the serializer and assigned in the viewset's write preparation hook:

impl ViewSet for TaskViewSet {
    type Model = Task;
    type Serializer = TaskSerializer;
    type ListSerializer = Self::Serializer;
    type QuerySet = che_orm::DatabaseQuery<Task>;
    type FilterSet = che_rest::FilterSet<Task>;
    type Permission = IsAuthenticated;

    fn prepare_create(
        &self,
        _state: &che_rest::AppState,
        current: Option<&che_rest::CurrentPrincipal>,
        write: che_rest::ValidatedWrite<Self::Model>,
    ) -> che_rest::AppResult<che_rest::ValidatedWrite<Self::Model>> {
        let user = current
            .map(che_rest::CurrentPrincipal::auth_user)
            .ok_or_else(|| che_rest::AppError::Unauthorized("authentication required".into()))?;
        Ok(write.set(Task::AUTHOR_ID, user.id))
    }
}

Breaking API Changes

ORM writes use generated field descriptors: use .set(Task::NAME, value) instead of string field names. Serializer validation returns ValidatedWrite; viewset prepare_* hooks can add server-owned fields before ValidatedWrite::save(database) persists the change.

Auth

che-rest includes an optional auth app. Install it to resolve token credentials and add a request-scoped CurrentPrincipal to request extensions. Its auth_user() is always the built-in framework user:

pub fn installed_apps() -> InstalledApps {
    InstalledApps::new()
        .add(che_rest::auth::module())
        .add(users::module())
}

Create the first superuser:

cargo run --bin manage -- migrate

Then create the first superuser:

cargo run --bin manage -- createsuperuser \
  --username admin \
  --password secret

The command reads app.toml by default. Use --config path/to/app.toml to select another configuration file. The auth users table must exist before running the command.

Get a token with the Django REST Framework compatible endpoint:

curl -X POST http://127.0.0.1:3000/api-token-auth/ \
  -H 'Content-Type: application/json' \
  -d '{"username":"admin","password":"secret"}'

Use the returned token for API requests:

Authorization: Token <token>

Authentication is optional at the middleware level. Protect a typed viewset by selecting type Permission = IsAuthenticated; unauthenticated requests then receive 401. Use AllowAny for public viewsets and IsAdminUser for administrator-only viewsets.

Application User

Applications can define one domain profile model related to auth::User. Configure an async resolver when the application state is created; the resolved model is stored only on the current request.

#[derive(Debug, Clone, che_orm::Model)]
pub struct Profile {
    #[orm(primary_key)]
    pub id: i64,
    #[orm(foreign_key = che_rest::auth::User, unique)]
    pub user_id: i64,
    pub organization_id: i64,
}

pub async fn resolve_profile(
    state: &AppState,
    user: &che_rest::auth::User,
) -> AppResult<Option<Profile>> {
    state
        .database()
        .query::<Profile>()
        .filter(Profile::USER_ID.eq(user.id))
        .first(state.database())
        .await
        .map_err(Into::into)
}

let state = AppState::from_config_file("app.toml")
    .await?
    .with_current_user_resolver(|state, user| Box::pin(resolve_profile(state, user)));

Keep the type recovery and the authorization error in one application function:

pub fn current_profile(current: Option<&CurrentPrincipal>) -> AppResult<&Profile> {
    let current = current.ok_or_else(|| AppError::Unauthorized("authentication required".into()))?;
    current
        .app::<Profile>()
        .ok_or_else(|| AppError::Forbidden("profile required".into()))
}

Viewsets and permissions then only call that function:

let profile = profiles::current_profile(current)?;

Profile is never part of che-rest; it is defined and resolved by the application. If the resolver returns None, the request remains framework-authenticated; only application code that calls current_profile requires a profile.

Generate the typed TypeScript client from installed app metadata:

cargo run --bin manage -- generate-ts --out frontend/client/src/generated

The generator writes api_client.ts, channels.ts, models.ts, api.ts, useModelList.ts, and useModelItem.ts; it also writes auth.ts when the auth app is installed. It does not scan Rust source files or require the HTTP server to be running.

Generated TypeScript clients expose setAuthToken(token) in api_client.ts. create and update return Model | null: successful writes without view permission have an empty response body, normalized to null. Regenerate clients after updating this authorization surface.

WebSocket Signals

Install the channel module. The WebSocket endpoint is available at /api/ws/ under the configured API prefix:

pub fn installed_apps() -> InstalledApps {
    InstalledApps::new()
        .add(che_rest::auth::module())
        .add(che_rest::channels::module())
        .add(users::module())
}

WebSocket clients subscribe only to declared public signals. CRUD viewsets can opt in to lifecycle signals by overriding ViewSet::signal_access; the default names are <resource>.created, <resource>.updated, and <resource>.deleted. The default lifecycle payload is { "id": <primary key> }; clients that need current object data should reload it through the REST endpoint, so viewset permissions still apply. Nested resource names use dots, for example /auth/users maps to auth.users.created when lifecycle signals are enabled. Modules can declare additional signals in init:

fn init(&self, ctx: &mut che_rest::ModuleContext) {
    ctx.signal("chat.message.created", che_rest::SignalAccess::Authenticated);
}

Publish a declared signal with:

state.signals().publish("chat.message.created", serde_json::json!({ "id": 42 }));

Modules can create separate internal application channels through AppState::app_channels(), which are never exposed to WebSocket clients:

let channels = state.app_channels().clone();
let app = Server::new(state)
    .install(apps::installed_apps())
    .build()
    .await?;

channels.publish("chat.message.created", serde_json::json!({ "id": 42 }));

Modules subscribe to internal channels in subscribe, before any module start hooks publish initial events. Both hooks run after the database schema is ready:

pub struct Notifications;

impl che_rest::AppModule for Notifications {
    fn name(&self) -> &'static str { "notifications" }

    fn init(&self, _ctx: &mut che_rest::ModuleContext) {}

    fn subscribe(&self, state: &che_rest::AppState) {
        let mut events = state.app_channels().subscribe("chat.message.created");
        tokio::spawn(async move {
            loop {
                match events.recv().await {
                    Ok(event) => {
                        // Send notifications, update counters, or write audit records.
                        println!("notification event: {event}");
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(count)) => {
                        eprintln!("resync notification channel, dropped {count} events");
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                }
            }
        });
    }

    fn start(&self, state: &che_rest::AppState) {
        state.app_channels().publish(
            "chat.message.created",
            serde_json::json!({ "kind": "startup" }),
        );
    }
}

Application channels use bounded broadcast queues. A slow subscriber receives Lagged and should resynchronize as needed. They are only available inside the server process.

Internal events can have multiple handlers; all of them run in independent application-channel subscriptions. Public WebSocket signals are independent from internal application channels.

Connections must be authenticated. Non-browser clients can provide Authorization: Token <token> during the WebSocket upgrade. Browser WebSocket connections use the existing same-origin session cookie, because the browser API cannot attach an Authorization header.

The TypeScript generator creates channels.ts with a cookie-authenticated ChannelClient:

import { ChannelClient } from "./generated/channels";

const channels = new ChannelClient({
  onMessage: (event) => console.log(event.signal, event.payload),
  onError: (event) => console.error(event.code, event.detail),
});

await channels.connect();
channels.subscribe("orders.created");

The client derives /api/ws/ from VITE_API_BASE_URL, converting http to ws and https to wss. Browser cookies are sent automatically for same-origin connections.

Subscribe and unsubscribe using text JSON frames:

const socket = new WebSocket("ws://127.0.0.1:3000/api/ws/");

socket.addEventListener("open", () => {
  socket.send(JSON.stringify({ action: "subscribe", signal: "orders.created" }));
});

socket.addEventListener("message", ({ data }) => {
  console.log(JSON.parse(data));
  // { type: "signal", signal: "orders.created", payload: { id: 42 } }
});

Clients cannot subscribe to undeclared signals. Private user signals can be published with publish_user and use user:{id}:<signal> names; only that user can subscribe after the signal has been created by server-side publication. Signal names may contain ASCII letters, numbers, :, -, _, and .. The server confirms subscription changes with subscribed and unsubscribed messages.

This is in-memory pub/sub for one server process: messages are delivered only to currently connected clients, are not persisted, and do not cross process boundaries. A slow receiver receives a lagged error when messages are dropped; it does not receive a replay.

Cookie Sessions

Token authentication and cookie sessions can be enabled together. Sessions use an HttpOnly cookie and a readable CSRF cookie. For same-origin applications, add optional configuration:

[auth.session]
cookie_name = "che_rest_session"
csrf_cookie_name = "csrf_token"
ttl_seconds = 604800
renewal_window_seconds = 86400 # renew active sessions during their final day
absolute_ttl_seconds = 2592000 # require login again after 30 days
secure = false # set true when serving over HTTPS
same_site = "Lax"

Login with a session cookie:

curl -i -c cookies.txt -X POST http://127.0.0.1:3000/api-session-auth/login/ \
  -H 'Content-Type: application/json' \
  -d '{"username":"admin","password":"secret"}'

Unsafe requests made with a session must include the value from the csrf_token cookie in the X-CSRF-Token header. Token-authenticated requests do not require CSRF validation.

Project-local src/bin/manage.rs:

use che_rest::Management;
use simple_rest_demo::apps;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    Management::new(apps::installed_apps()).run().await
}

Create a new app module in src/apps/<name>:

cargo run --bin manage -- startapp taskapp

By default startapp creates one model from the app name. If the app name ends with app, that suffix is removed first, so taskapp creates model Task. Pass one or more --model options to generate specific models:

cargo run --bin manage -- startapp taskapp --model Task --model Comment

Generated tables use <app>_<model_snake_case> names, for example taskapp_task. Routes use the model snake-case without adding an s, for example /api/task/.

Generated files:

src/apps/
  mod.rs
  taskapp/
    mod.rs
    models.rs
    serializers.rs
    filters.rs
    views.rs

The generated serializers.rs, filters.rs, and views.rs use the typed API shown above; the app module registers each generated viewset with ctx.viewset_with(...).

Then add the app to apps::installed_apps():

InstalledApps::new().add(taskapp::module())

Create migrations for all installed apps. The optional positional value names the generated migration:

cargo run --bin manage -- makemigrations
cargo run --bin manage -- makemigrations add_users

Generate TypeScript models and API client from installed app metadata:

cargo run --bin manage -- generate-ts --out src/generated

This writes:

  src/generated/
    api_client.ts
    channels.ts
    models.ts
    api.ts
    useModelList.ts
    useModelItem.ts

The OpenAPI document describes CRUD routes registered with ModuleContext::viewset and viewset_with, including list filters, limit, offset, and ordering query parameters. A ViewSet can add reusable behavior through ViewSetExtension instances in ViewSet::configure(). Extension routes, OpenAPI operations, and generated TypeScript methods are registered from the same operation descriptors. The same schema is also served by running applications at /api/openapi.json, with Swagger UI available at /api/ by default.

Generate a standalone Vue admin project from installed app metadata:

cargo run --bin manage -- generate-admin --out frontend/admin
cd frontend/admin
npm install
npm run dev

This writes a Vite + Vue + Bootstrap project:

frontend/admin/
  package.json
  index.html
  vite.config.ts
  tsconfig.json
  .env.example
  src/
    main.ts
    App.vue
    router.ts
    admin/
      AdminApp.vue
      AdminLogin.vue
      AdminModelList.vue
      AdminModelTable.vue
      AdminModelForm.vue
      adminRoutes.ts
      admin.css
      adminSchema.ts
      components/
        GenericModelTable.vue
        GenericModelForm.vue
      pages/
        UserList.vue
        UserForm.vue
    generated/
      adminSchema.ts
      adminRoutes.ts
    generated/
      api_client.ts
      channels.ts
      models.ts
      api.ts
      useModelList.ts
      useModelItem.ts

The first run creates the full project and one editable list/form page pair for each model. Later runs update generated files and create missing model pages, but leave existing Vue, CSS, config, package, and model page files untouched so local admin customizations are preserved. Use --force to overwrite static project files from templates:

cargo run --bin manage -- generate-admin --out frontend/admin --force

The generated admin uses session-cookie authentication through /api-session-auth/login/ and requires che_rest::auth::module() to be installed. The generated Vite dev server proxies /api and /api-session-auth/ to http://127.0.0.1:3000 by default. Configure the backend target and relative API URLs with Vite env variables:

VITE_API_TARGET=http://127.0.0.1:3000
VITE_API_BASE_URL=/api
VITE_AUTH_URL=/api-session-auth/login/
VITE_LOGOUT_URL=/api-session-auth/logout/

Static files are copied from the framework's canonical admin templates. Dynamic files are regenerated from installed app metadata:

Canonical templates are stored in the repository under src/admin/templates/. Change those files when changing the framework default admin UI; examples/cli_fullstack/frontend/admin/ is generated output and is not the template source. src/admin/generated/adminSchema.ts, src/admin/generated/adminRoutes.ts, the compatibility shim src/admin/adminSchema.ts, and src/generated/*.

Per-model pages in src/admin/pages are generated as thin wrappers around the generic CRUD components. Customize those page files for model-specific fields, actions, and layout; they are not overwritten on later runs unless --force is passed.

Defaults:

--name auto

makemigrations compares installed app schemas with the compiled migration history and writes reviewable Rust migration modules under src/apps/<app>/migrations/. It does not invoke an external migration tool:

cargo run --bin manage -- makemigrations

Generated migrations are stored under:

src/apps/<app>/migrations/

The database URL is read from [database].url in app.toml. Apply all project migrations with the built-in forward-only SQLite executor:

cargo run --bin manage -- migrate

Do not create model tables from application startup; production servers only apply already-created SQL migrations.

Compiled forward-only migrations

Each app exposes AppModule::migrations() and a writable migration_path(); Management::new(apps) collects the histories automatically. Generated apps use concat!(env!("CARGO_MANIFEST_DIR"), "/src/apps/<app>/migrations") for their path, which is recompiled when the module moves to another project. Library apps omit the writable path. The default makemigrations command handles all writable apps; makemigrations tasks --name add_title targets one app.

Management::migrations(...) remains available for legacy explicit registries. When moving an existing registry into an app, retain migration IDs, dependencies, operations and checksums, and remove its duplicate registration from the old registry. An empty registry is valid before the first migration. Management has no SQL-file migration fallback.

Preview pending compiled migrations before applying them:

cargo run --bin manage -- migrate --plan --config app.toml

The plan lists migrations in dependency order, their dependencies and operations, and warnings for table/column deletion, column changes and manual SQL. It validates the registered graph, applied checksums, dependency history and historical state. SQLite is opened read-only; a missing database is treated as empty and is not created. No migrations or history records are written. The command requires a file database path (plain or sqlite://) and cannot be combined with a migrate subcommand. It previews compiled migrations; SQL execution and live-schema compatibility are checked when applying them. Rebuild after changing migration sources, and inspect RunSql source before applying manual SQL.

Inspect the SQLite SQL for one registered migration without opening a database:

cargo run --bin manage -- sqlmigrate tasks 0002_add_title

sqlmigrate rebuilds only the selected migration's dependency state in memory, then prints its SQLite statements. Declarative table changes therefore show the same create-copy-drop-rename SQL used by the executor. RunSql is printed as authored. The command requires compiled migrations and does not validate the live database schema or execute any statement.

List registered compiled migrations and their database status with:

cargo run --bin manage -- showmigrations
cargo run --bin manage -- showmigrations tasks

[X] marks a migration recorded in che_migration_history; [ ] marks a pending migration. Dependencies are listed beneath each migration. The command opens a file database only in read-only mode, treats a missing database as an empty history and never creates the history table.

Apply a selected application's forward migration target with:

cargo run --bin manage -- migrate tasks
cargo run --bin manage -- migrate tasks latest
cargo run --bin manage -- migrate tasks 0002_add_title

The first two forms select the application's single latest migration. The executor applies only that target and its missing dependencies, each in a separate atomic SQLite transaction; unrelated pending migrations are left untouched. A target already passed by a later migration in the same application is rejected because rollback is not supported. Unknown applications and migration names are also rejected before the database is opened.

When two reviewed branches create compatible heads for one application, create an empty merge migration with:

cargo run --bin manage -- makemigrations tasks --merge --name merge

The command accepts exactly two heads. It rebuilds their common historical state, replays the two branches in both orders, and creates a migration that depends on both heads only when the resulting declarative states agree. It rejects RunSql, conflicting operations, and three or more heads; resolve those with an explicit reviewed migration. Use --dry-run to inspect generated Rust before the file and registry are changed.

For example, generate an application's migration with:

cargo run --bin manage -- makemigrations tasks --name initial --dir src/apps/tasks/migrations

The writer creates m0001_initial.rs and a managed section of mod.rs containing module declarations and pub fn all() -> Vec<che_orm::Migration>. Declare the migrations module in the owning application and pass its collector to management:

Management::new(installed_apps())
    .migrations(tasks::migrations::all())
    .run()
    .await?;

For multiple applications, concatenate their all() results. Rebuild the management binary after generation. Existing handwritten mod.rs files must have // che-orm: migrations begin and // che-orm: migrations end markers; the writer owns the declarations and collector inside those markers. Keep handwritten code outside them, and avoid another all() in the same module.

--empty produces zero operations even when models differ from history. Normal generation rejects conflicting branches and cross-application references whose target table or field is not yet present in compiled migration history. Generate and register the target application's migration first. Operations are ordered and replayed in memory before writing; unsupported dependency sequences require an explicit migration.

When SQLite must rebuild a table, generated migrations temporarily drop and restore declared triggers and views that reference it, including objects owned by other applications. The definitions are taken from compiled migration history. Review the generated operations before applying them, and rebuild manage after generation.

Use makemigrations <app> --check in CI: it exits with an error when the installed models have changes without a compiled migration. Use --dry-run to print the prospective Rust source without changing files. Before either command creates a migration, it compares m000N_*.rs files with the compiled registry; if a prior generation has not been rebuilt yet, it stops and asks for a rebuild.

For a new project whose applications contain cyclic cross-application foreign keys, omit the app name and provide a directory that will contain one directory per application:

cargo run --bin manage -- makemigrations --dir src/apps

This empty-history batch mode writes each app's 0001_initial without the cross-application FKs, then writes 0002_relationships migrations that depend on both initial migrations. Rebuild after generation and combine each app's migrations::all() when constructing Management.

New migration files are created exclusively. Registry updates use a directory lock and atomic replacement. A competing writer fails without overwriting files. An interrupted process may leave .che-migrations.lock or .che-mod.rs.tmp; inspect the directory and confirm no writer is active before removing them.

Push notifications

Enable feature push to install the portable notifications application. It owns compiled migrations, authenticated device registration, durable checkpoints and outbox, retry/lease handling and FCM HTTP v1 delivery. It is independent of model sync and domain identifier types.

Applications implement PushSource for event capture and current recipient checks, install push::module(config, source) and explicitly call push::start after migrations and router build. Installing the module alone does not start sending. The Android SDK handler, account filtering and navigation remain client concerns.

See installation, event/client contracts and checks. Default checks do not cover this optional feature: run cargo test --all-features and cargo clippy --all-features --all-targets -- -D warnings for changes to it.