feat(api): cursor listing contract — PageCursor trait + resource field

- Add src/application/dtos/cursor.rs with three shared types:
  · PageCursor trait  — default base64url+JSON encode/decode; one bare
    impl line per cursor struct
  · CursorQuery struct — standard limit/cursor/sort_by query params with
    limit_clamped() and decode_cursor<C>() helpers; compose via flatten
  · CursorListResponse<T> — standard {items, next_cursor?} envelope with
    from_oversized() and with_cursor() builders

- Migrate GrantCursor to impl PageCursor (remove duplicate encode/decode)

- Update GET /api/grants/incoming/resources:
  · SharedWithMeQuery now embeds CursorQuery via #[serde(flatten)]
  · Replace file/folder nullable pair with ResourceContentDto (untagged
    enum) under a single always-present 'resource' field
  · SharedWithMeDto is now a type alias for CursorListResponse<SharedWithMeItemDto>
  · Handler uses q.paging.limit_clamped() and decode_cursor<GrantCursor>()

- Add docs/architecture/resource-listing.md — authoritative contract for
  all listing endpoints (cursor design, SQL keyset WHERE, sort_by naming,
  Rust + JS skeletons, compliance table, migration guide)

- Register doc in VitePress sidebar and architecture index

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Edouard Vanbelle
2026-05-26 17:52:28 +02:00
parent 9a2782b67e
commit c65f2b5385
10 changed files with 565 additions and 53 deletions
+161
View File
@@ -0,0 +1,161 @@
//! Standard types for cursor-based, sortable listing endpoints.
//!
//! All `GET` endpoints that return a collection **must** use these types so
//! that every listing is consistent for API consumers.
//!
//! # Quick start
//!
//! ```rust,ignore
//! // 1. Define a cursor for your endpoint
//! #[derive(Serialize, Deserialize)]
//! pub struct MyCursor { pub created_at: DateTime<Utc>, pub id: Uuid }
//! impl PageCursor for MyCursor {} // encode/decode for free
//!
//! // 2. Compose the standard query params
//! #[derive(Deserialize, IntoParams)]
//! pub struct MyQuery {
//! #[serde(flatten)]
//! pub paging: CursorQuery,
//! pub my_filter: Option<String>, // endpoint-specific extras
//! }
//!
//! // 3. Return the standard envelope
//! async fn list_things(Query(q): Query<MyQuery>, …) -> Json<CursorListResponse<ThingDto>> {
//! let limit = q.paging.limit_clamped();
//! let cursor = q.paging.decode_cursor::<MyCursor>();
//! // fetch limit+1 rows …
//! Json(CursorListResponse::from_oversized(rows, limit, |r| MyCursor { … }))
//! }
//! ```
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};
// ToSchema is used on CursorQuery so it can be flattened into IntoParams structs
// ════════════════════════════════════════════════════════════════════════════
// PageCursor trait
// ════════════════════════════════════════════════════════════════════════════
/// Marker trait for opaque keyset-pagination cursors.
///
/// The default `encode` / `decode` implementations use
/// URL-safe base64url (no padding) over a JSON serialisation of `Self`.
/// Any struct that derives `Serialize + Deserialize` can implement this
/// with a bare `impl PageCursor for MyCursor {}`.
///
/// The encoding is intentionally opaque to API callers. Treat an
/// undecodable cursor as "start from the top" — never return an error.
pub trait PageCursor: Sized + Serialize + for<'de> Deserialize<'de> {
/// Encode `self` as a URL-safe, no-padding base64url string.
fn encode(&self) -> String {
URL_SAFE_NO_PAD.encode(serde_json::to_vec(self).unwrap_or_default())
}
/// Decode from a base64url string. Returns `None` on any parse failure.
fn decode(s: &str) -> Option<Self> {
let bytes = URL_SAFE_NO_PAD.decode(s).ok()?;
serde_json::from_slice(&bytes).ok()
}
}
// ════════════════════════════════════════════════════════════════════════════
// CursorQuery — standard query params
// ════════════════════════════════════════════════════════════════════════════
/// Standard query parameters for cursor-based listing endpoints.
///
/// Use `CursorQuery` directly as the `Query<CursorQuery>` extractor when an
/// endpoint has no extra filter params. When extra params are needed, declare
/// them in an endpoint-specific struct and **repeat** the three fields — Axum's
/// query extractor uses `serde_urlencoded` which does not support
/// `#[serde(flatten)]`. Use `CursorQuery::default_limit()` for the default
/// and the helpers `limit_clamped()` / `decode_cursor()` by either calling
/// them on `CursorQuery` directly or re-implementing them inline:
///
/// ```rust,ignore
/// #[derive(Deserialize, IntoParams)]
/// pub struct MyQuery {
/// #[serde(default = "CursorQuery::default_limit")]
/// pub limit: u32,
/// pub cursor: Option<String>,
/// pub sort_by: Option<String>,
/// pub status: Option<String>, // endpoint-specific
/// }
/// ```
#[derive(Debug, Deserialize, IntoParams, ToSchema)]
pub struct CursorQuery {
/// Maximum items per page (1–200, default 50).
#[serde(default = "CursorQuery::default_limit")]
pub limit: u32,
/// Opaque cursor from a previous response. Absent on the first page.
pub cursor: Option<String>,
/// Sort dimension. Valid values are endpoint-defined (e.g. `"granted_at"`,
/// `"name"`, `"granted_by"`). Unknown values should return HTTP 400.
pub sort_by: Option<String>,
}
impl CursorQuery {
/// Default value for the `limit` field — exposed `pub` so endpoint-specific
/// query structs can reference it in `#[serde(default = "CursorQuery::default_limit")]`.
pub fn default_limit() -> u32 {
50
}
/// Returns `limit` clamped to `[1, 200]`.
pub fn limit_clamped(&self) -> usize {
self.limit.clamp(1, 200) as usize
}
/// Decode the optional cursor string into type `C`.
/// Returns `None` when no cursor is present or when decoding fails
/// (invalid cursor → start from the top).
pub fn decode_cursor<C: PageCursor>(&self) -> Option<C> {
self.cursor.as_deref().and_then(C::decode)
}
}
// ════════════════════════════════════════════════════════════════════════════
// CursorListResponse — standard response envelope
// ════════════════════════════════════════════════════════════════════════════
/// Standard response envelope for cursor-paginated listing endpoints.
///
/// `next_cursor` is omitted from the JSON when `None` (i.e. last page).
/// Callers must treat a missing `next_cursor` as end-of-results — never
/// include a `total` count (that would require an expensive `COUNT(*)`).
#[derive(Debug, Serialize, ToSchema)]
pub struct CursorListResponse<T: Serialize> {
pub items: Vec<T>,
/// Opaque cursor for the next page. Absent when this is the last page.
#[serde(skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<String>,
}
impl<T: Serialize> CursorListResponse<T> {
/// Build a response from an over-fetched slice (fetch `limit + 1` rows).
///
/// If `items.len() > limit` a next page exists: `items` is truncated to
/// `limit` and `cursor_fn` is called on the **last kept item** to produce
/// the next cursor. Otherwise `next_cursor` is `None`.
pub fn from_oversized<C: PageCursor>(
mut items: Vec<T>,
limit: usize,
cursor_fn: impl FnOnce(&T) -> C,
) -> Self {
let next_cursor = if items.len() > limit {
let c = cursor_fn(&items[limit - 1]);
items.truncate(limit);
Some(c.encode())
} else {
None
};
Self { items, next_cursor }
}
/// Build a response when the next cursor is already known (e.g. returned
/// by a service layer that handles the `limit+1` logic internally).
pub fn with_cursor(items: Vec<T>, next_cursor: Option<String>) -> Self {
Self { items, next_cursor }
}
}
+45 -20
View File
@@ -8,6 +8,7 @@ use serde::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};
use uuid::Uuid;
use crate::application::dtos::cursor::{CursorListResponse, CursorQuery, PageCursor};
use crate::application::dtos::file_dto::FileDto;
use crate::application::dtos::folder_dto::FolderDto;
use crate::domain::services::authorization::{Grant, Permission, Resource, Subject};
@@ -232,26 +233,58 @@ impl From<Grant> for GrantDto {
// ════════════════════════════════════════════════════════════════════════════
/// Query parameters for `GET /api/grants/incoming/resources`.
///
/// `limit`, `cursor`, and `sort_by` follow the standard [`CursorQuery`]
/// contract. They are declared directly here rather than via
/// `#[serde(flatten)]` because `serde_urlencoded` (Axum's query extractor)
/// does not support flattening.
#[derive(Debug, Deserialize, IntoParams)]
pub struct SharedWithMeQuery {
/// Maximum number of items to return (1–200, default 50).
#[serde(default = "shared_with_me_default_limit")]
#[serde(default = "CursorQuery::default_limit")]
pub limit: u32,
/// Opaque cursor from a previous response. Omit to start from the
/// most-recently-granted item.
pub cursor: Option<String>,
/// Sort dimension. Supported values: `"granted_at"` (default),
/// `"granted_by"` (for swimlane grouping).
pub sort_by: Option<String>,
/// Comma-separated resource types to include, e.g. `file,folder`.
/// Omit to return all known types.
pub resource_types: Option<String>,
/// Opaque cursor returned by a previous call. Omit to start from the
/// most-recently-granted item.
pub cursor: Option<String>,
}
fn shared_with_me_default_limit() -> u32 {
50
impl SharedWithMeQuery {
/// Returns `limit` clamped to `[1, 200]`.
pub fn limit_clamped(&self) -> usize {
self.limit.clamp(1, 200) as usize
}
/// Decode the optional cursor string. Invalid cursor → start from top.
pub fn decode_cursor<C: PageCursor>(&self) -> Option<C> {
self.cursor.as_deref().and_then(C::decode)
}
}
/// One item in the shared-with-me list. Exactly one of `file` / `folder` is
/// populated, indicated by `resource_type`. Additional optional fields for
/// future resource types (playlist, addressbook, …) will be added here.
/// The resource payload for one item in the shared-with-me list.
///
/// The variant is discriminated by `resource_type` on the parent
/// [`SharedWithMeItemDto`]. Serialised as the inner object (no wrapper key)
/// via `#[serde(untagged)]`, so consumers see the file/folder fields directly
/// under the `resource` key.
#[derive(Debug, Serialize, ToSchema)]
#[serde(untagged)]
pub enum ResourceContentDto {
File(FileDto),
Folder(FolderDto),
}
/// One item in the shared-with-me list.
///
/// `resource_type` indicates whether `resource` contains a file or a folder.
/// Using a single `resource` field (instead of nullable `file`/`folder` pairs)
/// makes adding new resource types backward-compatible — only `resource_type`
/// gains a new variant; the wrapper shape stays the same.
#[derive(Debug, Serialize, ToSchema)]
pub struct SharedWithMeItemDto {
pub resource_type: ResourceTypeDto,
@@ -261,17 +294,9 @@ pub struct SharedWithMeItemDto {
pub granted_at: chrono::DateTime<chrono::Utc>,
/// UUID of the user who created the (earliest) grant.
pub granted_by: Uuid,
#[serde(skip_serializing_if = "Option::is_none")]
pub file: Option<FileDto>,
#[serde(skip_serializing_if = "Option::is_none")]
pub folder: Option<FolderDto>,
/// Full resource details. Shape is determined by `resource_type`.
pub resource: ResourceContentDto,
}
/// Response for `GET /api/grants/incoming/resources`.
#[derive(Debug, Serialize, ToSchema)]
pub struct SharedWithMeDto {
pub items: Vec<SharedWithMeItemDto>,
/// Opaque cursor for the next page. Absent when the last page is reached.
#[serde(skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<String>,
}
pub type SharedWithMeDto = CursorListResponse<SharedWithMeItemDto>;
+2
View File
@@ -1,4 +1,6 @@
pub mod address_book_dto;
pub mod cursor;
pub use cursor::{CursorListResponse, CursorQuery, PageCursor};
pub mod app_password_dto;
pub mod calendar_dto;
pub mod contact_dto;
+3 -15
View File
@@ -5,7 +5,7 @@
//! `AuthorizationEngine` port consumes them and the `PgAclEngine` implementation
//! maps them to / from `storage.access_grants` rows.
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crate::application::dtos::cursor::PageCursor;
use std::fmt;
use uuid::Uuid;
@@ -265,20 +265,8 @@ pub struct GrantCursor {
pub resource_id: Uuid,
}
impl GrantCursor {
/// Encode as a URL-safe base64 JSON string (no padding).
pub fn encode(&self) -> String {
let json = serde_json::to_vec(self).unwrap_or_default();
URL_SAFE_NO_PAD.encode(&json)
}
/// Decode from a URL-safe base64 JSON string. Returns `None` on any
/// parse failure — callers treat a bad cursor as "start from the top".
pub fn decode(s: &str) -> Option<Self> {
let bytes = URL_SAFE_NO_PAD.decode(s).ok()?;
serde_json::from_slice(&bytes).ok()
}
}
/// Delegate encode/decode to the shared [`PageCursor`] trait.
impl PageCursor for GrantCursor {}
#[cfg(test)]
mod tests {
+14 -11
View File
@@ -18,9 +18,10 @@ use tracing::{error, info, warn};
use utoipa::IntoParams;
use uuid::Uuid;
use crate::application::dtos::cursor::PageCursor;
use crate::application::dtos::grant_dto::{
CreateGrantDto, GrantDto, PermissionDto, ResourceDto, ResourceTypeDto, SharedWithMeDto,
SharedWithMeItemDto, SharedWithMeQuery, SubjectDto, UpdateRoleDto,
CreateGrantDto, GrantDto, PermissionDto, ResourceContentDto, ResourceDto, ResourceTypeDto,
SharedWithMeDto, SharedWithMeItemDto, SharedWithMeQuery, SubjectDto, UpdateRoleDto,
};
use crate::application::ports::authorization_ports::AuthorizationEngine;
use crate::application::ports::file_ports::FileRetrievalUseCase;
@@ -320,10 +321,10 @@ pub async fn list_shared_with_me(
.unwrap_or_default();
// Clamp limit to 1–200.
let limit = q.limit.clamp(1, 200);
let limit = q.limit_clamped() as u32;
// Decode cursor (treat invalid cursor as "start from top").
let cursor = q.cursor.as_deref().and_then(GrantCursor::decode);
let cursor = q.decode_cursor::<GrantCursor>();
// Fetch paged summaries from the ACL engine.
let (summaries, next_cursor) = match state
@@ -384,8 +385,9 @@ pub async fn list_shared_with_me(
permissions: summary.permissions.iter().map(|p| (*p).into()).collect(),
granted_at: summary.granted_at,
granted_by: summary.granted_by,
file: Some(file_dto.clone().without_hierarchy_info()),
folder: None,
resource: ResourceContentDto::File(
file_dto.clone().without_hierarchy_info(),
),
});
}
Err(e) if e.kind == ErrorKind::NotFound => {
@@ -414,8 +416,9 @@ pub async fn list_shared_with_me(
permissions: summary.permissions.iter().map(|p| (*p).into()).collect(),
granted_at: summary.granted_at,
granted_by: summary.granted_by,
file: None,
folder: Some(folder_dto.clone().without_hierarchy_info()),
resource: ResourceContentDto::Folder(
folder_dto.clone().without_hierarchy_info(),
),
});
}
Err(e) if e.kind == ErrorKind::NotFound => {
@@ -438,10 +441,10 @@ pub async fn list_shared_with_me(
(
StatusCode::OK,
Json(SharedWithMeDto {
Json(SharedWithMeDto::with_cursor(
items,
next_cursor: next_cursor.map(|c| c.encode()),
}),
next_cursor.map(|c| c.encode()),
)),
)
.into_response()
}