client.rs 36.4 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! S3-compatible object storage client for block management.
//!
//! This module provides an implementation of [`ObjectBlockOps`] using the AWS S3 SDK.
//! It supports S3-compatible storage services including MinIO.

use anyhow::{Result, anyhow};
use aws_sdk_s3::Client;
use aws_sdk_s3::error::ProvideErrorMetadata;
use aws_sdk_s3::primitives::ByteStream;
use bytes::Bytes;
use futures::future::BoxFuture;
use futures::stream::StreamExt;

use crate::object::{DefaultKeyFormatter, KeyFormatter, LayoutConfigExt, ObjectBlockOps};
use crate::{BlockId, SequenceHash};
use kvbm_common::LogicalLayoutHandle;
use kvbm_physical::transfer::PhysicalLayout;
use std::sync::Arc;

/// Configuration for S3 object storage client.
#[derive(Debug, Clone)]
pub struct S3Config {
    /// Custom endpoint URL for S3-compatible services (e.g., MinIO).
    /// If None, uses the default AWS S3 endpoint.
    pub endpoint_url: Option<String>,

    /// S3 bucket name for storing blocks.
    pub bucket: String,

    /// AWS region.
    pub region: String,

    /// Use path-style URLs instead of virtual-hosted-style.
    /// Required for MinIO and some S3-compatible services.
    pub force_path_style: bool,

    /// Maximum number of concurrent S3 requests.
    pub max_concurrent_requests: usize,
}

impl Default for S3Config {
    /// Returns a default configuration suitable for local MinIO testing.
    fn default() -> Self {
        Self {
            endpoint_url: Some("http://localhost:9000".into()),
            bucket: "kvbm-blocks".into(),
            region: "us-east-1".into(),
            force_path_style: true,
            max_concurrent_requests: 16,
        }
    }
}

impl S3Config {
    /// Create a new S3Config for AWS S3 (not MinIO).
    pub fn aws(bucket: String, region: String) -> Self {
        Self {
            endpoint_url: None,
            bucket,
            region,
            force_path_style: false,
            max_concurrent_requests: 16,
        }
    }

    /// Create a new S3Config for MinIO.
    pub fn minio(endpoint_url: String, bucket: String) -> Self {
        Self {
            endpoint_url: Some(endpoint_url),
            bucket,
            region: "us-east-1".into(),
            force_path_style: true,
            max_concurrent_requests: 16,
        }
    }

    /// Create from kvbm-config's S3ObjectConfig.
    pub fn from_object_config(config: &kvbm_config::S3ObjectConfig) -> Self {
        Self {
            endpoint_url: config.endpoint_url.clone(),
            bucket: config.bucket.clone(),
            region: config.region.clone(),
            force_path_style: config.force_path_style,
            max_concurrent_requests: config.max_concurrent_requests,
        }
    }

    /// Set the maximum number of concurrent requests.
    pub fn with_max_concurrent_requests(mut self, max: usize) -> Self {
        self.max_concurrent_requests = max;
        self
    }
}

/// S3-compatible object storage client for block operations.
///
/// This client implements [`ObjectBlockOps`] using the AWS S3 SDK.
/// It supports parallel block operations and uses rayon for CPU-bound memory copies.
///
/// # Key Formatting
///
/// Uses a [`KeyFormatter`] to convert `SequenceHash` to object keys. The formatter
/// can embed rank, namespace, or other prefixes for key uniqueness across workers.
pub struct S3ObjectBlockClient {
    /// AWS S3 client
    client: Client,

    /// S3 configuration
    config: S3Config,

    /// Key formatter for converting SequenceHash to object keys.
    key_formatter: Arc<dyn KeyFormatter>,
}

impl S3ObjectBlockClient {
    /// Create a new S3ObjectBlockClient with default key formatting.
    ///
    /// # Arguments
    /// * `config` - S3 configuration
    ///
    /// # Errors
    /// Returns an error if the S3 client cannot be initialized.
    pub async fn new(config: S3Config) -> Result<Self> {
        let client = build_s3_client(&config).await?;
        Ok(Self {
            client,
            config,
            key_formatter: Arc::new(DefaultKeyFormatter),
        })
    }

