sl-map-apis 0.3.3

Wraps the SL map API to convert grid coordinates to region names and vice versa and to fetch map tiles
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
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
//! Contains functionality related to converting region names to grid coordinates and vice versa
use redb::ReadableDatabase as _;
use sl_types::map::{GridCoordinates, GridRectangle, RegionName, RegionNameError, USBNotecard};

/// Represents the possible errors that can occur when converting a region name to grid coordinates
#[expect(
    clippy::module_name_repetitions,
    reason = "the type is going to be used outside the module"
)]
#[derive(Debug, thiserror::Error)]
pub enum RegionNameToGridCoordinatesError {
    /// HTTP error
    #[error("HTTP error: {0}")]
    Http(#[from] reqwest::Error),
    /// failed to clone request for creation of cache policy
    #[error("failed to clone request for creation of cache policy")]
    FailedToCloneRequest,
    /// Unexpected prefix in response body
    #[error("Unexpected prefix in response body: {0}")]
    UnexpectedPrefix(String),
    /// Unexpected suffix in response body
    #[error("Unexpected suffix in response body: {0}")]
    UnexpectedSuffix(String),
    /// Unexpected infix in response body
    #[error("Unexpected infix in response body: {0}")]
    UnexpectedInfix(String),
    /// error parsing the X coordinate
    #[error("error parsing the X coordinate {0}: {1}")]
    X(String, std::num::ParseIntError),
    /// error parsing the Y coordinate
    #[error("error parsing the Y coordinate {0}: {1}")]
    Y(String, std::num::ParseIntError),
}

/// converts a `RegionName` to `GridCoordinates` using the Linden Lab API
///
/// # Errors
///
/// returns an error if the HTTP request fails or if the result couldn't
/// be parsed properly
#[expect(
    clippy::module_name_repetitions,
    reason = "the function is going to be used outside the module"
)]
pub async fn region_name_to_grid_coordinates(
    client: &reqwest::Client,
    region_name: &RegionName,
    cached_value_with_cache_policy: Option<(
        Option<GridCoordinates>,
        http_cache_semantics::CachePolicy,
    )>,
) -> Result<
    (Option<GridCoordinates>, http_cache_semantics::CachePolicy),
    RegionNameToGridCoordinatesError,
> {
    tracing::debug!(
        "Looking up grid coordinates for region name {}",
        region_name
    );
    let url = format!(
        "https://cap.secondlife.com/cap/0/d661249b-2b5a-4436-966a-3d3b8d7a574f?var=coords&sim_name={}",
        region_name.to_string().replace(' ', "%20")
    );
    let request = client.get(&url).build()?;
    if let Some((cached_value, cache_policy)) = cached_value_with_cache_policy {
        let now = std::time::SystemTime::now();
        if let http_cache_semantics::BeforeRequest::Fresh(_) =
            cache_policy.before_request(&request, now)
        {
            tracing::debug!("Using cached grid coordinates/absence");
            return Ok((cached_value, cache_policy));
        }
    }
    let response = client
        .execute(
            request
                .try_clone()
                .ok_or(RegionNameToGridCoordinatesError::FailedToCloneRequest)?,
        )
        .await?;
    let cache_policy = http_cache_semantics::CachePolicy::new(&request, &response);
    let response = response.text().await?;
    if response == "var coords = {'error' : true };" {
        tracing::debug!("Received negative response");
        return Ok((None, cache_policy));
    }
    let Some(response) = response.strip_prefix("var coords = {'x' : ") else {
        return Err(RegionNameToGridCoordinatesError::UnexpectedPrefix(
            response.to_owned(),
        ));
    };
    let Some(response) = response.strip_suffix(" };") else {
        return Err(RegionNameToGridCoordinatesError::UnexpectedSuffix(
            response.to_owned(),
        ));
    };
    let parts = response.split(", 'y' : ").collect::<Vec<_>>();
    let [x, y] = parts.as_slice() else {
        return Err(RegionNameToGridCoordinatesError::UnexpectedInfix(
            response.to_owned(),
        ));
    };
    let x = x
        .parse::<u16>()
        .map_err(|err| RegionNameToGridCoordinatesError::X(x.to_string(), err))?;
    let y = y
        .parse::<u16>()
        .map_err(|err| RegionNameToGridCoordinatesError::Y(y.to_string(), err))?;
    let grid_coordinates = GridCoordinates::new(x, y);
    tracing::debug!("Received response: {:?}", grid_coordinates);
    Ok((Some(grid_coordinates), cache_policy))
}

