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
use super::error::{StorageError, StorageResult};
use std::path::PathBuf;
use tokio::fs;
/// Storage abstraction for uploaded files
///
/// For S3 storage, user_id is passed per-operation (not stored in config) to support
/// multi-tenant Lambda invocations where each request has its own user_id.
#[derive(Clone)]
pub enum UploadStorage {
/// Local filesystem storage
Local { path: PathBuf },
/// S3 storage for cloud deployments
#[cfg(feature = "aws-backend")]
S3 {
client: aws_sdk_s3::Client,
bucket: String,
/// Base prefix for organizing files (e.g., "uploads/")
prefix: String,
/// AWS region (needed for some operations)
region: String,
},
}
impl UploadStorage {
/// Create local upload storage
pub fn local(path: PathBuf) -> Self {
Self::Local { path }
}
/// Create S3 upload storage
///
/// # Arguments
/// * `bucket` - S3 bucket name
/// * `region` - AWS region (e.g., "us-east-1")
/// * `prefix` - Optional base prefix for organizing files (defaults to "uploads/")
///
/// Note: user_id is passed per-operation, not at construction time,
/// to support multi-tenant Lambda invocations.
/// Create S3 upload storage
///
/// # Arguments
/// * `bucket` - S3 bucket name
/// * `region` - AWS region (e.g., "us-east-1")
/// * `prefix` - Optional base prefix for organizing files (defaults to "uploads/")
///
/// Note: user_id is passed per-operation, not at construction time,
/// to support multi-tenant Lambda invocations.
#[cfg(feature = "aws-backend")]
pub async fn s3(
bucket: String,
region: String,
prefix: Option<String>,
) -> Result<Self, StorageError> {
let aws_config = aws_config::defaults(aws_config::BehaviorVersion::latest())
.region(aws_sdk_s3::config::Region::new(region.clone()))
.load()
.await;
let client = aws_sdk_s3::Client::new(&aws_config);
Ok(Self::S3 {
client,
bucket,
prefix: prefix.unwrap_or_else(|| "uploads/".to_string()),
region,
})
}
/// Get the full S3 key prefix including user_id if present
#[cfg(feature = "aws-backend")]
fn get_s3_key_prefix(prefix: &str, user_id: Option<&str>) -> String {
match user_id {
Some(uid) => format!("{}{}/", prefix, uid),
None => prefix.to_string(),
}
}
/// Save a file to storage
///
/// # Arguments
/// * `filename` - Name of the file to save
/// * `data` - File content as bytes
/// * `user_id` - Optional user ID for multi-tenant S3 isolation (files stored at {prefix}{user_id}/{filename})
///
/// Returns the path/key where the file was saved
pub async fn save_file(
&self,
filename: &str,
data: &[u8],
user_id: Option<&str>,
) -> StorageResult<PathBuf> {
match self {
Self::Local { path } => {
// For local storage, optionally use user_id subdirectory
let target_path = match user_id {
Some(uid) => path.join(uid),
None => path.clone(),
};
// Ensure directory exists
fs::create_dir_all(&target_path).await?;
let filepath = target_path.join(filename);
// Write file
fs::write(&filepath, data).await?;
Ok(filepath)
}
#[cfg(feature = "aws-backend")]
Self::S3 {
client,
bucket,
prefix,
..
} => {
let full_prefix = Self::get_s3_key_prefix(prefix, user_id);
let key = format!("{}{}", full_prefix, filename);
client
.put_object()
.bucket(bucket)
.key(&key)
.body(aws_sdk_s3::primitives::ByteStream::from(data.to_vec()))
.send()
.await
.map_err(|e| StorageError::UploadFailed(format!("S3 upload failed: {}", e)))?;
Ok(PathBuf::from(format!("s3://{}/{}", bucket, key)))
}
}
}
/// Read a file from storage
///
/// # Arguments
/// * `filename` - Name of the file to read
/// * `user_id` - Optional user ID for multi-tenant S3 isolation
pub async fn read_file(&self, filename: &str, user_id: Option<&str>) -> StorageResult<Vec<u8>> {
match self {
Self::Local { path } => {
let target_path = match user_id {
Some(uid) => path.join(uid),
None => path.clone(),
};
let filepath = target_path.join(filename);
Ok(fs::read(&filepath).await?)
}
#[cfg(feature = "aws-backend")]
Self::S3 {
client,
bucket,
prefix,
..
} => {
let full_prefix = Self::get_s3_key_prefix(prefix, user_id);
let key = format!("{}{}", full_prefix, filename);
let response = client
.get_object()
.bucket(bucket)
.key(&key)
.send()
.await
.map_err(|e| {
StorageError::DownloadFailed(format!("S3 download failed: {}", e))
})?;
let bytes = response
.body
.collect()
.await
.map_err(|e| {
StorageError::DownloadFailed(format!(
"Failed to read S3 response body: {}",
e
))
})?
.into_bytes();
Ok(bytes.to_vec())
}
}
}
/// Atomically save a file only if it doesn't already exist.
///
/// # Arguments
/// * `filename` - Name of the file to save
/// * `data` - File content as bytes
/// * `user_id` - Optional user ID for multi-tenant S3 isolation
///
/// Returns (PathBuf, bool) where:
/// - PathBuf is the path/key where the file was (or would be) saved
/// - bool is true if file already existed (duplicate), false if newly created
pub async fn save_file_if_not_exists(
&self,
filename: &str,
data: &[u8],
user_id: Option<&str>,
) -> StorageResult<(PathBuf, bool)> {
match self {
Self::Local { path } => {
let target_path = match user_id {
Some(uid) => path.join(uid),
None => path.clone(),
};
// Ensure directory exists
fs::create_dir_all(&target_path).await?;
let filepath = target_path.join(filename);
// Atomically create file only if it doesn't exist (prevents race condition)
match tokio::task::spawn_blocking({
let filepath = filepath.clone();
let data = data.to_vec();
move || {
use std::io::Write;
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&filepath)
.and_then(|mut f| f.write_all(&data))
}
})
.await
{
Ok(Ok(())) => {
// File created successfully (new file)
Ok((filepath, false))
}
Ok(Err(e)) if e.kind() == std::io::ErrorKind::AlreadyExists => {
// File already exists (duplicate upload detected atomically)
Ok((filepath, true))
}
Ok(Err(e)) => Err(StorageError::UploadFailed(format!(
"Failed to write file: {}",
e
))),
Err(e) => Err(StorageError::UploadFailed(format!(
"Task join error: {}",
e
))),
}
}
#[cfg(feature = "aws-backend")]
Self::S3 {
client,
bucket,
prefix,
..
} => {
let full_prefix = Self::get_s3_key_prefix(prefix, user_id);
let key = format!("{}{}", full_prefix, filename);
let s3_path = PathBuf::from(format!("s3://{}/{}", bucket, key));
// Check if object already exists
let exists = client
.head_object()
.bucket(bucket)
.key(&key)
.send()
.await
.is_ok();
if exists {
return Ok((s3_path, true));
}
// Upload the file
client
.put_object()
.bucket(bucket)
.key(&key)
.body(aws_sdk_s3::primitives::ByteStream::from(data.to_vec()))
.send()
.await
.map_err(|e| StorageError::UploadFailed(format!("S3 upload failed: {}", e)))?;
Ok((s3_path, false))
}
}
}
/// Check if a file exists in storage
///
/// # Arguments
/// * `filename` - Name of the file to check
/// * `user_id` - Optional user ID for multi-tenant S3 isolation
pub async fn file_exists(&self, filename: &str, user_id: Option<&str>) -> StorageResult<bool> {
match self {
Self::Local { path } => {
let target_path = match user_id {
Some(uid) => path.join(uid),
None => path.clone(),
};
Ok(target_path.join(filename).exists())
}
#[cfg(feature = "aws-backend")]
Self::S3 {
client,
bucket,
prefix,
..
} => {
let full_prefix = Self::get_s3_key_prefix(prefix, user_id);
let key = format!("{}{}", full_prefix, filename);
let result = client.head_object().bucket(bucket).key(&key).send().await;
Ok(result.is_ok())
}
}
}
/// Get the display path for a file (for logging/errors)
///
/// # Arguments
/// * `filename` - Name of the file
/// * `user_id` - Optional user ID for multi-tenant S3 isolation
pub fn get_display_path(&self, filename: &str, user_id: Option<&str>) -> String {
match self {
Self::Local { path } => {
let target_path = match user_id {
Some(uid) => path.join(uid),
None => path.clone(),
};
target_path.join(filename).display().to_string()
}
#[cfg(feature = "aws-backend")]
Self::S3 { bucket, prefix, .. } => {
let full_prefix = Self::get_s3_key_prefix(prefix, user_id);
format!("s3://{}/{}{}", bucket, full_prefix, filename)
}
}
}
/// Returns true if this is local storage
pub fn is_local(&self) -> bool {
matches!(self, Self::Local { .. })
}
/// Returns true if this is S3 storage
pub fn is_s3(&self) -> bool {
#[cfg(feature = "aws-backend")]
{
matches!(self, Self::S3 { .. })
}
#[cfg(not(feature = "aws-backend"))]
{
false
}
}
/// Download a file from an external S3 path (bucket/key)
/// This is used for S3 event-triggered ingestion where files come from external buckets
pub async fn download_from_s3_path(&self, _bucket: &str, _key: &str) -> StorageResult<Vec<u8>> {
match self {
Self::Local { .. } => {
Err(StorageError::DownloadFailed(
"S3 download not supported in local mode. Configure S3 storage to enable S3 downloads.".to_string()
))
}
#[cfg(feature = "aws-backend")]
Self::S3 { client, .. } => {
let response = client.get_object()
.bucket(_bucket)
.key(_key)
.send()
.await
.map_err(|e| StorageError::DownloadFailed(format!("S3 download from s3://{}/{} failed: {}", _bucket, _key, e)))?;
let bytes = response.body
.collect()
.await
.map_err(|e| StorageError::DownloadFailed(format!("Failed to read S3 response body: {}", e)))?
.into_bytes();
Ok(bytes.to_vec())
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[tokio::test]
async fn test_local_save_and_read() {
let temp_dir = tempdir().unwrap();
let storage = UploadStorage::local(temp_dir.path().to_path_buf());
let data = b"test content";
let path = storage.save_file("test.txt", data, None).await.unwrap();
assert!(path.exists());
let read_data = storage.read_file("test.txt", None).await.unwrap();
assert_eq!(read_data, data.to_vec());
}
#[tokio::test]
async fn test_local_save_and_read_with_user_id() {
let temp_dir = tempdir().unwrap();
let storage = UploadStorage::local(temp_dir.path().to_path_buf());
let data = b"user specific content";
let user_id = Some("user_123");
let path = storage.save_file("test.txt", data, user_id).await.unwrap();
assert!(path.exists());
assert!(path.to_string_lossy().contains("user_123"));
let read_data = storage.read_file("test.txt", user_id).await.unwrap();
assert_eq!(read_data, data.to_vec());
}
#[tokio::test]
async fn test_local_file_exists() {
let temp_dir = tempdir().unwrap();
let storage = UploadStorage::local(temp_dir.path().to_path_buf());
assert!(!storage.file_exists("nonexistent.txt", None).await.unwrap());
storage
.save_file("exists.txt", b"data", None)
.await
.unwrap();
assert!(storage.file_exists("exists.txt", None).await.unwrap());
}
#[tokio::test]
async fn test_local_save_if_not_exists() {
let temp_dir = tempdir().unwrap();
let storage = UploadStorage::local(temp_dir.path().to_path_buf());
// First save should succeed
let (path, existed) = storage
.save_file_if_not_exists("unique.txt", b"original", None)
.await
.unwrap();
assert!(!existed);
assert!(path.exists());
// Second save should detect duplicate
let (_, existed) = storage
.save_file_if_not_exists("unique.txt", b"duplicate", None)
.await
.unwrap();
assert!(existed);
// Original content should be preserved
let content = storage.read_file("unique.txt", None).await.unwrap();
assert_eq!(content, b"original".to_vec());
}
#[test]
fn test_is_local_and_is_s3() {
let local = UploadStorage::Local {
path: PathBuf::from("/tmp"),
};
assert!(local.is_local());
assert!(!local.is_s3());
}
#[test]
fn test_get_display_path_local() {
let storage = UploadStorage::Local {
path: PathBuf::from("/tmp/uploads"),
};
assert_eq!(
storage.get_display_path("file.txt", None),
"/tmp/uploads/file.txt"
);
assert_eq!(
storage.get_display_path("file.txt", Some("user_123")),
"/tmp/uploads/user_123/file.txt"
);
}
#[test]
fn test_multi_tenant_isolation() {
// Different users should have different paths
let storage = UploadStorage::Local {
path: PathBuf::from("/tmp/uploads"),
};
let path1 = storage.get_display_path("data.json", Some("user_1"));
let path2 = storage.get_display_path("data.json", Some("user_2"));
assert_ne!(path1, path2);
assert!(path1.contains("user_1"));
assert!(path2.contains("user_2"));
}
}