arcgis 0.1.3

Type-safe Rust SDK for the ArcGIS REST API with compile-time guarantees
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
//! Attachment operations for Feature Services.
//!
//! Feature attachments allow you to associate files (images, PDFs, etc.)
//! with individual features. Each feature can have multiple attachments.
//!
//! # Operations
//!
//! - [`query_attachments`](super::FeatureServiceClient::query_attachments) - List attachments for a feature
//! - [`add_attachment`](super::FeatureServiceClient::add_attachment) - Add a new attachment
//! - [`update_attachment`](super::FeatureServiceClient::update_attachment) - Update an existing attachment
//! - [`delete_attachments`](super::FeatureServiceClient::delete_attachments) - Delete one or more attachments
//! - [`download_attachment`](super::FeatureServiceClient::download_attachment) - Download attachment data
//!
//! # Example
//!
//! ```no_run
//! use arcgis::{ArcGISClient, ApiKeyAuth, FeatureServiceClient, LayerId, ObjectId, AttachmentSource, DownloadTarget};
//!
//! # 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);
//!
//! // Query attachments for a feature
//! let attachments = service
//!     .query_attachments(LayerId::new(0), ObjectId::new(123))
//!     .await?;
//!
//! println!("Feature has {} attachments", attachments.len());
//!
//! // Add attachment from file
//! service
//!     .add_attachment(
//!         LayerId::new(0),
//!         ObjectId::new(123),
//!         AttachmentSource::from_path("photo.jpg"),
//!     )
//!     .await?;
//!
//! // Download attachment
//! if let Some(attachment) = attachments.first() {
//!     service
//!         .download_attachment(
//!             LayerId::new(0),
//!             ObjectId::new(123),
//!             *attachment.id(),
//!             DownloadTarget::Path("downloaded.jpg".into()),
//!         )
//!         .await?;
//! }
//! # Ok(())
//! # }
//! ```

use crate::AttachmentId;
use derive_getters::Getters;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::io::{AsyncRead, AsyncWrite};

/// Information about a feature attachment.
///
/// Returned by [`query_attachments`](super::FeatureServiceClient::query_attachments).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Getters)]
#[serde(rename_all = "camelCase")]
pub struct AttachmentInfo {
    /// Unique identifier for the attachment.
    id: AttachmentId,

    /// Attachment filename.
    name: String,

    /// File size in bytes.
    size: u64,

    /// MIME type of the attachment.
    content_type: String,

    /// Optional keywords/tags for the attachment.
    #[serde(skip_serializing_if = "Option::is_none")]
    keywords: Option<String>,
}

/// Response from querying attachments.
///
/// Contains an array of attachment info objects.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AttachmentInfosResponse {
    /// Array of attachments for the feature.
    pub attachment_infos: Vec<AttachmentInfo>,
}

/// Result of adding an attachment.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Getters)]
#[serde(rename_all = "camelCase")]
pub struct AddAttachmentResult {
    /// ObjectID of the feature the attachment was added to (optional in some API responses).
    #[serde(default)]
    object_id: Option<crate::ObjectId>,

    /// GlobalID of the newly created attachment (if enabled).
    #[serde(skip_serializing_if = "Option::is_none")]
    global_id: Option<String>,

    /// Whether the operation succeeded.
    success: bool,
}

/// Wrapper for addAttachment API response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AddAttachmentResponse {
    /// The nested result object.
    pub(crate) add_attachment_result: AddAttachmentResult,
}

/// Result of updating an attachment.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Getters)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAttachmentResult {
    /// ObjectID of the feature.
    object_id: crate::ObjectId,

    /// Whether the operation succeeded.
    success: bool,
}

/// Wrapper for updateAttachment API response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct UpdateAttachmentResponse {
    /// The nested result object.
    pub(crate) update_attachment_result: UpdateAttachmentResult,
}

/// Response from deleting attachments.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteAttachmentsResponse {
    /// Array of delete results (one per attachment).
    pub delete_attachment_results: Vec<DeleteAttachmentResult>,
}

/// Individual result for a single attachment deletion.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Getters)]
#[serde(rename_all = "camelCase")]
pub struct DeleteAttachmentResult {
    /// ObjectID of the feature.
    object_id: crate::ObjectId,

    /// GlobalID of the attachment (if enabled).
    #[serde(skip_serializing_if = "Option::is_none")]
    global_id: Option<String>,

    /// Whether the operation succeeded.
    success: bool,
}

/// Source for attachment file data.
///
/// Supports loading from a file path, in-memory bytes, or async stream.
pub enum AttachmentSource {
    /// Stream from file path (efficient for large files).
    ///
    /// The file will be opened asynchronously and streamed to the server
    /// without loading the entire file into memory.
    Path(PathBuf),

    /// Use in-memory bytes (convenient for small files or generated data).
    ///
    /// The entire file content is held in memory during upload.
    Bytes {
        /// Filename to use for the attachment.
        filename: String,
        /// File data.
        data: Vec<u8>,
        /// Optional explicit content type. If None, will be guessed from filename.
        content_type: Option<String>,
    },

    /// Stream from async reader (advanced use cases).
    ///
    /// Allows streaming from any AsyncRead source. Useful for piping data
    /// from other sources without intermediate buffering.
    Stream {
        /// Filename to use for the attachment.
        filename: String,
        /// Async reader providing the file data.
        reader: Box<dyn AsyncRead + Send + Sync + Unpin>,
        /// MIME content type.
        content_type: String,
        /// Optional known size (helps with progress tracking).
        size: Option<u64>,
    },
}

