diff --git a/Cargo.lock b/Cargo.lock index 5dc5ff4b7..4db60f4ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -850,6 +850,17 @@ dependencies = [ "unicode-width 0.2.2", ] +[[package]] +name = "common" +version = "0.1.0" +dependencies = [ + "asap-planner", + "asap-types", + "async-trait", + "thiserror 1.0.69", + "tokio", +] + [[package]] name = "const-random" version = "0.1.18" diff --git a/Cargo.toml b/Cargo.toml index 5cd886380..daff37847 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] resolver = "2" members = [ + "crates/common", "crates/control-plane", "crates/data-plane", "crates/internal-metrics", @@ -12,11 +13,13 @@ edition = "2021" version = "0.1.0" [workspace.dependencies] -# The backend depends on two Planner crates, at one immutable revision: -# `asap-planner` to plan and `asap-executor` to execute. Planner IR types -# are reached through `asap_executor::planner`. +# The backend depends on three Planner crates, at one immutable revision: +# `asap-planner` to plan, `asap-executor` to execute, and `asap-types` for +# the plan types `common`'s boundary names (such as `QueryLanguage`). +# Elsewhere, Planner IR types are reached through `asap_executor::planner`. asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "1d527bca445b6372f0eb72aafd725d04a3a77dfb" } asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "1d527bca445b6372f0eb72aafd725d04a3a77dfb" } +asap-types = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "1d527bca445b6372f0eb72aafd725d04a3a77dfb" } # The sketch library the Planner's executor pins, for the byte encodings of # the sketch states the data plane persists; keep it at the Planner's rev # (here overridden below for the executor too). @@ -27,6 +30,7 @@ serde = { version = "1.0", features = ["derive"] } # (its predicted usage and prices are floats). serde_json = { version = "1.0", features = ["float_roundtrip"] } thiserror = "1.0" +async-trait = "0.1" anyhow = "1.0" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/README.md b/README.md index 83aa2df23..5de55a0b6 100644 --- a/README.md +++ b/README.md @@ -250,6 +250,7 @@ cargo clippy --workspace --all-targets --locked -- -D warnings cargo test --workspace --locked ``` -The Planner revision is pinned in `Cargo.toml` (ASAPPlanner `737bfb1`; `asap_sketchlib` patched -to `355093f`); see +The Planner revision is pinned in `Cargo.toml` (ASAPPlanner `1d527bc` for +`asap-planner`, `asap-executor` and `asap-types`; `asap_sketchlib` patched to +`355093f`); see [scripts/ci/README.md](scripts/ci/README.md). diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml new file mode 100644 index 000000000..0dc6e5bd7 --- /dev/null +++ b/crates/common/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "common" +version.workspace = true +edition.workspace = true + +# The data plane's boundary types and the fallback trait +# (docs/design/repo-layout.md). +# Only ASAPPlanner's plan types: `asap-planner` for `InstallablePlan` and +# `asap-types` for the IR types it does not re-export. No executor item is +# named here; `asap-planner` still compiles the executor and the frontends +# as its own dependencies. +[dependencies] +asap-planner.workspace = true +asap-types.workspace = true +# `FallbackClient` is used as `Arc`, so its async method must be +# object safe; native `async fn` in traits is not. +async-trait.workspace = true +thiserror.workspace = true + +[dev-dependencies] +tokio.workspace = true diff --git a/crates/common/src/fallback.rs b/crates/common/src/fallback.rs new file mode 100644 index 000000000..973332599 --- /dev/null +++ b/crates/common/src/fallback.rs @@ -0,0 +1,40 @@ +use async_trait::async_trait; + +use crate::QueryRequest; + +/// The client of the backend that answers a query the data plane does not: +/// a query that is not planned, not ready, or failed in the engine. +#[async_trait] +pub trait FallbackClient: Send + Sync { + /// Sends the query to the backend, with the client's `headers` (name, + /// value), and returns the backend's response as is. + async fn execute( + &self, + request: &QueryRequest, + headers: &[(String, String)], + ) -> Result; +} + +/// The backend's HTTP response, passed to the client unchanged. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FallbackResponse { + pub status_code: u16, + /// The `Content-Type` header value, e.g. `application/json`. + pub content_type: String, + pub body: Vec, +} + +/// The backend could not be reached or sent no response. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{message}")] +pub struct FallbackError { + pub message: String, +} + +impl FallbackError { + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + } + } +} diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs new file mode 100644 index 000000000..bd8e1ec3f --- /dev/null +++ b/crates/common/src/lib.rs @@ -0,0 +1,33 @@ +//! The data plane's boundary types and the `FallbackClient` trait, with the +//! names and shapes of ASAPQuery's engine-boundary design +//! (docs/design/repo-layout.md). Adapters and engines meet here; this crate +//! holds no implementation. +//! +//! It names ASAPPlanner's plan types only (`InstallablePlan`, the DAG's node +//! ids, `QueryLanguage`) and no executor item. +//! `asap-planner`, which defines `InstallablePlan`, still brings the +//! executor and the frontends in at compile time. + +mod fallback; +mod plan; +mod query_engine; +mod query_request; +mod query_result; + +pub use fallback::{FallbackClient, FallbackError, FallbackResponse}; +pub use plan::{InstallError, InstalledPlan, PlanId}; +pub use query_engine::{AnswerSource, EngineQueryResult, QueryEngineError}; +pub use query_request::{QueryEval, QueryRequest}; +pub use query_result::{ + InstantVector, InstantVectorElement, QueryResult, RangeVector, RangeVectorElement, Sample, + Table, TableValue, +}; + +/// One series' labels, name to value, `__name__` included, as query results +/// carry them. +pub type LabelSet = std::collections::BTreeMap; + +// The plan types the boundary names, so callers need no direct Planner +// dependency to use it. +pub use asap_planner::{InstallablePlan, PhysicalASAPNodeId}; +pub use asap_types::workload::QueryLanguage; diff --git a/crates/common/src/plan.rs b/crates/common/src/plan.rs new file mode 100644 index 000000000..1d5bebdb8 --- /dev/null +++ b/crates/common/src/plan.rs @@ -0,0 +1,30 @@ +use asap_planner::InstallablePlan; + +/// The installed plan's version for the workload: a counter the installer +/// increments per install. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct PlanId(pub u64); + +/// A validated `InstallablePlan` with the id it was installed under. Nothing +/// else: everything an engine derives from the plan, it computes from `plan`. +#[derive(Debug, Clone, PartialEq)] +pub struct InstalledPlan { + pub id: PlanId, + pub plan: InstallablePlan, +} + +/// Why an engine refused a plan; the installer keeps the current plan and +/// logs `message`. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{message}")] +pub struct InstallError { + pub message: String, +} + +impl InstallError { + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + } + } +} diff --git a/crates/common/src/query_engine.rs b/crates/common/src/query_engine.rs new file mode 100644 index 000000000..78b472663 --- /dev/null +++ b/crates/common/src/query_engine.rs @@ -0,0 +1,44 @@ +use asap_planner::PhysicalASAPNodeId; + +use crate::{PlanId, QueryResult}; + +/// What answers a query, as the dispatcher resolved it: the engine runs it +/// without matching the query again. +#[derive(Debug, Clone, PartialEq)] +pub enum AnswerSource { + /// The query is the plan's query `i`, answered by `dag.roots[i]`. + /// `plan` is the plan it was resolved against. + Planned { + plan: PlanId, + root: PhysicalASAPNodeId, + }, + // `CapabilityMatched { plan, matched }` goes here once capability + // matching (answering an unplanned query from the stored views) is + // designed. +} + +/// What the query engine reports for one query. +#[derive(Debug, Clone, PartialEq)] +pub enum EngineQueryResult { + /// The answer. + Ready { result: QueryResult }, + /// The stored data does not cover the whole query, or the plan changed + /// since the query was resolved; the query falls back. + NotReady, +} + +/// A query the engine failed to run. The dispatcher logs and counts it, and +/// the query falls back. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{message}")] +pub struct QueryEngineError { + pub message: String, +} + +impl QueryEngineError { + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + } + } +} diff --git a/crates/common/src/query_request.rs b/crates/common/src/query_request.rs new file mode 100644 index 000000000..53ae2f2c5 --- /dev/null +++ b/crates/common/src/query_request.rs @@ -0,0 +1,24 @@ +use asap_types::workload::QueryLanguage; + +/// One parsed query, independent of the protocol it arrived on. +#[derive(Debug, Clone, PartialEq)] +pub struct QueryRequest { + pub language: QueryLanguage, + /// The query text, as the client sent it. + pub query: String, + pub eval: QueryEval, +} + +/// When to evaluate a query, in unix epoch milliseconds. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QueryEval { + Instant { + time_ms: i64, + }, + /// At `start_ms`, then every `step_ms` up to `end_ms`. + Range { + start_ms: i64, + end_ms: i64, + step_ms: i64, + }, +} diff --git a/crates/common/src/query_result.rs b/crates/common/src/query_result.rs new file mode 100644 index 000000000..3f5087db7 --- /dev/null +++ b/crates/common/src/query_result.rs @@ -0,0 +1,63 @@ +//! A query's answer. Every variant carries its own label or column names. + +use crate::LabelSet; + +/// The result of a query. A response adapter returns an error for a +/// variant its protocol cannot express. +#[derive(Debug, Clone, PartialEq)] +pub enum QueryResult { + Vector(InstantVector), + Matrix(RangeVector), + /// One value at one time (a PromQL scalar). + Scalar(Sample), + /// Named columns and rows (a SQL result set). + Table(Table), +} + +/// One value per series, all at `timestamp_ms`. +#[derive(Debug, Clone, PartialEq)] +pub struct InstantVector { + pub timestamp_ms: i64, + pub series: Vec, +} + +/// One series of an instant vector: its labels and its value. +#[derive(Debug, Clone, PartialEq)] +pub struct InstantVectorElement { + pub labels: LabelSet, + pub value: f64, +} + +/// Samples over a time range, per series. +#[derive(Debug, Clone, PartialEq)] +pub struct RangeVector { + pub series: Vec, +} + +/// One series of a range vector: its labels and its samples, oldest first. +#[derive(Debug, Clone, PartialEq)] +pub struct RangeVectorElement { + pub labels: LabelSet, + pub samples: Vec, +} + +/// A value at a time. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Sample { + pub timestamp_ms: i64, + pub value: f64, +} + +/// A table: each row holds one value per column, in column order. +#[derive(Debug, Clone, PartialEq)] +pub struct Table { + pub columns: Vec, + pub rows: Vec>, +} + +/// One table cell. +#[derive(Debug, Clone, PartialEq)] +pub enum TableValue { + String(String), + Float(f64), +} diff --git a/crates/common/tests/trait_shapes.rs b/crates/common/tests/trait_shapes.rs new file mode 100644 index 000000000..aa28b07f4 --- /dev/null +++ b/crates/common/tests/trait_shapes.rs @@ -0,0 +1,38 @@ +//! `FallbackClient` can be implemented outside this crate and used as +//! `Arc`, as the query routes hold their fallback. The +//! fake is trivial: only the trait's shape is under test. + +use std::sync::Arc; + +use async_trait::async_trait; +use common::{ + FallbackClient, FallbackError, FallbackResponse, QueryEval, QueryLanguage, QueryRequest, +}; + +struct Unreachable; + +#[async_trait] +impl FallbackClient for Unreachable { + async fn execute( + &self, + _request: &QueryRequest, + _headers: &[(String, String)], + ) -> Result { + Err(FallbackError::new("connection refused")) + } +} + +#[tokio::test] +async fn the_fallback_client_is_usable_as_a_trait_object() { + let fallback: Arc = Arc::new(Unreachable); + let request = QueryRequest { + language: QueryLanguage::PromQL, + query: "up".into(), + eval: QueryEval::Range { + start_ms: 0, + end_ms: 60_000, + step_ms: 15_000, + }, + }; + assert!(fallback.execute(&request, &[]).await.is_err()); +} diff --git a/scripts/ci/README.md b/scripts/ci/README.md index ffc00818a..d369a65a9 100644 --- a/scripts/ci/README.md +++ b/scripts/ci/README.md @@ -2,7 +2,7 @@ The backend keeps reproducible Planner revisions in `Cargo.toml` and `Cargo.lock`. `Sync ASAPPlanner main` checks upstream main daily (or on manual dispatch), updates -both Planner dependencies (`asap-planner`, `asap-executor`) together, and opens or refreshes +the three Planner dependencies (`asap-planner`, `asap-executor`, `asap-types`) together, and opens or refreshes `automation/sync-asapplanner-main` against backend main. GitHub scheduled runs can be delayed. The existing `ASAP_CI_REPO_TOKEN` secret must have read access to private dependency diff --git a/scripts/ci/test_sync_planner.py b/scripts/ci/test_sync_planner.py index c9af27d5d..409ff1d89 100644 --- a/scripts/ci/test_sync_planner.py +++ b/scripts/ci/test_sync_planner.py @@ -33,7 +33,7 @@ class PlannerSyncTests(unittest.TestCase): revision = "a" * 40 manifest = ''.join( f'{name} = {{ git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "{"b" * 40}" }}\n' - for name in ['asap-planner', 'asap-executor'] + for name in ['asap-planner', 'asap-executor', 'asap-types'] ) def run_sync(self, manifest, revision=None, cargo_status=0): @@ -58,10 +58,11 @@ def test_updates_all_dependencies_and_lock_resolution(self): root, result = self.run_sync(self.manifest + other) self.assertEqual(result.returncode, 0, result.stderr) updated = (root / 'Cargo.toml').read_text() - self.assertEqual(updated.count(f'rev = "{self.revision}"'), 2) + self.assertEqual(updated.count(f'rev = "{self.revision}"'), 3) self.assertTrue(updated.endswith(other)) self.assertEqual((root / 'cargo-args').read_text().splitlines(), [ - 'update', '-p', 'asap-planner', '-p', 'asap-executor', '--precise', self.revision]) + 'update', '-p', 'asap-planner', '-p', 'asap-executor', '-p', 'asap-types', '--precise', + self.revision]) def test_repository_manifest_updates_only_locked_packages(self): """Every pin in the real Cargo.toml is rewritten and every `-p` names a locked package.""" diff --git a/scripts/sync-asapplanner-main.sh b/scripts/sync-asapplanner-main.sh index 37273d5df..5fc9e3d3b 100755 --- a/scripts/sync-asapplanner-main.sh +++ b/scripts/sync-asapplanner-main.sh @@ -20,14 +20,15 @@ pattern = re.compile( r'(git = "https://github.com/ProjectASAP/ASAPPlanner", rev = ")[0-9a-f]{40}("\s*[,}])' ) updated, replacements = pattern.subn(rf"\g<1>{revision}\2", text) -if replacements != 2: - raise SystemExit(f"expected two ASAPPlanner dependencies, found {replacements}") +if replacements != 3: + raise SystemExit(f"expected three ASAPPlanner dependencies, found {replacements}") path.write_text(updated) PY cargo update \ -p asap-planner \ -p asap-executor \ + -p asap-types \ --precise "$planner_rev" echo "synchronized ASAPPlanner dependencies to $planner_rev"