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
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
//! # Overview
//! This crate provides functions which can query a SkySpark server, using
//! the Haystack REST API and the SkySpark REST API's `eval` operation.
//! Some Haystack operations are not implemented
//! (watch* operations, pointWrite and invokeAction).
//!
//! # Example Usage
//! Put this in the main function in the `main.rs` file to create
//! and use a `SkySparkClient`:
//!
//! ```rust,no_run
//! # async fn run() {
//! use raystack::{ClientSeed, SkySparkClient, ValueExt};
//! use url::Url;
//!
//! let timeout_in_seconds = 30;
//! let client_seed = ClientSeed::new(timeout_in_seconds).unwrap();
//! let url = Url::parse("https://www.example.com/api/projName/").unwrap();
//! let mut client = SkySparkClient::new(url, "username", "p4ssw0rd", client_seed).await.unwrap();
//! let sites_grid = client.eval("readAll(site)").await.unwrap();
//!
//! // Print the raw JSON:
//! println!("{}", sites_grid.to_json_string_pretty());
//!
//! // Working with the Grid struct:
//! println!("All columns: {:?}", sites_grid.cols());
//! println!("first site id: {:?}", sites_grid.rows()[0]["id"].as_hs_ref().unwrap());
//! # }
//! ```
//!
//! See the `examples` folder for more usage examples.
//!
//! The Grid struct is a wrapper around the underlying JSON Value enum
//! provided by the `serde_json` crate. See the
//! [documentation for Value](https://docs.serde.rs/serde_json/enum.Value.html)
//! for more information on how to query for data stored within it.
//!
//! Additional functions for extracting Haystack values from the underlying
//! JSON are found in this crate's `ValueExt` trait.

mod api;
pub mod auth;
mod err;
pub mod eval;
mod grid;
mod hs_types;
mod tz;
mod value_ext;

use api::HaystackUrl;
pub use api::HisReadRange;
use chrono::Utc;
pub use err::{Error, NewClientSeedError, NewSkySparkClientError};
pub use grid::{Grid, ParseJsonGridError};
pub use hs_types::{Date, DateTime, Time};
pub use raystack_core::Coord;
pub use raystack_core::Number;
pub use raystack_core::{is_tag_name, ParseTagNameError, TagName};
pub use raystack_core::{Marker, Na, RemoveMarker, Symbol, Uri, Xstr};
pub use raystack_core::{ParseRefError, Ref};
use reqwest::Client as ReqwestClient;
use serde_json::json;
use std::convert::TryInto;
pub use tz::skyspark_tz_string_to_tz;
use url::Url;
pub use value_ext::ValueExt;

type Result<T> = std::result::Result<T, Error>;
type StdResult<T, E> = std::result::Result<T, E>;

/// Contains resources used by a `SkySparkClient`. If creating multiple
/// `SkySparkClient`s, the same `ClientSeed` should be reused for each,
/// by calling the `.clone()` method.
#[derive(Clone, Debug)]
pub struct ClientSeed {
    client: ReqwestClient,
    rng: ring::rand::SystemRandom,
}

impl ClientSeed {
    /// Create a new `ClientSeed`. The timeout determines how long the
    /// underlying HTTP library will wait before timing out.
    pub fn new(timeout_in_seconds: u64) -> StdResult<Self, NewClientSeedError> {
        use std::time::Duration;

        let client = ReqwestClient::builder()
            .timeout(Duration::from_secs(timeout_in_seconds))
            .build()?;

        Ok(Self {
            client,
            rng: ring::rand::SystemRandom::new(),
        })
    }

    /// Create a new `ClientSeed`. Use this method if sharing a
    /// `reqwest::Client` throughout your program.
    pub fn new_with_client(client: &ReqwestClient) -> Self {
        // This will reuse the underlying HTTP client because
        // `reqwest::Client` uses an `Arc` internally:
        let client = client.clone();
        Self {
            client,
            rng: ring::rand::SystemRandom::new(),
        }
    }

    fn client(&self) -> &reqwest::Client {
        &self.client
    }

    fn rng(&self) -> &ring::rand::SystemRandom {
        &self.rng
    }
}

pub(crate) async fn new_auth_token(
    project_api_url: &Url,
    client_seed: &ClientSeed,
    username: &str,
    password: &str,
) -> StdResult<String, crate::auth::AuthError> {
    let mut auth_url = project_api_url.clone();
    auth_url.set_path("/ui");

    let auth_token = auth::new_auth_token(
        client_seed.client(),
        auth_url.as_str(),
        username,
        password,
        client_seed.rng(),
    )
    .await?;

    Ok(auth_token)
}

/// A client for interacting with a SkySpark server.
#[derive(Debug)]
pub struct SkySparkClient {
    auth_token: String,
    client_seed: ClientSeed,
    username: String,
    password: String,
    project_api_url: Url,
}

