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,5 @@
|
||||
pub mod schema;
|
||||
pub mod validate;
|
||||
|
||||
pub use schema::{Lex, LexDef, LexRecord, Record};
|
||||
pub use validate::{validate_record, LexRegistry, ValidationError};
|
||||
@@ -0,0 +1,38 @@
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Lex {
|
||||
pub lexicon: u32,
|
||||
pub id: String,
|
||||
pub defs: serde_json::Map<String, Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LexDef {
|
||||
#[serde(rename = "type")]
|
||||
pub def_type: String,
|
||||
#[serde(flatten)]
|
||||
pub extra: serde_json::Map<String, Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LexRecord {
|
||||
#[serde(rename = "type")]
|
||||
pub def_type: String,
|
||||
pub key: String,
|
||||
pub record: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Record {
|
||||
pub collection: String,
|
||||
pub value: Value,
|
||||
}
|
||||
|
||||
impl Lex {
|
||||
pub fn from_json(s: &str) -> Result<Self> {
|
||||
Ok(serde_json::from_str(s)?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::schema::Lex;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ValidationError {
|
||||
#[error("text exceeds max length ({max}): got {got}")]
|
||||
TextTooLong { max: usize, got: usize },
|
||||
#[error("text contains forbidden chars: {0}")]
|
||||
TextInvalidChars(String),
|
||||
#[error("missing required field: {0}")]
|
||||
MissingField(&'static str),
|
||||
#[error("invalid datetime: {0}")]
|
||||
InvalidDatetime(String),
|
||||
#[error("type mismatch: expected {expected}, got {actual}")]
|
||||
TypeMismatch { expected: &'static str, actual: String },
|
||||
#[error("unknown lexicon: {0}")]
|
||||
UnknownLexicon(String),
|
||||
#[error("text exceeds max graphemes ({max}): got {got}")]
|
||||
GraphemesTooMany { max: usize, got: usize },
|
||||
}
|
||||
|
||||
pub fn validate_record(lex: &Lex, value: &Value) -> Result<(), ValidationError> {
|
||||
let main = lex
|
||||
.defs
|
||||
.get("main")
|
||||
.and_then(|v| v.as_object())
|
||||
.ok_or_else(|| ValidationError::UnknownLexicon(lex.id.clone()))?;
|
||||
let record = main
|
||||
.get("record")
|
||||
.and_then(|v| v.as_object())
|
||||
.ok_or_else(|| ValidationError::UnknownLexicon(lex.id.clone()))?;
|
||||
|
||||
let required: Vec<String> = record
|
||||
.get("required")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_str().map(|s| s.to_string()))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let obj = value.as_object().ok_or(ValidationError::TypeMismatch {
|
||||
expected: "object",
|
||||
actual: format!("{}", value),
|
||||
})?;
|
||||
|
||||
for f in &required {
|
||||
if !obj.contains_key(f) {
|
||||
let s: &'static str = Box::leak(f.clone().into_boxed_str());
|
||||
return Err(ValidationError::MissingField(s));
|
||||
}
|
||||
}
|
||||
|
||||
let props = record
|
||||
.get("properties")
|
||||
.and_then(|v| v.as_object())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(text_schema) = props.get("text").and_then(|v| v.as_object()) {
|
||||
if let Some(text) = obj.get("text").and_then(|v| v.as_str()) {
|
||||
if let Some(max) = text_schema.get("maxLength").and_then(|v| v.as_u64()) {
|
||||
let char_count = text.chars().count();
|
||||
if char_count > max as usize {
|
||||
return Err(ValidationError::TextTooLong {
|
||||
max: max as usize,
|
||||
got: char_count,
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(max_g) = text_schema.get("maxGraphemes").and_then(|v| v.as_u64()) {
|
||||
let g_count = grapheme_count(text);
|
||||
if g_count > max_g as usize {
|
||||
return Err(ValidationError::GraphemesTooMany {
|
||||
max: max_g as usize,
|
||||
got: g_count,
|
||||
});
|
||||
}
|
||||
}
|
||||
if text.is_empty() {
|
||||
return Err(ValidationError::TextInvalidChars(
|
||||
"empty text not allowed".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(dt_schema) = props.get("createdAt").and_then(|v| v.as_object()) {
|
||||
if let Some(dt) = obj.get("createdAt").and_then(|v| v.as_str()) {
|
||||
if dt_schema.get("type").and_then(|v| v.as_str()) == Some("datetime") {
|
||||
if chrono::DateTime::parse_from_rfc3339(dt).is_err() {
|
||||
return Err(ValidationError::InvalidDatetime(dt.into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn grapheme_count(s: &str) -> usize {
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
s.graphemes(true).count()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LexRegistry {
|
||||
pub lexicons: std::collections::HashMap<String, Lex>,
|
||||
}
|
||||
|
||||
impl LexRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
lexicons: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(lex: Lex) -> Self {
|
||||
let mut r = Self::new();
|
||||
r.lexicons.insert(lex.id.clone(), lex);
|
||||
r
|
||||
}
|
||||
|
||||
pub fn get(&self, id: &str) -> Option<&Lex> {
|
||||
self.lexicons.get(id)
|
||||
}
|
||||
|
||||
pub fn validate(&self, collection: &str, value: &Value) -> Result<(), ValidationError> {
|
||||
let lex = self
|
||||
.get(collection)
|
||||
.ok_or_else(|| ValidationError::UnknownLexicon(collection.into()))?;
|
||||
validate_record(lex, value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for LexRegistry {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
const LEX_160: &str = include_str!("../../../lexicons/app/twi/post.json");
|
||||
|
||||
#[test]
|
||||
fn accepts_under_limit() {
|
||||
let lex = Lex::from_json(LEX_160).unwrap();
|
||||
let v = json!({
|
||||
"text": "short",
|
||||
"createdAt": "2025-01-01T00:00:00Z"
|
||||
});
|
||||
validate_record(&lex, &v).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_over_limit() {
|
||||
let lex = Lex::from_json(LEX_160).unwrap();
|
||||
let long = "x".repeat(200);
|
||||
let v = json!({
|
||||
"text": long,
|
||||
"createdAt": "2025-01-01T00:00:00Z"
|
||||
});
|
||||
assert!(matches!(
|
||||
validate_record(&lex, &v),
|
||||
Err(ValidationError::TextTooLong { max: 160, .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_text_and_createdAt() {
|
||||
let lex = Lex::from_json(LEX_160).unwrap();
|
||||
let v = json!({ "text": "x" });
|
||||
assert!(matches!(
|
||||
validate_record(&lex, &v),
|
||||
Err(ValidationError::MissingField("createdAt"))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_graphemes_for_emoji() {
|
||||
let lex = Lex::from_json(LEX_160).unwrap();
|
||||
let v = json!({
|
||||
"text": "🎉".repeat(50),
|
||||
"createdAt": "2025-01-01T00:00:00Z"
|
||||
});
|
||||
assert!(validate_record(&lex, &v).is_ok());
|
||||
|
||||
let v2 = json!({
|
||||
"text": "🎉".repeat(200),
|
||||
"createdAt": "2025-01-01T00:00:00Z"
|
||||
});
|
||||
assert!(matches!(
|
||||
validate_record(&lex, &v2),
|
||||
Err(ValidationError::TextTooLong { max: 160, .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grapheme_count_handles_zwj() {
|
||||
let s = "\u{1f468}\u{200d}\u{1f4bb}";
|
||||
assert_eq!(s.chars().count(), 3);
|
||||
assert_eq!(grapheme_count(s), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_empty_text() {
|
||||
let lex = Lex::from_json(LEX_160).unwrap();
|
||||
let v = json!({
|
||||
"text": "",
|
||||
"createdAt": "2025-01-01T00:00:00Z"
|
||||
});
|
||||
assert!(matches!(
|
||||
validate_record(&lex, &v),
|
||||
Err(ValidationError::TextInvalidChars(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_lookup_works() {
|
||||
let lex = Lex::from_json(LEX_160).unwrap();
|
||||
let reg = LexRegistry::load(lex);
|
||||
assert!(reg.validate("app.twi.post", &json!({"text": "ok", "createdAt": "2025-01-01T00:00:00Z"})).is_ok());
|
||||
assert!(reg.validate("unknown.lex", &json!({})).is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user