udb 0.3.5

Universal Data Broker — a Rust gRPC broker over multiple databases (Postgres, MySQL, SQLite, MongoDB, ClickHouse, Cassandra, MSSQL, Redis, Qdrant, S3, Neo4j, …) with per-tenant RLS, 2PC, sagas, and CDC.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! S3 / MinIO object-store executor.
#![allow(clippy::result_large_err)]
//!
//! `BackendExecutor` over `aws_sdk_s3::Client` (newtype to satisfy the orphan
//! rule and to keep trait methods off the external client type). Stateless leaf
//! I/O; instance selection / circuit-breaking stay in the orchestration layer.
//! Request shapes mirror the former inline arms in `core.rs`.

use aws_sdk_s3::Client;
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
use bytes::Bytes;
use serde_json::Value as JsonValue;

use crate::runtime::executor_utils::{
    json_required_str, object_bytes_from_json, reject_oversized_object,
};
use crate::runtime::executors::{
    BackendExecutor, BackendHealth, BackendProbe, ExecutorByteStream, MutationExecutor,
    ObjectExecutor, QueryExecutor, ResourceAdminExecutor, SearchExecutor,
};

use crate::runtime::config::{s3_download_chunk_bytes, s3_multipart_part_bytes};

pub(crate) struct S3Executor(pub(crate) Client);

impl crate::runtime::backend_context::BackendContextEnforcer for S3Executor {
    fn backend_label(&self) -> &str {
        "s3"
    }

    fn enforce(
        &self,
        ctx: &crate::runtime::backend_context::AppliedContext,
    ) -> crate::runtime::backend_context::ContextEffect {
        if ctx.is_empty() {
            return crate::runtime::backend_context::ContextEffect::Advisory {
                recorded_in: "no_context_to_apply".into(),
            };
        }
        // C7/C8: the S3 IR compiler now prepends `t:<tenant>/p:<project>/`
        // to every resolved object key in compile_read/write/delete.
        // Combined with the bucket = schema convention, an S3 PUT or
        // GET cannot escape its tenant namespace at the key layer.
        crate::runtime::backend_context::ContextEffect::Enforced {
            mechanism: "key prefix t:<tenant>/p:<project>/ prepended by compile_read/write/delete"
                .into(),
        }
    }
}

impl BackendHealth for S3Executor {
    async fn ping(&self) -> Result<(), String> {
        // Constructed only from a configured client; reachability is checked by
        // the dedicated probe RPC, so the dispatch ping is a presence check.
        Ok(())
    }
}

impl QueryExecutor for S3Executor {
    async fn query(&self, _request_json: &str) -> Result<String, tonic::Status> {
        Err(tonic::Status::failed_precondition(
            "s3 does not support generic query",
        ))
    }
}

impl MutationExecutor for S3Executor {
    async fn mutate(&self, _request_json: &str) -> Result<String, tonic::Status> {
        Err(tonic::Status::failed_precondition(
            "s3 mutation is via get_object/put_object",
        ))
    }
}

impl SearchExecutor for S3Executor {
    async fn search(&self, _request_json: &str) -> Result<String, tonic::Status> {
        Err(tonic::Status::failed_precondition(
            "s3 does not support search",
        ))
    }
}

impl ObjectExecutor for S3Executor {
    /// `{"bucket":"b","object_key"|"key":"k"}`.
    async fn get_object(&self, request_json: &str) -> Result<Vec<u8>, tonic::Status> {
        let spec: JsonValue = serde_json::from_str(request_json)
            .map_err(|e| tonic::Status::invalid_argument(format!("invalid request json: {e}")))?;
        let bucket = json_required_str(&spec, "bucket")?;
        let object_key =
            json_required_str(&spec, "object_key").or_else(|_| json_required_str(&spec, "key"))?;
        let output = self
            .0
            .get_object()
            .bucket(bucket)
            .key(object_key)
            .send()
            .await
            .map_err(|err| tonic::Status::unavailable(format!("S3 get_object failed: {err}")))?;
        let bytes = output
            .body
            .collect()
            .await
            .map_err(|err| tonic::Status::unavailable(format!("S3 body read failed: {err}")))?
            .into_bytes()
            .to_vec();
        Ok(bytes)
    }