    /// Create a new S3ObjectBlockClient with a custom key formatter.
    ///
    /// # Arguments
    /// * `config` - S3 configuration
    /// * `key_formatter` - Custom key formatter for SequenceHash → String conversion
    ///
    /// # Errors
    /// Returns an error if the S3 client cannot be initialized.
    pub async fn with_key_formatter(
        config: S3Config,
        key_formatter: Arc<dyn KeyFormatter>,
    ) -> Result<Self> {
        let client = build_s3_client(&config).await?;
        Ok(Self {
            client,
            config,
            key_formatter,
        })
    }

    /// Create from an existing AWS S3 client with default key formatting.
    pub fn from_client(client: Client, config: S3Config) -> Self {
        Self {
            client,
            config,
            key_formatter: Arc::new(DefaultKeyFormatter),
        }
    }

    /// Create from an existing AWS S3 client with a custom key formatter.
    pub fn from_client_with_formatter(
        client: Client,
        config: S3Config,
        key_formatter: Arc<dyn KeyFormatter>,
    ) -> Self {
        Self {
            client,
            config,
            key_formatter,
        }
    }

    /// Get a reference to the S3 client.
    pub fn client(&self) -> &Client {
        &self.client
    }

    /// Get a reference to the configuration.
    pub fn config(&self) -> &S3Config {
        &self.config
    }

    /// Get a reference to the key formatter.
    pub fn key_formatter(&self) -> &Arc<dyn KeyFormatter> {
        &self.key_formatter
    }

    /// Get a reference to the bucket name.
    pub fn bucket(&self) -> &str {
        &self.config.bucket
    }

    /// Ensure the bucket exists, creating it if necessary.
    pub async fn ensure_bucket_exists(&self) -> Result<()> {
        match self
            .client
            .head_bucket()
            .bucket(&self.config.bucket)
            .send()
            .await
        {
            Ok(_) => Ok(()),
            Err(_) => {
                // Bucket doesn't exist, create it
                self.client
                    .create_bucket()
                    .bucket(&self.config.bucket)
                    .send()
                    .await
                    .map_err(|e| {
                        anyhow!("failed to create bucket '{}': {}", self.config.bucket, e)
                    })?;
                Ok(())
            }
        }
    }

    /// Put an object with a conditional check (If-None-Match: *).
    ///
    /// This performs an atomic write that only succeeds if the object does not
    /// already exist. Returns:
    /// - `Ok(true)` if the object was created successfully
    /// - `Ok(false)` if the object already exists (PreconditionFailed)
    /// - `Err(...)` for other errors
    ///
    /// # Arguments
    /// * `key` - Object key
    /// * `data` - Object data to write
    pub async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<bool> {
        match self
            .client
            .put_object()
            .bucket(&self.config.bucket)
            .key(key)
            .if_none_match("*")
            .body(ByteStream::from(data))
            .send()
            .await
        {
            Ok(_) => Ok(true),
            Err(e) => {
                // Check if this is a precondition failed error (HTTP 412)
                let service_error = e.into_service_error();
                if service_error.code() == Some("PreconditionFailed") {
                    Ok(false)
                } else {
                    Err(anyhow!(
                        "S3 conditional put failed for key '{}': {}",
                        key,
                        service_error
                    ))
                }
            }
        }
    }

    /// Get an object's raw bytes.
    ///
    /// # Arguments
    /// * `key` - Object key
    ///
    /// # Returns
    /// - `Ok(Some(bytes))` if the object exists
    /// - `Ok(None)` if the object does not exist
    /// - `Err(...)` for other errors
    pub async fn get_object(&self, key: &str) -> Result<Option<Bytes>> {
        match self
            .client
            .get_object()
            .bucket(&self.config.bucket)
            .key(key)
            .send()
            .await
        {
            Ok(resp) => {
                let data = resp
                    .body
                    .collect()
                    .await
                    .map_err(|e| anyhow!("failed to collect S3 response body: {}", e))?
                    .into_bytes();
                Ok(Some(data))
            }
            Err(e) => {
                let service_error = e.into_service_error();
                if service_error.code() == Some("NoSuchKey") {
                    Ok(None)
                } else {
                    Err(anyhow!(
                        "S3 get_object failed for key '{}': {}",
                        key,
                        service_error
                    ))
                }
            }
        }
    }

