zeyn 0.0.3

Rust web framework for data heavy applications, written by AI agents and reviewed by people
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use crate::ctx::{BoxFuture, Ctx, Dep};
use crate::i18n::Text;
use crate::model::ValidationErrors;
use crate::value::Value;
use serde::{Deserialize, Serialize};
use std::fmt;

/// Who may call an action or open a screen.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type", content = "permission", rename_all = "snake_case")]
pub enum Access {
    Public,
    Permission(&'static str),
}

/// Action definition generated by `#[action]`.
#[derive(Clone, Copy, Debug, Serialize)]
pub struct ActionMeta {
    pub name: &'static str,
    pub access: Access,
    pub audit: bool,
    /// The user must have signed in recently (see `App::reauth_within`) to call it.
    pub reauth: bool,
    /// First paragraph of the action's `///` doc comment. AI tools use it as their description.
    pub doc: &'static str,
    /// What AI models may do with it, from `ai = "..."`, `ai = false` and `confirm`.
    pub ai: Ai,
}

/// AI policy of an action or a screen, set with `#[action(ai = "...")]`, `ai = false` and
/// `confirm`. It applies to every way a model reaches the app: the MCP endpoint, WebMCP tools in
/// the browser and the built in assistant.
///
/// ```
/// use zeyn::prelude::*;
///
/// /// Archives a product. It stays in reports but cannot be sold.
/// #[action(permission = "stock.product.write", ai = "Ask for the product code first.", confirm)]
/// pub async fn archive_product(_code: String) -> Result<()> { Ok(()) }
///
/// let meta = <archive_product as Action>::META;
/// assert_eq!(meta.doc, "Archives a product. It stays in reports but cannot be sold.");
/// assert!(meta.ai.offered && meta.ai.confirm);
/// assert_eq!(meta.ai.hint, "Ask for the product code first.");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct Ai {
    /// `false` (from `ai = false`): never offered to any model.
    pub offered: bool,
    /// Extra guidance for models, added to the tool description.
    pub hint: &'static str,
    /// A model may call it only after the user confirms in the app's UI.
    pub confirm: bool,
}

impl Ai {
    /// Offered to models, no extra guidance, no confirmation beyond what writes need.
    pub const DEFAULT: Ai = Ai { offered: true, hint: "", confirm: false };
}

impl Default for Ai {
    fn default() -> Self {
        Ai::DEFAULT
    }
}

/// A server side action. Generated by `#[action]`, never written by hand.
pub trait Action: Copy + Send + Sync + 'static {
    type Input: Send + 'static;
    type Output: Send + 'static;
    const META: ActionMeta;

    /// Services the action needs; checked when the app starts.
    fn deps() -> Vec<Dep>;

    /// Runs the action with injected arguments. Access is checked by the caller.
    fn call(ctx: Ctx, input: Self::Input) -> BoxFuture<Result<Self::Output>>;
}

/// Zeyn errors.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "error", content = "detail", rename_all = "snake_case")]
pub enum Error {
    Forbidden,
    /// Denied by a guard, with the guard's reason.
    Denied(Text),
    NotFound,
    /// The record changed since it was loaded (row version mismatch).
    Conflict,
    Validation(ValidationErrors),
    /// The detail is logged, never shown to the user.
    Internal(String),
}

impl Error {
    /// Message for the user. Internal details are never included.
    pub fn message(&self) -> Text {
        match self {
            Error::Forbidden => Text::key("zeyn.error.forbidden"),
            Error::Denied(reason) => reason.clone(),
            Error::NotFound => Text::key("zeyn.error.not_found"),
            Error::Conflict => Text::key("zeyn.error.conflict"),
            Error::Validation(e) => Text::from(e.to_string()),
            Error::Internal(_) => Text::key("zeyn.error.internal"),
        }
    }

    /// Short machine readable code: `forbidden`, `not_found`, `conflict`, `validation`, `internal`.
    pub fn code(&self) -> &'static str {
        match self {
            Error::Forbidden | Error::Denied(_) => "forbidden",
            Error::NotFound => "not_found",
            Error::Conflict => "conflict",
            Error::Validation(_) => "validation",
            Error::Internal(_) => "internal",
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message().english())
    }
}

impl std::error::Error for Error {}

impl From<ValidationErrors> for Error {
    fn from(e: ValidationErrors) -> Self {
        Error::Validation(e)
    }
}

/// Result type of Zeyn actions.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Largest number of rows one request may return, whatever the client asks for.
pub const MAX_PAGE_SIZE: u32 = 500;

/// Page size used when the client sends none.
pub const DEFAULT_PAGE_SIZE: u32 = 50;

/// Opaque position in a list, used by infinite scroll. Built by the data layer from the last row's
/// sort values and key. It only says where to continue; filters and permissions are applied again.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Cursor(pub String);

