Skeleton, REST core, variables and JSON editor (M0–M2)

- knock-core: YAML collection format with unknown-field round trip,
  variable resolution across scopes with secrets and dynamic values,
  HTTP engine with manual redirects, cookie jar and large-body spill,
  basic/bearer/API key auth with debug output, assertions and extracts
- Tauri app: collection commands, file watcher, SQLite history,
  keyring-backed secrets
- Svelte UI: sidebar tree, tabs, request editor, response viewer,
  JSON form/code editor with schema hints, environments, settings
This commit is contained in:
2026-11-27 16:42:31 +01:00
commit f6484f4dc8
127 changed files with 22909 additions and 0 deletions
+623
View File
@@ -0,0 +1,623 @@
use crate::db;
use crate::state::AppState;
use crate::watch;
use indexmap::IndexMap;
use knock_core::collection::{Collection, EnvEntry, FolderNode, Problem};
use knock_core::model::*;
use knock_core::prepare::{ContextInput, RequestContext};
use knock_core::run::{execute, RunOutput};
use knock_core::secrets::{self, SecretStore};
use knock_core::vars::{VarInfo, DYNAMIC_VARS};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::sync::Arc;
use tauri::{AppHandle, Manager, State};
type Res<T> = Result<T, String>;
fn err(e: impl std::fmt::Display) -> String {
e.to_string()
}
fn errx(e: anyhow::Error) -> String {
format!("{e:#}")
}
// ---------------------------------------------------------------- collections
#[derive(Serialize)]
pub struct CollectionView {
pub id: String,
pub root: String,
pub name: String,
pub tree: FolderNode,
pub environments: Vec<EnvEntry>,
pub problems: Vec<Problem>,
}
fn view(c: &Collection) -> CollectionView {
CollectionView {
id: c.manifest.id.clone(),
root: c.root.display().to_string(),
name: c.manifest.name.clone(),
tree: c.tree.clone(),
environments: c.environments.clone(),
problems: c.problems.clone(),
}
}
fn remember_recent(state: &AppState, root: &str) {
let db = state.db.lock().unwrap();
let mut recent: Vec<String> = db::kv_get(&db, "recent")
.ok()
.flatten()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
recent.retain(|r| r != root);
recent.insert(0, root.to_string());
recent.truncate(12);
let _ = db::kv_set(&db, "recent", &serde_json::to_string(&recent).unwrap());
}
fn register(app: &AppHandle, state: &AppState, c: Collection) -> Res<CollectionView> {
let v = view(&c);
if let Ok(Some(json)) = db::jar_load(&state.db.lock().unwrap(), &v.id) {
state.engine.load_jar(&v.id, &json);
}
let root = c.root.clone();
state.collections.write().unwrap().insert(v.id.clone(), c);
remember_recent(state, &v.root);
watch::start(app, state, &v.id, &root);
Ok(v)
}
#[tauri::command]
pub fn collection_open(app: AppHandle, state: State<'_, AppState>, path: String) -> Res<CollectionView> {
let c = Collection::open(&path).map_err(errx)?;
register(&app, &state, c)
}
#[tauri::command]
pub fn collection_create(
app: AppHandle,
state: State<'_, AppState>,
path: String,
name: String,
) -> Res<CollectionView> {
let c = Collection::create(&path, &name).map_err(errx)?;
register(&app, &state, c)
}
#[tauri::command]
pub fn collection_get(state: State<'_, AppState>, id: String) -> Res<CollectionView> {
state.with_collection(&id, |c| Ok(view(c))).map_err(errx)
}
#[tauri::command]
pub fn collection_close(state: State<'_, AppState>, id: String) -> Res<()> {
state.collections.write().unwrap().remove(&id);
state.watchers.lock().unwrap().remove(&id);
Ok(())
}
#[tauri::command]
pub fn recent_collections(state: State<'_, AppState>) -> Res<Vec<String>> {
let db = state.db.lock().unwrap();
Ok(db::kv_get(&db, "recent")
.map_err(errx)?
.and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
.unwrap_or_default()
.into_iter()
.filter(|p| PathBuf::from(p).join("knock.yaml").exists())
.collect())
}
#[tauri::command]
pub fn recent_forget(state: State<'_, AppState>, path: String) -> Res<()> {
let db = state.db.lock().unwrap();
let mut recent: Vec<String> = db::kv_get(&db, "recent")
.map_err(errx)?
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
recent.retain(|r| r != &path);
db::kv_set(&db, "recent", &serde_json::to_string(&recent).unwrap()).map_err(errx)
}
// ---------------------------------------------------------------- tree edits
fn after_edit(state: &AppState, col: &str) -> Res<CollectionView> {
state.reload(col).map_err(errx)?;
state.with_collection(col, |c| Ok(view(c))).map_err(errx)
}
#[derive(Serialize)]
pub struct EditResult {
pub id: String,
pub collection: CollectionView,
}
#[tauri::command]
pub fn request_get(state: State<'_, AppState>, col: String, id: String) -> Res<Request> {
state.with_collection(&col, |c| c.request(&id)).map_err(errx)
}
#[tauri::command]
pub fn request_save(state: State<'_, AppState>, col: String, id: String, request: Request) -> Res<CollectionView> {
state.with_collection(&col, |c| c.save_request(&id, &request)).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn request_create(
state: State<'_, AppState>,
col: String,
folder: String,
request: Request,
) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.create_request(&folder, &request)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn folder_create(state: State<'_, AppState>, col: String, parent: String, name: String) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.create_folder(&parent, &name)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn node_rename(state: State<'_, AppState>, col: String, id: String, name: String) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.rename(&id, &name)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn node_duplicate(state: State<'_, AppState>, col: String, id: String) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.duplicate(&id)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn node_delete(state: State<'_, AppState>, col: String, id: String) -> Res<CollectionView> {
state.with_collection(&col, |c| c.delete(&id)).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn node_move(
state: State<'_, AppState>,
col: String,
id: String,
folder: String,
index: Option<usize>,
) -> Res<EditResult> {
let id = state.with_collection(&col, |c| c.move_node(&id, &folder, index)).map_err(errx)?;
Ok(EditResult { id, collection: after_edit(&state, &col)? })
}
#[tauri::command]
pub fn folder_get(state: State<'_, AppState>, col: String, id: String) -> Res<FolderMeta> {
state.with_collection(&col, |c| c.folder_meta(&id)).map_err(errx)
}
#[tauri::command]
pub fn folder_save(state: State<'_, AppState>, col: String, id: String, meta: FolderMeta) -> Res<CollectionView> {
state.with_collection(&col, |c| c.save_folder_meta(&id, &meta)).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn manifest_get(state: State<'_, AppState>, col: String) -> Res<Manifest> {
state.with_collection(&col, |c| Ok(c.manifest.clone())).map_err(errx)
}
#[tauri::command]
pub fn manifest_save(state: State<'_, AppState>, col: String, manifest: Manifest) -> Res<CollectionView> {
state.with_collection(&col, |c| c.save_manifest(&manifest)).map_err(errx)?;
after_edit(&state, &col)
}
// ---------------------------------------------------------------- environments
#[tauri::command]
pub fn env_get(state: State<'_, AppState>, col: String, id: String) -> Res<Environment> {
state.with_collection(&col, |c| c.environment(&id)).map_err(errx)
}
#[tauri::command]
pub fn env_save(state: State<'_, AppState>, col: String, id: String, env: Environment) -> Res<CollectionView> {
state.with_collection(&col, |c| c.save_environment(&id, &env)).map_err(errx)?;
after_edit(&state, &col)
}
#[tauri::command]
pub fn env_delete(state: State<'_, AppState>, col: String, id: String) -> Res<CollectionView> {
state.with_collection(&col, |c| c.delete_environment(&id)).map_err(errx)?;
after_edit(&state, &col)
}
#[derive(Serialize)]
pub struct SecretStatus {
pub name: String,
pub source: Option<secrets::SecretSource>,
pub value: Option<String>,
}
/// Where each secret of an environment currently comes from. Values are
/// returned so the UI can reveal them on demand; it masks by default.
#[tauri::command]
pub fn env_secrets(state: State<'_, AppState>, col: String, env: String) -> Res<Vec<SecretStatus>> {
let (e, file) = state
.with_collection(&col, |c| Ok((c.environment(&env)?, c.secrets_file(&env)?)))
.map_err(errx)?;
let store = SecretStore::new(&col, Some(&env), file.vars, true);
Ok(e.vars
.iter()
.filter(|(_, v)| v.secret)
.map(|(k, _)| {
let found = store.find(k);
SecretStatus {
name: k.clone(),
source: found.as_ref().map(|f| f.1),
value: found.map(|f| f.0),
}
})
.collect())
}
#[tauri::command]
pub fn secret_set(
state: State<'_, AppState>,
col: String,
env: Option<String>,
name: String,
value: Option<String>,
target: String,
) -> Res<()> {
match target.as_str() {
"file" => {
let env = env.ok_or("secrets files belong to an environment")?;
state
.with_collection(&col, |c| {
let mut f = c.secrets_file(&env)?;
match &value {
Some(v) => {
f.vars.insert(name.clone(), v.clone());
}
None => {
f.vars.shift_remove(&name);
}
}
c.save_secrets_file(&env, &f)
})
.map_err(errx)
}
_ => match value {
Some(v) => secrets::keyring_set(&col, env.as_deref(), &name, &v).map_err(|e| {
format!("could not write to the system keyring ({e:#}). Is a Secret Service (KWallet, GNOME Keyring) running? You can store it in the secrets file instead.")
}),
None => secrets::keyring_delete(&col, env.as_deref(), &name).map_err(errx),
},
}
}
// ---------------------------------------------------------------- variables
#[derive(Deserialize)]
pub struct ScopeArgs {
pub col: Option<String>,
pub request_id: Option<String>,
pub request: Request,
pub env: Option<String>,
}
pub fn build_context(state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestContext> {
let globals = db::globals_load(&state.db.lock().unwrap()).unwrap_or_default();
match &a.col {
Some(col) => {
let c = state.collection(col)?;
let file = a.env.as_deref().map(|e| c.secrets_file(e).unwrap_or_default()).unwrap_or_default();
let store = SecretStore::new(&c.manifest.id, a.env.as_deref(), file.vars, true);
let rid = a.request_id.clone().unwrap_or_else(|| "__unsaved__.yaml".into());
RequestContext::build(ContextInput {
collection: &c,
request_id: &rid,
request: &a.request,
env: a.env.as_deref(),
runtime: state.runtime_vars(col),
globals,
secrets: Arc::new(store),
oauth: Some(Arc::new(crate::oauth::TokenLookup::new(state, &c, a.env.as_deref()))),
})
}
None => {
let mut ctx = RequestContext::standalone(&a.request, std::env::temp_dir());
ctx.resolver.layers.push(knock_core::vars::Layer::new(
knock_core::vars::Scope::Global,
"global",
globals,
));
ctx.resolver.push_front(knock_core::vars::Layer::new(
knock_core::vars::Scope::Runtime,
"runtime",
state.runtime_vars(""),
));
Ok(ctx)
}
}
}
#[derive(Serialize)]
pub struct VarsView {
pub vars: Vec<VarInfo>,
pub dynamic: Vec<(String, String)>,
}
#[tauri::command]
pub fn vars_list(state: State<'_, AppState>, args: ScopeArgs) -> Res<VarsView> {
let ctx = build_context(&state, &args).map_err(errx)?;
Ok(VarsView {
vars: ctx.resolver.names(),
dynamic: DYNAMIC_VARS.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(),
})
}
#[tauri::command]
pub fn runtime_list(state: State<'_, AppState>, col: Option<String>) -> Res<IndexMap<String, String>> {
Ok(state.runtime_vars(col.as_deref().unwrap_or("")))
}
#[tauri::command]
pub fn runtime_set(
state: State<'_, AppState>,
col: Option<String>,
name: String,
value: Option<String>,
persist: bool,
) -> Res<()> {
state.set_runtime(col.as_deref().unwrap_or(""), &name, value, persist);
Ok(())
}
#[tauri::command]
pub fn globals_get(state: State<'_, AppState>) -> Res<IndexMap<String, String>> {
db::globals_load(&state.db.lock().unwrap()).map_err(errx)
}
#[tauri::command]
pub fn globals_save(state: State<'_, AppState>, vars: IndexMap<String, String>) -> Res<()> {
db::globals_save(&state.db.lock().unwrap(), &vars).map_err(errx)
}
// ---------------------------------------------------------------- sending
#[derive(Deserialize)]
pub struct SendArgs {
#[serde(flatten)]
pub scope: ScopeArgs,
pub tab: String,
/// Store up to this many bytes of the body in history (0 = none).
#[serde(default)]
pub history_body_limit: usize,
}
#[derive(Serialize)]
pub struct SendResult {
pub output: RunOutput,
pub body_id: Option<String>,
pub history_id: Option<i64>,
pub body_file: Option<String>,
}
#[tauri::command]
pub async fn request_send(app: AppHandle, args: SendArgs) -> Res<SendResult> {
let state = app.state::<AppState>();
let ctx = build_context(&state, &args.scope).map_err(errx)?;
let engine = state.engine.clone();
let req = args.scope.request.clone();
let host = crate::oauth::Host::new(app.clone(), args.scope.col.clone(), args.scope.env.clone());
let task = tokio::spawn(async move {
let out = execute(&engine, &req, &ctx, Some(&host)).await;
(out, ctx)
});
state.inflight.lock().unwrap().insert(args.tab.clone(), task.abort_handle());
let joined = task.await;
state.inflight.lock().unwrap().remove(&args.tab);
let (mut out, ctx) = match joined {
Ok(v) => v,
Err(e) if e.is_cancelled() => return Err("cancelled".into()),
Err(e) => return Err(err(e)),
};
let col_key = args.scope.col.clone().unwrap_or_default();
for x in &out.extracted {
if let Some(v) = &x.value {
state.set_runtime(&col_key, &x.var, Some(v.clone()), x.persist);
}
}
if let Some(col) = &args.scope.col {
let json = state.engine.save_jar(col);
let _ = db::jar_save(&state.db.lock().unwrap(), col, &json);
}
let mut body_id = None;
let mut body_file = None;
let mut stored_body: Option<Vec<u8>> = None;
if let Some(resp) = out.response.as_mut() {
let body = std::mem::take(&mut resp.body);
if args.history_body_limit > 0 && body.len() <= args.history_body_limit && resp.body_file.is_none() {
stored_body = Some(body.clone());
}
body_file = resp.body_file.as_ref().map(|p| p.display().to_string());
body_id = Some(state.store_body(body, resp.body_file.clone()));
}
// History never contains secrets in clear text.
let mask = |s: &str| ctx.resolver.mask(s);
let mut hist_req = args.scope.request.clone();
if let Some(sent) = &out.request {
hist_req.url = mask(&sent.url);
}
let req_json = mask(&serde_json::to_string(&hist_req).unwrap_or_default());
let meta = out.response.as_ref().map(|r| mask(&serde_json::to_string(r).unwrap_or_default()));
let history_id = {
let db = state.db.lock().unwrap();
db::history_add(
&db,
db::NewHistory {
collection: &col_key,
request_id: args.scope.request_id.as_deref(),
name: &args.scope.request.name,
method: out.request.as_ref().map(|r| r.method.as_str()).unwrap_or(args.scope.request.method()),
url: &out.request.as_ref().map(|r| mask(&r.url)).unwrap_or_else(|| args.scope.request.url.clone()),
status: out.response.as_ref().map(|r| r.status),
duration_ms: out.response.as_ref().map(|r| r.timings.total_ms),
size: out.response.as_ref().map(|r| r.size),
error: out.error.as_deref(),
request_json: &req_json,
response_meta: meta.as_deref(),
response_body: stored_body.as_deref(),
},
500 * 1024 * 1024,
)
.ok()
};
Ok(SendResult { output: out, body_id, history_id, body_file })
}
#[tauri::command]
pub fn request_cancel(state: State<'_, AppState>, tab: String) -> Res<()> {
if let Some(h) = state.inflight.lock().unwrap().remove(&tab) {
h.abort();
}
Ok(())
}
/// Raw body bytes; the frontend decodes them itself.
#[tauri::command]
pub fn response_body(state: State<'_, AppState>, id: String) -> Res<tauri::ipc::Response> {
let guard = state.responses.lock().unwrap();
let b = guard.0.get(&id).ok_or("response is no longer available")?;
Ok(tauri::ipc::Response::new(b.body.clone()))
}
#[tauri::command]
pub fn response_save(state: State<'_, AppState>, id: String, path: String) -> Res<()> {
let guard = state.responses.lock().unwrap();
let b = guard.0.get(&id).ok_or("response is no longer available")?;
match &b.file {
Some(f) => std::fs::copy(f, &path).map(|_| ()).map_err(err),
None => std::fs::write(&path, &b.body).map_err(err),
}
}
#[derive(Serialize)]
pub struct Preview {
pub request: Option<knock_core::run::SentRequest>,
pub auth: knock_core::auth::AuthDebug,
pub missing: Vec<String>,
pub error: Option<String>,
}
/// What would be sent, without sending: resolved URL, headers, body and auth.
/// OAuth tokens are not fetched here.
#[tauri::command]
pub async fn request_preview(app: AppHandle, args: ScopeArgs) -> Res<Preview> {
let state = app.state::<AppState>();
let ctx = build_context(&state, &args).map_err(errx)?;
let mut p = match knock_core::prepare::prepare(&args.request, &ctx) {
Ok(p) => p,
Err(e) => {
return Ok(Preview { request: None, auth: Default::default(), missing: vec![], error: Some(errx(e)) })
}
};
let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone());
let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false).await;
Ok(Preview {
request: Some(knock_core::run::SentRequest {
method: p.method.clone(),
url: p.url.clone(),
headers: p.headers.clone(),
body: match &p.body {
knock_core::prepare::PreparedBody::Bytes { preview, .. } => preview.clone(),
_ => String::new(),
},
}),
missing: p.missing.clone(),
auth,
error: None,
})
}
// ---------------------------------------------------------------- cookies
#[tauri::command]
pub fn cookies_list(state: State<'_, AppState>, col: String) -> Res<Vec<knock_core::http::CookieInfo>> {
Ok(state.engine.cookies(&col))
}
#[tauri::command]
pub fn cookie_delete(
state: State<'_, AppState>,
col: String,
domain: Option<String>,
path: Option<String>,
name: Option<String>,
) -> Res<()> {
match (domain, path, name) {
(Some(d), Some(p), Some(n)) => state.engine.delete_cookie(&col, &d, &p, &n),
_ => state.engine.clear_cookies(&col),
}
let json = state.engine.save_jar(&col);
db::jar_save(&state.db.lock().unwrap(), &col, &json).map_err(errx)
}
// ---------------------------------------------------------------- history
#[tauri::command]
pub fn history_list(state: State<'_, AppState>, query: String, limit: Option<u32>) -> Res<Vec<db::HistoryEntry>> {
db::history_list(&state.db.lock().unwrap(), &query, limit.unwrap_or(300)).map_err(errx)
}
#[derive(Serialize)]
pub struct HistoryView {
pub request: Request,
pub response: Option<serde_json::Value>,
pub body_id: Option<String>,
}
#[tauri::command]
pub fn history_get(state: State<'_, AppState>, id: i64) -> Res<HistoryView> {
let d = db::history_get(&state.db.lock().unwrap(), id)
.map_err(errx)?
.ok_or("history entry not found")?;
let request: Request = serde_json::from_str(&d.request_json).map_err(err)?;
let response = d.response_meta.and_then(|m| serde_json::from_str(&m).ok());
let body_id = d.response_body.map(|b| state.store_body(b, None));
Ok(HistoryView { request, response, body_id })
}
#[tauri::command]
pub fn history_delete(state: State<'_, AppState>, id: Option<i64>) -> Res<()> {
db::history_delete(&state.db.lock().unwrap(), id).map_err(errx)
}
// ---------------------------------------------------------------- misc
#[tauri::command]
pub fn setting_get(state: State<'_, AppState>, key: String) -> Res<Option<String>> {
db::kv_get(&state.db.lock().unwrap(), &format!("setting.{key}")).map_err(errx)
}
#[tauri::command]
pub fn setting_set(state: State<'_, AppState>, key: String, value: String) -> Res<()> {
db::kv_set(&state.db.lock().unwrap(), &format!("setting.{key}"), &value).map_err(errx)
}
#[tauri::command]
pub fn path_params(url: String) -> Vec<String> {
knock_core::prepare::path_param_names(&url)
}
#[tauri::command]
pub fn app_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
+247
View File
@@ -0,0 +1,247 @@
//! Local SQLite store: history, cookie jars, persisted runtime variables and
//! globals. Nothing in here is ever written to a collection folder.
use anyhow::Result;
use indexmap::IndexMap;
use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use std::path::Path;
pub fn open(path: &Path) -> Result<Connection> {
let conn = Connection::open(path)?;
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.execute_batch(
r#"
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
collection TEXT NOT NULL DEFAULT '',
request_id TEXT,
name TEXT NOT NULL DEFAULT '',
method TEXT NOT NULL,
url TEXT NOT NULL,
status INTEGER,
duration_ms REAL,
size INTEGER,
error TEXT,
request TEXT NOT NULL,
response_meta TEXT,
response_body BLOB
);
CREATE INDEX IF NOT EXISTS history_at ON history(at DESC);
CREATE TABLE IF NOT EXISTS cookie_jars (
collection TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS runtime_vars (
collection TEXT NOT NULL,
name TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (collection, name)
);
CREATE TABLE IF NOT EXISTS globals (
name TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS kv (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
"#,
)?;
Ok(conn)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoryEntry {
pub id: i64,
pub at: String,
pub collection: String,
pub request_id: Option<String>,
pub name: String,
pub method: String,
pub url: String,
pub status: Option<u16>,
pub duration_ms: Option<f64>,
pub size: Option<u64>,
pub error: Option<String>,
pub has_body: bool,
}
pub struct NewHistory<'a> {
pub collection: &'a str,
pub request_id: Option<&'a str>,
pub name: &'a str,
pub method: &'a str,
pub url: &'a str,
pub status: Option<u16>,
pub duration_ms: Option<f64>,
pub size: Option<u64>,
pub error: Option<&'a str>,
pub request_json: &'a str,
pub response_meta: Option<&'a str>,
pub response_body: Option<&'a [u8]>,
}
pub fn history_add(c: &Connection, h: NewHistory<'_>, total_limit: u64) -> Result<i64> {
c.execute(
"INSERT INTO history (at, collection, request_id, name, method, url, status, duration_ms, size, error, request, response_meta, response_body)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
params![
chrono::Utc::now().to_rfc3339(),
h.collection,
h.request_id,
h.name,
h.method,
h.url,
h.status,
h.duration_ms,
h.size,
h.error,
h.request_json,
h.response_meta,
h.response_body,
],
)?;
let id = c.last_insert_rowid();
// Keep stored bodies under the total budget by dropping the oldest ones.
let total: i64 = c.query_row(
"SELECT COALESCE(SUM(LENGTH(response_body)), 0) FROM history",
[],
|r| r.get(0),
)?;
if total as u64 > total_limit {
c.execute(
"UPDATE history SET response_body = NULL WHERE id IN (
SELECT id FROM history WHERE response_body IS NOT NULL ORDER BY id ASC LIMIT 50)",
[],
)?;
}
c.execute(
"DELETE FROM history WHERE id NOT IN (SELECT id FROM history ORDER BY id DESC LIMIT 5000)",
[],
)?;
Ok(id)
}
pub fn history_list(c: &Connection, query: &str, limit: u32) -> Result<Vec<HistoryEntry>> {
let like = format!("%{}%", query.replace('%', "\\%").replace('_', "\\_"));
let mut stmt = c.prepare(
"SELECT id, at, collection, request_id, name, method, url, status, duration_ms, size, error, response_body IS NOT NULL
FROM history
WHERE ?1 = '%%' OR url LIKE ?1 ESCAPE '\\' OR name LIKE ?1 ESCAPE '\\' OR method LIKE ?1 ESCAPE '\\' OR CAST(status AS TEXT) LIKE ?1 ESCAPE '\\'
ORDER BY id DESC LIMIT ?2",
)?;
let rows = stmt.query_map(params![like, limit], |r| {
Ok(HistoryEntry {
id: r.get(0)?,
at: r.get(1)?,
collection: r.get(2)?,
request_id: r.get(3)?,
name: r.get(4)?,
method: r.get(5)?,
url: r.get(6)?,
status: r.get(7)?,
duration_ms: r.get(8)?,
size: r.get(9)?,
error: r.get(10)?,
has_body: r.get(11)?,
})
})?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub struct HistoryDetail {
pub request_json: String,
pub response_meta: Option<String>,
pub response_body: Option<Vec<u8>>,
}
pub fn history_get(c: &Connection, id: i64) -> Result<Option<HistoryDetail>> {
Ok(c
.query_row(
"SELECT request, response_meta, response_body FROM history WHERE id = ?1",
[id],
|r| {
Ok(HistoryDetail {
request_json: r.get(0)?,
response_meta: r.get(1)?,
response_body: r.get(2)?,
})
},
)
.optional()?)
}
pub fn history_delete(c: &Connection, id: Option<i64>) -> Result<()> {
match id {
Some(id) => c.execute("DELETE FROM history WHERE id = ?1", [id])?,
None => c.execute("DELETE FROM history", [])?,
};
Ok(())
}
pub fn jar_load(c: &Connection, collection: &str) -> Result<Option<String>> {
Ok(c
.query_row("SELECT json FROM cookie_jars WHERE collection = ?1", [collection], |r| r.get(0))
.optional()?)
}
pub fn jar_save(c: &Connection, collection: &str, json: &str) -> Result<()> {
c.execute(
"INSERT INTO cookie_jars (collection, json) VALUES (?1, ?2)
ON CONFLICT(collection) DO UPDATE SET json = excluded.json",
params![collection, json],
)?;
Ok(())
}
pub fn runtime_load(c: &Connection, collection: &str) -> Result<IndexMap<String, String>> {
let mut stmt = c.prepare("SELECT name, value FROM runtime_vars WHERE collection = ?1 ORDER BY name")?;
let rows = stmt.query_map([collection], |r| Ok((r.get(0)?, r.get(1)?)))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn runtime_set(c: &Connection, collection: &str, name: &str, value: Option<&str>) -> Result<()> {
match value {
Some(v) => c.execute(
"INSERT INTO runtime_vars (collection, name, value) VALUES (?1, ?2, ?3)
ON CONFLICT(collection, name) DO UPDATE SET value = excluded.value",
params![collection, name, v],
)?,
None => c.execute(
"DELETE FROM runtime_vars WHERE collection = ?1 AND name = ?2",
params![collection, name],
)?,
};
Ok(())
}
pub fn globals_load(c: &Connection) -> Result<IndexMap<String, String>> {
let mut stmt = c.prepare("SELECT name, value FROM globals ORDER BY name")?;
let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn globals_save(c: &Connection, vars: &IndexMap<String, String>) -> Result<()> {
c.execute("DELETE FROM globals", [])?;
for (k, v) in vars {
c.execute("INSERT INTO globals (name, value) VALUES (?1, ?2)", params![k, v])?;
}
Ok(())
}
pub fn kv_get(c: &Connection, key: &str) -> Result<Option<String>> {
Ok(c
.query_row("SELECT value FROM kv WHERE key = ?1", [key], |r| r.get(0))
.optional()?)
}
pub fn kv_set(c: &Connection, key: &str, value: &str) -> Result<()> {
c.execute(
"INSERT INTO kv (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
params![key, value],
)?;
Ok(())
}
+72
View File
@@ -0,0 +1,72 @@
mod commands;
mod db;
mod oauth;
mod state;
mod watch;
use tauri::Manager;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
if let Some(w) = app.get_webview_window("main") {
let _ = w.unminimize();
let _ = w.set_focus();
}
}))
.plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.setup(|app| {
let dir = app.path().app_data_dir()?;
app.manage(state::AppState::new(dir)?);
Ok(())
})
.invoke_handler(tauri::generate_handler![
commands::collection_open,
commands::collection_create,
commands::collection_get,
commands::collection_close,
commands::recent_collections,
commands::recent_forget,
commands::request_get,
commands::request_save,
commands::request_create,
commands::folder_create,
commands::node_rename,
commands::node_duplicate,
commands::node_delete,
commands::node_move,
commands::folder_get,
commands::folder_save,
commands::manifest_get,
commands::manifest_save,
commands::env_get,
commands::env_save,
commands::env_delete,
commands::env_secrets,
commands::secret_set,
commands::vars_list,
commands::runtime_list,
commands::runtime_set,
commands::globals_get,
commands::globals_save,
commands::request_send,
commands::request_cancel,
commands::request_preview,
commands::response_body,
commands::response_save,
commands::cookies_list,
commands::cookie_delete,
commands::history_list,
commands::history_get,
commands::history_delete,
commands::setting_get,
commands::setting_set,
commands::path_params,
commands::app_version,
])
.run(tauri::generate_context!())
.expect("error while running knock");
}
+13
View File
@@ -0,0 +1,13 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
// WebKitGTK's DMA-BUF renderer breaks on a number of Wayland setups
// (blank window, explicit-sync errors). Opt back in with KNOCK_DMABUF=1.
#[cfg(target_os = "linux")]
if std::env::var_os("KNOCK_DMABUF").is_none()
&& std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none()
{
std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
}
knock_app_lib::run()
}
+59
View File
@@ -0,0 +1,59 @@
//! OAuth glue between the core flow code and the app (browser, keyring,
//! flow log). Filled in with the OAuth milestone.
use crate::state::AppState;
use knock_core::auth::{AuthHost, OauthResult, Step, StepStatus};
use knock_core::model::AuthConfig;
use knock_core::vars::{OauthLookup, Resolver};
use knock_core::Collection;
use tauri::AppHandle;
pub struct Host {
#[allow(dead_code)]
app: AppHandle,
#[allow(dead_code)]
col: Option<String>,
#[allow(dead_code)]
env: Option<String>,
#[allow(dead_code)]
interactive: bool,
}
impl Host {
pub fn new(app: AppHandle, col: Option<String>, env: Option<String>) -> Self {
Self { app, col, env, interactive: true }
}
pub fn preview(app: AppHandle, col: Option<String>, env: Option<String>) -> Self {
Self { app, col, env, interactive: false }
}
}
impl AuthHost for Host {
fn oauth2_token(
&self,
_cfg: &AuthConfig,
_resolver: &Resolver,
_force_refresh: bool,
) -> futures_util::future::BoxFuture<'_, OauthResult> {
Box::pin(async move {
OauthResult {
steps: vec![Step::new("token", "Get token", StepStatus::Error, "OAuth 2.0 is not wired up yet")],
..Default::default()
}
})
}
}
pub struct TokenLookup;
impl TokenLookup {
pub fn new(_state: &AppState, _c: &Collection, _env: Option<&str>) -> Self {
Self
}
}
impl OauthLookup for TokenLookup {
fn oauth_value(&self, _config: &str, _field: &str) -> Option<String> {
None
}
}
+112
View File
@@ -0,0 +1,112 @@
use crate::db;
use anyhow::{anyhow, Result};
use indexmap::IndexMap;
use knock_core::http::Engine;
use knock_core::Collection;
use rusqlite::Connection;
use std::collections::{HashMap, VecDeque};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
pub struct StoredBody {
pub body: Vec<u8>,
pub file: Option<PathBuf>,
}
pub struct AppState {
pub data_dir: PathBuf,
pub collections: RwLock<HashMap<String, Collection>>,
pub engine: Arc<Engine>,
pub db: Mutex<Connection>,
/// Runtime variables per collection id ("" for loose requests).
pub runtime: Mutex<HashMap<String, IndexMap<String, String>>>,
pub responses: Mutex<(HashMap<String, StoredBody>, VecDeque<String>)>,
pub inflight: Mutex<HashMap<String, tokio::task::AbortHandle>>,
pub watchers: Mutex<HashMap<String, notify::RecommendedWatcher>>,
}
const KEEP_RESPONSES: usize = 40;
impl AppState {
pub fn new(data_dir: PathBuf) -> Result<Self> {
std::fs::create_dir_all(&data_dir)?;
let db = db::open(&data_dir.join("knock.db"))?;
Ok(Self {
engine: Arc::new(Engine::new(data_dir.join("responses"))),
data_dir,
collections: RwLock::default(),
db: Mutex::new(db),
runtime: Mutex::default(),
responses: Mutex::default(),
inflight: Mutex::default(),
watchers: Mutex::default(),
})
}
pub fn collection(&self, id: &str) -> Result<Collection> {
self.collections
.read()
.unwrap()
.get(id)
.cloned()
.ok_or_else(|| anyhow!("collection is not open"))
}
pub fn with_collection<T>(&self, id: &str, f: impl FnOnce(&Collection) -> Result<T>) -> Result<T> {
let guard = self.collections.read().unwrap();
let c = guard.get(id).ok_or_else(|| anyhow!("collection is not open"))?;
f(c)
}
pub fn reload(&self, id: &str) -> Result<()> {
let mut guard = self.collections.write().unwrap();
if let Some(c) = guard.get_mut(id) {
c.reload()?;
}
Ok(())
}
pub fn runtime_vars(&self, collection: &str) -> IndexMap<String, String> {
let mut rt = self.runtime.lock().unwrap();
if !rt.contains_key(collection) {
let persisted = db::runtime_load(&self.db.lock().unwrap(), collection).unwrap_or_default();
rt.insert(collection.to_string(), persisted);
}
rt[collection].clone()
}
pub fn set_runtime(&self, collection: &str, name: &str, value: Option<String>, persist: bool) {
self.runtime_vars(collection);
let mut rt = self.runtime.lock().unwrap();
let map = rt.get_mut(collection).unwrap();
match &value {
Some(v) => {
map.insert(name.to_string(), v.clone());
}
None => {
map.shift_remove(name);
}
}
if persist || value.is_none() {
let _ = db::runtime_set(&self.db.lock().unwrap(), collection, name, value.as_deref());
}
}
pub fn store_body(&self, body: Vec<u8>, file: Option<PathBuf>) -> String {
let id = uuid::Uuid::new_v4().to_string();
let mut guard = self.responses.lock().unwrap();
let (map, order) = &mut *guard;
map.insert(id.clone(), StoredBody { body, file });
order.push_back(id.clone());
while order.len() > KEEP_RESPONSES {
if let Some(old) = order.pop_front() {
if let Some(b) = map.remove(&old) {
if let Some(f) = b.file {
let _ = std::fs::remove_file(f);
}
}
}
}
id
}
}
+71
View File
@@ -0,0 +1,71 @@
//! Reloads a collection when its files change outside knock (git pull, an
//! editor) and tells the frontend which files changed.
use crate::state::AppState;
use notify::{RecursiveMode, Watcher};
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager};
#[derive(Clone, Serialize)]
struct Changed {
collection: String,
paths: Vec<String>,
}
pub fn start(app: &AppHandle, state: &AppState, id: &str, root: &Path) {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<PathBuf>();
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
if let Ok(ev) = res {
if matches!(ev.kind, notify::EventKind::Access(_)) {
return;
}
for p in ev.paths {
let _ = tx.send(p);
}
}
});
let Ok(mut watcher) = watcher else { return };
if watcher.watch(root, RecursiveMode::Recursive).is_err() {
return;
}
state.watchers.lock().unwrap().insert(id.to_string(), watcher);
let app = app.clone();
let id = id.to_string();
let root = root.to_path_buf();
tauri::async_runtime::spawn(async move {
loop {
let Some(first) = rx.recv().await else { return };
let mut paths = vec![first];
// Debounce: a git checkout touches many files at once.
tokio::time::sleep(Duration::from_millis(250)).await;
while let Ok(p) = rx.try_recv() {
paths.push(p);
}
let rel: Vec<String> = paths
.iter()
.filter_map(|p| p.strip_prefix(&root).ok())
.map(|p| p.to_string_lossy().replace('\\', "/"))
.filter(|p| {
(p.ends_with(".yaml") || p.ends_with(".yml") || !p.contains('.'))
&& !p.ends_with(".tmp")
&& !p.starts_with(".git")
})
.collect();
if rel.is_empty() {
continue;
}
let state = app.state::<AppState>();
if !state.collections.read().unwrap().contains_key(&id) {
return;
}
let _ = state.reload(&id);
let mut rel = rel;
rel.sort();
rel.dedup();
let _ = app.emit("collection-changed", Changed { collection: id.clone(), paths: rel });
}
});
}