feat(recent): add cursor + groupby support
This commit is contained in:
@@ -1,10 +1,14 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use utoipa::{IntoParams, ToSchema};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::cursor::{CursorListResponse, CursorQuery, PageCursor};
|
||||
use super::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
};
|
||||
use super::grant_dto::{ResourceContentDto, ResourceTypeDto};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
|
||||
/// DTO for recent items, enriched with item metadata via SQL JOIN
|
||||
/// so the frontend does not need N+1 requests to resolve names/sizes.
|
||||
@@ -84,3 +88,109 @@ impl RecentItemDto {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// Cursor-paginated recent resources (GET /api/recent/resources)
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Raw row returned by the UNION ALL query for `/api/recent/resources`.
|
||||
pub struct RecentResourceRow {
|
||||
pub resource_type: String, // "file" | "folder"
|
||||
pub resource_id: Uuid,
|
||||
pub name: String,
|
||||
pub parent_id: Option<Uuid>,
|
||||
pub mime_type: Option<String>,
|
||||
/// `-1` for folders, actual byte-count for files.
|
||||
pub size: i64,
|
||||
pub resource_created_at: DateTime<Utc>,
|
||||
pub modified_at: DateTime<Utc>,
|
||||
pub owner_id: Uuid,
|
||||
/// `true` when `owner_id == requesting user_id`.
|
||||
pub is_owner: bool,
|
||||
pub accessed_at: DateTime<Utc>,
|
||||
/// Human-readable path. Always populated in the row; the handler clears it
|
||||
/// to `""` when `is_owner` is false.
|
||||
pub path: Option<String>,
|
||||
// Pre-computed sort fields for cursor construction.
|
||||
pub sort_str: Option<String>,
|
||||
pub sort_int: Option<i64>,
|
||||
pub sort_ts: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// Opaque keyset-pagination cursor for `GET /api/recent/resources`.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RecentCursor {
|
||||
/// Sort dimension active when this cursor was produced.
|
||||
/// Values: `"accessed_at"` (default), `"name"`, `"type"`, `"modified_at"`, `"size"`, `"owner"`.
|
||||
#[serde(default = "RecentCursor::default_order")]
|
||||
pub order_by: String,
|
||||
/// UUID of the last item on the previous page (tie-breaker).
|
||||
pub resource_id: Uuid,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_str: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_int: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sort_ts: Option<DateTime<Utc>>,
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl RecentCursor {
|
||||
fn default_order() -> String {
|
||||
"accessed_at".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl PageCursor for RecentCursor {}
|
||||
|
||||
/// Query parameters for `GET /api/recent/resources`.
|
||||
#[derive(Debug, Deserialize, IntoParams)]
|
||||
pub struct RecentResourcesQuery {
|
||||
/// Maximum items per page (1–200, default 50).
|
||||
#[serde(default = "CursorQuery::default_limit")]
|
||||
pub limit: u32,
|
||||
/// Opaque cursor from a previous response. Omit to start from the first page.
|
||||
pub cursor: Option<String>,
|
||||
/// Sort / group-by dimension. Supported: `"accessed_at"` (default), `"name"`,
|
||||
/// `"type"`, `"modified_at"`, `"size"`, `"owner"`.
|
||||
pub order_by: Option<String>,
|
||||
/// Comma-separated resource types to include, e.g. `"file,folder"`.
|
||||
/// Omit to include both.
|
||||
pub resource_types: Option<String>,
|
||||
/// Reverse the sort order. Default `false`.
|
||||
#[serde(default)]
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl RecentResourcesQuery {
|
||||
pub fn limit_clamped(&self) -> usize {
|
||||
self.limit.clamp(1, 200) as usize
|
||||
}
|
||||
|
||||
pub fn decode_cursor(&self) -> Option<RecentCursor> {
|
||||
self.cursor.as_deref().and_then(RecentCursor::decode)
|
||||
}
|
||||
|
||||
/// Returns `None` when `resource_types` is absent (= include all).
|
||||
pub fn resource_kinds(&self) -> Option<Vec<ResourceKind>> {
|
||||
self.resource_types.as_deref().map(|s| {
|
||||
s.split(',')
|
||||
.filter_map(|t| ResourceKind::parse(t.trim()))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One item in a `GET /api/recent/resources` page.
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct RecentResourceItemDto {
|
||||
pub resource_type: ResourceTypeDto,
|
||||
/// When the resource was last accessed.
|
||||
pub accessed_at: DateTime<Utc>,
|
||||
/// Full resource details — shape determined by `resource_type`.
|
||||
pub resource: ResourceContentDto,
|
||||
}
|
||||
|
||||
/// Response envelope for `GET /api/recent/resources`.
|
||||
pub type RecentResourcesDto = CursorListResponse<RecentResourceItemDto>;
|
||||
|
||||
@@ -51,4 +51,15 @@ pub trait RecentItemsRepositoryPort: Send + Sync + 'static {
|
||||
|
||||
/// Removes items exceeding `max_items` (the oldest ones).
|
||||
async fn prune(&self, user_id: Uuid, max_items: i32) -> Result<()>;
|
||||
|
||||
/// List recent items with cursor pagination, sorting, and optional type filter.
|
||||
async fn list_resources_paged(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
limit: usize,
|
||||
cursor: Option<&crate::application::dtos::recent_dto::RecentCursor>,
|
||||
order_by: &str,
|
||||
kinds: Option<&[crate::domain::services::authorization::ResourceKind]>,
|
||||
reverse: bool,
|
||||
) -> Result<Vec<crate::application::dtos::recent_dto::RecentResourceRow>>;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use crate::application::dtos::recent_dto::RecentItemDto;
|
||||
use crate::application::dtos::cursor::PageCursor;
|
||||
use crate::application::dtos::recent_dto::{RecentCursor, RecentItemDto, RecentResourceRow};
|
||||
use crate::application::ports::recent_ports::{RecentItemsRepositoryPort, RecentItemsUseCase};
|
||||
use crate::common::errors::{DomainError, ErrorKind, Result};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
use crate::infrastructure::repositories::pg::RecentItemsPgRepository;
|
||||
use std::sync::Arc;
|
||||
use tracing::info;
|
||||
@@ -109,3 +111,99 @@ impl RecentItemsUseCase for RecentService {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl RecentService {
|
||||
/// No authz needed — recent items are strictly user-scoped; the repository
|
||||
/// enforces `WHERE user_id = $1` so users can only see their own entries.
|
||||
///
|
||||
/// Returns `(rows, next_cursor_encoded)`.
|
||||
pub async fn list_resources_paged(
|
||||
&self,
|
||||
user_id: Uuid,
|
||||
limit: usize,
|
||||
cursor: Option<RecentCursor>,
|
||||
order_by: &str,
|
||||
kinds: Option<&[ResourceKind]>,
|
||||
reverse: bool,
|
||||
) -> Result<(Vec<RecentResourceRow>, Option<String>)> {
|
||||
// Fetch one extra row to detect whether a next page exists.
|
||||
let mut rows = self
|
||||
.repo
|
||||
.list_resources_paged(
|
||||
user_id,
|
||||
limit + 1,
|
||||
cursor.as_ref(),
|
||||
order_by,
|
||||
kinds,
|
||||
reverse,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let next_cursor = if rows.len() > limit {
|
||||
let last = &rows[limit - 1];
|
||||
let c = build_recent_cursor(last, order_by, reverse);
|
||||
rows.truncate(limit);
|
||||
Some(c.encode())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok((rows, next_cursor))
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the next-page cursor from the last row of the current page.
|
||||
/// `reverse` is stored in the cursor so subsequent pages use the same direction.
|
||||
fn build_recent_cursor(row: &RecentResourceRow, order_by: &str, reverse: bool) -> RecentCursor {
|
||||
match order_by {
|
||||
"name" => RecentCursor {
|
||||
order_by: "name".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: row.sort_str.clone(), // LOWER(name)
|
||||
sort_int: row.sort_int, // folder_first
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
"type" => RecentCursor {
|
||||
order_by: "type".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: row.sort_str.clone(), // LOWER(name)
|
||||
sort_int: row.sort_int, // type_order
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
"modified_at" => RecentCursor {
|
||||
order_by: "modified_at".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: None,
|
||||
sort_int: None,
|
||||
sort_ts: row.sort_ts, // modified_at timestamp
|
||||
reverse,
|
||||
},
|
||||
"size" => RecentCursor {
|
||||
order_by: "size".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: None,
|
||||
sort_int: row.sort_int, // size in bytes
|
||||
sort_ts: None,
|
||||
reverse,
|
||||
},
|
||||
"owner" => RecentCursor {
|
||||
order_by: "owner".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: row.sort_str.clone(), // LOWER(username)
|
||||
sort_int: None,
|
||||
sort_ts: row.sort_ts, // accessed_at timestamp (secondary)
|
||||
reverse,
|
||||
},
|
||||
_ => RecentCursor {
|
||||
// default: accessed_at DESC
|
||||
order_by: "accessed_at".to_owned(),
|
||||
resource_id: row.resource_id,
|
||||
sort_str: None,
|
||||
sort_int: None,
|
||||
sort_ts: row.sort_ts, // accessed_at timestamp
|
||||
reverse,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user