    /// Delete an object.
    ///
    /// # Arguments
    /// * `key` - Object key
    ///
    /// # Returns
    /// - `Ok(true)` if the object was deleted
    /// - `Ok(false)` if the object did not exist
    /// - `Err(...)` for other errors
    pub async fn delete_object(&self, key: &str) -> Result<bool> {
        match self
            .client
            .delete_object()
            .bucket(&self.config.bucket)
            .key(key)
            .send()
            .await
        {
            Ok(_) => Ok(true),
            Err(e) => {
                let service_error = e.into_service_error();
                if service_error.code() == Some("NoSuchKey") {
                    Ok(false)
                } else {
                    Err(anyhow!(
                        "S3 delete_object failed for key '{}': {}",
                        key,
                        service_error
                    ))
                }
            }
        }
    }

    /// Check if an object exists (HEAD request).
    ///
    /// # Arguments
    /// * `key` - Object key
    ///
    /// # Returns
    /// - `Ok(true)` if the object exists
    /// - `Ok(false)` if the object does not exist
    /// - `Err(...)` for other errors
    pub async fn has_object(&self, key: &str) -> Result<bool> {
        match self
            .client
            .head_object()
            .bucket(&self.config.bucket)
            .key(key)
            .send()
            .await
        {
            Ok(_) => Ok(true),
            Err(e) => {
                let service_error = e.into_service_error();
                // HeadObject returns "NotFound" when object doesn't exist
                if service_error.code() == Some("NotFound") {
                    Ok(false)
                } else {
                    Err(anyhow!(
                        "S3 head_object failed for key '{}': {}",
                        key,
                        service_error
                    ))
                }
            }
        }
    }

    /// Put an object unconditionally (overwrite if exists).
    ///
    /// # Arguments
    /// * `key` - Object key
    /// * `data` - Object data to write
    pub async fn put_object(&self, key: &str, data: Bytes) -> Result<()> {
        self.client
            .put_object()
            .bucket(&self.config.bucket)
            .key(key)
            .body(ByteStream::from(data))
            .send()
            .await
            .map_err(|e| anyhow!("S3 put_object failed for key '{}': {}", key, e))?;
        Ok(())
    }

    /// Put blocks to object storage using a physical layout.
    ///
    /// This is the internal implementation that workers call after resolving
    /// the logical layout handle to a physical layout.
    ///
    /// # Arguments
    /// * `keys` - Sequence hashes identifying each block
    /// * `layout` - Physical layout containing the block data
    /// * `block_ids` - Block IDs within the layout to upload
    ///
    /// Returns a vector of results for each block:
    /// - Ok(hash) indicates the block was successfully stored
    /// - Err(hash) indicates the block failed to store
    pub fn put_blocks_with_layout(
        &self,
        keys: Vec<SequenceHash>,
        layout: PhysicalLayout,
        block_ids: Vec<BlockId>,
    ) -> BoxFuture<'static, Vec<Result<SequenceHash, SequenceHash>>> {
        let config = layout.layout().config();
        let block_size = config.block_size_bytes();
        let region_size = config.region_size();
        let is_contiguous = layout.layout().is_fully_contiguous();
        let max_concurrent = self.config.max_concurrent_requests;
        let client = self.client.clone();
        let bucket = self.config.bucket.clone();
        let formatter = self.key_formatter.clone();