impl SkySparkClient {
    /// Create a new `SkySparkClient`.
    ///
    /// # Example
    /// ```rust,no_run
    /// # async fn run() {
    /// use raystack::{ClientSeed, SkySparkClient};
    /// use url::Url;
    /// let timeout_in_seconds = 30;
    /// let client_seed = ClientSeed::new(timeout_in_seconds).unwrap();
    /// let url = Url::parse("https://skyspark.company.com/api/bigProject/").unwrap();
    /// let mut client = SkySparkClient::new(url, "username", "p4ssw0rd", client_seed).await.unwrap();
    /// # }
    /// ```
    ///
    /// If creating multiple `SkySparkClient`s,
    /// the same `ClientSeed` should be used for each. For example:
    ///
    /// ```rust,no_run
    /// # async fn run() {
    /// use raystack::{ClientSeed, SkySparkClient};
    /// use url::Url;
    /// let client_seed = ClientSeed::new(30).unwrap();
    /// let url1 = Url::parse("http://test.com/api/bigProject/").unwrap();
    /// let client1 = SkySparkClient::new(url1, "name", "p4ssw0rd", client_seed.clone()).await.unwrap();
    /// let url2 = Url::parse("http://test.com/api/smallProj/").unwrap();
    /// let client2 = SkySparkClient::new(url2, "name", "p4ss", client_seed.clone()).await.unwrap();
    /// # }
    /// ```
    ///
    /// We pass in the `ClientSeed`
    /// struct because the underlying crypto library recommends that an
    /// application should create a single random number generator and use
    /// it for all randomness generation. Additionally, the underlying HTTP
    /// library recommends using a single copy of its HTTP client. These two
    /// resources are wrapped by this `ClientSeed` struct.
    pub async fn new(
        project_api_url: Url,
        username: &str,
        password: &str,
        client_seed: ClientSeed,
    ) -> std::result::Result<Self, NewSkySparkClientError> {
        let project_api_url = add_backslash_if_necessary(project_api_url);

        if project_api_url.cannot_be_a_base() {
            let url_err_msg = "the project API URL must be a valid base URL";
            return Err(NewSkySparkClientError::url(url_err_msg));
        }

        if !has_valid_path_segments(&project_api_url) {
            let url_err_msg = "URL must be formatted similarly to http://www.test.com/api/project/";
            return Err(NewSkySparkClientError::url(url_err_msg));
        }

        Ok(SkySparkClient {
            auth_token: new_auth_token(
                &project_api_url,
                &client_seed,
                username,
                password,
            )
            .await?,
            client_seed,
            username: username.to_owned(),
            password: password.to_owned(),
            project_api_url,
        })
    }

    #[cfg(test)]
    pub(crate) fn test_manually_set_auth_token(&mut self, auth_token: &str) {
        self.auth_token = auth_token.to_owned();
    }

    #[cfg(test)]
    pub(crate) fn test_auth_token(&self) -> &str {
        &self.auth_token
    }

    async fn update_auth_token(
        &mut self,
    ) -> StdResult<(), crate::auth::AuthError> {
        let auth_token = new_auth_token(
            self.project_api_url(),
            &self.client_seed,
            &self.username,
            &self.password,
        )
        .await?;
        self.auth_token = auth_token;
        Ok(())
    }

    fn client(&self) -> &reqwest::Client {
        self.client_seed.client()
    }

    fn auth_header_value(&self) -> String {
        format!("BEARER authToken={}", self.auth_token)
    }

    fn eval_url(&self) -> Url {
        self.append_to_url("eval")
    }

    async fn get(&mut self, url: Url) -> Result<Grid> {
        let res = self.get_response(url.clone()).await?;

        if res.status() == reqwest::StatusCode::FORBIDDEN {
            self.update_auth_token().await?;
            let retry_res = self.get_response(url).await?;
            http_response_to_grid(retry_res).await
        } else {
            http_response_to_grid(res).await
        }
    }

    async fn get_response(&self, url: Url) -> Result<reqwest::Response> {
        self.client()
            .get(url)
            .header("Accept", "application/json")
            .header("Authorization", self.auth_header_value())
            .send()
            .await
            .map_err(|err| err.into())
    }

    async fn post(&mut self, url: Url, grid: &Grid) -> Result<Grid> {
        let res = self.post_response(url.clone(), grid).await?;

        if res.status() == reqwest::StatusCode::FORBIDDEN {
            self.update_auth_token().await?;
            let retry_res = self.post_response(url, grid).await?;
            http_response_to_grid(retry_res).await
        } else {
            http_response_to_grid(res).await
        }
    }

    async fn post_response(
        &self,
        url: Url,
        grid: &Grid,
    ) -> Result<reqwest::Response> {
        self.client()
            .post(url)
            .header("Accept", "application/json")
            .header("Authorization", self.auth_header_value())
            .header("Content-Type", "application/json")
            .body(grid.to_json_string())
            .send()
            .await
            .map_err(|err| err.into())
    }