/// One page of a list.
///
/// ```
/// use zeyn::Page;
/// let page = Page::new(vec![1, 2, 3]).total(120);
/// assert_eq!(page.total, Some(120));
/// ```
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Page<M> {
    pub items: Vec<M>,
    /// Total row count. Optional because counting can be expensive on large tables.
    pub total: Option<u64>,
    /// Where the next batch starts. `None` means there is nothing more.
    pub next: Option<Cursor>,
    /// Column totals over the whole filtered result, not only this page. Filled for the
    /// aggregates the query asked for ([`DataQuery::aggregates`]).
    #[serde(default, skip_deserializing, skip_serializing_if = "Vec::is_empty")]
    pub totals: Vec<Total>,
    /// Groups of rows, filled instead of `items` when the query asks for them
    /// ([`DataQuery::group`]). `total` and `next` then count groups.
    #[serde(default, skip_deserializing, skip_serializing_if = "Vec::is_empty")]
    pub groups: Vec<Group>,
}

/// One group of rows that share a value: the value, how many rows have it and the totals the
/// query asked for over those rows.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Group {
    pub value: Value,
    pub count: u64,
    pub totals: Vec<Total>,
}

impl<M> Default for Page<M> {
    fn default() -> Self {
        Self { items: Vec::new(), total: None, next: None, totals: Vec::new(), groups: Vec::new() }
    }
}

impl<M> Page<M> {
    pub fn new(items: Vec<M>) -> Self {
        Self { items, total: None, next: None, totals: Vec::new(), groups: Vec::new() }
    }

    /// Adds a column total. Data layers that page in SQL compute totals with one aggregate query.
    pub fn with_total(mut self, field: impl Into<String>, op: Aggregate, value: Value) -> Self {
        self.totals.push(Total { field: field.into(), op, value });
        self
    }

    pub fn total(mut self, total: u64) -> Self {
        self.total = Some(total);
        self
    }

    pub fn next(mut self, cursor: Cursor) -> Self {
        self.next = Some(cursor);
        self
    }
}

impl<M: Clone> Page<M> {
    /// Pages an in memory list. Meant for small data, samples and tests; databases page in SQL.
    ///
    /// The cursor here is a row position, which is only stable because the list does not change.
    pub fn from_slice(all: &[M], query: &DataQuery) -> Self {
        let limit = query.limit() as usize;
        let start = match &query.page {
            PageRequest::Offset { offset, .. } => usize::try_from(*offset).unwrap_or(usize::MAX),
            PageRequest::After { cursor, .. } => cursor.as_ref().and_then(|c| c.0.parse().ok()).unwrap_or(0),
        }
        .min(all.len());
        let end = start.saturating_add(limit).min(all.len());
        let page = Page::new(all[start..end].to_vec()).total(all.len() as u64);
        if end < all.len() { page.next(Cursor(end.to_string())) } else { page }
    }
}

/// Which part of the list the client wants.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PageRequest {
    /// Numbered pages. Allows jumping to any page.
    Offset { offset: u64, limit: u32 },
    /// Next batch after a cursor. Used by infinite scroll; stable while rows are inserted or deleted.
    After { cursor: Option<Cursor>, limit: u32 },
}

impl Default for PageRequest {
    fn default() -> Self {
        PageRequest::Offset { offset: 0, limit: DEFAULT_PAGE_SIZE }
    }
}

/// Old name of [`DataQuery`]; kept for one release.
#[deprecated(since = "0.0.2", note = "renamed to `DataQuery`; `zeyn check --fix` rewrites it")]
pub type GridQuery = DataQuery;

/// Query a grid sends to the server.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct DataQuery {
    #[serde(default)]
    pub page: PageRequest,
    #[serde(default)]
    pub sort: Vec<Sort>,
    #[serde(default)]
    pub filters: Vec<Filter>,
    /// Whether the client needs the total count. Infinite scroll usually does not.
    #[serde(default)]
    pub with_total: bool,
    /// Column totals to compute over the whole filtered result. The grid keeps only the ones
    /// its columns declare, so a client cannot ask for others.
    #[serde(default)]
    pub aggregates: Vec<AggregateRequest>,
    /// Zone in which date filters on `DateTime` columns are read. Set by the server from the
    /// user's settings, never taken from the client.
    #[serde(skip)]
    pub time_zone: crate::time::TimeZone,
    /// When set, the data layer returns groups of the matching rows by this field in
    /// [`Page::groups`] (value, row count and the asked totals per group), sorted by the value in
    /// the direction of the sort key on that field, and paged like rows; `items` stays empty.
    /// SQL data layers answer with `GROUP BY`. Set by the grid, never taken from the client.
    #[serde(skip)]
    pub group: Option<String>,
}