impl AttachmentSource {
    /// Creates an attachment source from a file path.
    ///
    /// The file will be streamed efficiently without loading into memory.
    ///
    /// # Example
    ///
    /// ```
    /// use arcgis::AttachmentSource;
    ///
    /// let source = AttachmentSource::from_path("/path/to/photo.jpg");
    /// ```
    pub fn from_path(path: impl Into<PathBuf>) -> Self {
        Self::Path(path.into())
    }

    /// Creates an attachment source from in-memory bytes.
    ///
    /// Content type will be auto-detected from the filename extension.
    ///
    /// # Example
    ///
    /// ```
    /// use arcgis::AttachmentSource;
    ///
    /// let data = vec![0xFF, 0xD8, 0xFF]; // JPEG data...
    /// let source = AttachmentSource::from_bytes("photo.jpg", data);
    /// ```
    pub fn from_bytes(filename: impl Into<String>, data: Vec<u8>) -> Self {
        Self::Bytes {
            filename: filename.into(),
            data,
            content_type: None,
        }
    }

    /// Creates an attachment source from in-memory bytes with explicit content type.
    ///
    /// # Example
    ///
    /// ```
    /// use arcgis::AttachmentSource;
    ///
    /// let data = vec![0x25, 0x50, 0x44, 0x46]; // PDF data...
    /// let source = AttachmentSource::from_bytes_with_type(
    ///     "document.pdf",
    ///     data,
    ///     "application/pdf",
    /// );
    /// ```
    pub fn from_bytes_with_type(
        filename: impl Into<String>,
        data: Vec<u8>,
        content_type: impl Into<String>,
    ) -> Self {
        Self::Bytes {
            filename: filename.into(),
            data,
            content_type: Some(content_type.into()),
        }
    }

    /// Creates an attachment source from an async reader.
    ///
    /// This is an advanced method for streaming from arbitrary sources.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::AttachmentSource;
    /// use tokio::fs::File;
    ///
    /// # async fn example() -> std::io::Result<()> {
    /// let file = File::open("large_file.zip").await?;
    /// let source = AttachmentSource::from_stream(
    ///     "large_file.zip",
    ///     Box::new(file),
    ///     "application/zip",
    ///     Some(1024 * 1024 * 100), // 100 MB
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_stream(
        filename: impl Into<String>,
        reader: Box<dyn AsyncRead + Send + Sync + Unpin>,
        content_type: impl Into<String>,
        size: Option<u64>,
    ) -> Self {
        Self::Stream {
            filename: filename.into(),
            reader,
            content_type: content_type.into(),
            size,
        }
    }
}

/// Target for attachment download.
///
/// Specifies where to write the downloaded attachment data.
pub enum DownloadTarget {
    /// Download to file path.
    ///
    /// The file will be created (or overwritten) and data streamed to it.
    Path(PathBuf),

    /// Download to in-memory bytes.
    ///
    /// Returns `Vec<u8>` containing the entire attachment. Use for small files only.
    Bytes,

    /// Stream to async writer.
    ///
    /// Allows writing to any AsyncWrite destination.
    Writer(Box<dyn AsyncWrite + Send + Sync + Unpin>),
}

impl DownloadTarget {
    /// Creates a download target for a file path.
    ///
    /// # Example
    ///
    /// ```
    /// use arcgis::DownloadTarget;
    ///
    /// let target = DownloadTarget::to_path("/path/to/save/photo.jpg");
    /// ```
    pub fn to_path(path: impl Into<PathBuf>) -> Self {
        Self::Path(path.into())
    }

    /// Creates a download target for in-memory bytes.
    ///
    /// # Example
    ///
    /// ```
    /// use arcgis::DownloadTarget;
    ///
    /// let target = DownloadTarget::to_bytes();
    /// ```
    pub fn to_bytes() -> Self {
        Self::Bytes
    }

    /// Creates a download target for an async writer.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::DownloadTarget;
    /// use tokio::fs::File;
    ///
    /// # async fn example() -> std::io::Result<()> {
    /// let file = File::create("output.dat").await?;
    /// let target = DownloadTarget::to_writer(Box::new(file));
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_writer(writer: Box<dyn AsyncWrite + Send + Sync + Unpin>) -> Self {
        Self::Writer(writer)
    }
}

/// Result of downloading an attachment.
///
/// The variant matches the `DownloadTarget` used.
#[derive(Debug)]
pub enum DownloadResult {
    /// File written to path.
    ///
    /// Contains the path where the file was written.
    Path(PathBuf),

    /// Bytes loaded into memory.
    ///
    /// Contains the attachment data.
    Bytes(Vec<u8>),

    /// Bytes written to writer.
    ///
    /// Contains the number of bytes written.
    Written(u64),
}

impl DownloadResult {
    /// Returns the path if this is a Path result.
    pub fn path(&self) -> Option<&PathBuf> {
        match self {
            Self::Path(p) => Some(p),
            _ => None,
        }
    }

    /// Returns the bytes if this is a Bytes result.
    pub fn bytes(&self) -> Option<&[u8]> {
        match self {
            Self::Bytes(b) => Some(b),
            _ => None,
        }
    }

    /// Returns the bytes count if this is a Written result.
    pub fn written(&self) -> Option<u64> {
        match self {
            Self::Written(n) => Some(*n),
            _ => None,
        }
    }

    /// Consumes the result and returns the bytes if this is a Bytes result.
    pub fn into_bytes(self) -> Option<Vec<u8>> {
        match self {
            Self::Bytes(b) => Some(b),
            _ => None,
        }
    }
}