    fn append_to_url(&self, s: &str) -> Url {
        self.project_api_url
            .join(s)
            .expect("since url ends with '/' this should never fail")
    }

    /// Return the project name for this client.
    pub fn project_name(&self) -> &str {
        // Since the URL is validated by the `SkySparkClient::new` function,
        // the following code shouldn't panic:
        self.project_api_url
            .path_segments()
            .expect("proj api url is a valid base URL so this shouldn't fail")
            .nth(1)
            .expect("since URL is valid, the project name should be present")
    }

    /// Return the project API url being used by this client.
    pub fn project_api_url(&self) -> &Url {
        &self.project_api_url
    }
}

/// If the given url ends with a backslash, return the url without
/// any modifications. If the given url does not end with a backslash,
/// append a backslash to the end and return a new `Url`.
pub(crate) fn add_backslash_if_necessary(url: Url) -> Url {
    let chars = url.as_str().chars().collect::<Vec<_>>();
    let last_char = chars.last().expect("parsed url should have >= 1 chars");
    if *last_char != '/' {
        Url::parse(&(url.to_string() + "/")).expect("adding '/' to the end of a parsable url should create another parsable url")
    } else {
        url
    }
}

impl SkySparkClient {
    /// Returns a grid containing basic server information.
    pub async fn about(&mut self) -> Result<Grid> {
        self.get(self.about_url()).await
    }

    /// Returns a grid describing what MIME types are available.
    pub async fn formats(&mut self) -> Result<Grid> {
        self.get(self.formats_url()).await
    }

    /// Returns a grid of history data for a single point.
    pub async fn his_read(
        &mut self,
        id: &Ref,
        range: &HisReadRange,
    ) -> Result<Grid> {
        use raystack_core::Hayson;
        let row = json!({
            "id": id.to_hayson(),
            "range": range.to_json_request_string()
        });
        let req_grid = Grid::new_internal(vec![row]);

        self.post(self.his_read_url(), &req_grid).await
    }

    /// Writes boolean values to a single point.
    pub async fn his_write_bool(
        &mut self,
        id: &Ref,
        his_data: &[(DateTime, bool)],
    ) -> Result<Grid> {
        use raystack_core::Hayson;

        let rows = his_data
            .iter()
            .map(|(date_time, value)| {
                json!({
                    "ts": date_time.to_hayson(),
                    "val": value
                })
            })
            .collect();

        let mut req_grid = Grid::new_internal(rows);
        req_grid.add_ref_to_meta(id);

        self.post(self.his_write_url(), &req_grid).await
    }

    /// Writes numeric values to a single point. `unit` must be a valid
    /// Haystack unit literal, such as `L/s` or `celsius`.
    pub async fn his_write_num(
        &mut self,
        id: &Ref,
        his_data: &[(DateTime, Number)],
    ) -> Result<Grid> {
        use raystack_core::Hayson;

        let rows = his_data
            .iter()
            .map(|(date_time, value)| {
                json!({
                    "ts": date_time.to_hayson(),
                    "val": value.to_hayson(),
                })
            })
            .collect();

        let mut req_grid = Grid::new_internal(rows);
        req_grid.add_ref_to_meta(id);

        self.post(self.his_write_url(), &req_grid).await
    }

    /// Writes string values to a single point.
    pub async fn his_write_str(
        &mut self,
        id: &Ref,
        his_data: &[(DateTime, String)],
    ) -> Result<Grid> {
        use raystack_core::Hayson;

        let rows = his_data
            .iter()
            .map(|(date_time, value)| {
                json!({
                    "ts": date_time.to_hayson(),
                    "val": value
                })
            })
            .collect();

        let mut req_grid = Grid::new_internal(rows);
        req_grid.add_ref_to_meta(id);

        self.post(self.his_write_url(), &req_grid).await
    }

    /// Writes boolean values with UTC timestamps to a single point.
    /// `time_zone_name` must be a valid SkySpark timezone name.
    pub async fn utc_his_write_bool(
        &mut self,
        id: &Ref,
        time_zone_name: &str,
        his_data: &[(chrono::DateTime<Utc>, bool)],
    ) -> Result<Grid> {
        use raystack_core::Hayson;

        let tz = skyspark_tz_string_to_tz(time_zone_name).ok_or_else(|| {
            Error::TimeZone {
                err_time_zone: time_zone_name.to_owned(),
            }
        })?;

        let rows = his_data
            .iter()
            .map(|(date_time, value)| {
                let date_time: DateTime = date_time.with_timezone(&tz).into();
                json!({
                    "ts": date_time.to_hayson(),
                    "val": value
                })
            })
            .collect();

        let mut req_grid = Grid::new_internal(rows);
        req_grid.add_ref_to_meta(id);

        self.post(self.his_write_url(), &req_grid).await
    }

