Proxy storage: flows table, bodies in blobs.sqlite, settings (#751)

This commit is contained in:
Gregory Schier authored and GitHub committed 2026-10-14 13:50:26 -07:00
1 parent 694c0272cd
commit b5508e6bb1
25 files changed
+942 -289

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
use crate::models::{Flow, FlowBody, find_header};
use std::io::Cursor;
use tokio::io::AsyncReadExt;
use yaak_http::decompress::{ContentEncoding, streaming_decoder};
use yaak_models::blob_manager::BlobManager;
/// A flow's body as stored: the bytes on the wire, up to the capture limit.
pub fn read_raw_body(
blobs: &BlobManager,
flow_id: &str,
body: FlowBody,
) -> Result<Vec<u8>, String> {
let chunks =
blobs.connect().get_chunks(&Flow::body_id(flow_id, body)).map_err(|e| e.to_string())?;
Ok(chunks.into_iter().flat_map(|c| c.data).collect())
}
/// A flow's body decoded with its Content-Encoding. A truncated body decodes as far as its
/// stored bytes go.
pub async fn read_body(
blobs: &BlobManager,
flow: &Flow,
body: FlowBody,
) -> Result<Vec<u8>, String> {
let raw = read_raw_body(blobs, &flow.id, body)?;
let encoding = ContentEncoding::from_header(find_header(flow.headers(body), "content-encoding"));
if encoding == ContentEncoding::Identity {
return Ok(raw);
}
let mut decoded = Vec::new();
match streaming_decoder(Cursor::new(raw), encoding).read_to_end(&mut decoded).await {
Ok(_) => Ok(decoded),
Err(_) if flow.truncated(body) => Ok(decoded),
Err(e) => Err(format!("Failed to decode {encoding:?} body: {e}")),
}
}
+109 -9
View File
@@ -1,31 +1,131 @@
use include_dir::{Dir, include_dir};
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::{Transaction, TransactionBehavior};
use std::path::Path;
use yaak_database::{ConnectionOrTx, DbContext, run_migrations};
use std::time::Duration;
use yaak_database::{ConnectionOrTx, DbContext, Error, Result, SqlitePool, run_migrations};
static MIGRATIONS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/migrations");
/// Reads come from a pool; writes go through one connection, as in yaak-models'
/// `QueryManager`. WAL lets the CLI read `proxy.db` while the app writes it.
#[derive(Clone)]
pub struct ProxyQueryManager {
pool: Pool<SqliteConnectionManager>,
readers: SqlitePool,
writer: SqlitePool,
}
impl ProxyQueryManager {
pub fn new(db_path: &Path) -> Self {
let manager = SqliteConnectionManager::file(db_path);
let pool =
Pool::builder().max_size(5).build(manager).expect("Failed to create proxy DB pool");
run_migrations(&pool, &MIGRATIONS).expect("Failed to run proxy DB migrations");
Self { pool }
pub fn new(db_path: &Path) -> Result<Self> {
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent)?;
}
let writer = file_pool(db_path, 1)?;
run_migrations(&writer, &MIGRATIONS)?;
Ok(Self { readers: file_pool(db_path, 5)?, writer })
}
pub fn with_conn<F, T>(&self, func: F) -> T
where
F: FnOnce(&DbContext) -> T,
{
let conn = self.pool.get().expect("Failed to get proxy DB connection");
let conn = self.readers.get().expect("Failed to get proxy DB connection");
let ctx = DbContext::new(ConnectionOrTx::Connection(conn));
func(&ctx)
}
/// Run `func` in a transaction on the writer connection.
pub fn with_tx<T, E>(
&self,
func: impl FnOnce(&DbContext) -> std::result::Result<T, E>,
) -> std::result::Result<T, E>
where
E: From<Error>,
{
let conn = self.writer.get().map_err(Error::from)?;
let tx = Transaction::new_unchecked(&conn, TransactionBehavior::Immediate)
.map_err(Error::from)?;
let ctx = DbContext::new(ConnectionOrTx::Transaction(&tx));
let result = func(&ctx);
drop(ctx);
match result {
Ok(val) => {
tx.commit().map_err(Error::from)?;
Ok(val)
}
Err(e) => {
tx.rollback().map_err(Error::from)?;
Err(e)
}
}
}
}
fn file_pool(path: &Path, max_size: u32) -> Result<SqlitePool> {
let manager = SqliteConnectionManager::file(path).with_init(|conn| {
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.busy_timeout(Duration::from_millis(5000))
});
Pool::builder()
.max_size(max_size)
.connection_timeout(Duration::from_secs(10))
.build(manager)
.map_err(|e| Error::Database(e.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
use rusqlite::Connection;
fn columns(conn: &Connection, table: &str) -> Vec<String> {
let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})")).unwrap();
stmt.query_map([], |r| r.get::<_, String>("name")).unwrap().map(|c| c.unwrap()).collect()
}
#[test]
fn migrates_an_old_schema_db() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("proxy.db");
// The database as the first migration left it, with a row in it.
let conn = Connection::open(&path).unwrap();
conn.execute_batch(include_str!("../migrations/00000001_init.sql")).unwrap();
conn.execute_batch(
"CREATE TABLE _sqlx_migrations (
version TEXT PRIMARY KEY,
description TEXT NOT NULL,
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
);
INSERT INTO _sqlx_migrations (version, description)
VALUES ('00000001', '00000001_init.sql');
INSERT INTO http_exchanges (id, url, method, req_body, res_body)
VALUES ('he_old', 'https://example.com', 'GET', x'00', x'01');",
)
.unwrap();
drop(conn);
let db = ProxyQueryManager::new(&path).unwrap();
drop(db);
let conn = Connection::open(&path).unwrap();
let tables: Vec<String> = conn
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
.unwrap()
.query_map([], |r| r.get(0))
.unwrap()
.map(|t| t.unwrap())
.collect();
assert_eq!(tables, vec!["_sqlx_migrations", "flows"]);
let flow_columns = columns(&conn, "flows");
assert!(flow_columns.contains(&"response_truncated".to_string()));
assert!(!flow_columns.iter().any(|c| c.contains("body")), "{flow_columns:?}");
let journal_mode: String =
conn.query_row("PRAGMA journal_mode", [], |r| r.get(0)).unwrap();
assert_eq!(journal_mode, "wal");
}
}
+165 -119
View File
@@ -1,18 +1,23 @@
pub mod actions;
pub mod bodies;
pub mod db;
pub mod models;
pub mod settings;
use crate::actions::{ActionInvocation, ActionMetadata, GlobalAction};
use crate::db::ProxyQueryManager;
use crate::models::{HttpExchange, ModelPayload, ProxyHeader};
use crate::models::{Flow, FlowBody, ModelPayload, ProxyHeader, find_header};
use crate::settings::ProxySettings;
use chrono::{DateTime, Utc};
use log::warn;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use ts_rs::TS;
use yaak_database::{ModelChangeEvent, UpdateSource};
use yaak_proxy::{CaStore, CapturedRequest, ProxyConfig, ProxyEvent, ProxyHandle, RequestState};
use yaak_database::{ModelChangeEvent, UpdateSource, UpsertModelInfo};
use yaak_models::blob_manager::{BlobManager, BodyChunkWriter};
use yaak_proxy::{CaStore, ProxyConfig, ProxyEvent, ProxyHandle};
use yaak_rpc::{RpcError, RpcEventEmitter, define_rpc};
// -- Context --
@@ -21,20 +26,68 @@ use yaak_rpc::{RpcError, RpcEventEmitter, define_rpc};
#[derive(Clone)]
pub struct ProxyCtx {
handle: Arc<Mutex<Option<ProxyHandle>>>,
ca_dir: PathBuf,
data_dir: PathBuf,
pub db: ProxyQueryManager,
pub blobs: BlobManager,
pub events: RpcEventEmitter,
}
impl ProxyCtx {
pub fn new(db_path: &Path, events: RpcEventEmitter) -> Self {
let ca_dir = db_path.parent().unwrap_or(Path::new(".")).join("ca");
Self {
/// Opens `proxy.db` and `blobs.sqlite` in `data_dir`, the proxy app's data directory.
pub fn new(data_dir: &Path, events: RpcEventEmitter) -> Result<Self, String> {
let db = ProxyQueryManager::new(&data_dir.join("proxy.db"))
.map_err(|e| format!("Failed to open proxy database: {e}"))?;
let blobs = yaak_models::init_blob_store(data_dir.join("blobs.sqlite"))
.map_err(|e| format!("Failed to open proxy blob store: {e}"))?;
Ok(Self {
handle: Arc::new(Mutex::new(None)),
ca_dir,
db: ProxyQueryManager::new(db_path),
data_dir: data_dir.to_path_buf(),
db,
blobs,
events,
})
}
pub fn settings_path(&self) -> PathBuf {
self.data_dir.join("settings.json")
}
/// Starts the engine with the current `settings.json`. Does nothing if it is running.
pub fn start(&self) -> Result<(), String> {
let mut handle = self.handle.lock().map_err(|_| "lock poisoned".to_string())?;
if handle.is_some() {
return Ok(());
}
let settings = ProxySettings::load(&self.settings_path())?;
let ca = CaStore::load_or_create(&self.data_dir.join("ca"))
.map_err(|e| format!("Failed to load proxy CA: {e}"))?;
let mut config = ProxyConfig::new(settings.port, Arc::new(ca));
config.capture_body_limit = settings.capture_body_limit;
let mut proxy_handle = yaak_proxy::start_proxy(config)?;
if let Some(event_rx) = proxy_handle.take_event_rx() {
let db = self.db.clone();
let blobs = self.blobs.clone();
let events = self.events.clone();
std::thread::spawn(move || run_event_loop(event_rx, db, blobs, events));
}
*handle = Some(proxy_handle);
self.events.emit("proxy_state_changed", &ProxyStatePayload { state: ProxyState::Running });
Ok(())
}
pub fn stop(&self) -> Result<(), String> {
let mut handle = self.handle.lock().map_err(|_| "lock poisoned".to_string())?;
handle.take();
self.events.emit("proxy_state_changed", &ProxyStatePayload { state: ProxyState::Stopped });
Ok(())
}
/// The port the engine is bound to, while it runs.
pub fn port(&self) -> Option<u16> {
self.handle.lock().ok()?.as_ref().map(|h| h.port)
}
}
@@ -74,7 +127,7 @@ pub struct ListModelsRequest {}
#[ts(export, export_to = "gen_rpc.ts")]
#[serde(rename_all = "camelCase")]
pub struct ListModelsResponse {
pub http_exchanges: Vec<HttpExchange>,
pub flows: Vec<Flow>,
}
#[derive(Deserialize, TS)]
@@ -92,41 +145,11 @@ pub struct GetProxyStateResponse {
fn execute_action(ctx: &ProxyCtx, invocation: ActionInvocation) -> Result<bool, RpcError> {
match invocation {
ActionInvocation::Global { action } => match action {
GlobalAction::ProxyStart => {
let mut handle =
ctx.handle.lock().map_err(|_| RpcError { message: "lock poisoned".into() })?;
if handle.is_some() {
return Ok(true); // already running
}
let ca = CaStore::load_or_create(&ctx.ca_dir)
.map_err(|e| RpcError { message: format!("Failed to load proxy CA: {e}") })?;
let mut proxy_handle =
yaak_proxy::start_proxy(ProxyConfig::new(9090, Arc::new(ca)))
.map_err(|e| RpcError { message: e })?;
if let Some(event_rx) = proxy_handle.take_event_rx() {
let db = ctx.db.clone();
let events = ctx.events.clone();
std::thread::spawn(move || run_event_loop(event_rx, db, events));
}
*handle = Some(proxy_handle);
ctx.events
.emit("proxy_state_changed", &ProxyStatePayload { state: ProxyState::Running });
Ok(true)
}
GlobalAction::ProxyStop => {
let mut handle =
ctx.handle.lock().map_err(|_| RpcError { message: "lock poisoned".into() })?;
handle.take();
ctx.events
.emit("proxy_state_changed", &ProxyStatePayload { state: ProxyState::Stopped });
Ok(true)
}
GlobalAction::ProxyStart => ctx.start().map_err(|message| RpcError { message })?,
GlobalAction::ProxyStop => ctx.stop().map_err(|message| RpcError { message })?,
},
}
Ok(true)
}
fn get_proxy_state(
@@ -148,128 +171,151 @@ fn list_actions(
fn list_models(ctx: &ProxyCtx, _req: ListModelsRequest) -> Result<ListModelsResponse, RpcError> {
ctx.db.with_conn(|db| {
Ok(ListModelsResponse {
http_exchanges: db
.find_all::<HttpExchange>()
.map_err(|e| RpcError { message: e.to_string() })?,
flows: db.find_all::<Flow>().map_err(|e| RpcError { message: e.to_string() })?,
})
})
}
// -- Event loop --
/// A flow between its `RequestStart` and its end, with its bodies being written as they
/// stream.
struct InFlight {
flow: Flow,
request_body: Option<BodyChunkWriter>,
response_body: Option<BodyChunkWriter>,
}
fn run_event_loop(
rx: std::sync::mpsc::Receiver<ProxyEvent>,
db: ProxyQueryManager,
blobs: BlobManager,
events: RpcEventEmitter,
) {
let mut in_flight: HashMap<u64, CapturedRequest> = HashMap::new();
let mut in_flight: HashMap<u64, InFlight> = HashMap::new();
while let Ok(event) = rx.recv() {
match event {
ProxyEvent::RequestStart { id, method, url, http_version, .. } => {
ProxyEvent::RequestStart { id, started_at, method, url, http_version } => {
let flow_id = Flow::generate_id();
let request_body = Flow::body_id(&flow_id, FlowBody::Request);
let response_body = Flow::body_id(&flow_id, FlowBody::Response);
let flow = Flow {
id: flow_id,
started_at: DateTime::<Utc>::from(started_at).naive_utc(),
method,
url,
client_http_version: http_version,
..Default::default()
};
in_flight.insert(
id,
CapturedRequest {
id,
method,
url,
http_version,
status: None,
elapsed_ms: None,
remote_http_version: None,
request_headers: vec![],
request_body: None,
response_headers: vec![],
response_body: None,
response_body_size: 0,
state: RequestState::Sending,
error: None,
InFlight {
flow,
request_body: Some(BodyChunkWriter::new(blobs.clone(), request_body)),
response_body: Some(BodyChunkWriter::new(blobs.clone(), response_body)),
},
);
}
ProxyEvent::RequestHeader { id, name, value } => {
if let Some(r) = in_flight.get_mut(&id) {
r.request_headers.push((name, value));
if let Some(f) = in_flight.get_mut(&id) {
f.flow.request_headers.push(ProxyHeader { name, value });
}
}
ProxyEvent::RequestBodyChunk { id, data, .. } => {
if let Some(r) = in_flight.get_mut(&id)
&& !data.is_empty()
{
r.request_body.get_or_insert_default().extend_from_slice(&data);
// Counted per chunk too: the response can end, and the flow with it, before the
// upload does.
ProxyEvent::RequestBodyChunk { id, len, data } => {
if let Some(f) = in_flight.get_mut(&id) {
f.flow.request_size += len as i64;
f.flow.request_truncated |= data.len() < len;
write_body_chunk(&mut f.request_body, &data);
}
}
ProxyEvent::RequestBodyComplete { .. } => {}
ProxyEvent::ResponseStart { id, status, http_version, elapsed_ms, .. } => {
if let Some(r) = in_flight.get_mut(&id) {
r.status = Some(status);
r.remote_http_version = Some(http_version);
r.elapsed_ms = Some(elapsed_ms);
r.state = RequestState::Receiving;
ProxyEvent::RequestBodyComplete { id, size, truncated } => {
if let Some(f) = in_flight.get_mut(&id) {
f.flow.request_size = size as i64;
f.flow.request_truncated = truncated;
finish_body(f.request_body.take());
}
}
ProxyEvent::ResponseStart { id, status, http_version, remote_addr, elapsed_ms } => {
if let Some(f) = in_flight.get_mut(&id) {
f.flow.status = Some(status as i32);
f.flow.upstream_http_version = Some(http_version);
f.flow.remote_addr = remote_addr.map(|a| a.to_string());
f.flow.elapsed_headers_ms = Some(clamp_ms(elapsed_ms));
}
}
ProxyEvent::ResponseHeader { id, name, value } => {
if let Some(r) = in_flight.get_mut(&id) {
r.response_headers.push((name, value));
if let Some(f) = in_flight.get_mut(&id) {
f.flow.response_headers.push(ProxyHeader { name, value });
}
}
ProxyEvent::ResponseBodyChunk { id, data, .. } => {
if let Some(r) = in_flight.get_mut(&id)
&& !data.is_empty()
{
r.response_body.get_or_insert_default().extend_from_slice(&data);
if let Some(f) = in_flight.get_mut(&id) {
write_body_chunk(&mut f.response_body, &data);
}
}
ProxyEvent::ResponseBodyComplete { id, size, elapsed_ms, error, .. } => {
if let Some(mut r) = in_flight.remove(&id) {
r.response_body_size = size;
r.elapsed_ms = r.elapsed_ms.or(Some(elapsed_ms));
r.state =
if error.is_some() { RequestState::Error } else { RequestState::Complete };
r.error = error;
write_entry(&db, &events, &r);
ProxyEvent::ResponseBodyComplete { id, size, truncated, elapsed_ms, error } => {
if let Some(mut f) = in_flight.remove(&id) {
f.flow.response_size = size as i64;
f.flow.response_truncated = truncated;
f.flow.elapsed_ms = Some(clamp_ms(elapsed_ms));
f.flow.error = error;
finish_flow(&db, &events, f);
}
}
ProxyEvent::Error { id, error, .. } => {
if let Some(mut r) = in_flight.remove(&id) {
r.error = Some(error);
r.state = RequestState::Error;
write_entry(&db, &events, &r);
ProxyEvent::Error { id, error, elapsed_ms } => {
if let Some(mut f) = in_flight.remove(&id) {
f.flow.elapsed_ms = Some(clamp_ms(elapsed_ms));
f.flow.error = Some(error);
finish_flow(&db, &events, f);
}
}
}
}
}
fn write_entry(db: &ProxyQueryManager, events: &RpcEventEmitter, r: &CapturedRequest) {
let entry = HttpExchange {
url: r.url.clone(),
method: r.method.clone(),
req_headers: r
.request_headers
.iter()
.map(|(n, v)| ProxyHeader { name: n.clone(), value: v.clone() })
.collect(),
req_body: r.request_body.clone(),
res_status: r.status.map(|s| s as i32),
res_headers: r
.response_headers
.iter()
.map(|(n, v)| ProxyHeader { name: n.clone(), value: v.clone() })
.collect(),
res_body: r.response_body.clone(),
error: r.error.clone(),
..Default::default()
};
db.with_conn(|ctx| match ctx.upsert(&entry, &UpdateSource::Background) {
fn clamp_ms(ms: u64) -> i32 {
i32::try_from(ms).unwrap_or(i32::MAX)
}
/// Stops writing a body after its first failed write, keeping the chunks before it.
fn write_body_chunk(writer: &mut Option<BodyChunkWriter>, data: &[u8]) {
if data.is_empty() {
return;
}
if let Some(w) = writer.as_mut()
&& let Err(e) = w.write(data)
{
warn!("Failed to store proxy body chunk: {e}");
*writer = None;
}
}
fn finish_body(writer: Option<BodyChunkWriter>) {
if let Some(w) = writer
&& let Err(e) = w.finish()
{
warn!("Failed to store proxy body chunk: {e}");
}
}
fn finish_flow(db: &ProxyQueryManager, events: &RpcEventEmitter, f: InFlight) {
finish_body(f.request_body);
finish_body(f.response_body);
let mut flow = f.flow;
flow.content_type = find_header(&flow.response_headers, "content-type").map(String::from);
match db.with_tx(|ctx| ctx.upsert(&flow, &UpdateSource::Background)) {
Ok((saved, created)) => {
events.emit(
"model_write",
&ModelPayload { model: saved, change: ModelChangeEvent::Upsert { created } },
);
}
Err(e) => warn!("Failed to write proxy entry: {e}"),
});
Err(e) => warn!("Failed to write proxy flow: {e}"),
}
}
// -- Router + Schema --
+120 -38
View File
@@ -16,47 +16,102 @@ pub struct ProxyHeader {
pub value: String,
}
/// One proxied request and its response. The bodies are in `blobs.sqlite`, not the row.
#[derive(Debug, Clone, Default, Serialize, Deserialize, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
#[enum_def(table_name = "http_exchanges")]
pub struct HttpExchange {
#[enum_def(table_name = "flows")]
pub struct Flow {
pub id: String,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub url: String,
pub started_at: NaiveDateTime,
pub method: String,
pub req_headers: Vec<ProxyHeader>,
pub req_body: Option<Vec<u8>>,
pub res_status: Option<i32>,
pub res_headers: Vec<ProxyHeader>,
pub res_body: Option<Vec<u8>>,
pub url: String,
/// Version spoken by the client.
pub client_http_version: String,
/// Version spoken with the upstream server.
pub upstream_http_version: Option<String>,
pub remote_addr: Option<String>,
pub status: Option<i32>,
/// The response's Content-Type.
pub content_type: Option<String>,
pub request_headers: Vec<ProxyHeader>,
pub response_headers: Vec<ProxyHeader>,
/// Bytes of the request body on the wire, captured or not.
#[ts(type = "number")]
pub request_size: i64,
/// Bytes of the response body on the wire, captured or not.
#[ts(type = "number")]
pub response_size: i64,
/// Only the first `capture_body_limit` bytes of the body are stored.
pub request_truncated: bool,
/// Only the first `capture_body_limit` bytes of the body are stored.
pub response_truncated: bool,
/// Milliseconds from `started_at` to the response headers.
pub elapsed_headers_ms: Option<i32>,
/// Milliseconds from `started_at` to the end of the response.
pub elapsed_ms: Option<i32>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlowBody {
Request,
Response,
}
impl Flow {
/// The blob store id of one of a flow's bodies.
pub fn body_id(flow_id: &str, body: FlowBody) -> String {
match body {
FlowBody::Request => format!("{flow_id}.request"),
FlowBody::Response => format!("{flow_id}.response"),
}
}
pub fn headers(&self, body: FlowBody) -> &[ProxyHeader] {
match body {
FlowBody::Request => &self.request_headers,
FlowBody::Response => &self.response_headers,
}
}
pub fn truncated(&self, body: FlowBody) -> bool {
match body {
FlowBody::Request => self.request_truncated,
FlowBody::Response => self.response_truncated,
}
}
}
pub fn find_header<'a>(headers: &'a [ProxyHeader], name: &str) -> Option<&'a str> {
headers.iter().find(|h| h.name.eq_ignore_ascii_case(name)).map(|h| h.value.as_str())
}
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
pub struct ModelPayload {
pub model: HttpExchange,
pub model: Flow,
pub change: ModelChangeEvent,
}
impl UpsertModelInfo for HttpExchange {
impl UpsertModelInfo for Flow {
fn table_name() -> impl IntoTableRef + IntoIden {
HttpExchangeIden::Table
FlowIden::Table
}
fn id_column() -> impl IntoIden + Eq + Clone {
HttpExchangeIden::Id
FlowIden::Id
}
fn generate_id() -> String {
generate_prefixed_id("he")
generate_prefixed_id("fl")
}
fn order_by() -> (impl IntoColumnRef, Order) {
(HttpExchangeIden::CreatedAt, Order::Desc)
(FlowIden::StartedAt, Order::Desc)
}
fn get_id(&self) -> String {
@@ -67,32 +122,50 @@ impl UpsertModelInfo for HttpExchange {
self,
source: &UpdateSource,
) -> DbResult<Vec<(impl IntoIden + Eq, impl Into<SimpleExpr>)>> {
use HttpExchangeIden::*;
use FlowIden::*;
Ok(vec![
(CreatedAt, upsert_date(source, self.created_at)),
(UpdatedAt, upsert_date(source, self.updated_at)),
(Url, self.url.into()),
(StartedAt, self.started_at.into()),
(Method, self.method.into()),
(ReqHeaders, serde_json::to_string(&self.req_headers)?.into()),
(ReqBody, self.req_body.into()),
(ResStatus, self.res_status.into()),
(ResHeaders, serde_json::to_string(&self.res_headers)?.into()),
(ResBody, self.res_body.into()),
(Url, self.url.into()),
(ClientHttpVersion, self.client_http_version.into()),
(UpstreamHttpVersion, self.upstream_http_version.into()),
(RemoteAddr, self.remote_addr.into()),
(Status, self.status.into()),
(ContentType, self.content_type.into()),
(RequestHeaders, serde_json::to_string(&self.request_headers)?.into()),
(ResponseHeaders, serde_json::to_string(&self.response_headers)?.into()),
(RequestSize, self.request_size.into()),
(ResponseSize, self.response_size.into()),
(RequestTruncated, self.request_truncated.into()),
(ResponseTruncated, self.response_truncated.into()),
(ElapsedHeadersMs, self.elapsed_headers_ms.into()),
(ElapsedMs, self.elapsed_ms.into()),
(Error, self.error.into()),
])
}
fn update_columns() -> Vec<impl IntoIden> {
vec![
HttpExchangeIden::UpdatedAt,
HttpExchangeIden::Url,
HttpExchangeIden::Method,
HttpExchangeIden::ReqHeaders,
HttpExchangeIden::ReqBody,
HttpExchangeIden::ResStatus,
HttpExchangeIden::ResHeaders,
HttpExchangeIden::ResBody,
HttpExchangeIden::Error,
FlowIden::UpdatedAt,
FlowIden::StartedAt,
FlowIden::Method,
FlowIden::Url,
FlowIden::ClientHttpVersion,
FlowIden::UpstreamHttpVersion,
FlowIden::RemoteAddr,
FlowIden::Status,
FlowIden::ContentType,
FlowIden::RequestHeaders,
FlowIden::ResponseHeaders,
FlowIden::RequestSize,
FlowIden::ResponseSize,
FlowIden::RequestTruncated,
FlowIden::ResponseTruncated,
FlowIden::ElapsedHeadersMs,
FlowIden::ElapsedMs,
FlowIden::Error,
]
}
@@ -100,19 +173,28 @@ impl UpsertModelInfo for HttpExchange {
where
Self: Sized,
{
let req_headers: String = r.get("req_headers")?;
let res_headers: String = r.get("res_headers")?;
let request_headers: String = r.get("request_headers")?;
let response_headers: String = r.get("response_headers")?;
Ok(Self {
id: r.get("id")?,
created_at: r.get("created_at")?,
updated_at: r.get("updated_at")?,
url: r.get("url")?,
started_at: r.get("started_at")?,
method: r.get("method")?,
req_headers: serde_json::from_str(&req_headers).unwrap_or_default(),
req_body: r.get("req_body")?,
res_status: r.get("res_status")?,
res_headers: serde_json::from_str(&res_headers).unwrap_or_default(),
res_body: r.get("res_body")?,
url: r.get("url")?,
client_http_version: r.get("client_http_version")?,
upstream_http_version: r.get("upstream_http_version")?,
remote_addr: r.get("remote_addr")?,
status: r.get("status")?,
content_type: r.get("content_type")?,
request_headers: serde_json::from_str(&request_headers).unwrap_or_default(),
response_headers: serde_json::from_str(&response_headers).unwrap_or_default(),
request_size: r.get("request_size")?,
response_size: r.get("response_size")?,
request_truncated: r.get("request_truncated")?,
response_truncated: r.get("response_truncated")?,
elapsed_headers_ms: r.get("elapsed_headers_ms")?,
elapsed_ms: r.get("elapsed_ms")?,
error: r.get("error")?,
})
}
@@ -0,0 +1,85 @@
use serde::{Deserialize, Serialize};
use std::path::Path;
use yaak_proxy::DEFAULT_CAPTURE_BODY_LIMIT;
/// `settings.json` in the proxy data directory. Missing keys take their defaults.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ProxySettings {
pub port: u16,
/// Whether the system proxy points at the engine while it runs.
pub system_proxy: bool,
/// Bytes of each request and response body stored per flow.
pub capture_body_limit: usize,
}
impl Default for ProxySettings {
fn default() -> Self {
Self { port: 9090, system_proxy: false, capture_body_limit: DEFAULT_CAPTURE_BODY_LIMIT }
}
}
impl ProxySettings {
/// The settings at `path`, or the defaults when there is no file.
pub fn load(path: &Path) -> Result<Self, String> {
match std::fs::read_to_string(path) {
Ok(contents) => serde_json::from_str(&contents)
.map_err(|e| format!("Invalid settings in {}: {e}", path.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(e) => Err(format!("Failed to read {}: {e}", path.display())),
}
}
pub fn save(&self, path: &Path) -> Result<(), String> {
let contents = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
std::fs::write(path, contents)
.map_err(|e| format!("Failed to write {}: {e}", path.display()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_without_a_file() {
let dir = tempfile::tempdir().unwrap();
let settings = ProxySettings::load(&dir.path().join("settings.json")).unwrap();
assert_eq!(settings.port, 9090);
assert!(!settings.system_proxy);
assert_eq!(settings.capture_body_limit, 10 * 1024 * 1024);
}
#[test]
fn defaults_for_missing_keys() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
std::fs::write(&path, r#"{"port": 8888}"#).unwrap();
let settings = ProxySettings::load(&path).unwrap();
assert_eq!(settings, ProxySettings { port: 8888, ..Default::default() });
}
#[test]
fn round_trip() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
let settings = ProxySettings { port: 8080, system_proxy: true, capture_body_limit: 1024 };
settings.save(&path).unwrap();
assert_eq!(ProxySettings::load(&path).unwrap(), settings);
let json: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
assert_eq!(
json,
serde_json::json!({"port": 8080, "systemProxy": true, "captureBodyLimit": 1024})
);
}
#[test]
fn invalid_json_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
std::fs::write(&path, "{").unwrap();
assert!(ProxySettings::load(&path).is_err());
}
}