        Box::pin(async move {
            let work_items: Vec<_> = keys.into_iter().zip(block_ids).collect();

            let tasks = work_items.into_iter().map(|(key, block_id)| {
                let client = client.clone();
                let bucket = bucket.clone();
                let key_str = formatter.format_key(&key);
                let layout = layout.clone();

                async move {
                    let result: Result<(), anyhow::Error> = async {
                        // Copy block data to bytes on rayon thread pool
                        let data = tokio_rayon::spawn(move || {
                            copy_block_to_bytes(
                                &layout,
                                block_id,
                                block_size,
                                region_size,
                                is_contiguous,
                            )
                        })
                        .await?;

                        // Upload to S3
                        client
                            .put_object()
                            .bucket(&bucket)
                            .key(&key_str)
                            .body(ByteStream::from(data))
                            .send()
                            .await
                            .map_err(|e| anyhow!("S3 put_object failed: {}", e))?;

                        Ok(())
                    }
                    .await;

                    match result {
                        Ok(()) => Ok(key),
                        Err(e) => {
                            tracing::warn!(key = %key, error = %e, "put block transfer failed");
                            Err(key)
                        }
                    }
                }
            });

            futures::stream::iter(tasks)
                .buffer_unordered(max_concurrent)
                .collect()
                .await
        })
    }

    /// Get blocks from object storage into a physical layout.
    ///
    /// This is the internal implementation that workers call after resolving
    /// the logical layout handle to a physical layout.
    ///
    /// # Arguments
    /// * `keys` - Sequence hashes identifying each block
    /// * `layout` - Physical layout to write the block data into
    /// * `block_ids` - Block IDs within the layout to download into
    ///
    /// Returns a vector of results for each block:
    /// - Ok(hash) indicates the block was successfully retrieved
    /// - Err(hash) indicates the block failed to retrieve
    pub fn get_blocks_with_layout(
        &self,
        keys: Vec<SequenceHash>,
        layout: PhysicalLayout,
        block_ids: Vec<BlockId>,
    ) -> BoxFuture<'static, Vec<Result<SequenceHash, SequenceHash>>> {
        let config = layout.layout().config();
        let block_size = config.block_size_bytes();
        let region_size = config.region_size();
        let is_contiguous = layout.layout().is_fully_contiguous();
        let max_concurrent = self.config.max_concurrent_requests;
        let client = self.client.clone();
        let bucket = self.config.bucket.clone();
        let formatter = self.key_formatter.clone();

        Box::pin(async move {
            let work_items: Vec<_> = keys.into_iter().zip(block_ids).collect();

            let tasks = work_items.into_iter().map(|(key, block_id)| {
                let client = client.clone();
                let bucket = bucket.clone();
                let key_str = formatter.format_key(&key);
                let layout = layout.clone();

                async move {
                    let result: Result<(), anyhow::Error> = async {
                        // Download from S3
                        let resp = client
                            .get_object()
                            .bucket(&bucket)
                            .key(&key_str)
                            .send()
                            .await
                            .map_err(|e| anyhow!("S3 get_object failed: {}", e))?;

                        let data = resp
                            .body
                            .collect()
                            .await
                            .map_err(|e| anyhow!("failed to collect S3 response body: {}", e))?
                            .into_bytes();

                        // Copy bytes to block on rayon thread pool
                        tokio_rayon::spawn(move || {
                            copy_bytes_to_block(
                                &data,
                                &layout,
                                block_id,
                                block_size,
                                region_size,
                                is_contiguous,
                            )
                        })
                        .await?;

                        Ok(())
                    }
                    .await;

                    match result {
                        Ok(()) => Ok(key),
                        Err(e) => {
                            tracing::warn!(key = %key, error = %e, "get block transfer failed");
                            Err(key)
                        }
                    }
                }
            });

            futures::stream::iter(tasks)
                .buffer_unordered(max_concurrent)
                .collect()
                .await
        })
    }

    /// Get an object's raw bytes along with its ETag.
    ///
    /// Used for conditional updates (CAS-style operations) where the caller
    /// needs the current ETag to perform a conditional PUT.
    ///
    /// # Returns
    /// - `Ok(Some((bytes, etag)))` if the object exists
    /// - `Ok(None)` if the object does not exist
    /// - `Err(...)` for other errors
    pub async fn get_object_with_etag(&self, key: &str) -> Result<Option<(Bytes, Option<String>)>> {
        match self
            .client
            .get_object()
            .bucket(&self.config.bucket)
            .key(key)
            .send()
            .await
        {
            Ok(resp) => {
                let etag = resp.e_tag().map(|s| s.to_string());
                let data = resp
                    .body
                    .collect()
                    .await
                    .map_err(|e| anyhow!("failed to collect S3 response body: {}", e))?
                    .into_bytes();
                Ok(Some((data, etag)))
            }
            Err(e) => {
                let service_error = e.into_service_error();
                if service_error.code() == Some("NoSuchKey") {
                    Ok(None)
                } else {
                    Err(anyhow!(
                        "S3 get_object failed for key '{}': {}",
                        key,
                        service_error
                    ))
                }
            }
        }
    }

    /// Put an object with an ETag precondition (If-Match).
    ///
    /// This performs a conditional write that only succeeds if the object's current
    /// ETag matches the provided value. Used for CAS-style atomic updates.
    ///
    /// # Returns
    /// - `Ok(true)` if the write succeeded (ETag matched)
    /// - `Ok(false)` if the ETag did not match (412 PreconditionFailed — lost the race)
    /// - `Err(...)` for other errors
    pub async fn put_object_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<bool> {
        match self
            .client
            .put_object()
            .bucket(&self.config.bucket)
            .key(key)
            .if_match(etag)
            .body(ByteStream::from(data))
            .send()
            .await
        {
            Ok(_) => Ok(true),
            Err(e) => {
                let service_error = e.into_service_error();
                if service_error.code() == Some("PreconditionFailed") {
                    Ok(false)
                } else {
                    Err(anyhow!(
                        "S3 conditional put (if-match) failed for key '{}': {}",
                        key,
                        service_error
                    ))
                }
            }
        }
    }
}