    /// Writes numeric values with UTC timestamps to a single point.
    /// `unit` must be a valid Haystack unit literal, such as `L/s` or
    /// `celsius`.
    /// `time_zone_name` must be a valid SkySpark timezone name.
    pub async fn utc_his_write_num(
        &mut self,
        id: &Ref,
        time_zone_name: &str,
        his_data: &[(chrono::DateTime<Utc>, Number)],
    ) -> Result<Grid> {
        use raystack_core::Hayson;

        let tz = skyspark_tz_string_to_tz(time_zone_name).ok_or_else(|| {
            Error::TimeZone {
                err_time_zone: time_zone_name.to_owned(),
            }
        })?;

        let rows = his_data
            .iter()
            .map(|(date_time, value)| {
                let date_time: DateTime = date_time.with_timezone(&tz).into();

                json!({
                    "ts": date_time.to_hayson(),
                    "val": value.to_hayson(),
                })
            })
            .collect();

        let mut req_grid = Grid::new_internal(rows);
        req_grid.add_ref_to_meta(id);

        self.post(self.his_write_url(), &req_grid).await
    }

    /// Writes string values with UTC timestamps to a single point.
    /// `time_zone_name` must be a valid SkySpark timezone name.
    pub async fn utc_his_write_str(
        &mut self,
        id: &Ref,
        time_zone_name: &str,
        his_data: &[(chrono::DateTime<Utc>, String)],
    ) -> Result<Grid> {
        use raystack_core::Hayson;

        let tz = skyspark_tz_string_to_tz(time_zone_name).ok_or_else(|| {
            Error::TimeZone {
                err_time_zone: time_zone_name.to_owned(),
            }
        })?;

        let rows = his_data
            .iter()
            .map(|(date_time, value)| {
                let date_time: DateTime = date_time.with_timezone(&tz).into();

                json!({
                    "ts": date_time.to_hayson(),
                    "val": value,
                })
            })
            .collect();

        let mut req_grid = Grid::new_internal(rows);
        req_grid.add_ref_to_meta(id);

        self.post(self.his_write_url(), &req_grid).await
    }

    /// The Haystack nav operation.
    pub async fn nav(&mut self, nav_id: Option<&Ref>) -> Result<Grid> {
        use raystack_core::Hayson;
        let req_grid = match nav_id {
            Some(nav_id) => {
                let row = json!({ "navId": nav_id.to_hayson() });
                Grid::new_internal(vec![row])
            }
            None => Grid::new_internal(Vec::new()),
        };

        self.post(self.nav_url(), &req_grid).await
    }

    /// Returns a grid containing the operations available on the server.
    pub async fn ops(&mut self) -> Result<Grid> {
        self.get(self.ops_url()).await
    }

    /// Returns a grid containing the records matching the given Axon
    /// filter string.
    pub async fn read(
        &mut self,
        filter: &str,
        limit: Option<u64>,
    ) -> Result<Grid> {
        let row = match limit {
            Some(integer) => json!({"filter": filter, "limit": integer}),
            None => json!({ "filter": filter }),
        };

        let req_grid = Grid::new_internal(vec![row]);
        self.post(self.read_url(), &req_grid).await
    }

    /// Returns a grid containing the records matching the given id
    /// `Ref`s.
    pub async fn read_by_ids(&mut self, ids: &[Ref]) -> Result<Grid> {
        use raystack_core::Hayson;
        let rows = ids.iter().map(|id| json!({"id": id.to_hayson()})).collect();

        let req_grid = Grid::new_internal(rows);
        self.post(self.read_url(), &req_grid).await
    }
}

impl HaystackUrl for SkySparkClient {
    fn about_url(&self) -> Url {
        self.append_to_url("about")
    }

    fn formats_url(&self) -> Url {
        self.append_to_url("formats")
    }

    fn his_read_url(&self) -> Url {
        self.append_to_url("hisRead")
    }

    fn his_write_url(&self) -> Url {
        self.append_to_url("hisWrite")
    }

    fn nav_url(&self) -> Url {
        self.append_to_url("nav")
    }

    fn ops_url(&self) -> Url {
        self.append_to_url("ops")
    }

    fn read_url(&self) -> Url {
        self.append_to_url("read")
    }
}

impl SkySparkClient {
    pub async fn eval(&mut self, axon_expr: &str) -> Result<Grid> {
        let row = json!({ "expr": axon_expr });
        let req_grid = Grid::new_internal(vec![row]);
        self.post(self.eval_url(), &req_grid).await
    }
}

async fn http_response_to_grid(res: reqwest::Response) -> Result<Grid> {
    let json: serde_json::Value = res.json().await?;
    let grid: Grid = json.try_into()?;

    if grid.is_error() {
        Err(Error::Grid { err_grid: grid })
    } else {
        Ok(grid)
    }
}

