Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions clients/typescript/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5068,6 +5068,11 @@ export interface components {
RunStatementRecord: {
/** Format: int64 */
affected_rows?: number | null;
/**
* Format: int64
* @description Where the read that listed it stopped: pass it as `after` to read only the statements that changed since.
*/
cursor: number;
/** Format: double */
duration_ms?: number | null;
ended_at?: string | null;
Expand Down Expand Up @@ -9499,7 +9504,9 @@ export interface operations {
listPersonRunStatements: {
parameters: {
query?: {
/** @description Maximum statements; defaults to 1000, capped at 5000 */
/** @description A `cursor` from an earlier read: only statements with events stored since are listed, each in full; defaults to 0, every statement */
after?: number;
/** @description Maximum statements; defaults to 1000, capped at 5000. A full page's `cursor` reads on from where it stopped */
limit?: number;
};
header?: never;
Expand All @@ -9512,7 +9519,7 @@ export interface operations {
};
requestBody?: never;
responses: {
/** @description Statement metadata in start order, without SQL */
/** @description Statement metadata in start order, without SQL; each carries the cursor to read on from */
200: {
headers: {
[name: string]: unknown;
Expand Down
4 changes: 2 additions & 2 deletions crates/sqlbuild-cli/tests/native_commands/test_control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,13 +380,13 @@ fn given_a_control_store_when_running_server_migrate_then_dry_run_lists_and_migr
StoreMigrationCommandTestCase {
description: "migrate an empty store",
arguments: &["server", "migrate"],
expected_stdout: "The control store is empty: created schema version 13.\n",
expected_stdout: "The control store is empty: created schema version 14.\n",
expected_store: true,
},
StoreMigrationCommandTestCase {
description: "dry run on a current store",
arguments: &["server", "migrate", "--dry-run"],
expected_stdout: "The control store is at schema version 13: nothing to migrate.\n",
expected_stdout: "The control store is at schema version 14: nothing to migrate.\n",
expected_store: true,
},
];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Person reads of run nodes and their errors, node run history, catalog nodes, jobs and one job's declaration, triggers, ticks and publications; refusal precedes every lookup, so unknown objects look forbidden.

use std::sync::Arc;

use axum::extract::{Path, Query, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
Expand All @@ -12,8 +14,8 @@ use crate::api::_helpers::resources::runs::no_output_store;
use crate::api::errors::ApiError;
use crate::api::models::BrowserOrigin;
use crate::api::models::{
CostQuery, PlatformEventsQuery, ReadQuery, RunEventsQuery, RunNodePath, ServerFacts,
StatementSqlQuery, TargetTicksQuery,
CostQuery, PlatformEventsQuery, ReadQuery, RunEventsQuery, RunNodePath, RunStatementsQuery,
ServerFacts, StatementSqlQuery, TargetTicksQuery,
};
use crate::credentials::models::{AuditContext, AuthenticatedPerson, DefaultRole};
use crate::declarations::main::list_person_jobs::list_person_jobs;
Expand Down Expand Up @@ -237,8 +239,9 @@ pub(crate) async fn run_events(

#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/statements", operation_id = "listPersonRunStatements",
params(("location_id" = Uuid, Path), ("target" = String, Path), ("run_id" = Uuid, Path),
("limit" = Option<u32>, Query, description = "Maximum statements; defaults to 1000, capped at 5000")),
responses((status = 200, body = Vec<RunStatementRecord>, description = "Statement metadata in start order, without SQL"),
("after" = Option<i64>, Query, description = "A `cursor` from an earlier read: only statements with events stored since are listed, each in full; defaults to 0, every statement"),
("limit" = Option<u32>, Query, description = "Maximum statements; defaults to 1000, capped at 5000. A full page's `cursor` reads on from where it stopped")),
responses((status = 200, body = Vec<RunStatementRecord>, description = "Statement metadata in start order, without SQL; each carries the cursor to read on from"),
(status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody),
(status = 404, description = "Run not found for a person who may view the whole target")),
security(("session" = []), ("cliSession" = [])))]
Expand All @@ -247,7 +250,7 @@ pub(crate) async fn run_statements(
Extension(default_role): Extension<DefaultRole>,
(Path((location_id, target, run_id)), Query(options)): (
Path<(Uuid, String, Uuid)>,
Query<ReadQuery>,
Query<RunStatementsQuery>,
),
Extension(AuthenticatedPerson(principal, _)): Extension<AuthenticatedPerson>,
) -> Result<Json<Vec<RunStatementRecord>>, ApiError> {
Expand All @@ -256,12 +259,12 @@ pub(crate) async fn run_statements(
(&context, principal),
(
(location_id, &target, run_id),
options.limit.unwrap_or(1000),
(options.after.unwrap_or(0), options.limit.unwrap_or(1000)),
),
default_role,
)
.await?
.map(Json)
.map(|statements| Json(Arc::unwrap_or_clone(statements)))
.ok_or_else(|| not_found("run not found"))
}

Expand Down
25 changes: 21 additions & 4 deletions crates/sqlbuild-orchestration/src/api/errors.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! HTTP errors name the cause when the control database is unavailable; any other error never returns database diagnostics, connection strings or credentials.

use std::sync::Arc;

use axum::Json;
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
Expand Down Expand Up @@ -32,7 +34,20 @@ pub struct ApiError {

impl From<ControlError> for ApiError {
fn from(error: ControlError) -> Self {
let cause: Option<ControlCause> = control_cause(&error, (&ControlTarget::default(), false))
Self::from(&error)
}
}

/// A failure shared by every request that waited on one read.
impl From<Arc<ControlError>> for ApiError {
fn from(error: Arc<ControlError>) -> Self {
Self::from(&*error)
}
}

impl From<&ControlError> for ApiError {
fn from(error: &ControlError) -> Self {
let cause: Option<ControlCause> = control_cause(error, (&ControlTarget::default(), false))
.filter(ControlCause::unavailable);
if let Some(cause) = cause {
return Self {
Expand All @@ -57,7 +72,7 @@ impl From<ControlError> for ApiError {
cause: None,
};
match error {
ControlError::Invalid(message) => plain(StatusCode::BAD_REQUEST, message, None),
ControlError::Invalid(message) => plain(StatusCode::BAD_REQUEST, message.clone(), None),
ControlError::ReadTimedOut(_) => plain(
StatusCode::GATEWAY_TIMEOUT,
format!(
Expand All @@ -66,14 +81,16 @@ impl From<ControlError> for ApiError {
),
None,
),
ControlError::NotCheckingIn(message) => plain(StatusCode::CONFLICT, message, None),
ControlError::NotCheckingIn(message) => {
plain(StatusCode::CONFLICT, message.clone(), None)
}
ControlError::Denied {
reason,
decision_id,
} => plain(
StatusCode::FORBIDDEN,
format!("{reason}; decision {decision_id}"),
Some(decision_id),
Some(*decision_id),
),
ControlError::UnreadableSnapshot { .. }
| ControlError::StaleGeneration
Expand Down
8 changes: 8 additions & 0 deletions crates/sqlbuild-orchestration/src/api/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,14 @@ pub(crate) struct RunEventsQuery {
pub(crate) types: String,
}

/// A page of a run's statements: those with events after the cursor `after`, at most `limit`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RunStatementsQuery {
pub(crate) after: Option<i64>,
pub(crate) limit: Option<u32>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct StatementSqlQuery {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub(crate) fn note(cut_offs: &SessionCutOffs, store: &ControlStore, error: &sqlx
.lock()
.unwrap_or_else(PoisonError::into_inner);
pending.push((
database(store),
store.identity(),
SessionCutOff {
at: Utc::now(),
idle,
Expand All @@ -35,7 +35,7 @@ pub(crate) fn note(cut_offs: &SessionCutOffs, store: &ControlStore, error: &sqlx

/// `store`'s cut-off sessions in `cut_offs`, which the caller now owns.
pub(crate) fn take(cut_offs: &SessionCutOffs, store: &ControlStore) -> Vec<SessionCutOff> {
let key = database(store);
let key = store.identity();
let mut pending = cut_offs
.pending
.lock()
Expand All @@ -51,7 +51,7 @@ pub(crate) fn restore(
store: &ControlStore,
unreported: Vec<SessionCutOff>,
) {
let key = database(store);
let key = store.identity();
let mut pending = cut_offs
.pending
.lock()
Expand All @@ -76,19 +76,3 @@ fn cut_off(error: &sqlx_core::Error) -> Option<bool> {
};
(error.code()?.as_ref() == IDLE_IN_TRANSACTION_CODE).then_some(true)
}

/// Which database a store is: its PostgreSQL host, port and database, or its SQLite file.
fn database(store: &ControlStore) -> String {
match store {
ControlStore::Postgres(pool) => {
let options = pool.connect_options();
format!(
"{}:{}/{}",
options.get_host(),
options.get_port(),
options.get_database().unwrap_or_default()
)
}
ControlStore::Sqlite(sqlite) => sqlite.path.display().to_string(),
}
}
2 changes: 2 additions & 0 deletions crates/sqlbuild-orchestration/src/runs/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,8 @@ pub struct RunStatementRecord {
pub affected_rows: Option<i64>,
pub sql_available: bool,
pub sql_unavailable_reason: Option<String>,
/// Where the read that listed it stopped: pass it as `after` to read only the statements that changed since.
pub cursor: i64,
}

/// One statement's executed SQL; `sql` is null when capture was off or retention dropped it.
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlbuild-orchestration/src/store/indexes.sql
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ CREATE INDEX IF NOT EXISTS sqb_warehouse_fingerprints_received ON sqb_warehouse_
CREATE INDEX IF NOT EXISTS sqb_warehouse_consumption_received ON sqb_warehouse_consumption(location_id, target, received_at);
CREATE INDEX IF NOT EXISTS sqb_warehouse_observations_received ON sqb_warehouse_observations(location_id, target, received_at);
CREATE INDEX IF NOT EXISTS sqb_security_audit_attention ON sqb_security_audit((scope_json ->> 'location_id'), (scope_json ->> 'target'), (scope_json ->> 'key'), storage_id) WHERE action IN ('attention.acknowledged', 'attention.acknowledgement_withdrawn');
CREATE INDEX IF NOT EXISTS recall_events_invocation_statements ON recall_events(invocation_id, storage_id, statement_id, event_type) WHERE statement_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS recall_events_invocation_resources ON recall_events(invocation_id, resource_id, resource_name, resource_kind) WHERE resource_name IS NOT NULL;
19 changes: 19 additions & 0 deletions crates/sqlbuild-orchestration/src/store/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,25 @@ pub(crate) enum Connection {
Postgres(sqlx_core::transaction::Transaction<'static, sqlx_postgres::Postgres>),
}

impl ControlStore {
/// A PostgreSQL store's host, port, database and options (such as its schema), or a SQLite store's file.
pub(crate) fn identity(&self) -> String {
match self {
ControlStore::Postgres(pool) => {
let options = pool.connect_options();
format!(
"{}:{}/{}?{}",
options.get_host(),
options.get_port(),
options.get_database().unwrap_or_default(),
options.get_options().unwrap_or_default()
)
}
ControlStore::Sqlite(sqlite) => sqlite.path.display().to_string(),
}
}
}

impl ControlTransaction {
/// `column`, a compressed body, selected as hexadecimal text, never as bytes, which the store returns one JSON number per byte.
pub(crate) fn hex_column(&self, column: &str) -> String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ pub(crate) const MIGRATIONS: &[StoreMigration] = &[
postgres: include_str!("../sql/0013_write_claim_waits.postgres.sql"),
step: None,
},
StoreMigration {
name: "run_statement_reads",
sqlite: include_str!("../sql/0014_run_statement_reads.sqlite.sql"),
postgres: include_str!("../sql/0014_run_statement_reads.postgres.sql"),
step: None,
},
];

/// The schema version a store created by this build has.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- A run page reads a run's statement events stored after a cursor, and the names of their
-- resources, from these indexes alone instead of passing over every event of the run.
-- IF NOT EXISTS skips an index an operator pre-built. On a large Recall history, pre-build them
-- with CREATE INDEX CONCURRENTLY IF NOT EXISTS to keep runs reporting while the server upgrades.
CREATE INDEX IF NOT EXISTS recall_events_invocation_statements ON recall_events(invocation_id, storage_id, statement_id, event_type) WHERE statement_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS recall_events_invocation_resources ON recall_events(invocation_id, resource_id, resource_name, resource_kind) WHERE resource_name IS NOT NULL;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-- A run page reads a run's statement events stored after a cursor, and the names of their
-- resources, from these indexes alone instead of passing over every event of the run.
CREATE INDEX IF NOT EXISTS recall_events_invocation_statements ON recall_events(invocation_id, storage_id, statement_id, event_type) WHERE statement_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS recall_events_invocation_resources ON recall_events(invocation_id, resource_id, resource_name, resource_kind) WHERE resource_name IS NOT NULL;
Loading
Loading