feat: file/image upload + separated framework root (sessions/data/uploads)

- POST /api/uploads: base64 -> shared ~/.strata-ctl/uploads store (uuid+ext),
  content-sniffed kind (image/text/binary), text token-counted via the model
  tokenizer; metadata persisted in a new uploads table.
- Chat attachments routed by kind: images -> Vision bridge (multipart image_url),
  small text (<=2000 tokens) inlined, large text/binary -> path + shell_exec
  reminder; binaries never inlined. Attachment context persisted with the turn.
- GUI: attach button + file picker, removable chips, attachments sent with the
  turn and shown on the user bubble; cleared on session switch.
- Framework root ~/.strata-ctl separated by type: sessions/<name>/, data/ (SQLite,
  moved from ~/.config/strata-ctl), uploads/. Legacy DB copied once on first run.
- count_tokens seam on Formatter (real tokenizer override) + ChatService.
- i18n: upload errors + attachment markers (backend) and attach.* (GUI), it+en.
- 121 tests + 2 ignored; clippy/fmt clean; validated live (upload routing, real
  tokenizer count, image->Vision answered "Rosso", new layout).
This commit is contained in:
adm committed 2026-11-25 16:25:55 +01:00
1 parent 498e3dbc1b
commit 65f8111ba2
19 files changed
+672 -47

No files matched your search