/// Build an S3 client from configuration.
async fn build_s3_client(config: &S3Config) -> Result<Client> {
    let sdk_config = aws_config::defaults(aws_config::BehaviorVersion::latest())
        .region(aws_sdk_s3::config::Region::new(config.region.clone()))
        .load()
        .await;

    let mut s3_config_builder = aws_sdk_s3::config::Builder::from(&sdk_config);

    if let Some(endpoint) = &config.endpoint_url {
        s3_config_builder = s3_config_builder.endpoint_url(endpoint);
    }

    if config.force_path_style {
        s3_config_builder = s3_config_builder.force_path_style(true);
    }

    let s3_config = s3_config_builder.build();
    Ok(Client::from_conf(s3_config))
}

/// Copy block data from a layout to a Bytes buffer.
///
/// For fully contiguous layouts, this is a single memcpy.
/// For layer-separate layouts, this iterates over all regions.
fn copy_block_to_bytes(
    layout: &PhysicalLayout,
    block_id: BlockId,
    block_size: usize,
    region_size: usize,
    is_contiguous: bool,
) -> Result<Bytes> {
    if is_contiguous {
        // Fast path: single contiguous region — the layout guarantees that
        // block_size bytes are contiguous from region(block_id, 0, 0).addr().
        let region = layout.memory_region(block_id, 0, 0)?;
        let slice = unsafe { std::slice::from_raw_parts(region.addr() as *const u8, block_size) };
        Ok(Bytes::copy_from_slice(slice))
    } else {
        // Slow path: iterate over all regions
        let mut buf = Vec::with_capacity(block_size);
        let inner_layout = layout.layout();
        for layer_id in 0..inner_layout.num_layers() {
            for outer_id in 0..inner_layout.outer_dim() {
                let region = layout.memory_region(block_id, layer_id, outer_id)?;
                if region.size() < region_size {
                    return Err(anyhow!(
                        "memory region too small: got {} bytes, need {}",
                        region.size(),
                        region_size
                    ));
                }
                let slice =
                    unsafe { std::slice::from_raw_parts(region.addr() as *const u8, region_size) };
                buf.extend_from_slice(slice);
            }
        }
        Ok(Bytes::from(buf))
    }
}