/// Represents the possible errors that can occur when converting grid coordinates to a region name
#[derive(Debug, thiserror::Error)]
pub enum GridCoordinatesToRegionNameError {
    /// HTTP error
    #[error("HTTP error: {0}")]
    Http(#[from] reqwest::Error),
    /// failed to clone request for creation of cache policy
    #[error("failed to clone request for creation of cache policy")]
    FailedToCloneRequest,
    /// Unexpected prefix in response body
    #[error("Unexpected prefix in response body: {0}")]
    UnexpectedPrefix(String),
    /// Unexpected suffix in response body
    #[error("Unexpected suffix in response body: {0}")]
    UnexpectedSuffix(String),
    /// error parsing the region name
    #[error("error parsing the region name {0}: {1}")]
    RegionName(String, RegionNameError),
}

/// converts `GridCoordinates` to a `RegionName` using the Linden Lab API
///
/// # Errors
///
/// returns an error if the HTTP request fails or if the result couldn't
/// be parsed properly
pub async fn grid_coordinates_to_region_name(
    client: &reqwest::Client,
    grid_coordinates: &GridCoordinates,
    cached_value_with_cache_policy: Option<(Option<RegionName>, http_cache_semantics::CachePolicy)>,
) -> Result<(Option<RegionName>, http_cache_semantics::CachePolicy), GridCoordinatesToRegionNameError>
{
    tracing::debug!(
        "Looking up region name for grid coordinates {:?}",
        grid_coordinates
    );
    let url = format!(
        "https://cap.secondlife.com/cap/0/b713fe80-283b-4585-af4d-a3b7d9a32492?var=region&grid_x={}&grid_y={}",
        grid_coordinates.x(),
        grid_coordinates.y()
    );
    let request = client.get(&url).build()?;
    if let Some((cached_value, cache_policy)) = cached_value_with_cache_policy {
        let now = std::time::SystemTime::now();
        if let http_cache_semantics::BeforeRequest::Fresh(_) =
            cache_policy.before_request(&request, now)
        {
            tracing::debug!("Returning cached region name/absence");
            return Ok((cached_value, cache_policy));
        }
    }
    let response = client
        .execute(
            request
                .try_clone()
                .ok_or(GridCoordinatesToRegionNameError::FailedToCloneRequest)?,
        )
        .await?;
    let cache_policy = http_cache_semantics::CachePolicy::new(&request, &response);
    let response = response.text().await?;
    if response == "var region = {'error' : true };" {
        tracing::debug!("Received negative response");
        return Ok((None, cache_policy));
    }
    let Some(response) = response.strip_prefix("var region='") else {
        return Err(GridCoordinatesToRegionNameError::UnexpectedPrefix(
            response.to_string(),
        ));
    };
    let Some(response) = response.strip_suffix("';") else {
        return Err(GridCoordinatesToRegionNameError::UnexpectedSuffix(
            response.to_string(),
        ));
    };
    let region_name = RegionName::try_new(response)
        .map_err(|err| GridCoordinatesToRegionNameError::RegionName(response.to_owned(), err))?;
    tracing::debug!("Received region name: {region_name}");
    Ok((Some(region_name), cache_policy))
}

/// a cache for region names to grid coordinates
/// that allows lookups in both directions
#[expect(
    clippy::module_name_repetitions,
    reason = "the type is going to be used outside the module"
)]
#[derive(Debug)]
pub struct RegionNameToGridCoordinatesCache {
    /// the reqwest Client used to lookup data not cached locally
    client: reqwest::Client,
    /// the cache database
    db: redb::Database,
    /// the in memory cache of region names to grid coordinates
    grid_coordinate_cache:
        lru::LruCache<RegionName, (Option<GridCoordinates>, http_cache_semantics::CachePolicy)>,
    /// the in memory cache of grid coordinates to region names
    region_name_cache:
        lru::LruCache<GridCoordinates, (Option<RegionName>, http_cache_semantics::CachePolicy)>,
}

