use std::borrow::Cow;
use std::fmt;
use anyhow::Result;
use chrono::Utc;
use rusqlite::{Connection, OptionalExtension, params};
use uuid::Uuid;
use super::{MEMORY_COLS, SqliteStore, conversion_err, row_to_memory};
use crate::keys::identity_tag_of;
use crate::schema::{Memory, Scope};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Principal {
Owner,
User(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AccessDenied {
pub memory_id: Uuid,
}
impl fmt::Display for AccessDenied {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "memory {} belongs to another user", self.memory_id)
}
}
impl std::error::Error for AccessDenied {}
pub fn can_read(principal: &Principal, memory: &Memory) -> bool {
match principal {
Principal::Owner => true,
Principal::User(_) => memory.scope == Scope::Shared || owns(principal, memory),
}
}
pub fn can_change(principal: &Principal, memory: &Memory) -> bool {
match principal {
Principal::Owner => true,
Principal::User(_) => owns(principal, memory),
}
}
fn owns(principal: &Principal, memory: &Memory) -> bool {
matches!(principal, Principal::User(id) if memory.author.as_deref() == Some(id.as_str()))
}
impl SqliteStore {
pub fn local_author(&self) -> Result<String> {
local_author_on(&self.reader(), self.machine_id())
}
pub fn get_memory_for(&self, id: Uuid, principal: &Principal) -> Result<Option<Memory>> {
Ok(crate::store::Store::get_memory(self, id)?.filter(|m| can_read(principal, m)))
}
pub fn check_change(&self, id: Uuid, principal: &Principal) -> Result<()> {
match crate::store::Store::get_memory(self, id)? {
Some(memory) if !can_change(principal, &memory) => {
Err(AccessDenied { memory_id: id }.into())
}
_ => Ok(()),
}
}
pub fn set_memory_scope(&self, id: Uuid, scope: Scope, principal: &Principal) -> Result<bool> {
self.with_txn(|tx| {
let Some(memory) = Self::memory_on_tx(tx, id)? else {
return Ok(false);
};
if !can_change(principal, &memory) {
return Err(AccessDenied { memory_id: id }.into());
}
if memory.scope == scope {
return Ok(true);
}
tx.execute(
"UPDATE memories SET scope = ?2, updated_at = ?3 WHERE id = ?1",
params![id.to_string(), scope_to_str(scope), Utc::now().to_rfc3339()],
)?;
if let Some(memory) = Self::memory_on_tx(tx, id)? {
self.log_memory_update(tx, &memory)?;
}
Ok(true)
})
}
pub fn export_memories_for(
&self,
principal: &Principal,
sink: &mut dyn FnMut(Memory) -> Result<()>,
) -> Result<()> {
let conn = self.reader();
let mut stmt = conn.prepare(&format!("SELECT {MEMORY_COLS} FROM memories ORDER BY id"))?;
let mut rows = stmt.query([])?;
while let Some(row) = rows.next()? {
let memory = row_to_memory(row, false)?;
if can_read(principal, &memory) {
let mut full = self.full_text_form(&conn, &memory)?.into_owned();
full.embedding = Vec::new();
sink(full)?;
}
}
Ok(())
}
pub(crate) fn attributed<'m>(
&self,
conn: &Connection,
memory: &'m Memory,
) -> Result<Cow<'m, Memory>> {
match attribution(conn, memory.id)? {
Some(row) => Ok(overlay(Cow::Borrowed(memory), row)),
None if memory.author.is_some() => Ok(Cow::Borrowed(memory)),
None => Ok(Cow::Owned(Memory {
author: Some(local_author_on(conn, self.machine_id())?),
..memory.clone()
})),
}
}
pub(crate) fn with_row_attribution<'m>(
conn: &Connection,
memory: Cow<'m, Memory>,
) -> Result<Cow<'m, Memory>> {
Ok(match attribution(conn, memory.id)? {
Some(row) => overlay(memory, row),
None => memory,
})
}
}
fn overlay(memory: Cow<'_, Memory>, (author, scope): (Option<String>, Scope)) -> Cow<'_, Memory> {
if memory.author == author && memory.scope == scope {
return memory;
}
let mut owned = memory.into_owned();
owned.author = author;
owned.scope = scope;
Cow::Owned(owned)
}
fn attribution(conn: &Connection, id: Uuid) -> Result<Option<(Option<String>, Scope)>> {
conn.query_row(
"SELECT author, scope FROM memories WHERE id = ?1",
params![id.to_string()],
|r| Ok((r.get(0)?, parse_scope(&r.get::<_, String>(1)?)?)),
)
.optional()
.map_err(Into::into)
}
fn local_author_on(conn: &Connection, machine_id: &str) -> Result<String> {
Ok(identity_tag_of(conn, machine_id)?.unwrap_or_else(|| format!("device:{machine_id}")))
}
pub(crate) fn scope_to_str(scope: Scope) -> &'static str {
match scope {
Scope::Private => "private",
Scope::Shared => "shared",
}
}
pub(crate) fn parse_scope(s: &str) -> rusqlite::Result<Scope> {
match s {
"private" => Ok(Scope::Private),
"shared" => Ok(Scope::Shared),
other => Err(conversion_err(std::io::Error::other(format!(
"unknown scope: {other}"
)))),
}
}