/// Copy data from a Bytes buffer to a layout.
///
/// For fully contiguous layouts, this is a single memcpy.
/// For layer-separate layouts, this iterates over all regions.
fn copy_bytes_to_block(
    data: &[u8],
    layout: &PhysicalLayout,
    block_id: BlockId,
    block_size: usize,
    region_size: usize,
    is_contiguous: bool,
) -> Result<()> {
    if is_contiguous {
        // Fast path: single contiguous region — the layout guarantees that
        // block_size bytes are contiguous from region(block_id, 0, 0).addr().
        if data.len() < block_size {
            return Err(anyhow!(
                "S3 data too short: got {} bytes, expected {}",
                data.len(),
                block_size
            ));
        }
        let region = layout.memory_region(block_id, 0, 0)?;
        unsafe {
            std::ptr::copy_nonoverlapping(data.as_ptr(), region.addr() as *mut u8, block_size);
        }
    } else {
        // Slow path: iterate over all regions
        let mut offset = 0;
        let inner_layout = layout.layout();
        for layer_id in 0..inner_layout.num_layers() {
            for outer_id in 0..inner_layout.outer_dim() {
                if offset + region_size > data.len() {
                    return Err(anyhow!(
                        "S3 data too short at offset {}: need {} more bytes, only {} remain",
                        offset,
                        region_size,
                        data.len().saturating_sub(offset)
                    ));
                }
                let region = layout.memory_region(block_id, layer_id, outer_id)?;
                if region.size() < region_size {
                    return Err(anyhow!(
                        "memory region too small: got {} bytes, need {}",
                        region.size(),
                        region_size
                    ));
                }
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        data[offset..].as_ptr(),
                        region.addr() as *mut u8,
                        region_size,
                    );
                }
                offset += region_size;
            }
        }
    }
    Ok(())
}

impl ObjectBlockOps for S3ObjectBlockClient {
    fn has_blocks(
        &self,
        keys: Vec<SequenceHash>,
    ) -> BoxFuture<'static, Vec<(SequenceHash, Option<usize>)>> {
        let max_concurrent = self.config.max_concurrent_requests;
        let client = self.client.clone();
        let bucket = self.config.bucket.clone();
        let formatter = self.key_formatter.clone();

        Box::pin(async move {
            let tasks = keys.into_iter().map(|key| {
                let client = client.clone();
                let bucket = bucket.clone();
                let key_str = formatter.format_key(&key);

                async move {
                    match client
                        .head_object()
                        .bucket(&bucket)
                        .key(&key_str)
                        .send()
                        .await
                    {
                        Ok(resp) => (key, resp.content_length().map(|l| l as usize)),
                        Err(e) => {
                            tracing::warn!(key = %key, error = %e, "head_object failed, treating as missing");
                            (key, None)
                        }
                    }
                }
            });

            futures::stream::iter(tasks)
                .buffer_unordered(max_concurrent)
                .collect()
                .await
        })
    }

    fn put_blocks(
        &self,
        keys: Vec<SequenceHash>,
        _src_layout: LogicalLayoutHandle,
        _block_ids: Vec<BlockId>,
    ) -> BoxFuture<'static, Vec<Result<SequenceHash, SequenceHash>>> {
        // S3ObjectBlockClient cannot resolve LogicalLayoutHandle to PhysicalLayout.
        // Workers should use put_blocks_with_layout() instead after resolving the handle.
        tracing::error!(
            "S3ObjectBlockClient::put_blocks called with LogicalLayoutHandle - \
             use put_blocks_with_layout() via DirectWorker instead"
        );
        Box::pin(async move { keys.into_iter().map(Err).collect() })
    }

    fn get_blocks(
        &self,
        keys: Vec<SequenceHash>,
        _dst_layout: LogicalLayoutHandle,
        _block_ids: Vec<BlockId>,
    ) -> BoxFuture<'static, Vec<Result<SequenceHash, SequenceHash>>> {
        // S3ObjectBlockClient cannot resolve LogicalLayoutHandle to PhysicalLayout.
        // Workers should use get_blocks_with_layout() instead after resolving the handle.
        tracing::error!(
            "S3ObjectBlockClient::get_blocks called with LogicalLayoutHandle - \
             use get_blocks_with_layout() via DirectWorker instead"
        );
        Box::pin(async move { keys.into_iter().map(Err).collect() })
    }

    fn put_blocks_with_layout(
        &self,
        keys: Vec<SequenceHash>,
        layout: PhysicalLayout,
        block_ids: Vec<BlockId>,
    ) -> BoxFuture<'static, Vec<Result<SequenceHash, SequenceHash>>> {
        // Delegate to the inherent method
        S3ObjectBlockClient::put_blocks_with_layout(self, keys, layout, block_ids)
    }

    fn get_blocks_with_layout(
        &self,
        keys: Vec<SequenceHash>,
        layout: PhysicalLayout,
        block_ids: Vec<BlockId>,
    ) -> BoxFuture<'static, Vec<Result<SequenceHash, SequenceHash>>> {
        // Delegate to the inherent method
        S3ObjectBlockClient::get_blocks_with_layout(self, keys, layout, block_ids)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_s3_config_default() {
        let config = S3Config::default();
        assert_eq!(config.endpoint_url, Some("http://localhost:9000".into()));
        assert_eq!(config.bucket, "kvbm-blocks");
        assert_eq!(config.region, "us-east-1");
        assert!(config.force_path_style);
        assert_eq!(config.max_concurrent_requests, 16);
    }

    #[test]
    fn test_s3_config_aws() {
        let config = S3Config::aws("my-bucket".into(), "us-west-2".into());
        assert_eq!(config.endpoint_url, None);
        assert_eq!(config.bucket, "my-bucket");
        assert_eq!(config.region, "us-west-2");
        assert!(!config.force_path_style);
    }

    #[test]
    fn test_s3_config_minio() {
        let config = S3Config::minio("http://minio:9000".into(), "test-bucket".into());
        assert_eq!(config.endpoint_url, Some("http://minio:9000".into()));
        assert_eq!(config.bucket, "test-bucket");
        assert!(config.force_path_style);
    }
}