impl DataQuery {
    /// Requested page size, kept between 1 and [`MAX_PAGE_SIZE`]. Never use the raw value.
    pub fn limit(&self) -> u32 {
        let raw = match &self.page {
            PageRequest::Offset { limit, .. } | PageRequest::After { limit, .. } => *limit,
        };
        raw.clamp(1, MAX_PAGE_SIZE)
    }
}

/// Kind of column total.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Aggregate {
    Sum,
    Avg,
    Min,
    Max,
    /// Number of rows with a value in the column.
    Count,
}

impl Aggregate {
    /// Short code: `sum`, `avg`, `min`, `max`, `count`. Also the catalog key suffix `zeyn.grid.agg.*`.
    pub fn code(self) -> &'static str {
        match self {
            Aggregate::Sum => "sum",
            Aggregate::Avg => "avg",
            Aggregate::Min => "min",
            Aggregate::Max => "max",
            Aggregate::Count => "count",
        }
    }
}

/// One column total asked for by a grid query.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AggregateRequest {
    pub field: String,
    pub op: Aggregate,
}

/// One computed column total.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Total {
    pub field: String,
    pub op: Aggregate,
    pub value: Value,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sort {
    pub field: String,
    pub desc: bool,
}

/// Most filters one query may carry; the rest are dropped.
pub const MAX_FILTERS: usize = 32;
/// Longest filter text in characters; longer conditions are ignored.
pub const MAX_FILTER_TEXT: usize = 200;
/// Most choices one `any_of` condition may list; the rest are dropped.
pub const MAX_FILTER_CHOICES: usize = 100;

/// Column filter. Every condition that is set must hold; unset conditions are ignored.
///
/// Values arrive as strings in a fixed machine form, whatever the user's language: numbers and
/// money as `1234.56`, dates as `2026-03-31`, times as `14:30`, moments as a date (a whole day in
/// the user's time zone) or `2026-03-31T14:30`. A value that cannot be read is ignored.
///
/// ```
/// use zeyn::Filter;
/// let f = Filter::range("price", Some("10"), Some("99.90"));
/// assert_eq!(f.from.as_deref(), Some("10"));
/// let json = serde_json::json!({ "field": "code", "contains": "tea" });
/// assert_eq!(serde_json::from_value::<Filter>(json).unwrap(), Filter::contains("code", "tea"));
/// ```
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Filter {
    pub field: String,
    /// Text the shown value contains, ignoring case. Works on every column.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub contains: String,
    /// Text the value starts with, ignoring case. Text and choice columns.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub starts_with: Option<String>,
    /// Text equal to the value, ignoring case. Text and choice columns.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub equals: Option<String>,
    /// Lower bound, inclusive. Numbers, money, dates, times and moments.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// Upper bound, inclusive (a date bound on a moment column covers the whole day).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
    /// Choice values to keep. Empty means no condition.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub any_of: Vec<String>,
    /// Yes/no columns: keep rows whose value is this.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is: Option<bool>,
    /// Rows whose value is empty (`true`) or set (`false`). SQL data layers read it as
    /// `IS NULL` and `IS NOT NULL`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blank: Option<bool>,
}

impl Filter {
    /// Rows whose shown value contains `text`, ignoring case.
    pub fn contains(field: impl Into<String>, text: impl Into<String>) -> Self {
        Self { field: field.into(), contains: text.into(), ..Self::default() }
    }

    /// Rows whose value is between `from` and `to`, both inclusive; either may be open.
    pub fn range(field: impl Into<String>, from: Option<&str>, to: Option<&str>) -> Self {
        Self { field: field.into(), from: from.map(Into::into), to: to.map(Into::into), ..Self::default() }
    }

    /// Rows whose choice is one of `values`.
    pub fn any_of<I, S>(field: impl Into<String>, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self { field: field.into(), any_of: values.into_iter().map(Into::into).collect(), ..Self::default() }
    }

    /// Rows whose yes/no value is `value`.
    pub fn is(field: impl Into<String>, value: bool) -> Self {
        Self { field: field.into(), is: Some(value), ..Self::default() }
    }

    /// Rows whose value is empty (`true`) or set (`false`).
    pub fn blank(field: impl Into<String>, empty: bool) -> Self {
        Self { field: field.into(), blank: Some(empty), ..Self::default() }
    }

    /// Whether the filter sets no condition at all.
    pub fn is_empty(&self) -> bool {
        let blank = |s: &Option<String>| s.as_deref().is_none_or(|v| v.trim().is_empty());
        self.contains.trim().is_empty()
            && blank(&self.starts_with)
            && blank(&self.equals)
            && blank(&self.from)
            && blank(&self.to)
            && self.any_of.is_empty()
            && self.is.is_none()
            && self.blank.is_none()
    }
}