    /// `{"bucket","object_key"|"key", "content_type"?, inline bytes...}`.
    async fn put_object(
        &self,
        request_json: &str,
        bytes: Vec<u8>,
    ) -> Result<String, tonic::Status> {
        let spec: JsonValue = serde_json::from_str(request_json)
            .map_err(|e| tonic::Status::invalid_argument(format!("invalid request json: {e}")))?;
        let bucket = json_required_str(&spec, "bucket")?;
        let object_key =
            json_required_str(&spec, "object_key").or_else(|_| json_required_str(&spec, "key"))?;
        let body = if bytes.is_empty() {
            object_bytes_from_json(&spec)?
        } else {
            bytes
        };
        // Capture the length before moving `body` into the stream, so the body is
        // not cloned just to report its size in the response (#102).
        let body_len = body.len();
        reject_oversized_object(body_len)?;
        let mut request = self
            .0
            .put_object()
            .bucket(bucket)
            .key(object_key)
            .body(ByteStream::from(body));
        if let Some(content_type) = spec
            .get("content_type")
            .and_then(JsonValue::as_str)
            .filter(|value| !value.trim().is_empty())
        {
            request = request.content_type(content_type);
        }
        request
            .send()
            .await
            .map_err(|err| tonic::Status::unavailable(format!("S3 put_object failed: {err}")))?;
        Ok(serde_json::json!({
            "resource_uri": format!("s3://{bucket}/{object_key}"),
            "affected_rows": 1,
            "bytes": body_len
        })
        .to_string())
    }

    /// Streaming download (A.6): read the S3 body in `S3_DOWNLOAD_CHUNK_BYTES`
    /// frames without ever holding the whole object in memory.
    async fn get_object_stream(
        &self,
        request_json: &str,
    ) -> Result<ExecutorByteStream, tonic::Status> {
        let spec: JsonValue = serde_json::from_str(request_json)
            .map_err(|e| tonic::Status::invalid_argument(format!("invalid request json: {e}")))?;
        let bucket = json_required_str(&spec, "bucket")?.to_string();
        let object_key = json_required_str(&spec, "object_key")
            .or_else(|_| json_required_str(&spec, "key"))?
            .to_string();
        let output = self
            .0
            .get_object()
            .bucket(&bucket)
            .key(&object_key)
            .send()
            .await
            .map_err(|err| tonic::Status::unavailable(format!("S3 get_object failed: {err}")))?;
        let chunk_bytes = s3_download_chunk_bytes();
        let stream = async_stream::try_stream! {
            use tokio::io::AsyncReadExt as _;
            let mut reader = output.body.into_async_read();
            let mut buf = vec![0u8; chunk_bytes];
            loop {
                let read = reader.read(&mut buf).await.map_err(|err| {
                    tonic::Status::unavailable(format!("S3 body read failed: {err}"))
                })?;
                if read == 0 {
                    break;
                }
                yield Bytes::copy_from_slice(&buf[..read]);
            }
        };
        Ok(Box::pin(stream))
    }

