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
//! Map service client implementation.
use super::ResponseFormat;
use crate::{
ArcGISClient, ExportMapParams, ExportMapResponse, ExportResult, ExportTarget, IdentifyParams,
IdentifyResponse, LegendResponse, MapServiceMetadata, Result, TileCoordinate,
};
use futures::StreamExt;
use tokio::io::AsyncWriteExt;
use tracing::instrument;
/// Client for interacting with an ArcGIS Map Service.
///
/// Map Services provide dynamic map rendering, cached tiles, metadata,
/// legend information, and feature identification capabilities.
///
/// # Example
///
/// ```no_run
/// use arcgis::{ApiKeyAuth, ArcGISClient, MapServiceClient, ExportTarget};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
///
/// let map_service = MapServiceClient::new(
/// "https://services.arcgis.com/org/arcgis/rest/services/MapName/MapServer",
/// &client,
/// );
///
/// // Export a map image
/// let result = map_service
/// .export()
/// .bbox("-180,-90,180,90")
/// .size(800, 600)
/// .execute(ExportTarget::to_path("map.png"))
/// .await?;
/// # Ok(())
/// # }
/// ```
pub struct MapServiceClient<'a> {
/// Base URL of the map service.
base_url: String,
/// Reference to the ArcGIS client for HTTP operations.
client: &'a ArcGISClient,
}
impl<'a> MapServiceClient<'a> {
/// Creates a new Map Service client.
///
/// # Arguments
///
/// * `base_url` - The base URL of the map service (e.g., `https://services.arcgis.com/.../MapServer`)
/// * `client` - Reference to an authenticated ArcGIS client
///
/// # Example
///
/// ```no_run
/// use arcgis::{ApiKeyAuth, ArcGISClient, MapServiceClient};
///
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
///
/// let map_service = MapServiceClient::new(
/// "https://services.arcgis.com/org/arcgis/rest/services/MapName/MapServer",
/// &client,
/// );
/// ```
#[instrument(skip(base_url, client))]
pub fn new(base_url: impl Into<String>, client: &'a ArcGISClient) -> Self {
let base_url = base_url.into();
tracing::debug!(base_url = %base_url, "Creating MapServiceClient");
Self { base_url, client }
}
/// Creates a fluent builder for exporting maps.
///
/// This is the recommended way to export maps. It provides a more
/// ergonomic API than manually constructing [`ExportMapParams`].
///
/// # Example
///
/// ```no_run
/// use arcgis::{ApiKeyAuth, ArcGISClient, MapServiceClient, ExportTarget, ImageFormat};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new(
/// "https://services.arcgis.com/org/arcgis/rest/services/World/MapServer",
/// &client,
/// );
///
/// // Use the fluent export builder
/// let result = service
/// .export()
/// .bbox("-118.0,34.0,-117.0,35.0")
/// .size(800, 600)
/// .format(ImageFormat::Png32)
/// .transparent(true)
/// .execute(ExportTarget::to_bytes())
/// .await?;
///
/// if let Some(bytes) = result.bytes() {
/// println!("Exported {} bytes", bytes.len());
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self), fields(base_url = %self.base_url))]
pub fn export(&'a self) -> super::ExportMapBuilder<'a> {
tracing::debug!("Creating export builder");
super::ExportMapBuilder::new(self)
}
/// Exports a map with pre-built parameters.
///
/// For most use cases, prefer using the fluent [`export()`](Self::export) builder.
/// This method is useful when you need to construct parameters programmatically
/// or reuse the same parameters multiple times.
///
/// # Arguments
///
/// * `params` - Export parameters (bbox is required)
/// * `target` - Where to write the exported image (Path, Bytes, or Writer)
///
/// # Example
///
/// ```no_run
/// use arcgis::{
/// ApiKeyAuth, ArcGISClient, MapServiceClient, ExportMapParams,
/// ExportMapParamsBuilder, ExportTarget, ImageFormat,
/// };
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new("https://example.com/MapServer", &client);
///
/// let params = ExportMapParamsBuilder::default()
/// .bbox("-118.0,34.0,-117.0,35.0".to_string())
/// .size("800,600".to_string())
/// .format(ImageFormat::Png32)
/// .build()
/// .expect("Valid params");
///
/// let result = service
/// .export_map(params, ExportTarget::to_path("map.png"))
/// .await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, params, target), fields(bbox = %params.bbox(), size = ?params.size()))]
pub async fn export_map(
&self,
params: ExportMapParams,
target: ExportTarget,
) -> Result<ExportResult> {
tracing::debug!("Exporting map");
// Validate required parameters
if params.bbox().is_empty() {
tracing::error!("bbox parameter is required but empty");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: 400,
message: "bbox parameter is required".to_string(),
}));
}
let url = format!("{}/export", self.base_url);
let token_opt = self.client.get_token_if_required().await?;
tracing::debug!(url = %url, "Sending export request");
// Handle different response formats
match params.format_response() {
ResponseFormat::Image => {
// Direct binary response - stream immediately
self.stream_export(&url, ¶ms, token_opt.as_deref(), target)
.await
}
ResponseFormat::Json | ResponseFormat::PJson => {
// JSON response with href - fetch image from href
self.export_via_json(&url, ¶ms, token_opt.as_deref(), target)
.await
}
_ => {
tracing::error!(format = ?params.format_response(), "Unsupported response format");
Err(crate::Error::from(crate::ErrorKind::Api {
code: 400,
message: format!(
"Unsupported response format: {:?}",
params.format_response()
),
}))
}
}
}
/// Exports a tile from a cached map service.
///
/// Retrieves a specific tile from a tiled/cached map service.
/// Not all map services support tiles - check service metadata first.
///
/// # Arguments
///
/// * `coord` - Tile coordinate (level, row, column)
/// * `target` - Where to write the tile image (Path, Bytes, or Writer)
///
/// # Example
///
/// ```no_run
/// use arcgis::{ApiKeyAuth, ArcGISClient, MapServiceClient, TileCoordinate, ExportTarget};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new("https://example.com/MapServer", &client);
///
/// // Get tile at level 5, row 10, column 15
/// let coord = TileCoordinate::new(5, 10, 15);
/// let result = service
/// .export_tile(coord, ExportTarget::to_bytes())
/// .await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, target), fields(level = coord.level(), row = coord.row(), col = coord.col()))]
pub async fn export_tile(
&self,
coord: TileCoordinate,
target: ExportTarget,
) -> Result<ExportResult> {
tracing::debug!("Exporting tile");
let url = format!(
"{}/tile/{}/{}/{}",
self.base_url,
coord.level(),
coord.row(),
coord.col()
);
tracing::debug!(url = %url, "Sending tile 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, "export_tile failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
// Stream tile to target
self.stream_to_target(response, target).await
}
/// Retrieves the legend for all layers in the map service.
///
/// The legend provides information about the symbols and labels
/// used to represent features in each layer.
///
/// # Example
///
/// ```no_run
/// use arcgis::{ApiKeyAuth, ArcGISClient, MapServiceClient};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new("https://example.com/MapServer", &client);
///
/// let legend = service.get_legend().await?;
///
/// for layer in legend.layers() {
/// println!("Layer {}: {}", layer.layer_id(), layer.layer_name());
/// for symbol in layer.legend() {
/// println!(" - {}", symbol.label());
/// }
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self), fields(base_url = %self.base_url))]
pub async fn get_legend(&self) -> Result<LegendResponse> {
tracing::debug!("Retrieving legend");
let url = format!("{}/legend", self.base_url);
tracing::debug!(url = %url, "Sending legend 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, "get_legend failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let legend: LegendResponse = Self::parse_json_response(response, "legend").await?;
tracing::info!(layer_count = legend.layers().len(), "Legend retrieved");
Ok(legend)
}
/// Retrieves metadata about the map service.
///
/// Provides comprehensive information about the service including
/// layers, spatial reference, extent, tile info (if cached), and capabilities.
///
/// # Example
///
/// ```no_run
/// use arcgis::{ApiKeyAuth, ArcGISClient, MapServiceClient};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new("https://example.com/MapServer", &client);
///
/// let metadata = service.get_metadata().await?;
///
/// println!("Layers: {}", metadata.layers().len());
/// if let Some(desc) = metadata.description() {
/// println!("Description: {}", desc);
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self), fields(base_url = %self.base_url))]
pub async fn get_metadata(&self) -> Result<MapServiceMetadata> {
tracing::debug!("Retrieving metadata");
let url = &self.base_url;
tracing::debug!(url = %url, "Sending metadata 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, "get_metadata failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let metadata: MapServiceMetadata = Self::parse_json_response(response, "metadata").await?;
tracing::info!(layers = metadata.layers().len(), "Metadata retrieved");
Ok(metadata)
}
/// Identifies features at a specific location on the map.
///
/// Returns information about features from visible layers at the
/// specified geometry (typically a point, but can be other geometries).
///
/// # Arguments
///
/// * `params` - Identify parameters (geometry and image extent are required)
///
/// # Example
///
/// ```no_run
/// use arcgis::{
/// ApiKeyAuth, ArcGISClient, MapServiceClient, IdentifyParams,
/// IdentifyParamsBuilder, LayerSelection, GeometryType,
/// };
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new("https://example.com/MapServer", &client);
///
/// let params = IdentifyParamsBuilder::default()
/// .geometry("{\"x\":-118.0,\"y\":34.0}".to_string())
/// .geometry_type(GeometryType::Point)
/// .map_extent("-120,32,-116,36".to_string())
/// .image_display("800,600,96".to_string())
/// .layers(LayerSelection::Visible)
/// .build()
/// .expect("Valid params");
///
/// let response = service.identify(params).await?;
///
/// for result in response.results() {
/// println!("Found feature in layer {}", result.layer_id());
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, params), fields(geometry_type = ?params.geometry_type()))]
pub async fn identify(&self, params: IdentifyParams) -> Result<IdentifyResponse> {
tracing::debug!("Identifying features");
let url = format!("{}/identify", self.base_url);
tracing::debug!(url = %url, "Sending identify request");
let mut request = self.client.http().get(&url).query(¶ms);
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, "identify failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let identify_response: IdentifyResponse =
Self::parse_json_response(response, "identify").await?;
tracing::info!(
result_count = identify_response.results().len(),
"Identify completed"
);
Ok(identify_response)
}
// === Helper methods ===
/// Streams export response directly (for ResponseFormat::Image).
#[instrument(skip(self, params, token, target))]
async fn stream_export(
&self,
url: &str,
params: &ExportMapParams,
token: Option<&str>,
target: ExportTarget,
) -> Result<ExportResult> {
tracing::debug!("Streaming export (direct image response)");
let mut request = self.client.http().get(url).query(¶ms);
if let Some(token) = token {
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, "stream_export failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
self.stream_to_target(response, target).await
}
/// Exports via JSON response (fetches href).
#[instrument(skip(self, params, token, target))]
async fn export_via_json(
&self,
url: &str,
params: &ExportMapParams,
token: Option<&str>,
target: ExportTarget,
) -> Result<ExportResult> {
tracing::debug!("Exporting via JSON (will fetch href)");
let mut request = self.client.http().get(url).query(¶ms);
if let Some(token) = token {
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, "export_via_json failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let export_response: ExportMapResponse = response.json().await?;
tracing::debug!(
href = %export_response.href(),
width = export_response.width(),
height = export_response.height(),
"Received export response, fetching image"
);
// Build absolute URL from href (might be relative)
let image_url = if export_response.href().starts_with("http://")
|| export_response.href().starts_with("https://")
{
// Already absolute
export_response.href().to_string()
} else {
// Relative URL - combine with base service URL
let base_url = url::Url::parse(&self.base_url)?;
let image_url = base_url.join(export_response.href())?;
image_url.to_string()
};
tracing::debug!(resolved_url = %image_url, "Fetching image from URL");
// Fetch the actual image from href
let mut image_request = self.client.http().get(&image_url);
if let Some(token) = token {
image_request = image_request.query(&[("token", token)]);
}
let image_response = image_request.send().await?;
let status = image_response.status();
if !status.is_success() {
let error_text = image_response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error: {}", e));
tracing::error!(status = %status, error = %error_text, "Image fetch failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
self.stream_to_target(image_response, target).await
}
/// Streams response to target (Path, Bytes, or Writer).
#[instrument(skip(self, response, target))]
async fn stream_to_target(
&self,
response: reqwest::Response,
target: ExportTarget,
) -> Result<ExportResult> {
match target {
ExportTarget::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,
"Streaming to file completed"
);
Ok(ExportResult::Path(path))
}
ExportTarget::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(), "Streaming to bytes completed");
Ok(ExportResult::Bytes(buffer))
}
ExportTarget::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, "Streaming to writer completed");
Ok(ExportResult::Written(total_bytes))
}
}
}
/// Searches for features containing the specified text in a map service.
///
/// The find operation searches for text in one or more fields across multiple layers.
/// It returns features that contain the search text along with their attributes and geometries.
///
/// # Arguments
///
/// * `params` - Find parameters including search text, layers, and fields to search
///
/// # Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ApiKeyAuth, MapServiceClient, FindParams};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new("https://example.com/MapServer", &client);
///
/// let params = FindParams::builder()
/// .search_text("Main Street")
/// .layers(vec![0, 1])
/// .search_fields(vec!["NAME".to_string(), "STREET".to_string()])
/// .build()
/// .expect("Valid params");
///
/// let result = service.find(params).await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, params))]
pub async fn find(&self, params: crate::FindParams) -> Result<crate::FindResponse> {
tracing::debug!("Finding features by text search");
let url = format!("{}/find", self.base_url);
tracing::debug!(url = %url, search_text = %params.search_text(), "Sending find request");
let mut request = self
.client
.http()
.get(&url)
.query(¶ms)
.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, "find request failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let result: crate::FindResponse = Self::parse_json_response(response, "find").await?;
tracing::info!(result_count = result.results().len(), "Find completed");
Ok(result)
}
/// Generates KML (Keyhole Markup Language) output for the map service.
///
/// This operation returns a KML representation of the map that can be used
/// in Google Earth and other KML viewers.
///
/// # Arguments
///
/// * `params` - Parameters for KML generation including layers and image options
///
/// # Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ApiKeyAuth, MapServiceClient, GenerateKmlParams};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new("https://example.com/MapServer", &client);
///
/// let params = GenerateKmlParams::builder()
/// .doc_name("MyMap")
/// .layers(vec![0, 1])
/// .build()
/// .expect("Valid params");
///
/// let kml = service.generate_kml(params).await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, params))]
pub async fn generate_kml(&self, params: crate::GenerateKmlParams) -> Result<String> {
tracing::debug!("Generating KML");
let url = format!("{}/generateKml", self.base_url);
tracing::debug!(url = %url, doc_name = %params.doc_name(), "Sending generateKml request");
let form = serde_urlencoded::to_string(¶ms)?;
let mut request = self
.client
.http()
.get(&url)
.query(&[("f", "kmz")]) // KML format
.header("Content-Type", "application/x-www-form-urlencoded")
.body(form);
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, "generateKml request failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let kml = response.text().await?;
tracing::info!(kml_length = kml.len(), "KML generation completed");
Ok(kml)
}
/// Generates a classification renderer for a layer.
///
/// This operation generates renderer definitions (symbols, colors, class breaks)
/// based on the data in a layer field. Useful for creating dynamic visualizations
/// like choropleth maps, graduated symbols, etc.
///
/// # Arguments
///
/// * `layer_id` - The layer to generate renderer for
/// * `params` - Parameters for renderer generation including classification method
///
/// # Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ApiKeyAuth, MapServiceClient, GenerateRendererParams};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new("https://example.com/MapServer", &client);
///
/// let params = GenerateRendererParams::builder()
/// .classification_field("POPULATION")
/// .classification_method("natural-breaks")
/// .break_count(5)
/// .build()
/// .expect("Valid params");
///
/// let renderer = service.generate_renderer(0, params).await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, params), fields(layer_id = layer_id))]
pub async fn generate_renderer(
&self,
layer_id: i32,
params: crate::GenerateRendererParams,
) -> Result<crate::RendererResponse> {
tracing::debug!("Generating renderer for layer");
let url = format!("{}/{}/generateRenderer", self.base_url, layer_id);
tracing::debug!(
url = %url,
classification_field = %params.classification_field(),
"Sending generateRenderer request"
);
let params_json = serde_json::to_string(¶ms)?;
let mut form = vec![("classificationDef", params_json.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, "generateRenderer request failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let result: crate::RendererResponse = response.json().await?;
tracing::info!("Renderer generation completed");
Ok(result)
}
/// Queries field domains and subtype information for map service layers.
///
/// This operation retrieves domain definitions (coded values, ranges) and subtype
/// information for one or more layers in the map service. Useful for understanding
/// valid values and field constraints.
///
/// # Arguments
///
/// * `layers` - Vector of layer IDs to query domains for (empty for all layers)
///
/// # Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ApiKeyAuth, MapServiceClient, LayerId};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
/// let service = MapServiceClient::new("https://example.com/MapServer", &client);
///
/// // Query domains for specific layers
/// let domains = service
/// .query_domains(vec![LayerId::new(0), LayerId::new(1)])
/// .await?;
///
/// // Query domains for all layers
/// let all_domains = service.query_domains(vec![]).await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self), fields(layer_count = layers.len()))]
pub async fn query_domains(
&self,
layers: Vec<crate::LayerId>,
) -> Result<crate::QueryDomainsResponse> {
tracing::debug!("Querying map service domains");
let url = format!("{}/queryDomains", self.base_url);
let layers_str = layers
.iter()
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(",");
tracing::debug!(url = %url, layers = %layers_str, "Sending queryDomains request");
let mut form = vec![("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()));
}
if !layers_str.is_empty() {
form.push(("layers", &layers_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, "queryDomains request failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let result: crate::QueryDomainsResponse =
Self::parse_json_response(response, "queryDomains").await?;
tracing::info!(
layer_count = result.layers().len(),
"Map service queryDomains completed"
);
Ok(result)
}
/// Attempts to parse a JSON response, handling HTML error pages gracefully.
///
/// ArcGIS servers sometimes return HTTP 200 with HTML error pages instead of JSON.
/// This helper detects such cases and provides clear error messages while preserving
/// the original error content in the error chain.
///
/// # Arguments
///
/// * `response` - The HTTP response to parse
/// * `operation` - Name of the operation (for error messages)
async fn parse_json_response<T>(response: reqwest::Response, operation: &str) -> Result<T>
where
T: serde::de::DeserializeOwned,
{
// Extract content-type before consuming response
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string())
.unwrap_or_else(|| String::from(""));
// If content-type indicates HTML, extract error message
if content_type.contains("text/html") {
let html_body = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read HTML error response: {}", e));
tracing::error!(
content_type = %content_type,
operation = %operation,
body_preview = %&html_body.chars().take(200).collect::<String>(),
"Server returned HTML error page instead of JSON"
);
// Try to extract a meaningful error message from HTML
let error_msg = extract_html_error(&html_body)
.unwrap_or_else(|| "Server returned HTML error page".to_string());
return Err(crate::Error::from(crate::ErrorKind::Api {
code: 400,
message: format!(
"{} operation not supported: {}. HTML response: {}",
operation,
error_msg,
&html_body.chars().take(200).collect::<String>()
),
}));
}
// Try to parse as JSON, providing context if it fails
response.json().await.map_err(|e| {
tracing::error!(
error = %e,
operation = %operation,
content_type = %content_type,
"Failed to parse response as JSON"
);
crate::Error::from(crate::ErrorKind::Http(crate::HttpError::new(e)))
})
}
}
/// Extracts a meaningful error message from an HTML error page.
///
/// Looks for common patterns in ArcGIS Server error pages.
fn extract_html_error(html: &str) -> Option<String> {
// Look for common error message patterns
let patterns = [
("<p><b>Message:</b> <u>", "</u></p>"),
("<p><b>Description:</b> <u>", "</u></p>"),
("<h2>", "</h2>"),
("<h1>", "</h1>"),
];
for (start, end) in patterns {
if let Some(start_idx) = html.find(start) {
let content_start = start_idx + start.len();
if let Some(end_idx) = html[content_start..].find(end) {
let msg = &html[content_start..content_start + end_idx];
if !msg.trim().is_empty() {
return Some(msg.trim().to_string());
}
}
}
}
None
}