/// Returns true if the given URL appears to have the correct path
/// segments for a SkySpark API URL. The URL should end with a '/' character.
pub(crate) fn has_valid_path_segments(project_api_url: &Url) -> bool {
    if let Some(mut segments) = project_api_url.path_segments() {
        let api_literal = segments.next();
        let proj_name = segments.next();
        let blank = segments.next();
        let should_be_none = segments.next();

        match (api_literal, proj_name, blank, should_be_none) {
            (_, Some(""), _, _) => false,
            (Some("api"), Some(_), Some(""), None) => true,
            _ => false,
        }
    } else {
        false
    }
}

#[cfg(test)]
mod test {
    use crate::api::HisReadRange;
    use crate::ClientSeed;
    use crate::SkySparkClient;
    use crate::ValueExt;
    use raystack_core::{Number, Ref};
    use serde_json::json;
    use url::Url;

    fn project_api_url() -> Url {
        let url_str =
            std::env::var("RAYSTACK_SKYSPARK_PROJECT_API_URL").unwrap();
        Url::parse(&url_str).unwrap()
    }

    fn username() -> String {
        std::env::var("RAYSTACK_SKYSPARK_USERNAME").unwrap()
    }

    fn password() -> String {
        std::env::var("RAYSTACK_SKYSPARK_PASSWORD").unwrap()
    }

