use indexmap::IndexMap;
use serde::Serialize;
use serde_json::Value;
#[derive(Debug, Clone, Serialize)]
pub struct Gap {
pub object: String,
pub cause: String,
pub detail: String,
}
impl Gap {
#[must_use]
pub fn new(
object: impl Into<String>,
cause: impl Into<String>,
detail: impl Into<String>,
) -> Self {
Self {
object: object.into(),
cause: cause.into(),
detail: detail.into(),
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct Applied {
#[serde(skip_serializing_if = "Option::is_none")]
pub input_count: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output_count: Option<usize>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub content_truncated: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub content_redacted: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub output_truncated: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub dropped: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub has_more: Option<bool>,
#[serde(skip_serializing_if = "no_operation_gathered")]
pub accumulated_for: &'static [&'static str],
}
fn no_operation_gathered(names: &&'static [&'static str]) -> bool {
names.is_empty()
}
pub const SIGNATURE_OPERATION: &str = "checksum";
impl Applied {
#[must_use]
pub fn also_gathered_for_the_signature(mut self) -> Self {
let gathered = self.accumulated_for;
self.accumulated_for = match (gathered.contains(&"sort"), gathered.contains(&"count-only"))
{
(true, true) => &["sort", "count-only", SIGNATURE_OPERATION],
(true, false) => &["sort", SIGNATURE_OPERATION],
(false, true) => &["count-only", SIGNATURE_OPERATION],
(false, false) => &[SIGNATURE_OPERATION],
};
self
}
#[must_use]
pub const fn is_silent(&self) -> bool {
self.input_count.is_none()
&& self.output_count.is_none()
&& !self.content_truncated
&& !self.content_redacted
&& !self.output_truncated
&& self.dropped.is_none()
&& self.accumulated_for.is_empty()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TargetSource {
Argv,
Dsn,
Selector,
Config,
}
#[derive(Debug, Clone, Serialize)]
pub struct Target {
#[serde(skip_serializing_if = "Option::is_none")]
pub profile: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub port: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub socket: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub database: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Envelope {
pub command: &'static str,
pub schema_version: u32,
#[serde(rename = "target_resolved", skip_serializing_if = "Option::is_none")]
pub target: Option<Target>,
#[serde(skip_serializing_if = "Option::is_none")]
pub target_source: Option<TargetSource>,
pub data: Value,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub gaps: Vec<Gap>,
#[serde(skip_serializing_if = "Option::is_none")]
pub applied: Option<Applied>,
#[serde(skip_serializing_if = "Option::is_none")]
pub checksum: Option<String>,
#[serde(skip)]
pub raw_field: Option<&'static str>,
}
pub const SCHEMA_VERSION: u32 = 1;
impl Envelope {
#[must_use]
pub fn new(command: &'static str, data: Value) -> Self {
Self {
command,
schema_version: SCHEMA_VERSION,
target: None,
target_source: None,
data,
gaps: Vec::new(),
applied: None,
checksum: None,
raw_field: None,
}
}
#[must_use]
pub fn from_destination(mut self, target: Target, source: TargetSource) -> Self {
self.target = Some(target);
self.target_source = Some(source);
self
}
#[must_use]
pub fn with_raw_field(mut self, field: &'static str) -> Self {
self.raw_field = Some(field);
self
}
#[must_use]
pub fn raw_document(&self) -> Option<&str> {
self.data.get(self.raw_field?)?.as_str()
}
#[must_use]
pub fn with_gap(mut self, gap: Gap) -> Self {
self.gaps.push(gap);
self
}
#[must_use]
pub fn with_applied(mut self, applied: Applied) -> Self {
if !applied.is_silent() {
self.applied = Some(applied);
}
self
}
#[must_use]
pub fn with_checksum(mut self, checksum: impl Into<String>) -> Self {
self.checksum = Some(checksum.into());
self
}
#[must_use]
pub fn payload_columns_key(&self) -> Option<&'static str> {
const COLUMNS: &str = "columns";
let map = self.data.as_object()?;
let declared: Vec<&str> = map
.get(COLUMNS)?
.as_array()?
.iter()
.map(Value::as_str)
.collect::<Option<Vec<&str>>>()?;
if declared.is_empty() {
return None;
}
let rows = map.get(self.payload_array_key()?)?.as_array()?;
rows.iter()
.all(|row| {
row.as_object()
.is_some_and(|fields| fields.keys().all(|key| declared.contains(&key.as_str())))
})
.then_some(COLUMNS)
}
#[must_use]
pub fn payload_array_key(&self) -> Option<&'static str> {
const CANDIDATES: [&str; 6] = ["rows", "items", "objects", "results", "entries", "records"];
let map = self.data.as_object()?;
CANDIDATES
.into_iter()
.find(|key| map.get(*key).is_some_and(Value::is_array))
}
}
pub type Row = IndexMap<String, Value>;
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_clean_answer_carries_no_optional_weight() {
let envelope = Envelope::new("schema tables", json!({"rows": []}));
let line = serde_json::to_string(&envelope).expect("serialises");
assert!(!line.contains("gaps"), "empty gaps must not appear: {line}");
assert!(!line.contains("applied"), "silent pipeline must not appear");
assert!(
!line.contains("checksum"),
"absent checksum must not appear"
);
}
#[test]
fn a_declared_gap_appears_without_changing_the_shape() {
let envelope =
Envelope::new("schema databases", json!({"rows": ["a"]})).with_gap(Gap::new(
"restricted_db",
"permission",
"the credential may not list this database",
));
let parsed = serde_json::to_value(&envelope).expect("serialises");
assert_eq!(parsed["gaps"][0]["cause"], "permission");
assert_eq!(parsed["gaps"][0]["object"], "restricted_db");
}
#[test]
fn a_silent_pipeline_is_not_reported() {
let envelope =
Envelope::new("query run", json!({"rows": []})).with_applied(Applied::default());
assert!(envelope.applied.is_none());
}
#[test]
fn the_payload_array_is_found_by_published_order() {
let envelope = Envelope::new("query run", json!({"rows": [1, 2], "count": 2}));
assert_eq!(envelope.payload_array_key(), Some("rows"));
let no_array = Envelope::new("meta version", json!({"version": "0.1.0"}));
assert_eq!(no_array.payload_array_key(), None);
}
}