Merge pull request #396 from EdouardVanbelle/feat/itemview-and-swimlane

This commit is contained in:
Dionisio Pozo
2026-05-28 02:31:56 +02:00
committed by GitHub
61 changed files with 3772 additions and 1279 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 }
}
}
+25
View File
@@ -344,6 +344,31 @@ pub fn category_for(name: &str, mime: &str) -> &'static str {
"Document"
}
/// Returns the sort order for a file category, stored as `category_order` in `storage.files`.
///
/// Values are **sparse multiples of 100** so a future category can be slotted between two
/// existing ones (e.g. "RichText" = 550, between Document=500 and Spreadsheet=600) without
/// renumbering any rows. Folders are not handled here — the SQL query hard-codes 0 for them.
///
/// This function delegates to [`category_for`] so the two are always in sync.
pub fn category_order_for(name: &str, mime: &str) -> i16 {
match category_for(name, mime) {
"Image" => 100,
"Video" => 200,
"Audio" => 300,
"PDF" => 400,
"Document" => 500,
"Spreadsheet" => 600,
"Presentation" => 700,
"Archive" => 800,
"Code" => 900,
"Markdown" => 1000,
"Text" => 1100,
"Installer" => 1200,
_ => 9999, // Other / unknown
}
}
/// Formats a byte count into a human-readable string (1024-based).
///
/// Matches the JavaScript `formatFileSize()` output exactly so the frontend
+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;
@@ -85,6 +85,7 @@ pub trait AuthorizationEngine: Send + Sync + 'static {
kinds: &[ResourceKind],
limit: u32,
cursor: Option<GrantCursor>,
sort_by: &str,
) -> Result<(Vec<IncomingGrantSummary>, Option<GrantCursor>), DomainError>;
/// All grants on a specific resource (for "Manage sharing" UI). Caller
+29 -13
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;
@@ -258,28 +258,44 @@ pub struct IncomingGrantSummary {
/// Encodes the position of the last seen item in a cursor-paginated grant
/// listing. The encoding is opaque to API callers — only the backend
/// decodes it. Change the encoding algorithm in a major version bump.
/// decodes it.
///
/// The `sort_by` field must match the active sort dimension — if the caller
/// switches sort order the handler discards any cursor whose `sort_by` does
/// not match, restarting from the first page.
///
/// Sort-key fields populated per `sort_by` value:
/// - `"granted_at"` (default) — uses `granted_at` + `resource_id`
/// - `"name"` — uses `resource_name` (lowercased) + `resource_id`
/// - `"type"` — uses `type_order` + `resource_name` (lowercased) + `resource_id`
/// - `"granted_by"` — uses `resource_name` (owner display name, lowercased) + `granted_at` + `resource_id`
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GrantCursor {
/// Sort dimension that was active when this cursor was produced.
#[serde(default = "GrantCursor::default_sort")]
pub sort_by: String,
pub granted_at: chrono::DateTime<chrono::Utc>,
pub resource_id: Uuid,
/// Lowercased sort string — resource name for `"name"`/`"type"`,
/// owner display name for `"granted_by"`.
#[serde(skip_serializing_if = "Option::is_none")]
pub resource_name: Option<String>,
/// Generic integer sort key:
/// - `"type"` — category_order (0 = Folder, 100 = Image, …)
/// - `"size"` — file size in bytes (-1 = Folder sentinel)
#[serde(skip_serializing_if = "Option::is_none")]
pub sort_int: Option<i64>,
}
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()
fn default_sort() -> String {
"granted_at".to_owned()
}
}
/// Delegate encode/decode to the shared [`PageCursor`] trait.
impl PageCursor for GrantCursor {}
#[cfg(test)]
mod tests {
use super::*;
@@ -12,6 +12,7 @@ use std::path::PathBuf;
use std::sync::Arc;
use uuid::Uuid;
use crate::application::dtos::display_helpers::category_order_for;
use crate::application::ports::storage_ports::{CopyFolderTreeResult, FileWritePort};
use crate::common::errors::DomainError;
use crate::domain::entities::file::File;
@@ -226,8 +227,8 @@ impl FileBlobWriteRepository {
let row = match sqlx::query_as::<_, (String, i64, i64)>(
r#"
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type)
VALUES ($1, $2::uuid, $3, $4, $5, $6)
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type, category_order)
VALUES ($1, $2::uuid, $3, $4, $5, $6, $7)
RETURNING id::text,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint
@@ -239,6 +240,7 @@ impl FileBlobWriteRepository {
.bind(&blob_hash)
.bind(size as i64)
.bind(&content_type)
.bind(category_order_for(&name, &content_type))
.fetch_one(self.pool.as_ref())
.await
{
@@ -374,18 +376,19 @@ impl FileWritePort for FileBlobWriteRepository {
>(
r#"
WITH src AS (
SELECT name, folder_id, user_id, blob_hash, size, mime_type
SELECT name, folder_id, user_id, blob_hash, size, mime_type, category_order
FROM storage.files
WHERE id = $1::uuid AND NOT is_trashed
),
new_file AS (
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type)
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type, category_order)
SELECT name,
COALESCE($2::uuid, folder_id),
user_id,
blob_hash,
size,
mime_type
mime_type,
category_order
FROM src
RETURNING id::text, name, folder_id::text, size, mime_type,
EXTRACT(EPOCH FROM created_at)::bigint,
@@ -537,8 +540,8 @@ impl FileWritePort for FileBlobWriteRepository {
let row = sqlx::query_as::<_, (String, i64, i64)>(
r#"
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type)
VALUES ($1, $2::uuid, $3, $4, $5, $6)
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type, category_order)
VALUES ($1, $2::uuid, $3, $4, $5, $6, $7)
RETURNING id::text,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint
@@ -550,6 +553,7 @@ impl FileWritePort for FileBlobWriteRepository {
.bind(placeholder_hash)
.bind(size as i64)
.bind(&content_type)
.bind(category_order_for(&name, &content_type))
.fetch_one(self.pool.as_ref())
.await
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("deferred: {e}")))?;
+208 -52
View File
@@ -299,87 +299,243 @@ impl AuthorizationEngine for PgAclEngine {
kinds: &[ResourceKind],
limit: u32,
cursor: Option<GrantCursor>,
sort_by: &str,
) -> Result<(Vec<IncomingGrantSummary>, Option<GrantCursor>), DomainError> {
// Build kind filter array — NULL means "all kinds".
// ── Common setup ──────────────────────────────────────────────────────
let kind_strs: Option<Vec<&str>> = if kinds.is_empty() {
None
} else {
Some(kinds.iter().map(|k| k.as_str()).collect())
};
let cursor_at = cursor.as_ref().map(|c| c.granted_at);
let cursor_id = cursor.as_ref().map(|c| c.resource_id);
// Fetch limit+1 rows so we can detect whether a next page exists.
let fetch_limit = (limit as i64) + 1;
// Each row: (resource_type, resource_id, permissions_text_array,
// granted_at, granted_by)
// Unified row type — the last two columns carry the sort key when present,
// NULL otherwise. This lets every sort mode share a single query_as call.
// 0 resource_type String
// 1 resource_id Uuid
// 2 permissions Vec<String>
// 3 granted_at DateTime<Utc>
// 4 granted_by Uuid
// 5 sort_str Option<String> — resource_name (name/type) or owner_name (granted_by)
// 6 sort_int Option<i64> — category_order (type) or file size in bytes (size)
type Row = (
String,
Uuid,
Vec<String>,
chrono::DateTime<chrono::Utc>,
Uuid,
Option<String>,
Option<i64>,
);
let rows: Vec<Row> = sqlx::query_as(
r#"
WITH agg AS (
SELECT
resource_type,
resource_id,
array_agg(DISTINCT permission ORDER BY permission) AS permissions,
MIN(granted_at) AS granted_at,
(array_agg(granted_by ORDER BY granted_at))[1] AS granted_by
FROM storage.access_grants
WHERE subject_type = $1
AND subject_id = $2
AND ($3::text[] IS NULL OR resource_type = ANY($3))
GROUP BY resource_type, resource_id
)
SELECT resource_type, resource_id, permissions, granted_at, granted_by
FROM agg
WHERE ( $4::timestamptz IS NULL
OR granted_at < $4
OR (granted_at = $4 AND resource_id < $5::uuid))
ORDER BY granted_at DESC, resource_id DESC
LIMIT $6
"#,
)
.bind(subject.type_str())
.bind(subject.id())
.bind(kind_strs)
.bind(cursor_at)
.bind(cursor_id)
.bind(fetch_limit)
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| {
DomainError::internal_error("PgAcl", format!("list_incoming_resources_paged: {e}"))
})?;
// Extract all cursor fields up-front; each branch uses the subset it needs.
// Fixed parameter positions used in all SQL variants:
// $4 = cursor_str (resource_name / owner_name)
// $5 = cursor_int (type_order)
// $6 = cursor_at (granted_at)
// $7 = cursor_id (resource_id)
// $8 = fetch_limit
let cursor_str = cursor.as_ref().and_then(|c| c.resource_name.clone());
let cursor_int = cursor.as_ref().and_then(|c| c.sort_int);
let cursor_at = cursor.as_ref().map(|c| c.granted_at);
let cursor_id = cursor.as_ref().map(|c| c.resource_id);
// ── agg CTE (identical in all branches) ───────────────────────────────
const AGG: &str = r#"agg AS (
SELECT
resource_type,
resource_id,
array_agg(DISTINCT permission ORDER BY permission) AS permissions,
MIN(granted_at) AS granted_at,
(array_agg(granted_by ORDER BY granted_at))[1] AS granted_by
FROM storage.access_grants
WHERE subject_type = $1
AND subject_id = $2
AND ($3::text[] IS NULL OR resource_type = ANY($3))
GROUP BY resource_type, resource_id
)"#;
// ── Build sort-specific SQL fragments ─────────────────────────────────
// "name" and "type" share the same LEFT JOINs; only sort_int_expr,
// the cursor WHERE condition, and ORDER BY differ.
let sql = match sort_by {
"name" | "type" => {
let sort_int_expr = if sort_by == "type" {
"CASE WHEN agg.resource_type = 'folder' THEN 0 ELSE fi.category_order::bigint END"
} else {
"NULL::bigint"
};
let where_clause = if sort_by == "type" {
r#"( $5::integer IS NULL
OR sort_int > $5
OR (sort_int = $5 AND LOWER(sort_str) > $4)
OR (sort_int = $5 AND LOWER(sort_str) = $4 AND resource_id > $7::uuid))"#
} else {
r#"( $4::text IS NULL
OR LOWER(sort_str) > $4
OR (LOWER(sort_str) = $4 AND resource_id > $7::uuid))"#
};
let order_clause = if sort_by == "type" {
"sort_int ASC, LOWER(sort_str) ASC, resource_id ASC"
} else {
"LOWER(sort_str) ASC, resource_id ASC"
};
format!(
r#"WITH {AGG},
named AS (
SELECT agg.*,
COALESCE(
CASE WHEN agg.resource_type = 'folder' THEN f.name END,
CASE WHEN agg.resource_type = 'file' THEN fi.name END
) AS sort_str,
{sort_int_expr} AS sort_int
FROM agg
LEFT JOIN storage.folders f ON f.id = agg.resource_id AND agg.resource_type = 'folder'
LEFT JOIN storage.files fi ON fi.id = agg.resource_id AND agg.resource_type = 'file'
)
SELECT resource_type, resource_id, permissions, granted_at, granted_by, sort_str, sort_int
FROM named
WHERE {where_clause}
ORDER BY {order_clause}
LIMIT $8"#
)
}
"granted_by" => format!(
// Joins auth.users to sort alphabetically by username.
// Cursor encodes (owner_name=$4, granted_at=$6, resource_id=$7).
r#"WITH {AGG},
owner_named AS (
SELECT agg.*,
LOWER(u.username) AS sort_str,
NULL::bigint AS sort_int
FROM agg
LEFT JOIN auth.users u ON u.id = agg.granted_by
)
SELECT resource_type, resource_id, permissions, granted_at, granted_by, sort_str, sort_int
FROM owner_named
WHERE ( $4::text IS NULL
OR sort_str > $4
OR (sort_str = $4 AND (
$6::timestamptz IS NULL
OR granted_at < $6
OR (granted_at = $6 AND resource_id < $7::uuid))))
ORDER BY sort_str ASC, granted_at DESC, resource_id DESC
LIMIT $8"#
),
"size" => format!(
// Folders have no size — they sort first with a sentinel of -1.
// Files sort by size ASC; resource_id breaks ties.
// Cursor encodes (sort_int=$5, resource_id=$7); $4/$6 unused.
r#"WITH {AGG},
sized AS (
SELECT agg.*,
NULL::text AS sort_str,
CASE WHEN agg.resource_type = 'folder' THEN -1
ELSE fi.size
END AS sort_int
FROM agg
LEFT JOIN storage.files fi ON fi.id = agg.resource_id AND agg.resource_type = 'file'
)
SELECT resource_type, resource_id, permissions, granted_at, granted_by, sort_str, sort_int
FROM sized
WHERE ( $5::bigint IS NULL
OR sort_int > $5
OR (sort_int = $5 AND resource_id > $7::uuid))
ORDER BY sort_int ASC, resource_id ASC
LIMIT $8"#
),
_ => format!(
// Default: sort by grant date DESC (newest first).
// Cursor encodes (granted_at=$6, resource_id=$7); $4/$5 unused.
r#"WITH {AGG}
SELECT resource_type, resource_id, permissions, granted_at, granted_by,
NULL::text AS sort_str,
NULL::bigint AS sort_int
FROM agg
WHERE ( $6::timestamptz IS NULL
OR granted_at < $6
OR (granted_at = $6 AND resource_id < $7::uuid))
ORDER BY granted_at DESC, resource_id DESC
LIMIT $8"#
),
};
// ── Execute — uniform 8 binds for every sort mode ─────────────────────
let mut rows: Vec<Row> = sqlx::query_as::<_, Row>(&sql)
.bind(subject.type_str()) // $1
.bind(subject.id()) // $2
.bind(&kind_strs) // $3
.bind(&cursor_str) // $4 sort_str cursor
.bind(cursor_int) // $5 sort_int cursor
.bind(cursor_at) // $6 granted_at cursor
.bind(cursor_id) // $7 resource_id cursor
.bind(fetch_limit) // $8
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| {
DomainError::internal_error(
"PgAcl",
format!("list_incoming_resources_paged ({sort_by}): {e}"),
)
})?;
// ── Pagination ────────────────────────────────────────────────────────
let has_next = rows.len() > limit as usize;
let rows: Vec<Row> = rows.into_iter().take(limit as usize).collect();
rows.truncate(limit as usize);
// Determine the next cursor from the last item we're actually returning.
let next_cursor = if has_next {
rows.last().map(|r| GrantCursor {
granted_at: r.3,
resource_id: r.1,
rows.last().map(|r| {
let sort_str_lc = r.5.as_deref().map(str::to_lowercase);
match sort_by {
"name" => GrantCursor {
sort_by: "name".to_owned(),
granted_at: r.3,
resource_id: r.1,
resource_name: sort_str_lc,
sort_int: None,
},
"type" => GrantCursor {
sort_by: "type".to_owned(),
granted_at: r.3,
resource_id: r.1,
resource_name: sort_str_lc,
sort_int: r.6,
},
"granted_by" => GrantCursor {
sort_by: "granted_by".to_owned(),
granted_at: r.3,
resource_id: r.1,
resource_name: r.5.clone(), // already lowercased by SQL
sort_int: None,
},
"size" => GrantCursor {
sort_by: "size".to_owned(),
granted_at: r.3,
resource_id: r.1,
resource_name: None,
sort_int: r.6,
},
_ => GrantCursor {
sort_by: "granted_at".to_owned(),
granted_at: r.3,
resource_id: r.1,
resource_name: None,
sort_int: None,
},
}
})
} else {
None
};
// Convert rows into domain summaries.
// ── Convert rows to domain summaries ──────────────────────────────────
let summaries = rows
.into_iter()
.filter_map(|(rt, rid, perms_str, granted_at, granted_by)| {
.filter_map(|(rt, rid, perms_str, granted_at, granted_by, _, _)| {
let resource_type = ResourceKind::parse(&rt)?;
let permissions = perms_str
.iter()
.filter_map(|s| Permission::parse(s))
.into_iter()
.filter_map(|s| Permission::parse(&s))
.collect();
Some(IncomingGrantSummary {
resource_type,
+32 -13
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;
@@ -325,15 +326,31 @@ 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);
// Validate sort_by (defaults to "granted_at").
let sort_by = q.sort_by.as_deref().unwrap_or("granted_at");
if !matches!(
sort_by,
"granted_at" | "granted_by" | "name" | "type" | "size"
) {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({"error": "invalid sort_by; valid values: granted_at, granted_by, name, type, size"})),
)
.into_response();
}
// Decode cursor — discard it when the sort dimension changed to avoid
// keyset confusion across sort modes.
let cursor = q
.decode_cursor::<GrantCursor>()
.filter(|c| c.sort_by == sort_by);
// Fetch paged summaries from the ACL engine.
let (summaries, next_cursor) = match state
.authorization
.list_incoming_resources_paged(subject, &kinds, limit, cursor)
.list_incoming_resources_paged(subject, &kinds, limit, cursor, sort_by)
.await
{
Ok(r) => r,
@@ -389,8 +406,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 => {
@@ -419,8 +437,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 => {
@@ -443,10 +462,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()
}