/// describes an error that can occur as part of the cache operation for the `RegionNameToGridCoordinatesCache`
#[derive(Debug, thiserror::Error)]
pub enum CacheError {
    /// error decoding the JSON serialized CachePolicy
    #[error("error decoding the JSON serialized CachePolicy: {0}")]
    CachePolicyJsonDecodeError(#[from] serde_json::Error),
    /// redb database error
    #[error("redb database error: {0}")]
    DatabaseError(#[from] redb::DatabaseError),
    /// redb transaction error
    #[error("redb transaction error: {0}")]
    TransactionError(#[from] redb::TransactionError),
    /// redb table error
    #[error("redb table error: {0}")]
    TableError(#[from] redb::TableError),
    /// redb storage error
    #[error("redb storage error: {0}")]
    StorageError(#[from] redb::StorageError),
    /// redb commit error
    #[error("redb storage error: {0}")]
    CommitError(#[from] redb::CommitError),
    /// error looking up grid coordinates via HTTP
    #[error("error looking up grid coordinates via HTTP: {0}")]
    GridCoordinatesHttpError(#[from] RegionNameToGridCoordinatesError),
    /// error looking up region name via HTTP
    #[error("error looking up region name via HTTP: {0}")]
    RegionNameHttpError(#[from] GridCoordinatesToRegionNameError),
    /// error creating region name from cached string
    #[error("error creating region name from cached string: {0}")]
    RegionNameError(#[from] RegionNameError),
    /// error handling system time for cache age calculations
    #[error("error handling system time for cache age calculations: {0}")]
    SystemTimeError(#[from] std::time::SystemTimeError),
}

/// describes the redb table to store region names and grid coordinates
const GRID_COORDINATE_CACHE_TABLE: redb::TableDefinition<String, (u16, u16)> =
    redb::TableDefinition::new("grid_coordinates");

/// describes the redb table to store grid coordinates and region names
const REGION_NAME_CACHE_TABLE: redb::TableDefinition<(u16, u16), String> =
    redb::TableDefinition::new("region_name");

/// describes the redb table to store the `http_cache_semantics::CachePolicy`
/// serialized as JSON for a region name to grid coordinate lookup
const GRID_COORDINATE_CACHE_POLICY_TABLE: redb::TableDefinition<String, String> =
    redb::TableDefinition::new("grid_coordinate_cache_policy");

/// describes the redb table to store the `http_cache_semantics::CachePolicy`
/// serialized as JSON for a grid coordinate to region name lookup
const REGION_NAME_CACHE_POLICY_TABLE: redb::TableDefinition<(u16, u16), String> =
    redb::TableDefinition::new("region_name_cache_policy");

impl RegionNameToGridCoordinatesCache {
    /// create a new cache
    ///
    /// # Errors
    ///
    /// returns an error if the database could not be created or opened
    pub fn new(cache_directory: std::path::PathBuf) -> Result<Self, CacheError> {
        let client = reqwest::Client::new();
        let db = redb::Database::create(cache_directory.join("region_name.redb"))?;
        let grid_coordinate_cache = lru::LruCache::unbounded();
        let region_name_cache = lru::LruCache::unbounded();
        Ok(Self {
            client,
            db,
            grid_coordinate_cache,
            region_name_cache,
        })
    }

    /// get the grid coordinates for a region name
    ///
    /// # Errors
    ///
    /// returns an error if either the local database operations or the HTTP requests fail
    pub async fn get_grid_coordinates(
        &mut self,
        region_name: &RegionName,
    ) -> Result<Option<GridCoordinates>, CacheError> {
        tracing::debug!("Retrieving grid coordinates for region {region_name:?}");
        let cached_value_with_cache_policy = {
            if let Some(memory_cached_value) = self.grid_coordinate_cache.get(region_name) {
                Some(memory_cached_value.to_owned())
            } else {
                let read_txn = self.db.begin_read()?;
                let cache_policy = {
                    if let Ok(table) = read_txn.open_table(GRID_COORDINATE_CACHE_POLICY_TABLE) {
                        if let Some(access_guard) =
                            table.get(region_name.to_owned().into_inner())?
                        {
                            let cache_policy: http_cache_semantics::CachePolicy =
                                serde_json::from_str(&access_guard.value())?;
                            Some(cache_policy)
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                };
                if let Some(cache_policy) = cache_policy {
                    let cached_value = {
                        if let Ok(table) = read_txn.open_table(GRID_COORDINATE_CACHE_TABLE) {
                            if let Some(access_guard) =
                                table.get(region_name.to_owned().into_inner())?
                            {
                                let (x, y) = access_guard.value();
                                Some(GridCoordinates::new(x, y))
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    };
                    Some((cached_value, cache_policy))
                } else {
                    None
                }
            }
        };
        match region_name_to_grid_coordinates(
            &self.client,
            region_name,
            cached_value_with_cache_policy,
        )
        .await
        {
            Ok((Some(grid_coordinates), cache_policy)) => {
                if cache_policy.is_storable() {
                    tracing::debug!("Storing grid coordinates in cache");
                    let write_txn = self.db.begin_write()?;
                    {
                        let mut table = write_txn.open_table(GRID_COORDINATE_CACHE_POLICY_TABLE)?;
                        table.insert(
                            region_name.to_owned().into_inner(),
                            serde_json::to_string(&cache_policy)?,
                        )?;
                    }
                    {
                        let mut table = write_txn.open_table(GRID_COORDINATE_CACHE_TABLE)?;
                        table.insert(
                            region_name.to_owned().into_inner(),
                            (grid_coordinates.x(), grid_coordinates.y()),
                        )?;
                    }
                    write_txn.commit()?;
                    self.grid_coordinate_cache.put(
                        region_name.to_owned(),
                        (Some(grid_coordinates), cache_policy),
                    );
                } else {
                    tracing::debug!("Grid coordinates are not storable");
                    let write_txn = self.db.begin_write()?;
                    {
                        let mut table = write_txn.open_table(GRID_COORDINATE_CACHE_POLICY_TABLE)?;
                        table.remove(region_name.to_owned().into_inner())?;
                    }
                    {
                        let mut table = write_txn.open_table(GRID_COORDINATE_CACHE_TABLE)?;
                        table.remove(region_name.to_owned().into_inner())?;
                    }
                    write_txn.commit()?;
                    self.grid_coordinate_cache.pop(region_name);
                }
                tracing::debug!("Coordinates are {grid_coordinates:?}");
                Ok(Some(grid_coordinates))
            }
            Ok((None, cache_policy)) => {
                if cache_policy.is_storable() {
                    tracing::debug!("Storing negative response in cache");
                    let write_txn = self.db.begin_write()?;
                    {
                        let mut table = write_txn.open_table(GRID_COORDINATE_CACHE_POLICY_TABLE)?;
                        table.insert(
                            region_name.to_owned().into_inner(),
                            serde_json::to_string(&cache_policy)?,
                        )?;
                    }
                    {
                        let mut table = write_txn.open_table(GRID_COORDINATE_CACHE_TABLE)?;
                        table.remove(region_name.to_owned().into_inner())?;
                    }
                    write_txn.commit()?;
                    self.grid_coordinate_cache
                        .put(region_name.to_owned(), (None, cache_policy));
                } else {
                    tracing::debug!("Negative response is not storable");
                    let write_txn = self.db.begin_write()?;
                    {
                        let mut table = write_txn.open_table(GRID_COORDINATE_CACHE_POLICY_TABLE)?;
                        table.remove(region_name.to_owned().into_inner())?;
                    }
                    {
                        let mut table = write_txn.open_table(GRID_COORDINATE_CACHE_TABLE)?;
                        table.remove(region_name.to_owned().into_inner())?;
                    }
                    write_txn.commit()?;
                    self.grid_coordinate_cache.pop(region_name);
                }
                tracing::debug!("No coordinates exist for that name");
                Ok(None)
            }
            Err(err) => Err(CacheError::GridCoordinatesHttpError(err)),
        }
    }

    /// get the region name for a set of grid coordinates
    ///
    /// # Errors
    ///
    /// returns an error if either the local database operations or the HTTP requests fail
    pub async fn get_region_name(
        &mut self,
        grid_coordinates: &GridCoordinates,
    ) -> Result<Option<RegionName>, CacheError> {
        tracing::debug!("Retrieving region name for grid coordinates {grid_coordinates:?}");
        let cached_value_with_cache_policy = {
            if let Some(memory_cached_value) = self.region_name_cache.get(grid_coordinates) {
                Some(memory_cached_value.to_owned())
            } else {
                let read_txn = self.db.begin_read()?;
                let cache_policy = {
                    if let Ok(table) = read_txn.open_table(REGION_NAME_CACHE_POLICY_TABLE) {
                        if let Some(access_guard) =
                            table.get((grid_coordinates.x(), grid_coordinates.y()))?
                        {
                            let cache_policy: http_cache_semantics::CachePolicy =
                                serde_json::from_str(&access_guard.value())?;
                            Some(cache_policy)
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                };
                if let Some(cache_policy) = cache_policy {
                    let cached_value = {
                        if let Ok(table) = read_txn.open_table(REGION_NAME_CACHE_TABLE) {
                            if let Some(access_guard) =
                                table.get((grid_coordinates.x(), grid_coordinates.y()))?
                            {
                                let region_name = access_guard.value();
                                Some(RegionName::try_new(region_name)?)
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    };
                    Some((cached_value, cache_policy))
                } else {
                    None
                }
            }
        };
        match grid_coordinates_to_region_name(
            &self.client,
            grid_coordinates,
            cached_value_with_cache_policy,
        )
        .await
        {
            Ok((Some(region_name), cache_policy)) => {
                if cache_policy.is_storable() {
                    tracing::debug!("Storing region name in cache");
                    let write_txn = self.db.begin_write()?;
                    {
                        let mut table = write_txn.open_table(REGION_NAME_CACHE_POLICY_TABLE)?;
                        table.insert(
                            (grid_coordinates.x(), grid_coordinates.y()),
                            serde_json::to_string(&cache_policy)?,
                        )?;
                    }
                    {
                        let mut table = write_txn.open_table(REGION_NAME_CACHE_TABLE)?;
                        table.insert(
                            (grid_coordinates.x(), grid_coordinates.y()),
                            region_name.to_owned().into_inner(),
                        )?;
                    }
                    write_txn.commit()?;
                    self.region_name_cache.put(
                        grid_coordinates.to_owned(),
                        (Some(region_name.to_owned()), cache_policy),
                    );
                } else {
                    tracing::warn!("Region name response is not storable");
                    let write_txn = self.db.begin_write()?;
                    {
                        let mut table = write_txn.open_table(REGION_NAME_CACHE_POLICY_TABLE)?;
                        table.remove((grid_coordinates.x(), grid_coordinates.y()))?;
                    }
                    {
                        let mut table = write_txn.open_table(REGION_NAME_CACHE_TABLE)?;
                        table.remove((grid_coordinates.x(), grid_coordinates.y()))?;
                    }
                    write_txn.commit()?;
                    self.region_name_cache.pop(grid_coordinates);
                }
                tracing::debug!("Region name is {region_name:?}");
                Ok(Some(region_name))
            }
            Ok((None, cache_policy)) => {
                if cache_policy.is_storable() {
                    tracing::debug!("Storing negative response in cache");
                    let write_txn = self.db.begin_write()?;
                    {
                        let mut table = write_txn.open_table(REGION_NAME_CACHE_POLICY_TABLE)?;
                        table.insert(
                            (grid_coordinates.x(), grid_coordinates.y()),
                            serde_json::to_string(&cache_policy)?,
                        )?;
                    }
                    {
                        let mut table = write_txn.open_table(REGION_NAME_CACHE_TABLE)?;
                        table.remove((grid_coordinates.x(), grid_coordinates.y()))?;
                    }
                    write_txn.commit()?;
                    self.region_name_cache
                        .put(grid_coordinates.to_owned(), (None, cache_policy));
                } else {
                    tracing::debug!("Negative response is not storable");
                    let write_txn = self.db.begin_write()?;
                    {
                        let mut table = write_txn.open_table(REGION_NAME_CACHE_POLICY_TABLE)?;
                        table.remove((grid_coordinates.x(), grid_coordinates.y()))?;
                    }
                    {
                        let mut table = write_txn.open_table(REGION_NAME_CACHE_TABLE)?;
                        table.remove((grid_coordinates.x(), grid_coordinates.y()))?;
                    }
                    write_txn.commit()?;
                    self.region_name_cache.pop(grid_coordinates);
                }
                tracing::debug!("No region name exists for those grid coordinates");
                Ok(None)
            }
            Err(err) => Err(CacheError::RegionNameHttpError(err)),
        }
    }
}

/// errors that can occur when converting a USB notecard to a grid rectangle
#[derive(Debug, thiserror::Error)]
pub enum USBNotecardToGridRectangleError {
    /// there were no waypoints in the USB notecards so we could not determine
    /// a grid rectangle for it
    #[error(
        "There were no waypoints in the USB notecards which made determining a grid rectangle for it impossible"
    )]
    NoUSBNotecardWaypoints,
    /// there were errors when converting region names to grid coordinates
    #[error("error converting region name to grid coordinates: {0}")]
    CacheError(#[from] CacheError),
    /// no grid coordinates were returned for one of the region names in the
    /// USB Notecard
    #[error("No grid coordinates were returned for one of the regions in the USB notecard: {0}")]
    NoGridCoordinatesForRegion(RegionName),
}

/// converts a USB notecard to the `GridRectangle` that contains all the waypoints
///
/// # Errors
///
/// returns an error if there were no waypoints or if conversions to grid coordinates failed
pub async fn usb_notecard_to_grid_rectangle(
    region_name_to_grid_coordinates_cache: &mut RegionNameToGridCoordinatesCache,
    usb_notecard: &USBNotecard,
) -> Result<GridRectangle, USBNotecardToGridRectangleError> {
    let mut lower_left_x = None;
    let mut lower_left_y = None;
    let mut upper_right_x = None;
    let mut upper_right_y = None;
    for waypoint in usb_notecard.waypoints() {
        let grid_coordinates = region_name_to_grid_coordinates_cache
            .get_grid_coordinates(waypoint.location().region_name())
            .await?;
        if let Some(grid_coordinates) = grid_coordinates {
            if let Some(llx) = lower_left_x {
                lower_left_x = Some(std::cmp::min(llx, grid_coordinates.x()));
            } else {
                lower_left_x = Some(grid_coordinates.x());
            }
            if let Some(lly) = lower_left_y {
                lower_left_y = Some(std::cmp::min(lly, grid_coordinates.y()));
            } else {
                lower_left_y = Some(grid_coordinates.y());
            }
            if let Some(urx) = upper_right_x {
                upper_right_x = Some(std::cmp::max(urx, grid_coordinates.x()));
            } else {
                upper_right_x = Some(grid_coordinates.x());
            }
            if let Some(ury) = upper_right_y {
                upper_right_y = Some(std::cmp::max(ury, grid_coordinates.y()));
            } else {
                upper_right_y = Some(grid_coordinates.y());
            }
        } else {
            return Err(USBNotecardToGridRectangleError::NoGridCoordinatesForRegion(
                waypoint.location().region_name().to_owned(),
            ));
        }
    }
    let Some(lower_left_x) = lower_left_x else {
        return Err(USBNotecardToGridRectangleError::NoUSBNotecardWaypoints);
    };
    let Some(lower_left_y) = lower_left_y else {
        return Err(USBNotecardToGridRectangleError::NoUSBNotecardWaypoints);
    };
    let Some(upper_right_x) = upper_right_x else {
        return Err(USBNotecardToGridRectangleError::NoUSBNotecardWaypoints);
    };
    let Some(upper_right_y) = upper_right_y else {
        return Err(USBNotecardToGridRectangleError::NoUSBNotecardWaypoints);
    };
    Ok(GridRectangle::new(
        GridCoordinates::new(lower_left_x, lower_left_y),
        GridCoordinates::new(upper_right_x, upper_right_y),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[tokio::test]
    async fn test_region_name_to_grid_coordinates() -> Result<(), Box<dyn std::error::Error>> {
        let client = reqwest::Client::new();
        assert_eq!(
            region_name_to_grid_coordinates(&client, &RegionName::try_new("Thorkell")?, None)
                .await?
                .0,
            Some(GridCoordinates::new(1136, 1075))
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_grid_coordinates_to_region_name() -> Result<(), Box<dyn std::error::Error>> {
        let client = reqwest::Client::new();
        assert_eq!(
            grid_coordinates_to_region_name(&client, &GridCoordinates::new(1136, 1075), None)
                .await?
                .0,
            Some(RegionName::try_new("Thorkell")?)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_cache_region_name_to_grid_coordinates() -> Result<(), Box<dyn std::error::Error>>
    {
        let tempdir = tempfile::tempdir()?;
        let mut cache = RegionNameToGridCoordinatesCache::new(tempdir.path().to_path_buf())?;
        assert_eq!(
            cache
                .get_grid_coordinates(&RegionName::try_new("Thorkell")?)
                .await?,
            Some(GridCoordinates::new(1136, 1075))
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_cache_region_name_to_grid_coordinates_twice()
    -> Result<(), Box<dyn std::error::Error>> {
        let tempdir = tempfile::tempdir()?;
        let mut cache = RegionNameToGridCoordinatesCache::new(tempdir.path().to_path_buf())?;
        assert_eq!(
            cache
                .get_grid_coordinates(&RegionName::try_new("Thorkell")?)
                .await?,
            Some(GridCoordinates::new(1136, 1075))
        );
        assert_eq!(
            cache
                .get_grid_coordinates(&RegionName::try_new("Thorkell")?)
                .await?,
            Some(GridCoordinates::new(1136, 1075))
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_cache_region_name_to_grid_coordinates_negative_twice()
    -> Result<(), Box<dyn std::error::Error>> {
        let tempdir = tempfile::tempdir()?;
        let mut cache = RegionNameToGridCoordinatesCache::new(tempdir.path().to_path_buf())?;
        assert_eq!(
            cache
                .get_grid_coordinates(&RegionName::try_new("Thorkel")?)
                .await?,
            None,
        );
        assert_eq!(
            cache
                .get_grid_coordinates(&RegionName::try_new("Thorkel")?)
                .await?,
            None,
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_cache_grid_coordinates_to_region_name() -> Result<(), Box<dyn std::error::Error>>
    {
        let tempdir = tempfile::tempdir()?;
        let mut cache = RegionNameToGridCoordinatesCache::new(tempdir.path().to_path_buf())?;
        assert_eq!(
            cache
                .get_region_name(&GridCoordinates::new(1136, 1075))
                .await?,
            Some(RegionName::try_new("Thorkell")?)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_cache_grid_coordinates_to_region_name_twice()
    -> Result<(), Box<dyn std::error::Error>> {
        let tempdir = tempfile::tempdir()?;
        let mut cache = RegionNameToGridCoordinatesCache::new(tempdir.path().to_path_buf())?;
        assert_eq!(
            cache
                .get_region_name(&GridCoordinates::new(1136, 1075))
                .await?,
            Some(RegionName::try_new("Thorkell")?)
        );
        assert_eq!(
            cache
                .get_region_name(&GridCoordinates::new(1136, 1075))
                .await?,
            Some(RegionName::try_new("Thorkell")?)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_cache_grid_coordinates_to_region_name_negative_twice()
    -> Result<(), Box<dyn std::error::Error>> {
        let tempdir = tempfile::tempdir()?;
        let mut cache = RegionNameToGridCoordinatesCache::new(tempdir.path().to_path_buf())?;
        assert_eq!(
            cache
                .get_region_name(&GridCoordinates::new(11136, 1075))
                .await?,
            None,
        );
        assert_eq!(
            cache
                .get_region_name(&GridCoordinates::new(11136, 1075))
                .await?,
            None,
        );
        Ok(())
    }
}