    async fn new_client() -> SkySparkClient {
        let username = username();
        let password = password();
        let seed = ClientSeed::new(15).unwrap();
        SkySparkClient::new(project_api_url(), &username, &password, seed)
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn about() {
        let mut client = new_client().await;
        let grid = client.about().await.unwrap();
        assert_eq!(grid.rows()[0]["whoami"], json!(username()));
    }

    #[tokio::test]
    async fn formats() {
        let mut client = new_client().await;
        let grid = client.formats().await.unwrap();
        assert!(grid.rows()[0]["dis"].is_string());
    }

    #[tokio::test]
    async fn his_read_today() {
        let range = HisReadRange::Today;
        his_read(&range).await;
    }

    #[tokio::test]
    async fn his_read_yesterday() {
        let range = HisReadRange::Yesterday;
        his_read(&range).await;
    }

    #[tokio::test]
    async fn his_read_date() {
        let range =
            HisReadRange::Date(chrono::NaiveDate::from_ymd(2019, 1, 1).into());
        his_read(&range).await;
    }

    #[tokio::test]
    async fn his_read_date_span() {
        let range = HisReadRange::DateSpan {
            start: chrono::NaiveDate::from_ymd(2019, 1, 1).into(),
            end: chrono::NaiveDate::from_ymd(2019, 1, 2).into(),
        };
        his_read(&range).await;
    }

    #[tokio::test]
    async fn his_read_date_time_span() {
        use chrono::{DateTime, Duration};
        use chrono_tz::Australia::Sydney;

        let start = DateTime::parse_from_rfc3339("2019-01-01T00:00:00+10:00")
            .unwrap()
            .with_timezone(&Sydney);
        let end = start + Duration::days(1);
        let range = HisReadRange::DateTimeSpan {
            start: start.into(),
            end: end.into(),
        };
        his_read(&range).await;
    }

    #[tokio::test]
    async fn his_read_date_time() {
        use chrono::DateTime;
        use chrono_tz::Australia::Sydney;

        let date_time =
            DateTime::parse_from_rfc3339("2012-10-01T00:00:00+10:00")
                .unwrap()
                .with_timezone(&Sydney);
        let range = HisReadRange::SinceDateTime {
            date_time: date_time.into(),
        };
        his_read(&range).await;
    }

    #[tokio::test]
    async fn his_read_date_time_utc() {
        use chrono::DateTime;
        use chrono_tz::Etc::UTC;

        let date_time = DateTime::parse_from_rfc3339("2012-10-01T00:00:00Z")
            .unwrap()
            .with_timezone(&UTC);
        let range = HisReadRange::SinceDateTime {
            date_time: date_time.into(),
        };
        his_read(&range).await;
    }

    async fn his_read(range: &HisReadRange) {
        let filter = format!("point and his and hisEnd");

        let mut client = new_client().await;
        let points_grid = client.read(&filter, Some(1)).await.unwrap();

        let point_ref = points_grid.rows()[0]["id"].as_hs_ref().unwrap();
        let his_grid = client.his_read(&point_ref, &range).await.unwrap();

        assert!(his_grid.meta()["hisStart"].is_hs_date_time());
        assert!(his_grid.meta()["hisEnd"].is_hs_date_time());
    }

    async fn get_ref_for_filter(
        client: &mut SkySparkClient,
        filter: &str,
    ) -> Ref {
        let points_grid = client.read(filter, Some(1)).await.unwrap();
        let point_ref = points_grid.rows()[0]["id"].as_hs_ref().unwrap();
        point_ref
    }

    #[tokio::test]
    async fn utc_his_write_bool() {
        use chrono::{DateTime, Duration, NaiveDateTime, Utc};

        let ndt = NaiveDateTime::parse_from_str(
            "2021-01-10 00:00:00",
            "%Y-%m-%d %H:%M:%S",
        )
        .unwrap();

        let date_time1 = DateTime::from_utc(ndt, Utc);
        let date_time2 = date_time1 + Duration::minutes(5);
        let date_time3 = date_time1 + Duration::minutes(10);

        let mut client = new_client().await;

        let id = get_ref_for_filter(
            &mut client,
            "continuousIntegrationHisWritePoint and kind == \"Bool\"",
        )
        .await;
        let his_data = vec![
            (date_time1, false),
            (date_time2, false),
            (date_time3, false),
        ];

        let res = client
            .utc_his_write_bool(&id, "Sydney", &his_data[..])
            .await
            .unwrap();
        assert_eq!(res.rows().len(), 0);
    }

    #[tokio::test]
    async fn his_write_bool() {
        use chrono::{DateTime, Duration};
        use chrono_tz::Australia::Sydney;

        let mut client = new_client().await;

        let date_time1 =
            DateTime::parse_from_rfc3339("2019-08-01T00:00:00+10:00")
                .unwrap()
                .with_timezone(&Sydney);
        let date_time2 = date_time1 + Duration::minutes(5);
        let date_time3 = date_time1 + Duration::minutes(10);

        let id = get_ref_for_filter(
            &mut client,
            "continuousIntegrationHisWritePoint and kind == \"Bool\"",
        )
        .await;
        let his_data = vec![
            (date_time1.into(), true),
            (date_time2.into(), false),
            (date_time3.into(), true),
        ];

        let res = client.his_write_bool(&id, &his_data[..]).await.unwrap();
        assert_eq!(res.rows().len(), 0);
    }

    #[tokio::test]
    async fn utc_his_write_num() {
        use chrono::{Duration, NaiveDateTime, Utc};

        let ndt = NaiveDateTime::parse_from_str(
            "2021-01-10 00:00:00",
            "%Y-%m-%d %H:%M:%S",
        )
        .unwrap();

        let date_time1: chrono::DateTime<Utc> =
            chrono::DateTime::from_utc(ndt, Utc);
        let date_time2 = date_time1 + Duration::minutes(5);
        let date_time3 = date_time1 + Duration::minutes(10);

        let mut client = new_client().await;

        let id = get_ref_for_filter(
            &mut client,
            "continuousIntegrationHisWritePoint and kind == \"Number\" and unit",
        )
        .await;

        let unit = Some("L/s".to_owned());

        let his_data = vec![
            (date_time1, Number::new(111.111, unit.clone())),
            (date_time2, Number::new(222.222, unit.clone())),
            (date_time3, Number::new(333.333, unit.clone())),
        ];

        let res = client
            .utc_his_write_num(&id, "Sydney", &his_data[..])
            .await
            .unwrap();
        assert_eq!(res.rows().len(), 0);
    }

    #[tokio::test]
    async fn his_write_num() {
        use chrono::{DateTime, Duration};
        use chrono_tz::Australia::Sydney;

        let date_time1 =
            DateTime::parse_from_rfc3339("2019-08-01T00:00:00+10:00")
                .unwrap()
                .with_timezone(&Sydney);
        let date_time2 = date_time1 + Duration::minutes(5);
        let date_time3 = date_time1 + Duration::minutes(10);

        let mut client = new_client().await;

        let id = get_ref_for_filter(
            &mut client,
            "continuousIntegrationHisWritePoint and kind == \"Number\" and unit",
        )
        .await;

        let unit = Some("L/s".to_owned());

        let his_data = vec![
            (date_time1.into(), Number::new(10.0, unit.clone())),
            (date_time2.into(), Number::new(15.34, unit.clone())),
            (date_time3.into(), Number::new(1.234, unit.clone())),
        ];

        let res = client.his_write_num(&id, &his_data[..]).await.unwrap();
        assert_eq!(res.rows().len(), 0);
    }

    #[tokio::test]
    async fn utc_his_write_num_no_unit() {
        use chrono::{Duration, NaiveDateTime, Utc};

        let ndt = NaiveDateTime::parse_from_str(
            "2021-01-10 00:00:00",
            "%Y-%m-%d %H:%M:%S",
        )
        .unwrap();

        let date_time1: chrono::DateTime<Utc> =
            chrono::DateTime::from_utc(ndt, Utc);
        let date_time2 = date_time1 + Duration::minutes(5);
        let date_time3 = date_time1 + Duration::minutes(10);

        let mut client = new_client().await;

        let id = get_ref_for_filter(
            &mut client,
            "continuousIntegrationHisWritePoint and kind == \"Number\" and not unit",
        )
        .await;
        let his_data = vec![
            (date_time1, Number::new_unitless(11.11)),
            (date_time2, Number::new_unitless(22.22)),
            (date_time3, Number::new_unitless(33.33)),
        ];

        let res = client
            .utc_his_write_num(&id, "Sydney", &his_data[..])
            .await
            .unwrap();
        assert_eq!(res.rows().len(), 0);
    }

    #[tokio::test]
    async fn his_write_num_no_unit() {
        use chrono::{DateTime, Duration};
        use chrono_tz::Australia::Sydney;

        let date_time1 =
            DateTime::parse_from_rfc3339("2019-08-01T00:00:00+10:00")
                .unwrap()
                .with_timezone(&Sydney);
        let date_time2 = date_time1 + Duration::minutes(5);
        let date_time3 = date_time1 + Duration::minutes(10);

        let mut client = new_client().await;

        let id = get_ref_for_filter(
            &mut client,
            "continuousIntegrationHisWritePoint and kind == \"Number\" and not unit",
        )
        .await;

        let his_data = vec![
            (date_time1.into(), Number::new_unitless(10.0)),
            (date_time2.into(), Number::new_unitless(15.34)),
            (date_time3.into(), Number::new_unitless(1.234)),
        ];

        let res = client.his_write_num(&id, &his_data[..]).await.unwrap();
        assert_eq!(res.rows().len(), 0);
    }

    #[tokio::test]
    async fn utc_his_write_str() {
        use chrono::{DateTime, Duration, NaiveDateTime, Utc};

        let ndt = NaiveDateTime::parse_from_str(
            "2021-01-10 00:00:00",
            "%Y-%m-%d %H:%M:%S",
        )
        .unwrap();

        let date_time1 = DateTime::from_utc(ndt, Utc);
        let date_time2 = date_time1 + Duration::minutes(5);
        let date_time3 = date_time1 + Duration::minutes(10);

        let mut client = new_client().await;
        let id = get_ref_for_filter(
            &mut client,
            "continuousIntegrationHisWritePoint and kind == \"Str\"",
        )
        .await;

        let his_data = vec![
            (date_time1, "utc".to_owned()),
            (date_time2, "data".to_owned()),
            (date_time3, "here".to_owned()),
        ];

        let res = client
            .utc_his_write_str(&id, "Sydney", &his_data[..])
            .await
            .unwrap();
        assert_eq!(res.rows().len(), 0);
    }

    #[tokio::test]
    async fn his_write_str() {
        use chrono::{DateTime, Duration};
        use chrono_tz::Australia::Sydney;

        let date_time1 =
            DateTime::parse_from_rfc3339("2019-08-01T00:00:00+10:00")
                .unwrap()
                .with_timezone(&Sydney);
        let date_time2 = date_time1 + Duration::minutes(5);
        let date_time3 = date_time1 + Duration::minutes(10);

        let mut client = new_client().await;
        let id = get_ref_for_filter(
            &mut client,
            "continuousIntegrationHisWritePoint and kind == \"Str\"",
        )
        .await;

        let his_data = vec![
            (date_time1.into(), "hello".to_owned()),
            (date_time2.into(), "world".to_owned()),
            (date_time3.into(), "!".to_owned()),
        ];

        let res = client.his_write_str(&id, &his_data[..]).await.unwrap();
        assert_eq!(res.rows().len(), 0);
    }

    #[tokio::test]
    async fn nav_root() {
        let mut client = new_client().await;
        let grid = client.nav(None).await.unwrap();
        assert!(grid.rows()[0]["navId"].is_hs_ref());
    }

    #[tokio::test]
    async fn nav() {
        let mut client = new_client().await;
        let root_grid = client.nav(None).await.unwrap();
        let child_nav_id = root_grid.rows()[0]["navId"].as_hs_ref().unwrap();

        let child_grid = client.nav(Some(&child_nav_id)).await.unwrap();
        let final_nav_id = child_grid.rows()[0]["navId"].as_hs_ref().unwrap();
        assert_ne!(child_nav_id, final_nav_id);
    }

    #[tokio::test]
    async fn ops() {
        let mut client = new_client().await;
        let grid = client.ops().await.unwrap();
        assert!(grid.rows()[0]["name"].is_string());
    }

    #[tokio::test]
    async fn read_with_no_limit() {
        let mut client = new_client().await;
        let grid = client.read("point", None).await.unwrap();

        assert!(grid.rows()[0]["id"].is_hs_ref());
        assert!(grid.rows().len() > 10);
    }

    #[tokio::test]
    async fn read_with_zero_limit() {
        let mut client = new_client().await;
        let grid = client.read("id", Some(0)).await.unwrap();
        assert_eq!(grid.rows().len(), 0);
    }

    #[tokio::test]
    async fn read_with_non_zero_limit() {
        let mut client = new_client().await;
        let grid = client.read("id", Some(1)).await.unwrap();
        assert_eq!(grid.rows().len(), 1);

        let grid = client.read("id", Some(3)).await.unwrap();
        assert_eq!(grid.rows().len(), 3);
    }

    #[tokio::test]
    async fn read_by_ids_with_no_ids() {
        let mut client = new_client().await;
        let ids = vec![];
        let grid_result = client.read_by_ids(&ids).await;
        assert!(grid_result.is_err());
    }

    #[tokio::test]
    async fn read_by_ids_single() {
        let mut client = new_client().await;
        // Get some valid ids:
        let grid1 = client.read("id", Some(1)).await.unwrap();
        let ref1 = grid1.rows()[0]["id"].as_hs_ref().unwrap().clone();
        let ids = vec![ref1];
        let grid2 = client.read_by_ids(&ids).await.unwrap();
        assert_eq!(grid1, grid2);
    }

    #[tokio::test]
    async fn read_by_ids_multiple() {
        let mut client = new_client().await;
        // Get some valid ids:
        let grid1 = client.read("id", Some(2)).await.unwrap();
        let ref1 = grid1.rows()[0]["id"].as_hs_ref().unwrap().clone();
        let ref2 = grid1.rows()[1]["id"].as_hs_ref().unwrap().clone();

        let ids = vec![ref1, ref2];
        let grid2 = client.read_by_ids(&ids).await.unwrap();
        assert_eq!(grid1, grid2);
    }

    #[tokio::test]
    async fn eval() {
        let mut client = new_client().await;
        let axon_expr = "readAll(id and mod)[0..1].keepCols([\"id\", \"mod\"])";
        let grid = client.eval(axon_expr).await.unwrap();
        assert!(grid.rows()[0]["id"].is_hs_ref());
    }

    #[test]
    fn add_backslash_necessary() {
        use crate::add_backslash_if_necessary;
        let url = Url::parse("http://www.example.com/api/proj").unwrap();
        let expected = Url::parse("http://www.example.com/api/proj/").unwrap();
        assert_eq!(add_backslash_if_necessary(url), expected);
    }

    #[test]
    fn add_backslash_not_necessary() {
        use crate::add_backslash_if_necessary;
        let url = Url::parse("http://www.example.com/api/proj/").unwrap();
        let expected = Url::parse("http://www.example.com/api/proj/").unwrap();
        assert_eq!(add_backslash_if_necessary(url), expected);
    }

    #[tokio::test]
    async fn error_grid() {
        use crate::err::Error;

        let mut client = new_client().await;
        let grid_result = client.eval("reabDDDAll(test").await;

        assert!(grid_result.is_err());
        let err = grid_result.err().unwrap();

        match err {
            Error::Grid { err_grid } => {
                assert!(err_grid.is_error());
                assert!(err_grid.error_trace().is_some());
            }
            _ => panic!(),
        }
    }

    #[tokio::test]
    async fn project_name_works() {
        let client = new_client().await;
        assert!(client.project_name().len() > 3);
    }

    #[test]
    fn has_valid_path_segments_works() {
        use super::has_valid_path_segments;

        let good_url = Url::parse("http://www.test.com/api/proj/").unwrap();
        assert!(has_valid_path_segments(&good_url));
        let bad_url1 = Url::parse("http://www.test.com/api/proj").unwrap();
        assert!(!has_valid_path_segments(&bad_url1));
        let bad_url2 = Url::parse("http://www.test.com/api/").unwrap();
        assert!(!has_valid_path_segments(&bad_url2));
        let bad_url3 =
            Url::parse("http://www.test.com/api/proj/extra").unwrap();
        assert!(!has_valid_path_segments(&bad_url3));
        let bad_url4 = Url::parse("http://www.test.com").unwrap();
        assert!(!has_valid_path_segments(&bad_url4));
        let bad_url5 = Url::parse("http://www.test.com/api//extra").unwrap();
        assert!(!has_valid_path_segments(&bad_url5));
    }

    #[tokio::test]
    async fn recovers_from_invalid_auth_token() {
        let mut client = new_client().await;

        let bad_token = "badauthtoken";

        assert_ne!(client.test_auth_token(), bad_token);

        // Check the client works before modifying the auth token:
        let grid1 = client.about().await.unwrap();
        assert_eq!(grid1.rows()[0]["whoami"], json!(username()));

        client.test_manually_set_auth_token(bad_token);
        assert_eq!(client.test_auth_token(), bad_token);

        // Check the client still works after setting a bad auth token:
        let grid2 = client.about().await.unwrap();
        assert_eq!(grid2.rows()[0]["whoami"], json!(username()));
    }
}