    /// Streaming upload (A.6): forward the chunk stream to S3 multipart, buffering
    /// at most one ~8 MiB part. Objects that fit in a single part skip multipart
    /// and use a plain `PutObject`. On a part failure the multipart upload is
    /// aborted so no orphaned upload is left behind.
    async fn put_object_stream(
        &self,
        request_json: &str,
        stream: ExecutorByteStream,
    ) -> Result<String, tonic::Status> {
        use tokio_stream::StreamExt as _;
        let spec: JsonValue = serde_json::from_str(request_json)
            .map_err(|e| tonic::Status::invalid_argument(format!("invalid request json: {e}")))?;
        let bucket = json_required_str(&spec, "bucket")?.to_string();
        let object_key = json_required_str(&spec, "object_key")
            .or_else(|_| json_required_str(&spec, "key"))?
            .to_string();
        let content_type = spec
            .get("content_type")
            .and_then(JsonValue::as_str)
            .filter(|value| !value.trim().is_empty())
            .map(str::to_string);

        let part_size = s3_multipart_part_bytes();
        let mut stream = stream;
        let mut buf: Vec<u8> = Vec::with_capacity(part_size);
        // (upload_id, completed parts, next part number)
        let mut mpu: Option<(String, Vec<CompletedPart>, i32)> = None;

        while let Some(chunk) = stream.next().await {
            let chunk = chunk?;
            buf.extend_from_slice(&chunk);
            if buf.len() < part_size {
                continue;
            }
            if mpu.is_none() {
                let mut create = self
                    .0
                    .create_multipart_upload()
                    .bucket(&bucket)
                    .key(&object_key);
                if let Some(ct) = &content_type {
                    create = create.content_type(ct);
                }
                let created = create.send().await.map_err(|e| {
                    tonic::Status::unavailable(format!("S3 create_multipart_upload failed: {e}"))
                })?;
                let upload_id = created
                    .upload_id()
                    .ok_or_else(|| {
                        tonic::Status::unavailable(
                            "S3 create_multipart_upload returned no upload_id",
                        )
                    })?
                    .to_string();
                mpu = Some((upload_id, Vec::new(), 1));
            }
            let (upload_id, parts, part_number) =
                mpu.as_mut().expect("multipart initialized above");
            let part = std::mem::replace(&mut buf, Vec::with_capacity(part_size));
            match self
                .0
                .upload_part()
                .bucket(&bucket)
                .key(&object_key)
                .upload_id(upload_id.clone())
                .part_number(*part_number)
                .body(ByteStream::from(part))
                .send()
                .await
            {
                Ok(resp) => {
                    parts.push(
                        CompletedPart::builder()
                            .e_tag(resp.e_tag().unwrap_or_default().to_string())
                            .part_number(*part_number)
                            .build(),
                    );
                    *part_number += 1;
                }
                Err(e) => {
                    let _ = self
                        .0
                        .abort_multipart_upload()
                        .bucket(&bucket)
                        .key(&object_key)
                        .upload_id(upload_id.clone())
                        .send()
                        .await;
                    return Err(tonic::Status::unavailable(format!(
                        "S3 upload_part failed: {e}"
                    )));
                }
            }
        }

        match mpu {
            // Never reached the part threshold → small object, single PutObject.
            None => {
                let mut request = self
                    .0
                    .put_object()
                    .bucket(&bucket)
                    .key(&object_key)
                    .body(ByteStream::from(buf));
                if let Some(ct) = &content_type {
                    request = request.content_type(ct);
                }
                request.send().await.map_err(|e| {
                    tonic::Status::unavailable(format!("S3 put_object failed: {e}"))
                })?;
            }
            Some((upload_id, mut parts, part_number)) => {
                // Flush the trailing (< part-size) remainder as the final part.
                if !buf.is_empty() {
                    match self
                        .0
                        .upload_part()
                        .bucket(&bucket)
                        .key(&object_key)
                        .upload_id(upload_id.clone())
                        .part_number(part_number)
                        .body(ByteStream::from(buf))
                        .send()
                        .await
                    {
                        Ok(resp) => parts.push(
                            CompletedPart::builder()
                                .e_tag(resp.e_tag().unwrap_or_default().to_string())
                                .part_number(part_number)
                                .build(),
                        ),
                        Err(e) => {
                            let _ = self
                                .0
                                .abort_multipart_upload()
                                .bucket(&bucket)
                                .key(&object_key)
                                .upload_id(upload_id.clone())
                                .send()
                                .await;
                            return Err(tonic::Status::unavailable(format!(
                                "S3 upload_part (final) failed: {e}"
                            )));
                        }
                    }
                }
                let completed = CompletedMultipartUpload::builder()
                    .set_parts(Some(parts))
                    .build();
                if let Err(e) = self
                    .0
                    .complete_multipart_upload()
                    .bucket(&bucket)
                    .key(&object_key)
                    .upload_id(upload_id.clone())
                    .multipart_upload(completed)
                    .send()
                    .await
                {
                    let _ = self
                        .0
                        .abort_multipart_upload()
                        .bucket(&bucket)
                        .key(&object_key)
                        .upload_id(upload_id)
                        .send()
                        .await;
                    return Err(tonic::Status::unavailable(format!(
                        "S3 complete_multipart_upload failed: {e}"
                    )));
                }
            }
        }
        Ok(serde_json::json!({
            "resource_uri": format!("s3://{bucket}/{object_key}"),
            "affected_rows": 1
        })
        .to_string())
    }