#[cfg(all(test, feature = "testing"))]
mod bounds_check_tests {
    use super::*;
    use crate::object::LayoutConfigExt;
    use kvbm_physical::testing::{create_fc_layout, create_lw_layout, create_test_agent};
    use kvbm_physical::transfer::StorageKind;

    #[test]
    fn test_copy_bytes_to_block_rejects_short_data_contiguous() {
        let agent = create_test_agent("test_short_data_fc");
        let layout = create_fc_layout(agent, StorageKind::System, 2);
        let config = layout.layout().config();
        let block_size = config.block_size_bytes();
        let region_size = config.region_size();

        // Data is one byte short
        let short_data = vec![0u8; block_size - 1];
        let err = copy_bytes_to_block(&short_data, &layout, 0, block_size, region_size, true)
            .expect_err("should reject short data");
        assert!(
            err.to_string().contains("S3 data too short"),
            "unexpected error: {}",
            err
        );
    }

    #[test]
    fn test_copy_bytes_to_block_rejects_short_data_non_contiguous() {
        let agent = create_test_agent("test_short_data_lw");
        let layout = create_lw_layout(agent, StorageKind::System, 2);
        let config = layout.layout().config();
        let block_size = config.block_size_bytes();
        let region_size = config.region_size();

        // Data is one region short
        let short_data = vec![0u8; block_size - region_size];
        let err = copy_bytes_to_block(&short_data, &layout, 0, block_size, region_size, false)
            .expect_err("should reject short data in non-contiguous path");
        assert!(
            err.to_string().contains("S3 data too short"),
            "unexpected error: {}",
            err
        );
    }

    #[test]
    fn test_copy_bytes_to_block_accepts_exact_size() {
        let agent = create_test_agent("test_exact_fc");
        let layout = create_fc_layout(agent, StorageKind::System, 2);
        let config = layout.layout().config();
        let block_size = config.block_size_bytes();
        let region_size = config.region_size();

        let data = vec![42u8; block_size];
        copy_bytes_to_block(&data, &layout, 0, block_size, region_size, true)
            .expect("exact-size data should succeed");
    }

    #[test]
    fn test_copy_block_to_bytes_roundtrip_contiguous() {
        let agent = create_test_agent("test_roundtrip_fc");
        let layout = create_fc_layout(agent, StorageKind::System, 2);
        let config = layout.layout().config();
        let block_size = config.block_size_bytes();
        let region_size = config.region_size();

        // Write known data
        let data = vec![0xAB_u8; block_size];
        copy_bytes_to_block(&data, &layout, 0, block_size, region_size, true).unwrap();

        // Read it back
        let out = copy_block_to_bytes(&layout, 0, block_size, region_size, true).unwrap();
        assert_eq!(out.as_ref(), &data[..]);
    }

