Skip to main content

claude_api/messages/
metadata.rs

1//! Per-request metadata and the request-side `service_tier` field.
2//!
3//! Note: the request-side [`RequestServiceTier`] (`auto` / `standard_only`)
4//! is distinct from the response-side
5//! [`ServiceTier`](crate::types::ServiceTier) (`standard` / `priority` / `batch`).
6
7use serde::{Deserialize, Serialize};
8
9/// Optional metadata sent with a Messages request.
10#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
11#[non_exhaustive]
12pub struct MessageMetadata {
13    /// Stable user identifier; passed through to abuse-detection systems.
14    #[serde(default, skip_serializing_if = "Option::is_none")]
15    pub user_id: Option<String>,
16}
17
18impl MessageMetadata {
19    /// Convenience constructor that sets `user_id`.
20    pub fn with_user(user_id: impl Into<String>) -> Self {
21        Self {
22            user_id: Some(user_id.into()),
23        }
24    }
25}
26
27/// Request-side `service_tier` field on a Messages request.
28///
29/// Differs from the response-side [`ServiceTier`](crate::types::ServiceTier),
30/// which reports the tier the request *actually ran on*.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33#[non_exhaustive]
34pub enum RequestServiceTier {
35    /// Server picks the best available tier.
36    Auto,
37    /// Restrict to standard tier only (no priority / no batch).
38    StandardOnly,
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use pretty_assertions::assert_eq;
45    use serde_json::json;
46
47    #[test]
48    fn message_metadata_round_trips() {
49        let m = MessageMetadata::with_user("user_42");
50        let v = serde_json::to_value(&m).unwrap();
51        assert_eq!(v, json!({"user_id": "user_42"}));
52        let parsed: MessageMetadata = serde_json::from_value(v).unwrap();
53        assert_eq!(parsed, m);
54    }
55
56    #[test]
57    fn message_metadata_default_omits_user_id() {
58        let m = MessageMetadata::default();
59        let v = serde_json::to_value(&m).unwrap();
60        assert_eq!(v, json!({}));
61    }
62
63    #[test]
64    fn request_service_tier_round_trips() {
65        for (variant, wire) in [
66            (RequestServiceTier::Auto, "auto"),
67            (RequestServiceTier::StandardOnly, "standard_only"),
68        ] {
69            let v = serde_json::to_value(variant).unwrap();
70            assert_eq!(v, json!(wire));
71            let parsed: RequestServiceTier = serde_json::from_value(v).unwrap();
72            assert_eq!(parsed, variant);
73        }
74    }
75}