objectstore_types/batch.rs
1//! Wire types of the JSON layout of the batch endpoint.
2//!
3//! In this layout, the operation at position `i` of a request is described by a [`Descriptor`]
4//! part named `"<i>"`. The server answers with a [`ResultPart`] named `"<i>"` per operation, in
5//! completion order. A part named `"<i>.payload"` carries the object bytes of an insert in a
6//! request, or of a successful get in a response, and directly follows the part it belongs to.
7
8use serde::{Deserialize, Serialize};
9
10use crate::api::ApiErrorResponse;
11use crate::metadata::{ReadMetadata, WriteMetadata};
12
13/// Maximum number of operations in one batch request.
14pub const MAX_BATCH_OPERATIONS: usize = 1000;
15
16/// Maximum size in bytes of the body of a part that carries object bytes.
17pub const MAX_BATCH_PART_SIZE: usize = 1024 * 1024;
18
19/// Maximum size in bytes of the body of a [`Descriptor`] part.
20pub const MAX_DESCRIPTOR_SIZE: usize = 64 * 1024;
21
22/// Suffix that marks a payload part.
23pub const PAYLOAD_SUFFIX: &str = ".payload";
24
25/// Returns the name of the payload part of the operation at `index`, for example `"0.payload"`.
26///
27/// ```
28/// use objectstore_types::batch::payload_part_name;
29///
30/// assert_eq!(payload_part_name(3), "3.payload");
31/// ```
32pub fn payload_part_name(index: usize) -> String {
33 format!("{index}{PAYLOAD_SUFFIX}")
34}
35
36/// The kind of a batch operation.
37///
38/// Kinds that this version does not know deserialize and convert from names as
39/// [`OperationKind::Unknown`], so that a client can still read results of operations added to the
40/// server later. Names are matched case-sensitively.
41///
42/// ```
43/// use objectstore_types::batch::OperationKind;
44///
45/// let kind: OperationKind = serde_json::from_str(r#""copy""#)?;
46/// assert_eq!(kind, OperationKind::Unknown);
47/// assert_eq!(OperationKind::from("insert"), OperationKind::Insert);
48/// # Ok::<(), serde_json::Error>(())
49/// ```
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "lowercase")]
52pub enum OperationKind {
53 /// Reads an object and its metadata.
54 Get,
55 /// Reads the metadata of an object.
56 Head,
57 /// Deletes an object.
58 Delete,
59 /// Stores an object.
60 Insert,
61 /// A kind that this version does not know.
62 ///
63 /// Only produced when reading a kind name. It serializes as `"unknown"`.
64 #[serde(other)]
65 Unknown,
66}
67
68impl OperationKind {
69 /// Returns the name of the kind as used on the wire, for example `"insert"`.
70 pub const fn as_str(self) -> &'static str {
71 match self {
72 Self::Get => "get",
73 Self::Head => "head",
74 Self::Delete => "delete",
75 Self::Insert => "insert",
76 Self::Unknown => "unknown",
77 }
78 }
79}
80
81impl From<&str> for OperationKind {
82 fn from(name: &str) -> Self {
83 match name {
84 "get" => Self::Get,
85 "head" => Self::Head,
86 "delete" => Self::Delete,
87 "insert" => Self::Insert,
88 _ => Self::Unknown,
89 }
90 }
91}
92
93/// The JSON body of a descriptor part, which describes one operation of a request.
94///
95/// Unknown fields are ignored when deserializing.
96///
97/// ```
98/// use objectstore_types::batch::Descriptor;
99///
100/// let json = r#"{"kind":"get","key":"a/b"}"#;
101/// let descriptor: Descriptor = serde_json::from_str(json)?;
102/// assert_eq!(descriptor, Descriptor::Get { key: "a/b".to_owned() });
103/// assert_eq!(serde_json::to_string(&descriptor)?, json);
104/// # Ok::<(), serde_json::Error>(())
105/// ```
106#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(tag = "kind", rename_all = "lowercase")]
108pub enum Descriptor {
109 /// Reads the object with the given key.
110 Get {
111 /// The key of the object.
112 key: String,
113 },
114 /// Reads the metadata of the object with the given key.
115 Head {
116 /// The key of the object.
117 key: String,
118 },
119 /// Deletes the object with the given key.
120 Delete {
121 /// The key of the object.
122 key: String,
123 },
124 /// Stores an object, whose bytes are in the payload part that follows.
125 Insert {
126 /// The key of the object. The server generates one if it is absent.
127 #[serde(default, skip_serializing_if = "Option::is_none")]
128 key: Option<String>,
129 /// The metadata of the object.
130 #[serde(default)]
131 metadata: WriteMetadata,
132 },
133}
134
135/// The JSON body of a result part, which reports the outcome of one operation.
136///
137/// Unknown fields are ignored when deserializing.
138#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
139pub struct ResultPart {
140 /// The HTTP status code of the operation.
141 pub status: u16,
142 /// The kind of the operation. Absent if the operation failed with an [`error`](Self::error).
143 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub kind: Option<OperationKind>,
145 /// The key of the object. Absent if the operation failed with an [`error`](Self::error).
146 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub key: Option<String>,
148 /// The metadata of the object, for a successful get or head.
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub metadata: Option<ReadMetadata>,
151 /// The error, for a failed operation.
152 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub error: Option<ApiErrorResponse>,
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159
160 #[test]
161 fn result_part_with_unknown_kind_is_readable() {
162 let json = r#"{"status":200,"kind":"copy","key":"a"}"#;
163 let result: ResultPart = serde_json::from_str(json).unwrap();
164
165 assert_eq!(result.status, 200);
166 assert_eq!(result.kind, Some(OperationKind::Unknown));
167 assert_eq!(result.key.as_deref(), Some("a"));
168 }
169
170 #[test]
171 fn kind_from_name() {
172 assert_eq!(OperationKind::from("get"), OperationKind::Get);
173 assert_eq!(OperationKind::from("head"), OperationKind::Head);
174 assert_eq!(OperationKind::from("delete"), OperationKind::Delete);
175 assert_eq!(OperationKind::from("insert"), OperationKind::Insert);
176 assert_eq!(OperationKind::from("copy"), OperationKind::Unknown);
177 }
178}