//! Generated by `trust-tasks-codegen` — do not edit by hand.
//!
//! Spec slug: `did-management/server/metrics`. Version: `0.1`.
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};
/// Error types.
pub mod error {
/// Error from a `TryFrom` or `FromStr` implementation.
pub struct ConversionError(::std::borrow::Cow<'static, str>);
impl ::std::error::Error for ConversionError {}
impl ::std::fmt::Display for ConversionError {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> {
::std::fmt::Display::fmt(&self.0, f)
}
}
impl ::std::fmt::Debug for ConversionError {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> {
::std::fmt::Debug::fmt(&self.0, f)
}
}
impl From<&'static str> for ConversionError {
fn from(value: &'static str) -> Self {
Self(value.into())
}
}
impl From<String> for ConversionError {
fn from(value: String) -> Self {
Self(value.into())
}
}
}
///Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "title": "Ext",
/// "description": "Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.",
/// "type": "object",
/// "minProperties": 1,
/// "additionalProperties": true,
/// "propertyNames": {
/// "pattern": "^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$"
/// }
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(transparent)]
pub struct Ext(pub ::std::collections::HashMap<ExtKey, ::serde_json::Value>);
impl ::std::ops::Deref for Ext {
type Target = ::std::collections::HashMap<ExtKey, ::serde_json::Value>;
fn deref(&self) -> &::std::collections::HashMap<ExtKey, ::serde_json::Value> {
&self.0
}
}
impl ::std::convert::From<Ext> for ::std::collections::HashMap<ExtKey, ::serde_json::Value> {
fn from(value: Ext) -> Self {
value.0
}
}
impl ::std::convert::From<::std::collections::HashMap<ExtKey, ::serde_json::Value>> for Ext {
fn from(value: ::std::collections::HashMap<ExtKey, ::serde_json::Value>) -> Self {
Self(value)
}
}
///`ExtKey`
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "type": "string",
/// "pattern": "^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$"
///}
/// ```
/// </details>
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[serde(transparent)]
pub struct ExtKey(::std::string::String);
impl ::std::ops::Deref for ExtKey {
type Target = ::std::string::String;
fn deref(&self) -> &::std::string::String {
&self.0
}
}
impl ::std::convert::From<ExtKey> for ::std::string::String {
fn from(value: ExtKey) -> Self {
value.0
}
}
impl ::std::str::FromStr for ExtKey {
type Err = self::error::ConversionError;
fn from_str(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
static PATTERN: ::std::sync::LazyLock<::regress::Regex> =
::std::sync::LazyLock::new(|| {
::regress::Regex::new("^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$").unwrap()
});
if PATTERN.find(value).is_none() {
return Err("doesn't match pattern \"^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$\"".into());
}
Ok(Self(value.to_string()))
}
}
impl ::std::convert::TryFrom<&str> for ExtKey {
type Error = self::error::ConversionError;
fn try_from(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl ::std::convert::TryFrom<&::std::string::String> for ExtKey {
type Error = self::error::ConversionError;
fn try_from(
value: &::std::string::String,
) -> ::std::result::Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl ::std::convert::TryFrom<::std::string::String> for ExtKey {
type Error = self::error::ConversionError;
fn try_from(
value: ::std::string::String,
) -> ::std::result::Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl<'de> ::serde::Deserialize<'de> for ExtKey {
fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
::std::string::String::deserialize(deserializer)?
.parse()
.map_err(|e: self::error::ConversionError| {
<D::Error as ::serde::de::Error>::custom(e.to_string())
})
}
}
///One histogram's distribution, in the Prometheus cumulative-bucket convention: each bucket's `count` includes every observation at or below its `le`.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "title": "Histogram",
/// "description": "One histogram's distribution, in the Prometheus cumulative-bucket convention: each bucket's `count` includes every observation at or below its `le`.",
/// "type": "object",
/// "required": [
/// "buckets",
/// "count",
/// "name",
/// "sum"
/// ],
/// "properties": {
/// "buckets": {
/// "description": "Cumulative buckets, ordered by ascending `le`. Empty when the service exposes no bucket breakdown for this histogram — count and sum still apply. Always present, for the same reason as the snapshot's own arrays.",
/// "type": "array",
/// "items": {
/// "$ref": "#/definitions/HistogramBucket"
/// }
/// },
/// "count": {
/// "description": "Total number of observations.",
/// "type": "integer",
/// "minimum": 0.0
/// },
/// "labels": {
/// "description": "Dimensions the distribution is broken down by. Absent or empty when the histogram carries none.",
/// "type": "object",
/// "additionalProperties": {
/// "type": "string"
/// }
/// },
/// "name": {
/// "description": "The histogram's stable name (e.g. `did_hosting_resolve_seconds`).",
/// "type": "string",
/// "minLength": 1
/// },
/// "sum": {
/// "description": "Sum of all observed values.",
/// "type": "number"
/// }
/// },
/// "additionalProperties": false
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Histogram {
///Cumulative buckets, ordered by ascending `le`. Empty when the service exposes no bucket breakdown for this histogram — count and sum still apply. Always present, for the same reason as the snapshot's own arrays.
pub buckets: ::std::vec::Vec<HistogramBucket>,
///Total number of observations.
pub count: u64,
///Dimensions the distribution is broken down by. Absent or empty when the histogram carries none.
#[serde(
default,
skip_serializing_if = ":: std :: collections :: HashMap::is_empty"
)]
pub labels: ::std::collections::HashMap<::std::string::String, ::std::string::String>,
///The histogram's stable name (e.g. `did_hosting_resolve_seconds`).
pub name: HistogramName,
///Sum of all observed values.
pub sum: f64,
}
impl Histogram {
pub fn builder() -> builder::Histogram {
Default::default()
}
}
///`HistogramBucket`
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "title": "HistogramBucket",
/// "type": "object",
/// "required": [
/// "count",
/// "le"
/// ],
/// "properties": {
/// "count": {
/// "description": "Number of observations at or below `le`.",
/// "type": "integer",
/// "minimum": 0.0
/// },
/// "le": {
/// "description": "Upper bound of this bucket, inclusive. The final bucket conventionally reports the same value as the histogram's own `count` at whatever `le` the service treats as its ceiling.",
/// "type": "number"
/// }
/// },
/// "additionalProperties": false
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct HistogramBucket {
///Number of observations at or below `le`.
pub count: u64,
///Upper bound of this bucket, inclusive. The final bucket conventionally reports the same value as the histogram's own `count` at whatever `le` the service treats as its ceiling.
pub le: f64,
}
impl HistogramBucket {
pub fn builder() -> builder::HistogramBucket {
Default::default()
}
}
///The histogram's stable name (e.g. `did_hosting_resolve_seconds`).
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "description": "The histogram's stable name (e.g. `did_hosting_resolve_seconds`).",
/// "type": "string",
/// "minLength": 1
///}
/// ```
/// </details>
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[serde(transparent)]
pub struct HistogramName(::std::string::String);
impl ::std::ops::Deref for HistogramName {
type Target = ::std::string::String;
fn deref(&self) -> &::std::string::String {
&self.0
}
}
impl ::std::convert::From<HistogramName> for ::std::string::String {
fn from(value: HistogramName) -> Self {
value.0
}
}
impl ::std::str::FromStr for HistogramName {
type Err = self::error::ConversionError;
fn from_str(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
if value.chars().count() < 1usize {
return Err("shorter than 1 characters".into());
}
Ok(Self(value.to_string()))
}
}
impl ::std::convert::TryFrom<&str> for HistogramName {
type Error = self::error::ConversionError;
fn try_from(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl ::std::convert::TryFrom<&::std::string::String> for HistogramName {
type Error = self::error::ConversionError;
fn try_from(
value: &::std::string::String,
) -> ::std::result::Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl ::std::convert::TryFrom<::std::string::String> for HistogramName {
type Error = self::error::ConversionError;
fn try_from(
value: ::std::string::String,
) -> ::std::result::Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl<'de> ::serde::Deserialize<'de> for HistogramName {
fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
::std::string::String::deserialize(deserializer)?
.parse()
.map_err(|e: self::error::ConversionError| {
<D::Error as ::serde::de::Error>::custom(e.to_string())
})
}
}
///One counter or gauge reading.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "title": "Metric",
/// "description": "One counter or gauge reading.",
/// "type": "object",
/// "required": [
/// "name",
/// "value"
/// ],
/// "properties": {
/// "labels": {
/// "description": "Dimensions the value is broken down by (e.g. `{\"method\": \"resolve\"}`). Absent or empty when the metric carries none.",
/// "type": "object",
/// "additionalProperties": {
/// "type": "string"
/// }
/// },
/// "name": {
/// "description": "The metric's stable name (e.g. `did_hosting_requests_total`). Implementation-defined; the framework imposes no vocabulary.",
/// "type": "string",
/// "minLength": 1
/// },
/// "value": {
/// "description": "The current reading.",
/// "type": "number"
/// }
/// },
/// "additionalProperties": false
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Metric {
///Dimensions the value is broken down by (e.g. `{"method": "resolve"}`). Absent or empty when the metric carries none.
#[serde(
default,
skip_serializing_if = ":: std :: collections :: HashMap::is_empty"
)]
pub labels: ::std::collections::HashMap<::std::string::String, ::std::string::String>,
///The metric's stable name (e.g. `did_hosting_requests_total`). Implementation-defined; the framework imposes no vocabulary.
pub name: MetricName,
///The current reading.
pub value: f64,
}
impl Metric {
pub fn builder() -> builder::Metric {
Default::default()
}
}
///The metric's stable name (e.g. `did_hosting_requests_total`). Implementation-defined; the framework imposes no vocabulary.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "description": "The metric's stable name (e.g. `did_hosting_requests_total`). Implementation-defined; the framework imposes no vocabulary.",
/// "type": "string",
/// "minLength": 1
///}
/// ```
/// </details>
#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[serde(transparent)]
pub struct MetricName(::std::string::String);
impl ::std::ops::Deref for MetricName {
type Target = ::std::string::String;
fn deref(&self) -> &::std::string::String {
&self.0
}
}
impl ::std::convert::From<MetricName> for ::std::string::String {
fn from(value: MetricName) -> Self {
value.0
}
}
impl ::std::str::FromStr for MetricName {
type Err = self::error::ConversionError;
fn from_str(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
if value.chars().count() < 1usize {
return Err("shorter than 1 characters".into());
}
Ok(Self(value.to_string()))
}
}
impl ::std::convert::TryFrom<&str> for MetricName {
type Error = self::error::ConversionError;
fn try_from(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl ::std::convert::TryFrom<&::std::string::String> for MetricName {
type Error = self::error::ConversionError;
fn try_from(
value: &::std::string::String,
) -> ::std::result::Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl ::std::convert::TryFrom<::std::string::String> for MetricName {
type Error = self::error::ConversionError;
fn try_from(
value: ::std::string::String,
) -> ::std::result::Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl<'de> ::serde::Deserialize<'de> for MetricName {
fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
::std::string::String::deserialize(deserializer)?
.parse()
.map_err(|e: self::error::ConversionError| {
<D::Error as ::serde::de::Error>::custom(e.to_string())
})
}
}
///`MetricsSnapshot`
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "title": "MetricsSnapshot",
/// "type": "object",
/// "required": [
/// "counters",
/// "gauges",
/// "histograms",
/// "takenAt"
/// ],
/// "properties": {
/// "counters": {
/// "description": "Monotonically increasing totals (e.g. requests served, errors raised). Empty when the service exposes none. Always present, so a collector can tell \"no counters\" from \"the field was dropped\".",
/// "type": "array",
/// "items": {
/// "$ref": "#/definitions/Metric"
/// }
/// },
/// "ext": {
/// "$ref": "#/definitions/Ext"
/// },
/// "gauges": {
/// "description": "Point-in-time values that can rise or fall (e.g. open connections, queue depth). Empty when the service exposes none. Always present, for the same reason as counters.",
/// "type": "array",
/// "items": {
/// "$ref": "#/definitions/Metric"
/// }
/// },
/// "histograms": {
/// "description": "Distributions of observed values (e.g. request latency). Empty when the service exposes none. Always present, for the same reason as counters.",
/// "type": "array",
/// "items": {
/// "$ref": "#/definitions/Histogram"
/// }
/// },
/// "takenAt": {
/// "description": "When the service read these values from its own instrumentation. Not the same as the envelope's issuedAt when a snapshot is cached briefly before answering.",
/// "type": "string",
/// "format": "date-time"
/// }
/// },
/// "additionalProperties": false
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct MetricsSnapshot {
///Monotonically increasing totals (e.g. requests served, errors raised). Empty when the service exposes none. Always present, so a collector can tell "no counters" from "the field was dropped".
pub counters: ::std::vec::Vec<Metric>,
#[serde(default, skip_serializing_if = "::std::option::Option::is_none")]
pub ext: ::std::option::Option<Ext>,
///Point-in-time values that can rise or fall (e.g. open connections, queue depth). Empty when the service exposes none. Always present, for the same reason as counters.
pub gauges: ::std::vec::Vec<Metric>,
///Distributions of observed values (e.g. request latency). Empty when the service exposes none. Always present, for the same reason as counters.
pub histograms: ::std::vec::Vec<Histogram>,
///When the service read these values from its own instrumentation. Not the same as the envelope's issuedAt when a snapshot is cached briefly before answering.
#[serde(rename = "takenAt")]
pub taken_at: ::chrono::DateTime<::chrono::offset::Utc>,
}
impl MetricsSnapshot {
pub fn builder() -> builder::MetricsSnapshot {
Default::default()
}
}
///The read takes no selector — the whole snapshot is returned. The outer document members (id, type, issuer, recipient, issuedAt, expiresAt, proof) are owned by the framework — SPEC §6.3.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "$id": "https://trusttasks.org/spec/did-management/server/metrics/0.1",
/// "title": "Payload",
/// "description": "The read takes no selector — the whole snapshot is returned. The outer document members (id, type, issuer, recipient, issuedAt, expiresAt, proof) are owned by the framework — SPEC §6.3.",
/// "type": "object",
/// "properties": {
/// "ext": {
/// "$ref": "#/definitions/Ext"
/// }
/// },
/// "additionalProperties": false
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Payload {
#[serde(default, skip_serializing_if = "::std::option::Option::is_none")]
pub ext: ::std::option::Option<Ext>,
}
impl ::std::default::Default for Payload {
fn default() -> Self {
Self {
ext: Default::default(),
}
}
}
impl Payload {
pub fn builder() -> builder::Payload {
Default::default()
}
}
///The service's current metrics snapshot. Carried in a Trust Task document whose type is https://trusttasks.org/spec/did-management/server/metrics/0.1#response.
///
/// <details><summary>JSON schema</summary>
///
/// ```json
///{
/// "title": "Response",
/// "description": "The service's current metrics snapshot. Carried in a Trust Task document whose type is https://trusttasks.org/spec/did-management/server/metrics/0.1#response.",
/// "type": "object",
/// "required": [
/// "snapshot"
/// ],
/// "properties": {
/// "ext": {
/// "$ref": "#/definitions/Ext"
/// },
/// "snapshot": {
/// "$ref": "#/definitions/MetricsSnapshot"
/// }
/// },
/// "additionalProperties": false,
/// "$anchor": "response"
///}
/// ```
/// </details>
#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Response {
#[serde(default, skip_serializing_if = "::std::option::Option::is_none")]
pub ext: ::std::option::Option<Ext>,
pub snapshot: MetricsSnapshot,
}
impl Response {
pub fn builder() -> builder::Response {
Default::default()
}
}
/// Types for composing complex structures.
pub mod builder {
#[derive(Clone, Debug)]
pub struct Histogram {
buckets:
::std::result::Result<::std::vec::Vec<super::HistogramBucket>, ::std::string::String>,
count: ::std::result::Result<u64, ::std::string::String>,
labels: ::std::result::Result<
::std::collections::HashMap<::std::string::String, ::std::string::String>,
::std::string::String,
>,
name: ::std::result::Result<super::HistogramName, ::std::string::String>,
sum: ::std::result::Result<f64, ::std::string::String>,
}
impl ::std::default::Default for Histogram {
fn default() -> Self {
Self {
buckets: Err("no value supplied for buckets".to_string()),
count: Err("no value supplied for count".to_string()),
labels: Ok(Default::default()),
name: Err("no value supplied for name".to_string()),
sum: Err("no value supplied for sum".to_string()),
}
}
}
impl Histogram {
pub fn buckets<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<::std::vec::Vec<super::HistogramBucket>>,
T::Error: ::std::fmt::Display,
{
self.buckets = value
.try_into()
.map_err(|e| format!("error converting supplied value for buckets: {e}"));
self
}
pub fn count<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<u64>,
T::Error: ::std::fmt::Display,
{
self.count = value
.try_into()
.map_err(|e| format!("error converting supplied value for count: {e}"));
self
}
pub fn labels<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<
::std::collections::HashMap<::std::string::String, ::std::string::String>,
>,
T::Error: ::std::fmt::Display,
{
self.labels = value
.try_into()
.map_err(|e| format!("error converting supplied value for labels: {e}"));
self
}
pub fn name<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<super::HistogramName>,
T::Error: ::std::fmt::Display,
{
self.name = value
.try_into()
.map_err(|e| format!("error converting supplied value for name: {e}"));
self
}
pub fn sum<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<f64>,
T::Error: ::std::fmt::Display,
{
self.sum = value
.try_into()
.map_err(|e| format!("error converting supplied value for sum: {e}"));
self
}
}
impl ::std::convert::TryFrom<Histogram> for super::Histogram {
type Error = super::error::ConversionError;
fn try_from(
value: Histogram,
) -> ::std::result::Result<Self, super::error::ConversionError> {
Ok(Self {
buckets: value.buckets?,
count: value.count?,
labels: value.labels?,
name: value.name?,
sum: value.sum?,
})
}
}
impl ::std::convert::From<super::Histogram> for Histogram {
fn from(value: super::Histogram) -> Self {
Self {
buckets: Ok(value.buckets),
count: Ok(value.count),
labels: Ok(value.labels),
name: Ok(value.name),
sum: Ok(value.sum),
}
}
}
#[derive(Clone, Debug)]
pub struct HistogramBucket {
count: ::std::result::Result<u64, ::std::string::String>,
le: ::std::result::Result<f64, ::std::string::String>,
}
impl ::std::default::Default for HistogramBucket {
fn default() -> Self {
Self {
count: Err("no value supplied for count".to_string()),
le: Err("no value supplied for le".to_string()),
}
}
}
impl HistogramBucket {
pub fn count<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<u64>,
T::Error: ::std::fmt::Display,
{
self.count = value
.try_into()
.map_err(|e| format!("error converting supplied value for count: {e}"));
self
}
pub fn le<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<f64>,
T::Error: ::std::fmt::Display,
{
self.le = value
.try_into()
.map_err(|e| format!("error converting supplied value for le: {e}"));
self
}
}
impl ::std::convert::TryFrom<HistogramBucket> for super::HistogramBucket {
type Error = super::error::ConversionError;
fn try_from(
value: HistogramBucket,
) -> ::std::result::Result<Self, super::error::ConversionError> {
Ok(Self {
count: value.count?,
le: value.le?,
})
}
}
impl ::std::convert::From<super::HistogramBucket> for HistogramBucket {
fn from(value: super::HistogramBucket) -> Self {
Self {
count: Ok(value.count),
le: Ok(value.le),
}
}
}
#[derive(Clone, Debug)]
pub struct Metric {
labels: ::std::result::Result<
::std::collections::HashMap<::std::string::String, ::std::string::String>,
::std::string::String,
>,
name: ::std::result::Result<super::MetricName, ::std::string::String>,
value: ::std::result::Result<f64, ::std::string::String>,
}
impl ::std::default::Default for Metric {
fn default() -> Self {
Self {
labels: Ok(Default::default()),
name: Err("no value supplied for name".to_string()),
value: Err("no value supplied for value".to_string()),
}
}
}
impl Metric {
pub fn labels<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<
::std::collections::HashMap<::std::string::String, ::std::string::String>,
>,
T::Error: ::std::fmt::Display,
{
self.labels = value
.try_into()
.map_err(|e| format!("error converting supplied value for labels: {e}"));
self
}
pub fn name<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<super::MetricName>,
T::Error: ::std::fmt::Display,
{
self.name = value
.try_into()
.map_err(|e| format!("error converting supplied value for name: {e}"));
self
}
pub fn value<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<f64>,
T::Error: ::std::fmt::Display,
{
self.value = value
.try_into()
.map_err(|e| format!("error converting supplied value for value: {e}"));
self
}
}
impl ::std::convert::TryFrom<Metric> for super::Metric {
type Error = super::error::ConversionError;
fn try_from(value: Metric) -> ::std::result::Result<Self, super::error::ConversionError> {
Ok(Self {
labels: value.labels?,
name: value.name?,
value: value.value?,
})
}
}
impl ::std::convert::From<super::Metric> for Metric {
fn from(value: super::Metric) -> Self {
Self {
labels: Ok(value.labels),
name: Ok(value.name),
value: Ok(value.value),
}
}
}
#[derive(Clone, Debug)]
pub struct MetricsSnapshot {
counters: ::std::result::Result<::std::vec::Vec<super::Metric>, ::std::string::String>,
ext: ::std::result::Result<::std::option::Option<super::Ext>, ::std::string::String>,
gauges: ::std::result::Result<::std::vec::Vec<super::Metric>, ::std::string::String>,
histograms: ::std::result::Result<::std::vec::Vec<super::Histogram>, ::std::string::String>,
taken_at:
::std::result::Result<::chrono::DateTime<::chrono::offset::Utc>, ::std::string::String>,
}
impl ::std::default::Default for MetricsSnapshot {
fn default() -> Self {
Self {
counters: Err("no value supplied for counters".to_string()),
ext: Ok(Default::default()),
gauges: Err("no value supplied for gauges".to_string()),
histograms: Err("no value supplied for histograms".to_string()),
taken_at: Err("no value supplied for taken_at".to_string()),
}
}
}
impl MetricsSnapshot {
pub fn counters<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<::std::vec::Vec<super::Metric>>,
T::Error: ::std::fmt::Display,
{
self.counters = value
.try_into()
.map_err(|e| format!("error converting supplied value for counters: {e}"));
self
}
pub fn ext<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<::std::option::Option<super::Ext>>,
T::Error: ::std::fmt::Display,
{
self.ext = value
.try_into()
.map_err(|e| format!("error converting supplied value for ext: {e}"));
self
}
pub fn gauges<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<::std::vec::Vec<super::Metric>>,
T::Error: ::std::fmt::Display,
{
self.gauges = value
.try_into()
.map_err(|e| format!("error converting supplied value for gauges: {e}"));
self
}
pub fn histograms<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<::std::vec::Vec<super::Histogram>>,
T::Error: ::std::fmt::Display,
{
self.histograms = value
.try_into()
.map_err(|e| format!("error converting supplied value for histograms: {e}"));
self
}
pub fn taken_at<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<::chrono::DateTime<::chrono::offset::Utc>>,
T::Error: ::std::fmt::Display,
{
self.taken_at = value
.try_into()
.map_err(|e| format!("error converting supplied value for taken_at: {e}"));
self
}
}
impl ::std::convert::TryFrom<MetricsSnapshot> for super::MetricsSnapshot {
type Error = super::error::ConversionError;
fn try_from(
value: MetricsSnapshot,
) -> ::std::result::Result<Self, super::error::ConversionError> {
Ok(Self {
counters: value.counters?,
ext: value.ext?,
gauges: value.gauges?,
histograms: value.histograms?,
taken_at: value.taken_at?,
})
}
}
impl ::std::convert::From<super::MetricsSnapshot> for MetricsSnapshot {
fn from(value: super::MetricsSnapshot) -> Self {
Self {
counters: Ok(value.counters),
ext: Ok(value.ext),
gauges: Ok(value.gauges),
histograms: Ok(value.histograms),
taken_at: Ok(value.taken_at),
}
}
}
#[derive(Clone, Debug)]
pub struct Payload {
ext: ::std::result::Result<::std::option::Option<super::Ext>, ::std::string::String>,
}
impl ::std::default::Default for Payload {
fn default() -> Self {
Self {
ext: Ok(Default::default()),
}
}
}
impl Payload {
pub fn ext<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<::std::option::Option<super::Ext>>,
T::Error: ::std::fmt::Display,
{
self.ext = value
.try_into()
.map_err(|e| format!("error converting supplied value for ext: {e}"));
self
}
}
impl ::std::convert::TryFrom<Payload> for super::Payload {
type Error = super::error::ConversionError;
fn try_from(value: Payload) -> ::std::result::Result<Self, super::error::ConversionError> {
Ok(Self { ext: value.ext? })
}
}
impl ::std::convert::From<super::Payload> for Payload {
fn from(value: super::Payload) -> Self {
Self { ext: Ok(value.ext) }
}
}
#[derive(Clone, Debug)]
pub struct Response {
ext: ::std::result::Result<::std::option::Option<super::Ext>, ::std::string::String>,
snapshot: ::std::result::Result<super::MetricsSnapshot, ::std::string::String>,
}
impl ::std::default::Default for Response {
fn default() -> Self {
Self {
ext: Ok(Default::default()),
snapshot: Err("no value supplied for snapshot".to_string()),
}
}
}
impl Response {
pub fn ext<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<::std::option::Option<super::Ext>>,
T::Error: ::std::fmt::Display,
{
self.ext = value
.try_into()
.map_err(|e| format!("error converting supplied value for ext: {e}"));
self
}
pub fn snapshot<T>(mut self, value: T) -> Self
where
T: ::std::convert::TryInto<super::MetricsSnapshot>,
T::Error: ::std::fmt::Display,
{
self.snapshot = value
.try_into()
.map_err(|e| format!("error converting supplied value for snapshot: {e}"));
self
}
}
impl ::std::convert::TryFrom<Response> for super::Response {
type Error = super::error::ConversionError;
fn try_from(value: Response) -> ::std::result::Result<Self, super::error::ConversionError> {
Ok(Self {
ext: value.ext?,
snapshot: value.snapshot?,
})
}
}
impl ::std::convert::From<super::Response> for Response {
fn from(value: super::Response) -> Self {
Self {
ext: Ok(value.ext),
snapshot: Ok(value.snapshot),
}
}
}
}
impl crate::Payload for Payload {
const TYPE_URI: &'static str = "https://trusttasks.org/spec/did-management/server/metrics/0.1";
const IS_PROOF_REQUIRED: bool = true;
const IS_RECIPIENT_REQUIRED: bool = true;
const PAYLOAD_SCHEMA: Option<&'static str> = Some(
"{\n \"$defs\": {\n \"Ext\": {\n \"additionalProperties\": true,\n \"description\": \"Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.\",\n \"minProperties\": 1,\n \"propertyNames\": {\n \"pattern\": \"^[a-z][a-z0-9-]*(\\\\.[a-z0-9-]+)+$\"\n },\n \"title\": \"Ext\",\n \"type\": \"object\"\n },\n \"Histogram\": {\n \"additionalProperties\": false,\n \"description\": \"One histogram's distribution, in the Prometheus cumulative-bucket convention: each bucket's `count` includes every observation at or below its `le`.\",\n \"properties\": {\n \"buckets\": {\n \"description\": \"Cumulative buckets, ordered by ascending `le`. Empty when the service exposes no bucket breakdown for this histogram — count and sum still apply. Always present, for the same reason as the snapshot's own arrays.\",\n \"items\": {\n \"$ref\": \"#/$defs/HistogramBucket\"\n },\n \"type\": \"array\"\n },\n \"count\": {\n \"description\": \"Total number of observations.\",\n \"minimum\": 0,\n \"type\": \"integer\"\n },\n \"labels\": {\n \"additionalProperties\": {\n \"type\": \"string\"\n },\n \"description\": \"Dimensions the distribution is broken down by. Absent or empty when the histogram carries none.\",\n \"type\": \"object\"\n },\n \"name\": {\n \"description\": \"The histogram's stable name (e.g. `did_hosting_resolve_seconds`).\",\n \"minLength\": 1,\n \"type\": \"string\"\n },\n \"sum\": {\n \"description\": \"Sum of all observed values.\",\n \"type\": \"number\"\n }\n },\n \"required\": [\n \"name\",\n \"count\",\n \"sum\",\n \"buckets\"\n ],\n \"title\": \"Histogram\",\n \"type\": \"object\"\n },\n \"HistogramBucket\": {\n \"additionalProperties\": false,\n \"properties\": {\n \"count\": {\n \"description\": \"Number of observations at or below `le`.\",\n \"minimum\": 0,\n \"type\": \"integer\"\n },\n \"le\": {\n \"description\": \"Upper bound of this bucket, inclusive. The final bucket conventionally reports the same value as the histogram's own `count` at whatever `le` the service treats as its ceiling.\",\n \"type\": \"number\"\n }\n },\n \"required\": [\n \"le\",\n \"count\"\n ],\n \"title\": \"HistogramBucket\",\n \"type\": \"object\"\n },\n \"Metric\": {\n \"additionalProperties\": false,\n \"description\": \"One counter or gauge reading.\",\n \"properties\": {\n \"labels\": {\n \"additionalProperties\": {\n \"type\": \"string\"\n },\n \"description\": \"Dimensions the value is broken down by (e.g. `{\\\"method\\\": \\\"resolve\\\"}`). Absent or empty when the metric carries none.\",\n \"type\": \"object\"\n },\n \"name\": {\n \"description\": \"The metric's stable name (e.g. `did_hosting_requests_total`). Implementation-defined; the framework imposes no vocabulary.\",\n \"minLength\": 1,\n \"type\": \"string\"\n },\n \"value\": {\n \"description\": \"The current reading.\",\n \"type\": \"number\"\n }\n },\n \"required\": [\n \"name\",\n \"value\"\n ],\n \"title\": \"Metric\",\n \"type\": \"object\"\n },\n \"MetricsSnapshot\": {\n \"additionalProperties\": false,\n \"properties\": {\n \"counters\": {\n \"description\": \"Monotonically increasing totals (e.g. requests served, errors raised). Empty when the service exposes none. Always present, so a collector can tell \\\"no counters\\\" from \\\"the field was dropped\\\".\",\n \"items\": {\n \"$ref\": \"#/$defs/Metric\"\n },\n \"type\": \"array\"\n },\n \"ext\": {\n \"$ref\": \"#/$defs/Ext\"\n },\n \"gauges\": {\n \"description\": \"Point-in-time values that can rise or fall (e.g. open connections, queue depth). Empty when the service exposes none. Always present, for the same reason as counters.\",\n \"items\": {\n \"$ref\": \"#/$defs/Metric\"\n },\n \"type\": \"array\"\n },\n \"histograms\": {\n \"description\": \"Distributions of observed values (e.g. request latency). Empty when the service exposes none. Always present, for the same reason as counters.\",\n \"items\": {\n \"$ref\": \"#/$defs/Histogram\"\n },\n \"type\": \"array\"\n },\n \"takenAt\": {\n \"description\": \"When the service read these values from its own instrumentation. Not the same as the envelope's issuedAt when a snapshot is cached briefly before answering.\",\n \"format\": \"date-time\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"takenAt\",\n \"counters\",\n \"gauges\",\n \"histograms\"\n ],\n \"title\": \"MetricsSnapshot\",\n \"type\": \"object\"\n },\n \"Response\": {\n \"$anchor\": \"response\",\n \"additionalProperties\": false,\n \"description\": \"The service's current metrics snapshot. Carried in a Trust Task document whose type is https://trusttasks.org/spec/did-management/server/metrics/0.1#response.\",\n \"properties\": {\n \"ext\": {\n \"$ref\": \"#/$defs/Ext\"\n },\n \"snapshot\": {\n \"$ref\": \"#/$defs/MetricsSnapshot\"\n }\n },\n \"required\": [\n \"snapshot\"\n ],\n \"title\": \"DID Management — Server Metrics — response payload\",\n \"type\": \"object\"\n }\n },\n \"$id\": \"https://trusttasks.org/spec/did-management/server/metrics/0.1\",\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"additionalProperties\": false,\n \"description\": \"The read takes no selector — the whole snapshot is returned. The outer document members (id, type, issuer, recipient, issuedAt, expiresAt, proof) are owned by the framework — SPEC §6.3.\",\n \"properties\": {\n \"ext\": {\n \"$ref\": \"#/$defs/Ext\"\n }\n },\n \"title\": \"DID Management — Server Metrics — payload\",\n \"type\": \"object\"\n}\n",
);
}
impl crate::Payload for Response {
const TYPE_URI: &'static str =
"https://trusttasks.org/spec/did-management/server/metrics/0.1#response";
const IS_PROOF_REQUIRED: bool = true;
const IS_RECIPIENT_REQUIRED: bool = true;
const PAYLOAD_SCHEMA: Option<&'static str> = Some(
"{\n \"$defs\": {\n \"Ext\": {\n \"additionalProperties\": true,\n \"description\": \"Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.\",\n \"minProperties\": 1,\n \"propertyNames\": {\n \"pattern\": \"^[a-z][a-z0-9-]*(\\\\.[a-z0-9-]+)+$\"\n },\n \"title\": \"Ext\",\n \"type\": \"object\"\n },\n \"Histogram\": {\n \"additionalProperties\": false,\n \"description\": \"One histogram's distribution, in the Prometheus cumulative-bucket convention: each bucket's `count` includes every observation at or below its `le`.\",\n \"properties\": {\n \"buckets\": {\n \"description\": \"Cumulative buckets, ordered by ascending `le`. Empty when the service exposes no bucket breakdown for this histogram — count and sum still apply. Always present, for the same reason as the snapshot's own arrays.\",\n \"items\": {\n \"$ref\": \"#/$defs/HistogramBucket\"\n },\n \"type\": \"array\"\n },\n \"count\": {\n \"description\": \"Total number of observations.\",\n \"minimum\": 0,\n \"type\": \"integer\"\n },\n \"labels\": {\n \"additionalProperties\": {\n \"type\": \"string\"\n },\n \"description\": \"Dimensions the distribution is broken down by. Absent or empty when the histogram carries none.\",\n \"type\": \"object\"\n },\n \"name\": {\n \"description\": \"The histogram's stable name (e.g. `did_hosting_resolve_seconds`).\",\n \"minLength\": 1,\n \"type\": \"string\"\n },\n \"sum\": {\n \"description\": \"Sum of all observed values.\",\n \"type\": \"number\"\n }\n },\n \"required\": [\n \"name\",\n \"count\",\n \"sum\",\n \"buckets\"\n ],\n \"title\": \"Histogram\",\n \"type\": \"object\"\n },\n \"HistogramBucket\": {\n \"additionalProperties\": false,\n \"properties\": {\n \"count\": {\n \"description\": \"Number of observations at or below `le`.\",\n \"minimum\": 0,\n \"type\": \"integer\"\n },\n \"le\": {\n \"description\": \"Upper bound of this bucket, inclusive. The final bucket conventionally reports the same value as the histogram's own `count` at whatever `le` the service treats as its ceiling.\",\n \"type\": \"number\"\n }\n },\n \"required\": [\n \"le\",\n \"count\"\n ],\n \"title\": \"HistogramBucket\",\n \"type\": \"object\"\n },\n \"Metric\": {\n \"additionalProperties\": false,\n \"description\": \"One counter or gauge reading.\",\n \"properties\": {\n \"labels\": {\n \"additionalProperties\": {\n \"type\": \"string\"\n },\n \"description\": \"Dimensions the value is broken down by (e.g. `{\\\"method\\\": \\\"resolve\\\"}`). Absent or empty when the metric carries none.\",\n \"type\": \"object\"\n },\n \"name\": {\n \"description\": \"The metric's stable name (e.g. `did_hosting_requests_total`). Implementation-defined; the framework imposes no vocabulary.\",\n \"minLength\": 1,\n \"type\": \"string\"\n },\n \"value\": {\n \"description\": \"The current reading.\",\n \"type\": \"number\"\n }\n },\n \"required\": [\n \"name\",\n \"value\"\n ],\n \"title\": \"Metric\",\n \"type\": \"object\"\n },\n \"MetricsSnapshot\": {\n \"additionalProperties\": false,\n \"properties\": {\n \"counters\": {\n \"description\": \"Monotonically increasing totals (e.g. requests served, errors raised). Empty when the service exposes none. Always present, so a collector can tell \\\"no counters\\\" from \\\"the field was dropped\\\".\",\n \"items\": {\n \"$ref\": \"#/$defs/Metric\"\n },\n \"type\": \"array\"\n },\n \"ext\": {\n \"$ref\": \"#/$defs/Ext\"\n },\n \"gauges\": {\n \"description\": \"Point-in-time values that can rise or fall (e.g. open connections, queue depth). Empty when the service exposes none. Always present, for the same reason as counters.\",\n \"items\": {\n \"$ref\": \"#/$defs/Metric\"\n },\n \"type\": \"array\"\n },\n \"histograms\": {\n \"description\": \"Distributions of observed values (e.g. request latency). Empty when the service exposes none. Always present, for the same reason as counters.\",\n \"items\": {\n \"$ref\": \"#/$defs/Histogram\"\n },\n \"type\": \"array\"\n },\n \"takenAt\": {\n \"description\": \"When the service read these values from its own instrumentation. Not the same as the envelope's issuedAt when a snapshot is cached briefly before answering.\",\n \"format\": \"date-time\",\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"takenAt\",\n \"counters\",\n \"gauges\",\n \"histograms\"\n ],\n \"title\": \"MetricsSnapshot\",\n \"type\": \"object\"\n },\n \"Response\": {\n \"$anchor\": \"response\",\n \"additionalProperties\": false,\n \"description\": \"The service's current metrics snapshot. Carried in a Trust Task document whose type is https://trusttasks.org/spec/did-management/server/metrics/0.1#response.\",\n \"properties\": {\n \"ext\": {\n \"$ref\": \"#/$defs/Ext\"\n },\n \"snapshot\": {\n \"$ref\": \"#/$defs/MetricsSnapshot\"\n }\n },\n \"required\": [\n \"snapshot\"\n ],\n \"title\": \"DID Management — Server Metrics — response payload\",\n \"type\": \"object\"\n }\n },\n \"$ref\": \"#/$defs/Response\",\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\"\n}\n",
);
}
impl crate::RequestPayload for Payload {
type Response = Response;
}
/// The extended error codes this specification declares (SPEC §7.3 item 9,
/// §8.5), in declaration order. Empty when it declares none.
pub const ERROR_CODES: &[crate::DeclaredErrorCode] = &[];
#[cfg(test)]
mod conformance {
//! Round-trip tests harvested from the spec's `spec.md`,
//! plus a `rejects_invalid_examples` test for any fixtures
//! in `payload.invalid-examples.json` (validate feature).
#[test]
fn request_example_1() {
const JSON: &str = "{\n \"id\": \"urn:uuid:d38f4a1e-9c6b-4d2f-8a1e-2b3c4d5e6f01\",\n \"type\": \"https://trusttasks.org/spec/did-management/server/metrics/0.1\",\n \"issuer\": \"did:webvh:QmAdminScid1:admin.example.com:alice\",\n \"recipient\": \"did:webvh:QmControlScid2:control.example.com\",\n \"issuedAt\": \"2026-09-27T09:00:00Z\",\n \"payload\": {}\n}\n";
let doc: crate::TrustTask<super::Payload> =
serde_json::from_str(JSON).expect("deserialize request example");
let rendered = serde_json::to_value(&doc).expect("re-serialize");
let expected: serde_json::Value = serde_json::from_str(JSON).expect("re-parse expected");
assert_eq!(rendered, expected, "request example failed round-trip");
}
#[test]
fn response_example_1() {
const JSON: &str = "{\n \"id\": \"urn:uuid:d38f4a1e-9c6b-4d2f-8a1e-2b3c4d5e6f02\",\n \"type\": \"https://trusttasks.org/spec/did-management/server/metrics/0.1#response\",\n \"threadId\": \"urn:uuid:d38f4a1e-9c6b-4d2f-8a1e-2b3c4d5e6f01\",\n \"issuer\": \"did:webvh:QmControlScid2:control.example.com\",\n \"recipient\": \"did:webvh:QmAdminScid1:admin.example.com:alice\",\n \"issuedAt\": \"2026-09-27T09:00:01Z\",\n \"payload\": {\n \"snapshot\": {\n \"takenAt\": \"2026-09-27T09:00:01Z\",\n \"counters\": [\n {\n \"name\": \"did_hosting_requests_total\",\n \"value\": 184213.0,\n \"labels\": { \"task\": \"did-management/did/log\" }\n }\n ],\n \"gauges\": [\n { \"name\": \"did_hosting_registry_instances\", \"value\": 4.0 }\n ],\n \"histograms\": [\n {\n \"name\": \"did_hosting_resolve_seconds\",\n \"count\": 9210,\n \"sum\": 184.4,\n \"buckets\": [\n { \"le\": 0.01, \"count\": 8000 },\n { \"le\": 0.1, \"count\": 9100 },\n { \"le\": 1.0, \"count\": 9210 }\n ]\n }\n ]\n }\n }\n}\n";
let doc: crate::TrustTask<super::Response> =
serde_json::from_str(JSON).expect("deserialize response example");
let rendered = serde_json::to_value(&doc).expect("re-serialize");
let expected: serde_json::Value = serde_json::from_str(JSON).expect("re-parse expected");
assert_eq!(rendered, expected, "response example failed round-trip");
}
/// Each fixture in `payload.invalid-examples.json` MUST be
/// rejected by at least one of: serde deserialization, or
/// JSON-Schema validation under the `validate` feature. The
/// fixture file documents the producer-side bug class that
/// each payload exemplifies; this generated test pins it.
#[cfg(feature = "validate")]
#[test]
fn rejects_invalid_examples() {
use crate::validate::ValidatedPayload;
let fixtures: &[(&str, &str)] = &[
(
"The read takes no selector — the whole snapshot is returned.",
"{\n \"names\": [\n \"did_hosting_requests_total\"\n ]\n}",
),
(
"Not a member of this task's payload; it belongs to a response snapshot.",
"{\n \"counters\": []\n}",
),
];
for (i, (note, raw)) in fixtures.iter().enumerate() {
let value: serde_json::Value = match serde_json::from_str(raw) {
Ok(v) => v,
Err(_) => continue,
};
let serde_ok = serde_json::from_value::<super::Payload>(value.clone()).is_ok();
let schema_ok = super::Payload::validate_value(&value).is_ok();
assert!(
!(serde_ok && schema_ok),
"invalid-example #{} ({:?}) was accepted by both serde and JSON Schema; \
the fixture's stated failure class is no longer caught:\n{}",
i + 1,
note,
raw
);
}
}
}