Skip to content
Draft
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: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 7 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[workspace]
resolver = "2"
members = [
"crates/common",
"crates/control-plane",
"crates/data-plane",
"crates/internal-metrics",
Expand All @@ -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).
Expand All @@ -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"] }
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
21 changes: 21 additions & 0 deletions crates/common/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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<dyn …>`, 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
40 changes: 40 additions & 0 deletions crates/common/src/fallback.rs
Original file line number Diff line number Diff line change
@@ -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<FallbackResponse, FallbackError>;
}

/// 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<u8>,
}

/// 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<String>) -> Self {
Self {
message: message.into(),
}
}
}
33 changes: 33 additions & 0 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<String, String>;

// 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;
30 changes: 30 additions & 0 deletions crates/common/src/plan.rs
Original file line number Diff line number Diff line change
@@ -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<String>) -> Self {
Self {
message: message.into(),
}
}
}
44 changes: 44 additions & 0 deletions crates/common/src/query_engine.rs
Original file line number Diff line number Diff line change
@@ -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<String>) -> Self {
Self {
message: message.into(),
}
}
}
24 changes: 24 additions & 0 deletions crates/common/src/query_request.rs
Original file line number Diff line number Diff line change
@@ -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,
},
}
63 changes: 63 additions & 0 deletions crates/common/src/query_result.rs
Original file line number Diff line number Diff line change
@@ -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<InstantVectorElement>,
}

/// 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<RangeVectorElement>,
}

/// 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<Sample>,
}

/// 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<String>,
pub rows: Vec<Vec<TableValue>>,
}

/// One table cell.
#[derive(Debug, Clone, PartialEq)]
pub enum TableValue {
String(String),
Float(f64),
}
38 changes: 38 additions & 0 deletions crates/common/tests/trait_shapes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//! `FallbackClient` can be implemented outside this crate and used as
//! `Arc<dyn FallbackClient>`, 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<FallbackResponse, FallbackError> {
Err(FallbackError::new("connection refused"))
}
}

#[tokio::test]
async fn the_fallback_client_is_usable_as_a_trait_object() {
let fallback: Arc<dyn FallbackClient> = 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());
}
2 changes: 1 addition & 1 deletion scripts/ci/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions scripts/ci/test_sync_planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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."""
Expand Down
Loading