    #[test]
    fn test_copy_block_to_bytes_roundtrip_non_contiguous() {
        let agent = create_test_agent("test_roundtrip_lw");
        let layout = create_lw_layout(agent, StorageKind::System, 2);
        let config = layout.layout().config();
        let block_size = config.block_size_bytes();
        let region_size = config.region_size();

        let data = vec![0xCD_u8; block_size];
        copy_bytes_to_block(&data, &layout, 0, block_size, region_size, false).unwrap();

        let out = copy_block_to_bytes(&layout, 0, block_size, region_size, false).unwrap();
        assert_eq!(out.as_ref(), &data[..]);
    }
}

#[cfg(all(test, feature = "testing-s3"))]
pub mod s3_integration {
    use super::*;

    /// Create an S3ObjectBlockClient connected to the test MinIO instance.
    ///
    /// Reads `S3_TEST_ENDPOINT` from the environment (set by `test-s3.sh`).
    /// Falls back to `http://localhost:9876`.
    pub async fn create_test_client(bucket: &str) -> S3ObjectBlockClient {
        let endpoint =
            std::env::var("S3_TEST_ENDPOINT").unwrap_or_else(|_| "http://localhost:9876".into());
        let config = S3Config::minio(endpoint, bucket.to_string());
        let client = S3ObjectBlockClient::new(config).await.unwrap();
        client.ensure_bucket_exists().await.unwrap();
        client
    }

    #[tokio::test]
    async fn test_put_get_roundtrip() {
        let client = create_test_client("test-roundtrip").await;
        let key = format!("roundtrip-{}", uuid::Uuid::new_v4());
        let payload = Bytes::from("hello world");

        client.put_object(&key, payload.clone()).await.unwrap();

        let result = client.get_object(&key).await.unwrap();
        assert_eq!(result, Some(payload));

        // Cleanup
        client.delete_object(&key).await.unwrap();
    }

    #[tokio::test]
    async fn test_put_object_if_match_rejects_stale_etag() {
        let client = create_test_client("test-if-match").await;
        let key = format!("if-match-{}", uuid::Uuid::new_v4());

        // Write initial object
        client
            .put_object(&key, Bytes::from("version1"))
            .await
            .unwrap();

        // Get with ETag
        let (_, etag) = client
            .get_object_with_etag(&key)
            .await
            .unwrap()
            .expect("object should exist");
        let etag = etag.expect("should have etag");

        // Overwrite the object to change its ETag
        client
            .put_object(&key, Bytes::from("version2"))
            .await
            .unwrap();

        // Conditional put with stale ETag should fail
        let won = client
            .put_object_if_match(&key, Bytes::from("version3"), &etag)
            .await
            .unwrap();
        assert!(!won, "conditional put with stale ETag should return false");

        // Verify the object still has version2
        let data = client.get_object(&key).await.unwrap().unwrap();
        assert_eq!(data, Bytes::from("version2"));

        // Cleanup
        client.delete_object(&key).await.unwrap();
    }

    #[tokio::test]
    async fn test_put_object_if_match_accepts_current_etag() {
        let client = create_test_client("test-if-match-ok").await;
        let key = format!("if-match-ok-{}", uuid::Uuid::new_v4());

        client
            .put_object(&key, Bytes::from("version1"))
            .await
            .unwrap();

        let (_, etag) = client
            .get_object_with_etag(&key)
            .await
            .unwrap()
            .expect("object should exist");
        let etag = etag.expect("should have etag");

        // Conditional put with current ETag should succeed
        let won = client
            .put_object_if_match(&key, Bytes::from("version2"), &etag)
            .await
            .unwrap();
        assert!(won, "conditional put with current ETag should succeed");

        let data = client.get_object(&key).await.unwrap().unwrap();
        assert_eq!(data, Bytes::from("version2"));

        // Cleanup
        client.delete_object(&key).await.unwrap();
    }
}