maarcadetweet: initial commit
AT Protocol PDS + AppView + Tauri Desktop Client, 160-char post limit. - PDS (Rust + axum + sqlx) - Auth: createAccount, createSession, refreshSession - Records: createRecord, deleteRecord (race-safe via SELECT FOR UPDATE) - Feed: feed.like.create, feed.repost.create - Sync: getRepo, getBlocks, getLatestCommit, getRecord (with MST proof), listRepos - Identity: resolveHandle - MST: spec-conformant (at-mst crate, 27 tests) - Repo: signed commits, TID counter (monotonic, 4096 wrap safe) - AppView (Rust + axum + sqlx) - Jetstream consumer (WebSocket, exponential backoff, 38k+ events indexed) - REST API: timeline/home (graph-aware), profile, search, post (with thread hydration) - Handle-sync worker (did:plc + did:web) - JSONB embed storage + thread columns (migration 0003) - Like/repost counter cache (migration 0004) - Tauri 2 + Svelte 5 Desktop Client - System tray (Show/Compose/Quit menu) - OS notifications (tauri-plugin-notification) - Auto-update (tauri-plugin-updater, placeholder endpoint) - Window-state (tauri-plugin-window-state) - 160-char compose with live counter - Image/Link embed rendering - LocalStorage-persisted like state - Timeline with poll (prepend new posts) - Custom TitleBar (transparent, no decorations) - Orange/IBM Plex Mono maarcade design Tests: 231 Rust + 9 vitest = 240 passed.
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
//! Opaque pagination cursor for `GET /api/timeline/home`.
|
||||
//!
|
||||
//! The cursor is a base64url-encoded `<indexed_at_micros>:<post_uri>`
|
||||
//! pair. The format is intentionally not stable across releases — it's
|
||||
//! an implementation detail of the API. The client must treat it as
|
||||
//! an opaque string and pass it back unchanged.
|
||||
//!
|
||||
//! `decode` returns [`CursorState`] which the route uses to build a
|
||||
//! `WHERE (indexed_at, uri) < ($1, $2)` predicate for stable
|
||||
//! keyset pagination (avoids `OFFSET` drift when new posts land
|
||||
//! between page fetches).
|
||||
|
||||
use base64::Engine;
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
|
||||
/// Internal decoded representation of a timeline cursor.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CursorState {
|
||||
/// Microseconds since the unix epoch of the last seen post.
|
||||
pub ts: i64,
|
||||
/// URI of the last seen post.
|
||||
pub uri: String,
|
||||
}
|
||||
|
||||
/// Encode `(indexed_at, uri)` into the wire-format cursor string.
|
||||
pub fn encode(indexed_at: DateTime<Utc>, uri: &str) -> String {
|
||||
let ts = indexed_at.timestamp_micros();
|
||||
let raw = format!("{ts}:{uri}");
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw.as_bytes())
|
||||
}
|
||||
|
||||
/// Decode a wire-format cursor string back into a [`CursorState`].
|
||||
///
|
||||
/// Returns an error string (not a typed error) so the route can put it
|
||||
/// directly into the 400 response body. The `Result` type is local.
|
||||
pub fn decode(s: &str) -> Result<CursorState, String> {
|
||||
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(s.as_bytes())
|
||||
.map_err(|e| format!("invalid cursor: {e}"))?;
|
||||
let text = std::str::from_utf8(&bytes).map_err(|e| format!("invalid cursor utf8: {e}"))?;
|
||||
let (ts_s, uri) = text
|
||||
.split_once(':')
|
||||
.ok_or_else(|| "invalid cursor: missing ':'".to_string())?;
|
||||
let ts: i64 = ts_s
|
||||
.parse()
|
||||
.map_err(|e| format!("invalid cursor ts: {e}"))?;
|
||||
Ok(CursorState {
|
||||
ts,
|
||||
uri: uri.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Helper for tests / callers that want a `DateTime<Utc>` back from a
|
||||
/// [`CursorState`]. The route doesn't need it (it uses the raw
|
||||
/// micros), but exposing it keeps the API symmetric.
|
||||
#[allow(dead_code)]
|
||||
pub fn ts_to_datetime(ts: i64) -> Option<DateTime<Utc>> {
|
||||
Utc.timestamp_micros(ts).single()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn encode_decode_round_trip() {
|
||||
let dt = Utc
|
||||
.timestamp_micros(1_700_000_000_123_456)
|
||||
.single()
|
||||
.expect("valid ts");
|
||||
let uri = "at://did:plc:abc/app.twi.post/3k2";
|
||||
let encoded = encode(dt, uri);
|
||||
// Encoded form is base64url (no '+' / '/') and unpadded.
|
||||
assert!(!encoded.contains('='));
|
||||
assert!(!encoded.contains('+'));
|
||||
assert!(!encoded.contains('/'));
|
||||
let decoded = decode(&encoded).unwrap();
|
||||
assert_eq!(decoded.ts, dt.timestamp_micros());
|
||||
assert_eq!(decoded.uri, uri);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_garbage() {
|
||||
assert!(decode("!!!not-base64!!!").is_err());
|
||||
assert!(decode("").is_err());
|
||||
// Valid base64 but missing colon
|
||||
let no_colon = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.encode(b"1234567890");
|
||||
assert!(decode(&no_colon).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_non_numeric_ts() {
|
||||
let bad = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.encode(b"notanumber:at://x");
|
||||
assert!(decode(&bad).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ts_round_trip_through_datetime() {
|
||||
let dt = Utc
|
||||
.timestamp_micros(1_700_000_000_000_001)
|
||||
.single()
|
||||
.expect("valid ts");
|
||||
let encoded = encode(dt, "at://x/y/z");
|
||||
let decoded = decode(&encoded).unwrap();
|
||||
let back = ts_to_datetime(decoded.ts).unwrap();
|
||||
assert_eq!(back, dt);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
//! Wire types for the AppView's read API.
|
||||
//!
|
||||
//! These structs are the exact JSON shape the Tauri client and any other
|
||||
//! consumer sees. They are `Serialize` for the HTTP response and
|
||||
//! `FromRow` for the SQL row, which is why each field is a flat
|
||||
//! primitive or `Vec<String>`.
|
||||
//!
|
||||
//! `langs` is stored in the DB as a nullable `TEXT[]` (see the
|
||||
//! `posts.langs` column in `migrations/appview/0001_init.sql`). The
|
||||
//! wire format, however, guarantees `Vec<String>` — never `null` — so
|
||||
//! we use a custom `sqlx::Decode` impl via the `Langs` newtype that
|
||||
//! collapses `NULL` and an empty array into `vec![]`.
|
||||
//!
|
||||
//! `embed` is stored as nullable `JSONB` and round-trips as
|
||||
//! `Option<serde_json::Value>` — the UI sniffs `$type` to decide
|
||||
//! which sub-component to render (`app.bsky.embed.images` etc.).
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use sqlx::{Decode, FromRow, Postgres, Row, Type, ValueRef};
|
||||
|
||||
use crate::indexer::EmbedColumn;
|
||||
|
||||
/// One row of `posts` as returned by the read API.
|
||||
///
|
||||
/// `handle` may be empty for posts indexed via Jetstream (we don't
|
||||
/// currently back-resolve the DID); callers should display `@<handle>`
|
||||
/// and fall back to a derived value from the DID when this is empty.
|
||||
///
|
||||
/// `embed` is the verbatim AT-Protocol embed object — `None` for
|
||||
/// plain-text posts.
|
||||
///
|
||||
/// `like_count` / `repost_count` are denormalized counters maintained
|
||||
/// by `upsert_like` / `upsert_repost` against the migration-0004
|
||||
/// unique index. They are read with zero extra SQL when the row is
|
||||
/// fetched (just one more column), so they scale even when the
|
||||
/// `likes` / `reposts` tables have 100k+ rows.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PostRow {
|
||||
pub uri: String,
|
||||
pub did: String,
|
||||
pub handle: String,
|
||||
pub rkey: String,
|
||||
pub collection: String,
|
||||
pub text: String,
|
||||
pub cid: String,
|
||||
pub parent_uri: Option<String>,
|
||||
pub root_uri: Option<String>,
|
||||
pub embed: Option<Value>,
|
||||
pub langs: Langs,
|
||||
pub created_at: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
pub like_count: i64,
|
||||
#[serde(default)]
|
||||
pub repost_count: i64,
|
||||
}
|
||||
|
||||
/// Raw `FromRow` impl — we read `embed` as the helper newtype then
|
||||
/// unwrap it to `Option<Value>` so the wire shape stays clean.
|
||||
impl<'r> FromRow<'r, sqlx::postgres::PgRow> for PostRow {
|
||||
fn from_row(row: &'r sqlx::postgres::PgRow) -> sqlx::Result<Self> {
|
||||
let embed: EmbedColumn = row.try_get("embed")?;
|
||||
Ok(PostRow {
|
||||
uri: row.try_get("uri")?,
|
||||
did: row.try_get("did")?,
|
||||
handle: row.try_get("handle")?,
|
||||
rkey: row.try_get("rkey")?,
|
||||
collection: row.try_get("collection")?,
|
||||
text: row.try_get("text")?,
|
||||
cid: row.try_get("cid")?,
|
||||
parent_uri: row.try_get("parent_uri")?,
|
||||
root_uri: row.try_get("root_uri")?,
|
||||
embed: embed.0,
|
||||
langs: row.try_get("langs")?,
|
||||
created_at: row.try_get("created_at")?,
|
||||
like_count: row.try_get::<i64, _>("like_count").unwrap_or(0),
|
||||
repost_count: row.try_get::<i64, _>("repost_count").unwrap_or(0),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal companion row used by the timeline cursor builder: the
|
||||
/// `PostRow` payload plus the post's `indexed_at` so the route can
|
||||
/// encode the next cursor without a second SELECT. Not serialised.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PostRowWithIndexed {
|
||||
pub uri: String,
|
||||
pub did: String,
|
||||
pub handle: String,
|
||||
pub rkey: String,
|
||||
pub collection: String,
|
||||
pub text: String,
|
||||
pub cid: String,
|
||||
pub parent_uri: Option<String>,
|
||||
pub root_uri: Option<String>,
|
||||
pub embed: Option<Value>,
|
||||
pub langs: Langs,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub indexed_at: DateTime<Utc>,
|
||||
pub like_count: i64,
|
||||
pub repost_count: i64,
|
||||
}
|
||||
|
||||
impl<'r> FromRow<'r, sqlx::postgres::PgRow> for PostRowWithIndexed {
|
||||
fn from_row(row: &'r sqlx::postgres::PgRow) -> sqlx::Result<Self> {
|
||||
let embed: EmbedColumn = row.try_get("embed")?;
|
||||
Ok(PostRowWithIndexed {
|
||||
uri: row.try_get("uri")?,
|
||||
did: row.try_get("did")?,
|
||||
handle: row.try_get("handle")?,
|
||||
rkey: row.try_get("rkey")?,
|
||||
collection: row.try_get("collection")?,
|
||||
text: row.try_get("text")?,
|
||||
cid: row.try_get("cid")?,
|
||||
parent_uri: row.try_get("parent_uri")?,
|
||||
root_uri: row.try_get("root_uri")?,
|
||||
embed: embed.0,
|
||||
langs: row.try_get("langs")?,
|
||||
created_at: row.try_get("created_at")?,
|
||||
indexed_at: row.try_get("indexed_at")?,
|
||||
like_count: row.try_get::<i64, _>("like_count").unwrap_or(0),
|
||||
repost_count: row.try_get::<i64, _>("repost_count").unwrap_or(0),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PostRowWithIndexed> for PostRow {
|
||||
fn from(r: PostRowWithIndexed) -> Self {
|
||||
PostRow {
|
||||
uri: r.uri,
|
||||
did: r.did,
|
||||
handle: r.handle,
|
||||
rkey: r.rkey,
|
||||
collection: r.collection,
|
||||
text: r.text,
|
||||
cid: r.cid,
|
||||
parent_uri: r.parent_uri,
|
||||
root_uri: r.root_uri,
|
||||
embed: r.embed,
|
||||
langs: r.langs,
|
||||
created_at: r.created_at,
|
||||
like_count: r.like_count,
|
||||
repost_count: r.repost_count,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /api/timeline/home` response. `cursor` is `None` when the
|
||||
/// caller has reached the end of the available rows.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct TimelineResponse {
|
||||
pub posts: Vec<PostRow>,
|
||||
pub cursor: Option<String>,
|
||||
}
|
||||
|
||||
/// `GET /api/profile/...` response.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ProfileResponse {
|
||||
pub did: String,
|
||||
pub handle: String,
|
||||
pub posts: Vec<PostRow>,
|
||||
pub followers: i64,
|
||||
pub following: i64,
|
||||
}
|
||||
|
||||
/// `GET /api/search` response. `q` echoes the search string so the
|
||||
/// client can correlate the request with the response.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SearchResponse {
|
||||
pub posts: Vec<PostRow>,
|
||||
pub q: String,
|
||||
}
|
||||
|
||||
// -- Langs newtype ----------------------------------------------------------
|
||||
|
||||
/// A list of language tags. Always serialises as `Vec<String>`, never
|
||||
/// as `null`. Decodes a nullable `TEXT[]` column into an empty vector
|
||||
/// when the column is SQL `NULL`, and otherwise parses the array.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct Langs(pub Vec<String>);
|
||||
|
||||
impl From<Vec<String>> for Langs {
|
||||
fn from(v: Vec<String>) -> Self {
|
||||
Langs(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Langs {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Postgres> for Langs {
|
||||
fn decode(
|
||||
value: <Postgres as sqlx::Database>::ValueRef<'r>,
|
||||
) -> Result<Self, sqlx::error::BoxDynError> {
|
||||
// A `TEXT[]` column can come back as NULL (Option<Vec<String>>)
|
||||
// or as a real array. We collapse both into `Langs(vec![])` when
|
||||
// there are no elements, so the wire shape is always an array.
|
||||
if value.is_null() {
|
||||
return Ok(Langs(Vec::new()));
|
||||
}
|
||||
let raw: Option<Vec<String>> = <Option<Vec<String>> as Decode<Postgres>>::decode(value)?;
|
||||
Ok(Langs(raw.unwrap_or_default()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Type<Postgres> for Langs {
|
||||
fn type_info() -> <Postgres as sqlx::Database>::TypeInfo {
|
||||
<Vec<String> as Type<Postgres>>::type_info()
|
||||
}
|
||||
fn compatible(ty: &<Postgres as sqlx::Database>::TypeInfo) -> bool {
|
||||
<Vec<String> as Type<Postgres>>::compatible(ty)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user