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
//! Attachment operations for the Feature Service client.
use super::super::{
AddAttachmentResult, AttachmentInfo, AttachmentInfosResponse, AttachmentSource,
DeleteAttachmentsResponse, DownloadResult, DownloadTarget,
};
use super::FeatureServiceClient;
use crate::{AttachmentId, LayerId, ObjectId, Result};
use futures::StreamExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tracing::instrument;
impl<'a> FeatureServiceClient<'a> {
/// Queries attachments for a specific feature.
///
/// Returns metadata about all attachments associated with the feature.
/// To download attachment data, use [`download_attachment`](Self::download_attachment).
///
/// # Arguments
///
/// * `layer_id` - The layer containing the feature
/// * `object_id` - The feature to query attachments for
///
/// # Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ApiKeyAuth, FeatureServiceClient, LayerId, ObjectId};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = FeatureServiceClient::new("https://example.com/FeatureServer", &client);
///
/// let attachments = service
/// .query_attachments(LayerId::new(0), ObjectId::new(123))
/// .await?;
///
/// for attachment in &attachments {
/// println!("Attachment: {} ({} bytes)", attachment.name(), attachment.size());
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self), fields(layer_id = %layer_id, object_id = %object_id))]
pub async fn query_attachments(
&self,
layer_id: LayerId,
object_id: ObjectId,
) -> Result<Vec<AttachmentInfo>> {
tracing::debug!("Querying attachments for feature");
let url = format!("{}/{}/{}/attachments", self.base_url, layer_id, object_id);
tracing::debug!(url = %url, "Sending queryAttachments request");
let mut request = self.client.http().get(&url).query(&[("f", "json")]);
if let Some(token) = self.client.get_token_if_required().await? {
request = request.query(&[("token", token)]);
}
let response = request.send().await?;
let status = response.status();
if !status.is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error: {}", e));
tracing::error!(status = %status, error = %error_text, "queryAttachments failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let result: AttachmentInfosResponse = response.json().await?;
tracing::info!(
attachment_count = result.attachment_infos.len(),
"queryAttachments completed"
);
Ok(result.attachment_infos)
}
/// Deletes one or more attachments from a feature.
///
/// # Arguments
///
/// * `layer_id` - The layer containing the feature
/// * `object_id` - The feature that owns the attachments
/// * `attachment_ids` - Vector of attachment IDs to delete
///
/// # Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ApiKeyAuth, FeatureServiceClient, LayerId, ObjectId, AttachmentId};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = FeatureServiceClient::new("https://example.com/FeatureServer", &client);
///
/// let ids_to_delete = vec![AttachmentId::new(1), AttachmentId::new(2)];
///
/// let result = service
/// .delete_attachments(LayerId::new(0), ObjectId::new(123), ids_to_delete)
/// .await?;
///
/// for item in &result.delete_attachment_results {
/// if *item.success() {
/// println!("Deleted attachment from feature {}", item.object_id());
/// }
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, attachment_ids), fields(layer_id = %layer_id, object_id = %object_id, count = attachment_ids.len()))]
pub async fn delete_attachments(
&self,
layer_id: LayerId,
object_id: ObjectId,
attachment_ids: Vec<AttachmentId>,
) -> Result<DeleteAttachmentsResponse> {
tracing::debug!("Deleting attachments from feature");
let url = format!(
"{}/{}/{}/deleteAttachments",
self.base_url, layer_id, object_id
);
// Convert AttachmentIds to comma-separated string
let attachment_ids_str = attachment_ids
.iter()
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(",");
tracing::debug!(
url = %url,
attachment_ids = %attachment_ids_str,
"Sending deleteAttachments request"
);
let mut form = vec![
("attachmentIds", attachment_ids_str.as_str()),
("f", "json"),
];
// Add token if required by auth provider
let token_opt = self.client.get_token_if_required().await?;
let token_str;
if let Some(token) = token_opt {
token_str = token;
form.push(("token", token_str.as_str()));
}
let response = self.client.http().post(&url).form(&form).send().await?;
let status = response.status();
if !status.is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error: {}", e));
tracing::error!(status = %status, error = %error_text, "deleteAttachments failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let result: DeleteAttachmentsResponse = response.json().await?;
let success_count = result
.delete_attachment_results
.iter()
.filter(|r| *r.success())
.count();
tracing::info!(
success_count = success_count,
total_count = result.delete_attachment_results.len(),
"deleteAttachments completed"
);
Ok(result)
}
/// Adds an attachment to a feature.
///
/// Uploads a file and associates it with the specified feature.
/// Supports streaming for efficient handling of large files.
///
/// # Arguments
///
/// * `layer_id` - The layer containing the feature
/// * `object_id` - The feature to attach the file to
/// * `source` - The attachment source (file path, bytes, or stream)
///
/// # Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ApiKeyAuth, FeatureServiceClient, LayerId, ObjectId, AttachmentSource};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = FeatureServiceClient::new("https://example.com/FeatureServer", &client);
///
/// // From file path (streaming)
/// let result = service
/// .add_attachment(
/// LayerId::new(0),
/// ObjectId::new(123),
/// AttachmentSource::from_path("/path/to/photo.jpg"),
/// )
/// .await?;
///
/// if *result.success() {
/// println!("Attachment added successfully");
/// }
///
/// // From bytes
/// let image_data = vec![0xFF, 0xD8, 0xFF]; // JPEG header...
/// let result = service
/// .add_attachment(
/// LayerId::new(0),
/// ObjectId::new(456),
/// AttachmentSource::from_bytes("photo.jpg", image_data),
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, source), fields(layer_id = %layer_id, object_id = %object_id))]
pub async fn add_attachment(
&self,
layer_id: LayerId,
object_id: ObjectId,
source: AttachmentSource,
) -> Result<AddAttachmentResult> {
tracing::debug!("Adding attachment to feature");
let url = format!("{}/{}/{}/addAttachment", self.base_url, layer_id, object_id);
// Build multipart form
let mut form = reqwest::multipart::Form::new();
// Add the file part based on source
match source {
AttachmentSource::Path(path) => {
tracing::debug!(path = %path.display(), "Loading attachment from file");
// Get filename
let filename = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("attachment")
.to_string();
// Open file for streaming
let file = tokio::fs::File::open(&path).await?;
let metadata = file.metadata().await?;
let file_size = metadata.len();
// Detect content type
let content_type = mime_guess::from_path(&path)
.first_or_octet_stream()
.to_string();
tracing::debug!(
filename = %filename,
content_type = %content_type,
size = file_size,
"File opened for streaming"
);
// Create streaming body
let part = reqwest::multipart::Part::stream(reqwest::Body::from(file))
.file_name(filename)
.mime_str(&content_type)?;
form = form.part("attachment", part);
}
AttachmentSource::Bytes {
filename,
data,
content_type,
} => {
tracing::debug!(
filename = %filename,
size = data.len(),
"Using in-memory attachment data"
);
let content_type = content_type.unwrap_or_else(|| {
mime_guess::from_path(&filename)
.first_or_octet_stream()
.to_string()
});
tracing::debug!(content_type = %content_type, "Content type determined");
let part = reqwest::multipart::Part::bytes(data)
.file_name(filename)
.mime_str(&content_type)?;
form = form.part("attachment", part);
}
AttachmentSource::Stream {
filename,
mut reader,
content_type,
size,
} => {
tracing::debug!(
filename = %filename,
size = ?size,
"Streaming from async reader"
);
// Read from the async reader into a buffer
let mut buffer = Vec::new();
reader.read_to_end(&mut buffer).await?;
tracing::debug!(bytes_read = buffer.len(), "Data read from stream");
let part = reqwest::multipart::Part::bytes(buffer)
.file_name(filename)
.mime_str(&content_type)?;
form = form.part("attachment", part);
}
}
// Add standard parameters
form = form.text("f", "json");
// Add token if required by auth provider
if let Some(token) = self.client.get_token_if_required().await? {
form = form.text("token", token);
}
tracing::debug!(url = %url, "Sending addAttachment request");
let response = self.client.http().post(&url).multipart(form).send().await?;
let status = response.status();
if !status.is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error: {}", e));
tracing::error!(status = %status, error = %error_text, "addAttachment failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
// Get raw response text for debugging
let response_text = response.text().await?;
tracing::debug!(response = %response_text, "addAttachment raw response");
let response_wrapper: crate::services::feature::attachment::AddAttachmentResponse =
serde_json::from_str(&response_text)?;
let result = response_wrapper.add_attachment_result;
tracing::info!(
success = result.success(),
object_id = ?result.object_id(),
"addAttachment completed"
);
Ok(result)
}
/// Updates an existing attachment.
///
/// Replaces the attachment file while keeping the same attachment ID.
/// Supports streaming for efficient handling of large files.
///
/// # Arguments
///
/// * `layer_id` - The layer containing the feature
/// * `object_id` - The feature that owns the attachment
/// * `attachment_id` - The attachment to update
/// * `source` - The new attachment source (file path, bytes, or stream)
///
/// # Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ApiKeyAuth, FeatureServiceClient, LayerId, ObjectId, AttachmentId, AttachmentSource};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = FeatureServiceClient::new("https://example.com/FeatureServer", &client);
///
/// let result = service
/// .update_attachment(
/// LayerId::new(0),
/// ObjectId::new(123),
/// AttachmentId::new(5),
/// AttachmentSource::from_path("/path/to/updated_photo.jpg"),
/// )
/// .await?;
///
/// if *result.success() {
/// println!("Attachment updated successfully");
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, source), fields(layer_id = %layer_id, object_id = %object_id, attachment_id = %attachment_id))]
pub async fn update_attachment(
&self,
layer_id: LayerId,
object_id: ObjectId,
attachment_id: AttachmentId,
source: AttachmentSource,
) -> Result<crate::UpdateAttachmentResult> {
tracing::debug!("Updating attachment");
let url = format!(
"{}/{}/{}/updateAttachment",
self.base_url, layer_id, object_id
);
// Build multipart form
let mut form = reqwest::multipart::Form::new();
// Add attachment ID
form = form.text("attachmentId", attachment_id.to_string());
// Add the file part based on source
match source {
AttachmentSource::Path(path) => {
tracing::debug!(path = %path.display(), "Loading attachment from file");
let filename = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("attachment")
.to_string();
let file = tokio::fs::File::open(&path).await?;
let metadata = file.metadata().await?;
let file_size = metadata.len();
let content_type = mime_guess::from_path(&path)
.first_or_octet_stream()
.to_string();
tracing::debug!(
filename = %filename,
content_type = %content_type,
size = file_size,
"File opened for streaming"
);
let part = reqwest::multipart::Part::stream(reqwest::Body::from(file))
.file_name(filename)
.mime_str(&content_type)?;
form = form.part("attachment", part);
}
AttachmentSource::Bytes {
filename,
data,
content_type,
} => {
tracing::debug!(
filename = %filename,
size = data.len(),
"Using in-memory attachment data"
);
let content_type = content_type.unwrap_or_else(|| {
mime_guess::from_path(&filename)
.first_or_octet_stream()
.to_string()
});
tracing::debug!(content_type = %content_type, "Content type determined");
let part = reqwest::multipart::Part::bytes(data)
.file_name(filename)
.mime_str(&content_type)?;
form = form.part("attachment", part);
}
AttachmentSource::Stream {
filename,
mut reader,
content_type,
size,
} => {
tracing::debug!(
filename = %filename,
size = ?size,
"Streaming from async reader"
);
let mut buffer = Vec::new();
reader.read_to_end(&mut buffer).await?;
tracing::debug!(bytes_read = buffer.len(), "Data read from stream");
let part = reqwest::multipart::Part::bytes(buffer)
.file_name(filename)
.mime_str(&content_type)?;
form = form.part("attachment", part);
}
}
// Add standard parameters
form = form.text("f", "json");
// Add token if required by auth provider
if let Some(token) = self.client.get_token_if_required().await? {
form = form.text("token", token);
}
tracing::debug!(url = %url, "Sending updateAttachment request");
let response = self.client.http().post(&url).multipart(form).send().await?;
let status = response.status();
if !status.is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error: {}", e));
tracing::error!(status = %status, error = %error_text, "updateAttachment failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let response_text = response.text().await?;
tracing::debug!(response = %response_text, "updateAttachment raw response");
let response_wrapper: crate::services::feature::attachment::UpdateAttachmentResponse =
serde_json::from_str(&response_text)?;
let result = response_wrapper.update_attachment_result;
tracing::info!(
success = result.success(),
object_id = %result.object_id(),
"updateAttachment completed"
);
Ok(result)
}
/// Downloads an attachment from a feature.
///
/// Streams the attachment data to the specified target (file, bytes, or writer).
/// Efficient for large files as it doesn't load the entire file into memory unless
/// using the Bytes target.
///
/// # Arguments
///
/// * `layer_id` - The layer containing the feature
/// * `object_id` - The feature that owns the attachment
/// * `attachment_id` - The attachment to download
/// * `target` - Where to write the downloaded data
///
/// # Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ApiKeyAuth, FeatureServiceClient, LayerId, ObjectId, AttachmentId, DownloadTarget};
/// use std::path::PathBuf;
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = FeatureServiceClient::new("https://example.com/FeatureServer", &client);
///
/// // Download to file (streaming)
/// let result = service
/// .download_attachment(
/// LayerId::new(0),
/// ObjectId::new(123),
/// AttachmentId::new(5),
/// DownloadTarget::to_path("/path/to/save/photo.jpg"),
/// )
/// .await?;
///
/// if let Some(path) = result.path() {
/// println!("Downloaded to {:?}", path);
/// }
///
/// // Download to memory
/// let result = service
/// .download_attachment(
/// LayerId::new(0),
/// ObjectId::new(123),
/// AttachmentId::new(6),
/// DownloadTarget::to_bytes(),
/// )
/// .await?;
///
/// if let Some(bytes) = result.bytes() {
/// println!("Downloaded {} bytes", bytes.len());
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, target), fields(layer_id = %layer_id, object_id = %object_id, attachment_id = %attachment_id))]
pub async fn download_attachment(
&self,
layer_id: LayerId,
object_id: ObjectId,
attachment_id: AttachmentId,
target: DownloadTarget,
) -> Result<DownloadResult> {
tracing::debug!("Downloading attachment");
let url = format!(
"{}/{}/{}/attachments/{}",
self.base_url, layer_id, object_id, attachment_id
);
tracing::debug!(url = %url, "Sending download request");
let mut request = self.client.http().get(&url);
if let Some(token) = self.client.get_token_if_required().await? {
request = request.query(&[("token", token)]);
}
let response = request.send().await?;
let status = response.status();
if !status.is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error: {}", e));
tracing::error!(status = %status, error = %error_text, "download attachment failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
// Stream the response based on target
match target {
DownloadTarget::Path(path) => {
tracing::debug!(path = %path.display(), "Streaming to file");
let mut file = tokio::fs::File::create(&path).await?;
let mut stream = response.bytes_stream();
let mut total_bytes = 0u64;
while let Some(chunk_result) = stream.next().await {
let chunk = chunk_result?;
file.write_all(&chunk).await?;
total_bytes += chunk.len() as u64;
}
file.flush().await?;
tracing::info!(
path = %path.display(),
bytes = total_bytes,
"Download to file completed"
);
Ok(DownloadResult::Path(path))
}
DownloadTarget::Bytes => {
tracing::debug!("Collecting bytes to memory");
let mut stream = response.bytes_stream();
let mut buffer = Vec::new();
while let Some(chunk_result) = stream.next().await {
let chunk = chunk_result?;
buffer.extend_from_slice(&chunk);
}
tracing::info!(bytes = buffer.len(), "Download to bytes completed");
Ok(DownloadResult::Bytes(buffer))
}
DownloadTarget::Writer(mut writer) => {
tracing::debug!("Streaming to writer");
let mut stream = response.bytes_stream();
let mut total_bytes = 0u64;
while let Some(chunk_result) = stream.next().await {
let chunk = chunk_result?;
writer.write_all(&chunk).await?;
total_bytes += chunk.len() as u64;
}
writer.flush().await?;
tracing::info!(bytes = total_bytes, "Download to writer completed");
Ok(DownloadResult::Written(total_bytes))
}
}
}
}