+6
View File
@@ -69,6 +69,12 @@ pub trait Formatter: Send + Sync {
2048
}
/// Token count of a text, used to route uploads (small-text inline threshold).
/// Default is a byte-length estimate; dialects with a real tokenizer override.
fn count_tokens(&self, text: &str) -> usize {
text.len()
}
/// Render the conversation to a prompt and derive the engine request.
/// Errors map straight to an HTTP 400.
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope>;
+1
View File
@@ -11,6 +11,7 @@ pub mod service;
mod sessions;
pub mod stop;
pub mod types;
mod uploads;
mod web;
pub use formatter::{Decoder, Formatter, Piece, Prompt};
+3 -1
View File
@@ -15,7 +15,7 @@ use std::sync::Arc;
use super::anthropic::{self, AnthropicRequest, AnthropicStream};
use super::service::ChatService;
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
use super::{sessions, web};
use super::{sessions, uploads, web};
use crate::store::Store;
/// Build the router. Mount this inside any axum `Router` or serve it directly.
@@ -80,6 +80,7 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router {
)
.route("/api/sessions/{id}/messages", get(sessions::get_messages))
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
.route("/api/uploads", post(uploads::upload))
.route(
"/api/settings/defaults",
get(sessions::get_defaults).put(sessions::put_defaults),
@@ -178,6 +179,7 @@ pub(crate) struct AppState {
}
/// An OpenAI error with the HTTP status the code implies.
#[derive(Debug)]
pub struct Error {
status: StatusCode,
body: ApiErrorEnvelope,
+5
View File
@@ -38,6 +38,11 @@ impl ChatService {
self.fmt.model_name()
}
/// Token count of a text via the formatter's tokenizer (upload routing).
pub fn count_tokens(&self, text: &str) -> usize {
self.fmt.count_tokens(text)
}
/// One-shot completion.
pub async fn complete(&self, req: &ChatRequest) -> Result<ChatResponse, ApiErrorEnvelope> {
let mut prompt = self.build_prompt_blocking(req).await?;
+46 -8
View File
@@ -17,6 +17,7 @@ use serde::Deserialize;
use super::routes::{AppState, Error};
use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage};
use super::uploads;
use crate::agent::shell::{HostShell, ShellRunner};
use crate::agent::{self, AgentEvent};
use crate::i18n::t;
@@ -25,7 +26,7 @@ use crate::store::{NewMessage, Session, SessionSettings, Stats, Store, StoredMes
use tokio_stream::wrappers::UnboundedReceiverStream;
/// Run a synchronous store operation off the async runtime.
async fn with_store<T, F>(st: &AppState, f: F) -> Result<T, Error>
pub(crate) async fn with_store<T, F>(st: &AppState, f: F) -> Result<T, Error>
where
F: FnOnce(Arc<dyn Store>) -> anyhow::Result<T> + Send + 'static,
T: Send + 'static,
@@ -69,6 +70,9 @@ pub(crate) struct SessionChat {
/// Run the model as an agent with the `shell_exec` tool (host mode).
#[serde(default)]
agent: bool,
/// Uploaded file ids to attach to this turn (routed by kind/token count).
#[serde(default)]
attachments: Vec<String>,
#[serde(default)]
max_tokens: Option<u32>,
#[serde(default)]
@@ -208,7 +212,13 @@ fn text_message(role: Role, text: String) -> ChatMessage {
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest {
fn build_request(
sess: &Session,
history: &[StoredMessage],
body: &SessionChat,
extra: &str,
images: &[serde_json::Value],
) -> ChatRequest {
let mut messages = Vec::new();
// Structural identity reminder: always present, not an editable setting. It
// tells the agent its name and personal workspace folder.
@@ -228,7 +238,24 @@ fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat)
.and_then(|s| serde_json::from_str(s).ok());
messages.push(msg);
}
messages.push(text_message(Role::User, body.content.clone()));
// The user turn: typed text + attachment context (inline files / path
// reminders / image markers). Images become multipart image_url parts that
// the Vision bridge materializes; without images it stays a plain string.
let user_text = format!("{}{}", body.content, extra);
if images.is_empty() {
messages.push(text_message(Role::User, user_text));
} else {
let mut parts = vec![serde_json::json!({"type": "text", "text": user_text})];
parts.extend(images.iter().cloned());
messages.push(ChatMessage {
role: Role::User,
content: Some(serde_json::Value::Array(parts)),
tool_call_id: None,
tool_calls: None,
name: None,
reasoning_content: None,
});
}
ChatRequest {
model: sess.model.clone(),
messages,
@@ -339,7 +366,7 @@ pub(crate) async fn session_chat(
// workspace folder (its identity). Done before building the prompt so the
// identity reminder can reference the folder.
if history.is_empty() {
let root = st.workspace_root.clone();
let root = st.workspace_root.join("sessions");
let title = sess.title.clone();
let idc = id.clone();
if let Ok(folder) = with_store(&st, move |s| {
@@ -362,10 +389,20 @@ pub(crate) async fn session_chat(
}
}
let mut req = build_request(&sess, &history, &body);
// Resolve attachments (upload ids) into metadata and route by kind/tokens.
let mut metas = Vec::new();
for aid in &body.attachments {
let aid = aid.clone();
if let Ok(Some(m)) = with_store(&st, move |s| s.get_upload(&aid)).await {
metas.push(m);
}
}
let extra = uploads::context_text(&metas);
let images = uploads::image_parts(&metas);
let mut req = build_request(&sess, &history, &body, &extra, &images);
// Persist the user turn before generating.
let user_content = body.content.clone();
// Persist the user turn (text + attachment context) before generating.
let user_content = format!("{}{}", body.content, extra);
if let Err(e) = with_store(&st, {
let id = id.clone();
move |s| {
@@ -556,11 +593,12 @@ mod tests {
content: "ciao".into(),
stream: false,
agent: false,
attachments: Vec::new(),
max_tokens: None,
temperature: None,
top_p: None,
};
let req = build_request(&sess, &[], &body);
let req = build_request(&sess, &[], &body, "", &[]);
// Identity reminder first (name + folder), then the session SP, then user.
assert!(matches!(req.messages[0].role, Role::System));
let t0 = req.messages[0].text().unwrap();
+239
View File
@@ -0,0 +1,239 @@
//! File/image uploads for the GUI.
//!
//! Bytes land in a single shared on-disk store (`<workspace_root>/uploads`,
//! filename converted to a uuid keeping the extension); metadata is persisted.
//! Content is classified by *sniffing* (not extension) and routed at chat time:
//! images go through the Vision bridge, small text is inlined into context,
//! large text and binaries are handed to the agent as a path (it reads
//! selectively via `shell_exec`). "Small" is measured in model tokens, never
//! characters. Binaries never enter the context directly.
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use axum::extract::State;
use axum::response::Json;
use base64::Engine;
use serde::Deserialize;
use serde_json::{json, Value as JsonValue};
use super::routes::{AppState, Error};
use super::sessions::with_store;
use crate::i18n::t;
use crate::store::UploadMeta;
/// Cap on an uploaded file body.
const MAX_UPLOAD_BYTES: usize = 32 * 1024 * 1024;
/// Text files at or below this token count are inlined into context; larger ones
/// are handed to the agent as a path. A knob, not a dogma.
pub const INLINE_TOKEN_THRESHOLD: u32 = 2000;
#[derive(Deserialize)]
pub(crate) struct UploadRequest {
name: String,
/// File bytes as base64 (raw, or a `data:...;base64,` URL).
data: String,
}
/// Unique filename stem without a `uuid` dependency (nanos + counter).
fn unique_stem() -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
format!("{nanos:016x}{n:08x}")
}
/// Magic-byte image detection (formats the Vision bridge reads or normalizes).
fn image_ext(data: &[u8]) -> Option<&'static str> {
if data.starts_with(&[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n']) {
Some(".png")
} else if data.starts_with(&[0xff, 0xd8, 0xff]) {
Some(".jpg")
} else if data.starts_with(b"GIF") {
Some(".gif")
} else if data.starts_with(b"BM") {
Some(".bmp")
} else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
Some(".webp")
} else {
None
}
}
/// Classify by content: image (magic bytes), text (valid UTF-8, no NUL), else
/// binary. The extension is irrelevant to the decision.
pub fn sniff_kind(data: &[u8]) -> &'static str {
if image_ext(data).is_some() {
"image"
} else if !data.contains(&0) && std::str::from_utf8(data).is_ok() {
"text"
} else {
"binary"
}
}
/// Whether an attachment is inlined into context (small text) rather than handed
/// to the agent as a path. Images go through Vision; binaries never inline.
pub fn routes_inline(kind: &str, tokens: u32) -> bool {
kind == "text" && tokens <= INLINE_TOKEN_THRESHOLD
}
/// Text appended to the user turn for attachments: inline small text files,
/// path reminders for large/binary files, markers for images. Used both for the
/// live prompt and for persistence, so context survives across turns.
pub fn context_text(metas: &[UploadMeta]) -> String {
let mut s = String::new();
for m in metas {
if m.kind == "image" {
s.push_str(&t("upload.image_marker", &[("name", &m.original_name)]));
} else if routes_inline(&m.kind, m.tokens) {
let content = std::fs::read_to_string(&m.path).unwrap_or_default();
s.push_str(&t(
"upload.inline_file",
&[("name", &m.original_name), ("content", &content)],
));
} else {
s.push_str(&t(
"upload.path_file",
&[("name", &m.original_name), ("path", &m.path)],
));
}
}
s
}
/// `image_url` parts for the live request; the Vision bridge reads the local path.
pub fn image_parts(metas: &[UploadMeta]) -> Vec<JsonValue> {
metas
.iter()
.filter(|m| m.kind == "image")
.map(|m| json!({"type": "image_url", "image_url": {"url": m.path}}))
.collect()
}
/// A safe extension taken from the original name, if present and sane.
fn original_ext(name: &str) -> Option<String> {
let ext = name.rsplit_once('.')?.1;
if !ext.is_empty() && ext.len() <= 8 && ext.chars().all(|c| c.is_ascii_alphanumeric()) {
Some(format!(".{}", ext.to_ascii_lowercase()))
} else {
None
}
}
fn decode_data(data: &str) -> Result<Vec<u8>, Error> {
let b64 = match data.strip_prefix("data:") {
Some(rest) => rest.split_once(',').map(|(_, d)| d).unwrap_or(rest),
None => data,
};
base64::engine::general_purpose::STANDARD
.decode(b64.trim())
.map_err(|_| Error::bad_request(t("upload.bad_base64", &[])))
}
/// `POST /api/uploads` — store a file and return its metadata (kind, tokens, path).
pub(crate) async fn upload(
State(st): State<AppState>,
Json(body): Json<UploadRequest>,
) -> Result<Json<UploadMeta>, Error> {
let bytes = decode_data(&body.data)?;
if bytes.is_empty() {
return Err(Error::bad_request(t("upload.empty", &[])));
}
if bytes.len() > MAX_UPLOAD_BYTES {
return Err(Error::bad_request(t("upload.too_large", &[])));
}
let kind = sniff_kind(&bytes);
let ext = match kind {
"image" => image_ext(&bytes).unwrap_or(".png").to_string(),
"text" => original_ext(&body.name).unwrap_or_else(|| ".txt".to_string()),
_ => original_ext(&body.name).unwrap_or_else(|| ".bin".to_string()),
};
let id = format!("{}{}", unique_stem(), ext);
let dir = st.workspace_root.join("uploads");
let path = dir.join(&id);
let size = bytes.len() as u64;
let kind_s = kind.to_string();
let svc = st.service.clone();
// File write + token count run off the async runtime (tokenizer can be heavy).
let (path_str, tokens) =
tokio::task::spawn_blocking(move || -> anyhow::Result<(String, u32)> {
std::fs::create_dir_all(&dir)?;
std::fs::write(&path, &bytes)?;
let tokens = if kind_s == "text" {
svc.count_tokens(&String::from_utf8_lossy(&bytes)) as u32
} else {
0
};
Ok((path.to_string_lossy().into_owned(), tokens))
})
.await
.map_err(|e| Error::internal(format!("upload task failed: {e}")))?
.map_err(|e| Error::internal(format!("upload write failed: {e}")))?;
let meta = UploadMeta {
id,
original_name: body.name,
path: path_str,
kind: kind.to_string(),
tokens,
size,
created_at: SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0),
};
let m = meta.clone();
with_store(&st, move |s| s.save_upload(&m)).await?;
Ok(Json(meta))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sniff_by_content_not_extension() {
assert_eq!(sniff_kind(b"hello world"), "text");
assert_eq!(sniff_kind("ciao àèì".as_bytes()), "text");
assert_eq!(
sniff_kind(&[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n']),
"image"
);
assert_eq!(sniff_kind(&[0xff, 0xd8, 0xff, 0x00]), "image");
assert_eq!(sniff_kind(b"\x7fELF\x00\x01"), "binary"); // ELF magic, has NUL
assert_eq!(sniff_kind(&[0x00, 0x01, 0x02]), "binary"); // NUL -> binary
assert_eq!(sniff_kind(&[0xff, 0xfe, 0xfd]), "binary"); // invalid UTF-8
}
#[test]
fn extension_sanitized() {
assert_eq!(original_ext("note.TXT").as_deref(), Some(".txt"));
assert_eq!(original_ext("archive.tar.gz").as_deref(), Some(".gz"));
assert_eq!(original_ext("noext"), None);
assert_eq!(original_ext("bad./etc/passwd"), None);
assert_eq!(original_ext("file.verylongext"), None);
}
#[test]
fn inline_routing_by_tokens() {
assert!(routes_inline("text", 100));
assert!(routes_inline("text", INLINE_TOKEN_THRESHOLD));
assert!(!routes_inline("text", INLINE_TOKEN_THRESHOLD + 1));
assert!(!routes_inline("binary", 0));
assert!(!routes_inline("image", 0));
}
#[test]
fn decode_raw_and_data_url() {
let raw = base64::engine::general_purpose::STANDARD.encode(b"ciao");
assert_eq!(decode_data(&raw).unwrap(), b"ciao");
let url = format!("data:text/plain;base64,{raw}");
assert_eq!(decode_data(&url).unwrap(), b"ciao");
assert!(decode_data("!!!not base64!!!").is_err());
}
}
+37 -10
View File
@@ -84,7 +84,9 @@ pub struct Config {
#[serde(default)]
pub system_prompt: Option<String>,
/// Parent of the per-session personal workspace folders (default `~/.strata-ctl`).
/// Framework root (default `~/.strata-ctl`, the Linux user's home). Content
/// is separated into subfolders by type: `sessions/` (agent workspace
/// folders), `data/` (SQLite), `uploads/` (uploaded files).
#[serde(default)]
pub workspace_root: Option<String>,
@@ -109,7 +111,7 @@ pub struct Config {
pub allowed_hosts: Option<Vec<String>>,
/// Path to the GUI session database (SQLite). Defaults to
/// `~/.config/strata-ctl/sessions.db`.
/// `<framework_root>/data/sessions.db`.
#[serde(default)]
pub db_path: Option<String>,
@@ -209,13 +211,12 @@ impl Config {
Duration::from_secs(self.silence_timeout_secs.unwrap_or(600))
}
/// Effective GUI database path: config > `~/.config/strata-ctl/sessions.db`.
/// Effective GUI database path: config > `<framework_root>/data/sessions.db`.
pub fn gui_db_path(&self) -> PathBuf {
if let Some(p) = &self.db_path {
return PathBuf::from(p);
}
let home = std::env::var("HOME").unwrap_or_default();
PathBuf::from(home).join(".config/strata-ctl/sessions.db")
self.data_dir().join("sessions.db")
}
/// The global default settings template for new GUI sessions, seeded from
@@ -232,8 +233,8 @@ impl Config {
}
}
/// Effective workspace root: config > `~/.strata-ctl`. Each session's
/// personal folder is created under this root at its first interaction.
/// Effective framework root: config > `~/.strata-ctl` (the Linux user's
/// home). Content is separated into subfolders by type.
pub fn workspace_root(&self) -> PathBuf {
if let Some(p) = &self.workspace_root {
return PathBuf::from(p);
@@ -242,6 +243,21 @@ impl Config {
PathBuf::from(home).join(".strata-ctl")
}
/// Per-session personal workspace folders: `<root>/sessions/<slug>`.
pub fn sessions_dir(&self) -> PathBuf {
self.workspace_root().join("sessions")
}
/// SQLite store directory: `<root>/data`.
pub fn data_dir(&self) -> PathBuf {
self.workspace_root().join("data")
}
/// Shared upload store: `<root>/uploads`.
pub fn upload_dir(&self) -> PathBuf {
self.workspace_root().join("uploads")
}
/// Effective language: config > `it`.
pub fn language(&self) -> String {
self.language.clone().unwrap_or_else(|| "it".to_string())
@@ -396,10 +412,21 @@ mod tests {
#[test]
fn gui_db_path_default_and_override() {
let cfg = Config::parse(REAL, "test").unwrap();
assert!(cfg
.gui_db_path()
.ends_with(".config/strata-ctl/sessions.db"));
assert!(cfg.gui_db_path().ends_with(".strata-ctl/data/sessions.db"));
let cfg2 = Config::parse(r#"{"exe":"/x/e","db_path":"/tmp/x.db"}"#, "test").unwrap();
assert_eq!(cfg2.gui_db_path(), PathBuf::from("/tmp/x.db"));
}
#[test]
fn framework_root_separates_content_types() {
let cfg = Config::parse(r#"{"exe":"/x/e","workspace_root":"/tmp/fwk"}"#, "test").unwrap();
assert_eq!(cfg.workspace_root(), PathBuf::from("/tmp/fwk"));
assert_eq!(cfg.sessions_dir(), PathBuf::from("/tmp/fwk/sessions"));
assert_eq!(cfg.data_dir(), PathBuf::from("/tmp/fwk/data"));
assert_eq!(cfg.upload_dir(), PathBuf::from("/tmp/fwk/uploads"));
assert_eq!(
cfg.gui_db_path(),
PathBuf::from("/tmp/fwk/data/sessions.db")
);
}
}
+7
View File
@@ -69,6 +69,13 @@ impl Formatter for InklingFormatter {
self.max_new_default
}
fn count_tokens(&self, text: &str) -> usize {
self.tok
.encode(text)
.map(|v| v.len())
.unwrap_or_else(|_| text.len())
}
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
let mut msgs = Self::messages_json(req);
prepare_messages(&mut msgs);
+34
View File
@@ -180,6 +180,7 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
// Open the GUI session store (SQLite). The web GUI + session API are mounted
// only when this succeeds; the standard /v1 API is unaffected either way.
let db_path = cfg.gui_db_path();
migrate_legacy_db(&db_path);
let store: Arc<dyn Store> = match SqliteStore::open(&db_path) {
Ok(s) => Arc::new(s),
Err(e) => {
@@ -266,6 +267,39 @@ fn print_plan(cfg: &Config, path: &std::path::Path, cli_host: Option<&str>, cli_
}
}
/// One-time relocation of the session DB from the old default
/// (`~/.config/strata-ctl/sessions.db`) into the framework `data/` dir. Copies
/// (never deletes) the legacy file plus any WAL/SHM siblings, so existing
/// history is preserved. A no-op once the new path exists or no legacy DB is
/// present.
fn migrate_legacy_db(db_path: &Path) {
if db_path.exists() {
return;
}
let home = std::env::var("HOME").unwrap_or_default();
let legacy = Path::new(&home).join(".config/strata-ctl/sessions.db");
if !legacy.exists() || legacy == db_path {
return;
}
if let Some(parent) = db_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
for suffix in ["", "-wal", "-shm"] {
let mut from = legacy.as_os_str().to_os_string();
from.push(suffix);
let mut to = db_path.as_os_str().to_os_string();
to.push(suffix);
if Path::new(&from).exists() {
let _ = std::fs::copy(&from, &to);
}
}
tracing::info!(
from = %legacy.display(),
to = %db_path.display(),
"relocated legacy session database into the framework data dir"
);
}
fn report_config_error(path: &std::path::Path, err: ConfigError) -> ExitCode {
eprintln!("error: {err}");
if let ConfigError::MissingExe = err {
+61
View File
@@ -120,6 +120,21 @@ pub struct Stats {
pub completion_tokens: u64,
}
/// Metadata for an uploaded file (bytes live on disk under the shared upload dir).
#[derive(Debug, Clone, Serialize)]
pub struct UploadMeta {
/// Stored filename (uuid + extension), unique; resolves the on-disk path.
pub id: String,
pub original_name: String,
pub path: String,
/// "image" | "text" | "binary" — decided by content sniff, not extension.
pub kind: String,
/// Token count for text (0 otherwise), measured with the model tokenizer.
pub tokens: u32,
pub size: u64,
pub created_at: i64,
}
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
pub trait Store: Send + Sync {
fn create_session(
@@ -141,6 +156,8 @@ pub trait Store: Send + Sync {
/// The global default settings template (None until seeded).
fn get_defaults(&self) -> Result<Option<SessionSettings>>;
fn set_defaults(&self, settings: &SessionSettings) -> Result<()>;
fn save_upload(&self, meta: &UploadMeta) -> Result<()>;
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>>;
}
fn now_secs() -> i64 {
@@ -190,6 +207,15 @@ CREATE TABLE IF NOT EXISTS defaults (
id INTEGER PRIMARY KEY CHECK (id = 1),
settings_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS uploads (
id TEXT PRIMARY KEY,
original_name TEXT NOT NULL,
path TEXT NOT NULL,
kind TEXT NOT NULL,
tokens INTEGER NOT NULL DEFAULT 0,
size INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
";
/// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for
@@ -470,6 +496,41 @@ impl Store for SqliteStore {
)?;
Ok(())
}
fn save_upload(&self, meta: &UploadMeta) -> Result<()> {
let conn = self.lock();
conn.execute(
"INSERT OR REPLACE INTO uploads (id, original_name, path, kind, tokens, size, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
meta.id,
meta.original_name,
meta.path,
meta.kind,
meta.tokens as i64,
meta.size as i64,
meta.created_at
],
)?;
Ok(())
}
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>> {
let conn = self.lock();
let mut stmt = conn.prepare("SELECT * FROM uploads WHERE id = ?1")?;
let mut rows = stmt.query_map(params![id], |r| {
Ok(UploadMeta {
id: r.get("id")?,
original_name: r.get("original_name")?,
path: r.get("path")?,
kind: r.get("kind")?,
tokens: r.get::<_, i64>("tokens")? as u32,
size: r.get::<_, i64>("size")? as u64,
created_at: r.get("created_at")?,
})
})?;
Ok(rows.next().transpose()?)
}
}
#[cfg(test)]