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
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
//! Geoprocessing service client implementation.

use crate::{ArcGISClient, BuilderError, Result};
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;
use tracing::instrument;

use super::types::{GPExecuteResult, GPJobInfo, GPMessage};

/// Client for interacting with ArcGIS Geoprocessing Services (GPServer).
///
/// The Geoprocessing Service enables execution of server-side geoprocessing tasks.
/// It supports both synchronous (immediate) and asynchronous (job-based) execution.
///
/// # Example
///
/// ```no_run
/// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient};
/// use std::collections::HashMap;
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let gp_service = GeoprocessingServiceClient::new(
///     "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/ESRI_Elevation_World/GPServer/ProfileService",
///     &client
/// );
///
/// // Execute synchronous task
/// let mut params = HashMap::new();
/// params.insert("InputParameter".to_string(), serde_json::json!("value"));
/// let result = gp_service.execute(params).await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct GeoprocessingServiceClient<'a> {
    /// Base URL of the geoprocessing service.
    url: String,

    /// Reference to the ArcGIS client.
    client: &'a ArcGISClient,
}

impl<'a> GeoprocessingServiceClient<'a> {
    /// Creates a new geoprocessing service client.
    ///
    /// # Arguments
    ///
    /// * `url` - Base URL of the geoprocessing service (e.g., `https://server/arcgis/rest/services/Folder/ServiceName/GPServer/TaskName`)
    /// * `client` - Reference to an [`ArcGISClient`] for making requests
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient};
    ///
    /// let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// let client = ArcGISClient::new(auth);
    /// let gp_service = GeoprocessingServiceClient::new(
    ///     "https://server/arcgis/rest/services/GP/MyTask/GPServer/Execute",
    ///     &client
    /// );
    /// ```
    pub fn new(url: impl Into<String>, client: &'a ArcGISClient) -> Self {
        GeoprocessingServiceClient {
            url: url.into(),
            client,
        }
    }

    /// Executes a synchronous geoprocessing task.
    ///
    /// Synchronous execution is appropriate for tasks that complete quickly (typically < 30 seconds).
    /// For longer-running tasks, use [`submit_job`](Self::submit_job) for asynchronous execution.
    ///
    /// # Arguments
    ///
    /// * `parameters` - HashMap of parameter name to parameter value (as JSON)
    ///
    /// # Returns
    ///
    /// Result containing execution results and messages.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient};
    /// use std::collections::HashMap;
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// let client = ArcGISClient::new(auth);
    /// let gp_service = GeoprocessingServiceClient::new(
    ///     "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/ESRI_Elevation_World/GPServer/ProfileService",
    ///     &client
    /// );
    ///
    /// let mut params = HashMap::new();
    /// params.insert("InputLineFeatures".to_string(), serde_json::json!({
    ///     "geometryType": "esriGeometryPolyline",
    ///     "features": []
    /// }));
    ///
    /// let result = gp_service.execute(params).await?;
    /// tracing::info!(result_count = result.results().len(), "Task completed");
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self, parameters), fields(param_count = parameters.len()))]
    pub async fn execute(&self, parameters: HashMap<String, Value>) -> Result<GPExecuteResult> {
        tracing::debug!("Executing synchronous geoprocessing task");

        let execute_url = format!("{}/execute", self.url);

        let mut form: Vec<(&str, String)> = Vec::new();
        form.push(("f", "json".to_string()));

        // Serialize parameters
        for (key, value) in parameters.iter() {
            let value_str = match value {
                // For string values, use the raw string without JSON encoding
                Value::String(s) => s.clone(),
                // For other types (objects, arrays, numbers), JSON-serialize them
                _ => serde_json::to_string(value)?,
            };
            form.push((key.as_str(), value_str));
        }

        let response = self
            .client
            .http()
            .post(&execute_url)
            .form(&form)
            .send()
            .await?;

        let result: GPExecuteResult = response.json().await?;

        tracing::debug!(
            result_count = result.results().len(),
            message_count = result.messages().len(),
            "Task execution completed"
        );

        Ok(result)
    }

    /// Submits an asynchronous geoprocessing job.
    ///
    /// Use this for long-running tasks. After submission, use [`get_job_status`](Self::get_job_status)
    /// to check progress and [`get_job_result`](Self::get_job_result) to retrieve results.
    ///
    /// # Arguments
    ///
    /// * `parameters` - HashMap of parameter name to parameter value (as JSON)
    ///
    /// # Returns
    ///
    /// Job information including the job ID.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient};
    /// use std::collections::HashMap;
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// let client = ArcGISClient::new(auth);
    /// let gp_service = GeoprocessingServiceClient::new(
    ///     "https://server/arcgis/rest/services/GP/LongTask/GPServer/Execute",
    ///     &client
    /// );
    ///
    /// let mut params = HashMap::new();
    /// params.insert("InputParameter".to_string(), serde_json::json!("value"));
    ///
    /// let job = gp_service.submit_job(params).await?;
    /// tracing::info!(job_id = %job.job_id(), "Job submitted");
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self, parameters), fields(param_count = parameters.len()))]
    pub async fn submit_job(&self, parameters: HashMap<String, Value>) -> Result<GPJobInfo> {
        tracing::debug!("Submitting asynchronous geoprocessing job");

        let submit_url = format!("{}/submitJob", self.url);
        tracing::debug!(url = %submit_url, "Submitting job to URL");

        let mut form: Vec<(&str, String)> = Vec::new();
        form.push(("f", "json".to_string()));

        // Add authentication token if required
        if let Some(token) = self.client.get_token_if_required().await? {
            tracing::debug!("Adding authentication token to request");
            form.push(("token", token));
        }

        // Serialize parameters
        for (key, value) in parameters.iter() {
            let value_str = match value {
                // For string values, use the raw string without JSON encoding
                Value::String(s) => s.clone(),
                // For other types (objects, arrays, numbers), JSON-serialize them
                _ => serde_json::to_string(value)?,
            };

            // Log parameter (truncate long values for readability)
            let display_value = if value_str.len() > 100 {
                format!("{}... ({} chars)", &value_str[..100], value_str.len())
            } else {
                value_str.clone()
            };
            tracing::debug!(param = %key, value = %display_value, "Adding parameter");

            form.push((key.as_str(), value_str));
        }

        let response = self
            .client
            .http()
            .post(&submit_url)
            .form(&form)
            .send()
            .await?;

        let status = response.status();
        tracing::debug!(status_code = %status, "Received response");

        // Get response text for better error reporting
        let response_text = response.text().await?;
        tracing::debug!(response_body = %response_text, "Raw response body");

        // Try to parse as GPJobInfo
        let job_info: GPJobInfo = serde_json::from_str(&response_text).map_err(|e| {
            tracing::error!(
                parse_error = %e,
                response = %response_text,
                "Failed to parse job submission response"
            );
            e
        })?;

        tracing::info!(
            job_id = %job_info.job_id(),
            status = ?job_info.job_status(),
            "Job submitted"
        );

        Ok(job_info)
    }

    /// Gets the current status of an asynchronous job.
    ///
    /// # Arguments
    ///
    /// * `job_id` - Job identifier returned from [`submit_job`](Self::submit_job)
    ///
    /// # Returns
    ///
    /// Current job information including status.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient};
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// # let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// # let client = ArcGISClient::new(auth);
    /// # let gp_service = GeoprocessingServiceClient::new("https://server/gp", &client);
    /// # let job_id = "job123";
    /// let status = gp_service.get_job_status(job_id).await?;
    /// tracing::info!(status = ?status.job_status(), "Job status");
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self), fields(job_id))]
    pub async fn get_job_status(&self, job_id: &str) -> Result<GPJobInfo> {
        tracing::debug!("Getting job status");

        let status_url = format!("{}/jobs/{}", self.url, job_id);
        tracing::debug!(url = %status_url, "Getting job status from URL");

        // Build query parameters
        let mut query_params = vec![("f", "json")];

        // Add authentication token if required
        let token_string;
        if let Some(token) = self.client.get_token_if_required().await? {
            tracing::debug!("Adding authentication token to status request");
            token_string = token;
            query_params.push(("token", token_string.as_str()));
        }

        let response = self
            .client
            .http()
            .get(&status_url)
            .query(&query_params)
            .send()
            .await?;

        let status = response.status();
        tracing::debug!(status_code = %status, "Received status response");

        // Get response text for better error reporting
        let response_text = response.text().await?;
        tracing::debug!(response_body = %response_text, "Raw status response body");

        // Try to parse as GPJobInfo
        let job_info: GPJobInfo = serde_json::from_str(&response_text).map_err(|e| {
            tracing::error!(
                parse_error = %e,
                response = %response_text,
                "Failed to parse job status response"
            );
            e
        })?;

        tracing::debug!(status = ?job_info.job_status(), "Job status retrieved");

        Ok(job_info)
    }

    /// Gets the results of a completed asynchronous job.
    ///
    /// The job must be in a completed state (succeeded) before calling this method.
    ///
    /// # Arguments
    ///
    /// * `job_id` - Job identifier
    ///
    /// # Returns
    ///
    /// Job information including results.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient, GPJobStatus};
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// # let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// # let client = ArcGISClient::new(auth);
    /// # let gp_service = GeoprocessingServiceClient::new("https://server/gp", &client);
    /// # let job_id = "job123";
    /// let result = gp_service.get_job_result(job_id).await?;
    /// if result.job_status() == &GPJobStatus::Succeeded {
    ///     tracing::info!(result_count = result.results().len(), "Job succeeded");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self), fields(job_id))]
    pub async fn get_job_result(&self, job_id: &str) -> Result<GPJobInfo> {
        tracing::debug!("Getting job result");

        // Get status first to ensure job is complete
        let job_info = self.get_job_status(job_id).await?;

        if !job_info.job_status().is_terminal() {
            tracing::warn!(
                status = ?job_info.job_status(),
                "Job is not in terminal state"
            );
        }

        Ok(job_info)
    }

    /// Cancels an asynchronous job.
    ///
    /// # Arguments
    ///
    /// * `job_id` - Job identifier to cancel
    ///
    /// # Returns
    ///
    /// Updated job information.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient};
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// # let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// # let client = ArcGISClient::new(auth);
    /// # let gp_service = GeoprocessingServiceClient::new("https://server/gp", &client);
    /// # let job_id = "job123";
    /// let result = gp_service.cancel_job(job_id).await?;
    /// tracing::info!("Job cancelled");
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self), fields(job_id))]
    pub async fn cancel_job(&self, job_id: &str) -> Result<GPJobInfo> {
        tracing::debug!("Cancelling job");

        let cancel_url = format!("{}/jobs/{}/cancel", self.url, job_id);

        let response = self
            .client
            .http()
            .post(&cancel_url)
            .form(&[("f", "json")])
            .send()
            .await?;

        let job_info: GPJobInfo = response.json().await?;

        tracing::info!(status = ?job_info.job_status(), "Job cancel requested");

        Ok(job_info)
    }

    /// Gets messages for an asynchronous job.
    ///
    /// # Arguments
    ///
    /// * `job_id` - Job identifier
    ///
    /// # Returns
    ///
    /// Vector of messages generated during job execution.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient};
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// # let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// # let client = ArcGISClient::new(auth);
    /// # let gp_service = GeoprocessingServiceClient::new("https://server/gp", &client);
    /// # let job_id = "job123";
    /// let messages = gp_service.get_job_messages(job_id).await?;
    /// for msg in messages.iter() {
    ///     tracing::info!(message_type = ?msg.message_type(), description = %msg.description());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self), fields(job_id))]
    pub async fn get_job_messages(&self, job_id: &str) -> Result<Vec<GPMessage>> {
        tracing::debug!("Getting job messages");

        let messages_url = format!("{}/jobs/{}/messages", self.url, job_id);
        tracing::debug!(url = %messages_url, "Getting job messages from URL");

        #[derive(Deserialize)]
        struct MessagesResponse {
            messages: Vec<GPMessage>,
        }

        // Build query parameters
        let mut query_params = vec![("f", "json")];

        // Add authentication token if required
        let token_string;
        if let Some(token) = self.client.get_token_if_required().await? {
            tracing::debug!("Adding authentication token to messages request");
            token_string = token;
            query_params.push(("token", token_string.as_str()));
        }

        let response = self
            .client
            .http()
            .get(&messages_url)
            .query(&query_params)
            .send()
            .await?;

        let messages_response: MessagesResponse = response.json().await?;

        tracing::debug!(
            message_count = messages_response.messages.len(),
            "Messages retrieved"
        );

        Ok(messages_response.messages)
    }

    /// Fetches the actual data for a specific result parameter.
    ///
    /// When a job completes, the result parameters may contain `paramUrl` instead of `value`.
    /// This method fetches the actual data from that URL.
    ///
    /// # Arguments
    ///
    /// * `job_id` - Job identifier
    /// * `param_name` - Name of the result parameter (e.g., "OutputSummary")
    ///
    /// # Returns
    ///
    /// The parameter value as JSON.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient};
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// # let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// # let client = ArcGISClient::new(auth);
    /// # let gp_service = GeoprocessingServiceClient::new("https://server/gp", &client);
    /// # let job_id = "job123";
    /// let value = gp_service.get_result_data(job_id, "OutputParameter").await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self), fields(job_id, param_name))]
    pub async fn get_result_data(&self, job_id: &str, param_name: &str) -> Result<Value> {
        tracing::debug!("Getting result data for parameter");

        let result_url = format!("{}/jobs/{}/results/{}", self.url, job_id, param_name);
        tracing::debug!(url = %result_url, "Fetching result data from URL");

        // Build query parameters
        let mut query_params = vec![("f", "json")];

        // Add authentication token if required
        let token_string;
        if let Some(token) = self.client.get_token_if_required().await? {
            tracing::debug!("Adding authentication token to result data request");
            token_string = token;
            query_params.push(("token", token_string.as_str()));
        }

        let response = self
            .client
            .http()
            .get(&result_url)
            .query(&query_params)
            .send()
            .await?;

        let status = response.status();
        tracing::debug!(status_code = %status, "Received result data response");

        // Get response text
        let response_text = response.text().await?;
        tracing::debug!(response_body = %response_text, "Raw result data response");

        // Parse as JSON
        let result_json: Value = serde_json::from_str(&response_text).map_err(|e| {
            tracing::error!(
                parse_error = %e,
                response = %response_text,
                "Failed to parse result data response"
            );
            e
        })?;

        tracing::debug!("Result data retrieved and parsed");

        Ok(result_json)
    }

    /// Polls a job until it reaches a terminal state (succeeded, failed, etc.).
    ///
    /// This is a convenience method that repeatedly checks job status with exponential backoff.
    ///
    /// # Arguments
    ///
    /// * `job_id` - Job identifier
    /// * `initial_delay_ms` - Initial delay between polls in milliseconds (default: 1000)
    /// * `max_delay_ms` - Maximum delay between polls in milliseconds (default: 30000)
    /// * `timeout_ms` - Optional timeout in milliseconds (None for no timeout)
    ///
    /// # Returns
    ///
    /// Final job information when terminal state is reached.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, GeoprocessingServiceClient};
    /// use std::collections::HashMap;
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// let client = ArcGISClient::new(auth);
    /// let gp_service = GeoprocessingServiceClient::new("https://server/gp", &client);
    ///
    /// let mut params = HashMap::new();
    /// params.insert("Input".to_string(), serde_json::json!("value"));
    ///
    /// let job = gp_service.submit_job(params).await?;
    /// let result = gp_service.poll_until_complete(job.job_id(), 1000, 30000, None).await?;
    /// tracing::info!(status = ?result.job_status(), "Job complete");
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self), fields(job_id, initial_delay_ms, max_delay_ms, timeout_ms))]
    pub async fn poll_until_complete(
        &self,
        job_id: &str,
        initial_delay_ms: u64,
        max_delay_ms: u64,
        timeout_ms: Option<u64>,
    ) -> Result<GPJobInfo> {
        use tokio::time::{Duration, Instant, sleep};

        tracing::info!("Polling job until complete");

        let start_time = Instant::now();
        let mut delay_ms = initial_delay_ms;

        loop {
            // Check timeout
            if let Some(timeout) = timeout_ms {
                if start_time.elapsed().as_millis() > timeout as u128 {
                    tracing::error!("Job polling timed out");
                    return Err(BuilderError::new(format!(
                        "Job polling timed out after {}ms",
                        timeout
                    ))
                    .into());
                }
            }

            // Get job status
            let job_info = self.get_job_status(job_id).await?;

            tracing::debug!(
                status = ?job_info.job_status(),
                elapsed_ms = start_time.elapsed().as_millis(),
                "Polling job"
            );

            // Check if terminal state
            if job_info.job_status().is_terminal() {
                tracing::info!(
                    status = ?job_info.job_status(),
                    elapsed_ms = start_time.elapsed().as_millis(),
                    "Job reached terminal state"
                );
                return Ok(job_info);
            }

            // Wait before next poll with exponential backoff
            sleep(Duration::from_millis(delay_ms)).await;
            delay_ms = (delay_ms * 2).min(max_delay_ms);
        }
    }
}