    /// `{"bucket","object_key"|"key"}` — deletes the object. S3 delete is
    /// idempotent (deleting a missing key succeeds).
    async fn delete_object(&self, request_json: &str) -> Result<(), tonic::Status> {
        let spec: JsonValue = serde_json::from_str(request_json)
            .map_err(|e| tonic::Status::invalid_argument(format!("invalid request json: {e}")))?;
        let bucket = json_required_str(&spec, "bucket")?;
        let object_key =
            json_required_str(&spec, "object_key").or_else(|_| json_required_str(&spec, "key"))?;
        self.0
            .delete_object()
            .bucket(bucket)
            .key(object_key)
            .send()
            .await
            .map(|_| ())
            .map_err(|err| tonic::Status::unavailable(format!("S3 delete_object failed: {err}")))
    }
}

impl ResourceAdminExecutor for S3Executor {
    async fn ensure_resource(
        &self,
        resource_name: &str,
        _spec_json: &str,
    ) -> Result<(), tonic::Status> {
        self.0
            .create_bucket()
            .bucket(resource_name)
            .send()
            .await
            .map(|_| ())
            .or_else(|err| {
                use aws_sdk_s3::error::ProvideErrorMetadata;
                // BucketAlreadyOwnedByYou / BucketAlreadyExists are idempotent
                // success. The aws-sdk-s3 v1 `SdkError` `Display` is the opaque
                // "service error" — the modeled code lives in the structured
                // ServiceError — so detect the already-exists cases STRUCTURALLY
                // (the old `to_string().contains(...)` never matched, turning an
                // existing bucket into a hard failure). For real failures, surface
                // the actual code + message instead of "service error".
                if err.as_service_error().is_some_and(|svc| {
                    svc.is_bucket_already_owned_by_you() || svc.is_bucket_already_exists()
                }) {
                    Ok(())
                } else {
                    Err(tonic::Status::internal(format!(
                        "s3 create_bucket failed: {}: {}",
                        err.code().unwrap_or("unknown"),
                        err.message().unwrap_or_default()
                    )))
                }
            })
    }
    async fn drop_resource(&self, resource_name: &str) -> Result<(), tonic::Status> {
        self.0
            .delete_bucket()
            .bucket(resource_name)
            .send()
            .await
            .map(|_| ())
            .map_err(|e| tonic::Status::internal(format!("s3 delete_bucket failed: {e}")))
    }
    async fn list_resources(&self) -> Result<Vec<String>, tonic::Status> {
        let resp = self
            .0
            .list_buckets()
            .send()
            .await
            .map_err(|e| tonic::Status::internal(format!("s3 list_buckets failed: {e}")))?;
        Ok(resp
            .buckets()
            .iter()
            .filter_map(|b| b.name())
            .map(str::to_owned)
            .collect())
    }
}

impl BackendExecutor for S3Executor {
    async fn transaction(&self, _request_json: &str) -> Result<String, tonic::Status> {
        Err(tonic::Status::failed_precondition(
            "s3 does not support transactions",
        ))
    }
    async fn probe(&self) -> Result<BackendProbe, tonic::Status> {
        Ok(BackendProbe {
            backend: "s3".to_string(),
            instance: None,
            ok: true,
            error: None,
        })
    }
}