-
Notifications
You must be signed in to change notification settings - Fork 159
/
catalog.rs
1759 lines (1533 loc) · 55.5 KB
/
catalog.rs
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! This module contains rest catalog implementation.
use std::collections::HashMap;
use std::str::FromStr;
use async_trait::async_trait;
use itertools::Itertools;
use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue};
use reqwest::{Method, StatusCode, Url};
use tokio::sync::OnceCell;
use typed_builder::TypedBuilder;
use crate::client::HttpClient;
use crate::types::{
CatalogConfig, CommitTableRequest, CommitTableResponse, CreateTableRequest, ErrorResponse,
ListNamespaceResponse, ListTableResponse, LoadTableResponse, NamespaceSerde,
RenameTableRequest, NO_CONTENT, OK,
};
use iceberg::io::FileIO;
use iceberg::table::Table;
use iceberg::Result;
use iceberg::{
Catalog, Error, ErrorKind, Namespace, NamespaceIdent, TableCommit, TableCreation, TableIdent,
};
const ICEBERG_REST_SPEC_VERSION: &str = "0.14.1";
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
const PATH_V1: &str = "v1";
/// Rest catalog configuration.
#[derive(Clone, Debug, TypedBuilder)]
pub struct RestCatalogConfig {
uri: String,
#[builder(default, setter(strip_option))]
warehouse: Option<String>,
#[builder(default)]
props: HashMap<String, String>,
}
impl RestCatalogConfig {
fn url_prefixed(&self, parts: &[&str]) -> String {
[&self.uri, PATH_V1]
.into_iter()
.chain(self.props.get("prefix").map(|s| &**s))
.chain(parts.iter().cloned())
.join("/")
}
fn config_endpoint(&self) -> String {
[&self.uri, PATH_V1, "config"].join("/")
}
pub(crate) fn get_token_endpoint(&self) -> String {
if let Some(auth_url) = self.props.get("rest.authorization-url") {
auth_url.to_string()
} else {
[&self.uri, PATH_V1, "oauth", "tokens"].join("/")
}
}
fn namespaces_endpoint(&self) -> String {
self.url_prefixed(&["namespaces"])
}
fn namespace_endpoint(&self, ns: &NamespaceIdent) -> String {
self.url_prefixed(&["namespaces", &ns.to_url_string()])
}
fn tables_endpoint(&self, ns: &NamespaceIdent) -> String {
self.url_prefixed(&["namespaces", &ns.to_url_string(), "tables"])
}
fn rename_table_endpoint(&self) -> String {
self.url_prefixed(&["tables", "rename"])
}
fn table_endpoint(&self, table: &TableIdent) -> String {
self.url_prefixed(&[
"namespaces",
&table.namespace.to_url_string(),
"tables",
&table.name,
])
}
/// Get the token from the config.
///
/// Client will use `token` to send requests if exists.
pub(crate) fn token(&self) -> Option<String> {
self.props.get("token").cloned()
}
/// Get the credentials from the config. Client will use `credential`
/// to fetch a new token if exists.
///
/// ## Output
///
/// - `None`: No credential is set.
/// - `Some(None, client_secret)`: No client_id is set, use client_secret directly.
/// - `Some(Some(client_id), client_secret)`: Both client_id and client_secret are set.
pub(crate) fn credential(&self) -> Option<(Option<String>, String)> {
let cred = self.props.get("credential")?;
match cred.split_once(':') {
Some((client_id, client_secret)) => {
Some((Some(client_id.to_string()), client_secret.to_string()))
}
None => Some((None, cred.to_string())),
}
}
/// Get the extra headers from config.
///
/// We will include:
///
/// - `content-type`
/// - `x-client-version`
/// - `user-agnet`
/// - all headers specified by `header.xxx` in props.
pub(crate) fn extra_headers(&self) -> Result<HeaderMap> {
let mut headers = HeaderMap::from_iter([
(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
),
(
HeaderName::from_static("x-client-version"),
HeaderValue::from_static(ICEBERG_REST_SPEC_VERSION),
),
(
header::USER_AGENT,
HeaderValue::from_str(&format!("iceberg-rs/{}", CARGO_PKG_VERSION)).unwrap(),
),
]);
for (key, value) in self
.props
.iter()
.filter(|(k, _)| k.starts_with("header."))
// The unwrap here is same since we are filtering the keys
.map(|(k, v)| (k.strip_prefix("header.").unwrap(), v))
{
headers.insert(
HeaderName::from_str(key).map_err(|e| {
Error::new(
ErrorKind::DataInvalid,
format!("Invalid header name: {key}"),
)
.with_source(e)
})?,
HeaderValue::from_str(value).map_err(|e| {
Error::new(
ErrorKind::DataInvalid,
format!("Invalid header value: {value}"),
)
.with_source(e)
})?,
);
}
Ok(headers)
}
/// Get the optional oauth headers from the config.
pub(crate) fn extra_oauth_params(&self) -> HashMap<String, String> {
let mut params = HashMap::new();
if let Some(scope) = self.props.get("scope") {
params.insert("scope".to_string(), scope.to_string());
} else {
params.insert("scope".to_string(), "catalog".to_string());
}
let optional_params = ["audience", "resource"];
for param_name in optional_params {
if let Some(value) = self.props.get(param_name) {
params.insert(param_name.to_string(), value.to_string());
}
}
params
}
/// Merge the config with the given config fetched from rest server.
pub(crate) fn merge_with_config(mut self, mut config: CatalogConfig) -> Self {
if let Some(uri) = config.overrides.remove("uri") {
self.uri = uri;
}
let mut props = config.defaults;
props.extend(self.props);
props.extend(config.overrides);
self.props = props;
self
}
}
#[derive(Debug)]
struct RestContext {
client: HttpClient,
/// Runtime config is fetched from rest server and stored here.
///
/// It's could be different from the user config.
config: RestCatalogConfig,
}
impl RestContext {}
/// Rest catalog implementation.
#[derive(Debug)]
pub struct RestCatalog {
/// User config is stored as-is and never be changed.
///
/// It's could be different from the config fetched from the server and used at runtime.
user_config: RestCatalogConfig,
ctx: OnceCell<RestContext>,
}
impl RestCatalog {
/// Creates a rest catalog from config.
pub fn new(config: RestCatalogConfig) -> Self {
Self {
user_config: config,
ctx: OnceCell::new(),
}
}
/// Get the context from the catalog.
async fn context(&self) -> Result<&RestContext> {
self.ctx
.get_or_try_init(|| async {
let catalog_config = RestCatalog::load_config(&self.user_config).await?;
let config = self.user_config.clone().merge_with_config(catalog_config);
let client = HttpClient::new(&config)?;
Ok(RestContext { config, client })
})
.await
}
/// Load the runtime config from the server by user_config.
///
/// It's required for a rest catalog to update it's config after creation.
async fn load_config(user_config: &RestCatalogConfig) -> Result<CatalogConfig> {
let client = HttpClient::new(user_config)?;
let mut request = client.request(Method::GET, user_config.config_endpoint());
if let Some(warehouse_location) = &user_config.warehouse {
request = request.query(&[("warehouse", warehouse_location)]);
}
let config = client
.query::<CatalogConfig, ErrorResponse, OK>(request.build()?)
.await?;
Ok(config)
}
async fn load_file_io(
&self,
metadata_location: Option<&str>,
extra_config: Option<HashMap<String, String>>,
) -> Result<FileIO> {
let mut props = self.context().await?.config.props.clone();
if let Some(config) = extra_config {
props.extend(config);
}
// If the warehouse is a logical identifier instead of a URL we don't want
// to raise an exception
let warehouse_path = match self.context().await?.config.warehouse.as_deref() {
Some(url) if Url::parse(url).is_ok() => Some(url),
Some(_) => None,
None => None,
};
let file_io = match warehouse_path.or(metadata_location) {
Some(url) => FileIO::from_path(url)?.with_props(props).build()?,
None => {
return Err(Error::new(
ErrorKind::Unexpected,
"Unable to load file io, neither warehouse nor metadata location is set!",
))?
}
};
Ok(file_io)
}
}
#[async_trait]
impl Catalog for RestCatalog {
/// List namespaces from table.
async fn list_namespaces(
&self,
parent: Option<&NamespaceIdent>,
) -> Result<Vec<NamespaceIdent>> {
let mut request = self.context().await?.client.request(
Method::GET,
self.context().await?.config.namespaces_endpoint(),
);
if let Some(ns) = parent {
request = request.query(&[("parent", ns.to_url_string())]);
}
let resp = self
.context()
.await?
.client
.query::<ListNamespaceResponse, ErrorResponse, OK>(request.build()?)
.await?;
resp.namespaces
.into_iter()
.map(NamespaceIdent::from_vec)
.collect::<Result<Vec<NamespaceIdent>>>()
}
/// Create a new namespace inside the catalog.
async fn create_namespace(
&self,
namespace: &NamespaceIdent,
properties: HashMap<String, String>,
) -> Result<Namespace> {
let request = self
.context()
.await?
.client
.request(
Method::POST,
self.context().await?.config.namespaces_endpoint(),
)
.json(&NamespaceSerde {
namespace: namespace.as_ref().clone(),
properties: Some(properties),
})
.build()?;
let resp = self
.context()
.await?
.client
.query::<NamespaceSerde, ErrorResponse, OK>(request)
.await?;
Namespace::try_from(resp)
}
/// Get a namespace information from the catalog.
async fn get_namespace(&self, namespace: &NamespaceIdent) -> Result<Namespace> {
let request = self
.context()
.await?
.client
.request(
Method::GET,
self.context().await?.config.namespace_endpoint(namespace),
)
.build()?;
let resp = self
.context()
.await?
.client
.query::<NamespaceSerde, ErrorResponse, OK>(request)
.await?;
Namespace::try_from(resp)
}
/// Update a namespace inside the catalog.
///
/// # Behavior
///
/// The properties must be the full set of namespace.
async fn update_namespace(
&self,
_namespace: &NamespaceIdent,
_properties: HashMap<String, String>,
) -> Result<()> {
Err(Error::new(
ErrorKind::FeatureUnsupported,
"Updating namespace not supported yet!",
))
}
async fn namespace_exists(&self, ns: &NamespaceIdent) -> Result<bool> {
let request = self
.context()
.await?
.client
.request(
Method::HEAD,
self.context().await?.config.namespace_endpoint(ns),
)
.build()?;
self.context()
.await?
.client
.do_execute::<bool, ErrorResponse>(request, |resp| match resp.status() {
StatusCode::NO_CONTENT => Some(true),
StatusCode::NOT_FOUND => Some(false),
_ => None,
})
.await
}
/// Drop a namespace from the catalog.
async fn drop_namespace(&self, namespace: &NamespaceIdent) -> Result<()> {
let request = self
.context()
.await?
.client
.request(
Method::DELETE,
self.context().await?.config.namespace_endpoint(namespace),
)
.build()?;
self.context()
.await?
.client
.execute::<ErrorResponse, NO_CONTENT>(request)
.await
}
/// List tables from namespace.
async fn list_tables(&self, namespace: &NamespaceIdent) -> Result<Vec<TableIdent>> {
let request = self
.context()
.await?
.client
.request(
Method::GET,
self.context().await?.config.tables_endpoint(namespace),
)
.build()?;
let resp = self
.context()
.await?
.client
.query::<ListTableResponse, ErrorResponse, OK>(request)
.await?;
Ok(resp.identifiers)
}
/// Create a new table inside the namespace.
async fn create_table(
&self,
namespace: &NamespaceIdent,
creation: TableCreation,
) -> Result<Table> {
let table_ident = TableIdent::new(namespace.clone(), creation.name.clone());
let request = self
.context()
.await?
.client
.request(
Method::POST,
self.context().await?.config.tables_endpoint(namespace),
)
.json(&CreateTableRequest {
name: creation.name,
location: creation.location,
schema: creation.schema,
partition_spec: creation.partition_spec,
write_order: creation.sort_order,
// We don't support stage create yet.
stage_create: Some(false),
properties: if creation.properties.is_empty() {
None
} else {
Some(creation.properties)
},
})
.build()?;
let resp = self
.context()
.await?
.client
.query::<LoadTableResponse, ErrorResponse, OK>(request)
.await?;
let file_io = self
.load_file_io(resp.metadata_location.as_deref(), resp.config)
.await?;
let table = Table::builder()
.identifier(table_ident)
.file_io(file_io)
.metadata(resp.metadata)
.metadata_location(resp.metadata_location.ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
"Metadata location missing in create table response!",
)
})?)
.build();
Ok(table)
}
/// Load table from the catalog.
async fn load_table(&self, table: &TableIdent) -> Result<Table> {
let request = self
.context()
.await?
.client
.request(
Method::GET,
self.context().await?.config.table_endpoint(table),
)
.build()?;
let resp = self
.context()
.await?
.client
.query::<LoadTableResponse, ErrorResponse, OK>(request)
.await?;
let file_io = self
.load_file_io(resp.metadata_location.as_deref(), resp.config)
.await?;
let table_builder = Table::builder()
.identifier(table.clone())
.file_io(file_io)
.metadata(resp.metadata);
if let Some(metadata_location) = resp.metadata_location {
Ok(table_builder.metadata_location(metadata_location).build())
} else {
Ok(table_builder.build())
}
}
/// Drop a table from the catalog.
async fn drop_table(&self, table: &TableIdent) -> Result<()> {
let request = self
.context()
.await?
.client
.request(
Method::DELETE,
self.context().await?.config.table_endpoint(table),
)
.build()?;
self.context()
.await?
.client
.execute::<ErrorResponse, NO_CONTENT>(request)
.await
}
/// Check if a table exists in the catalog.
async fn table_exists(&self, table: &TableIdent) -> Result<bool> {
let request = self
.context()
.await?
.client
.request(
Method::HEAD,
self.context().await?.config.table_endpoint(table),
)
.build()?;
self.context()
.await?
.client
.do_execute::<bool, ErrorResponse>(request, |resp| match resp.status() {
StatusCode::NO_CONTENT => Some(true),
StatusCode::NOT_FOUND => Some(false),
_ => None,
})
.await
}
/// Rename a table in the catalog.
async fn rename_table(&self, src: &TableIdent, dest: &TableIdent) -> Result<()> {
let request = self
.context()
.await?
.client
.request(
Method::POST,
self.context().await?.config.rename_table_endpoint(),
)
.json(&RenameTableRequest {
source: src.clone(),
destination: dest.clone(),
})
.build()?;
self.context()
.await?
.client
.execute::<ErrorResponse, NO_CONTENT>(request)
.await
}
/// Update table.
async fn update_table(&self, mut commit: TableCommit) -> Result<Table> {
let request = self
.context()
.await?
.client
.request(
Method::POST,
self.context()
.await?
.config
.table_endpoint(commit.identifier()),
)
.json(&CommitTableRequest {
identifier: commit.identifier().clone(),
requirements: commit.take_requirements(),
updates: commit.take_updates(),
})
.build()?;
let resp = self
.context()
.await?
.client
.query::<CommitTableResponse, ErrorResponse, OK>(request)
.await?;
let file_io = self
.load_file_io(Some(&resp.metadata_location), None)
.await?;
Ok(Table::builder()
.identifier(commit.identifier().clone())
.file_io(file_io)
.metadata(resp.metadata)
.metadata_location(resp.metadata_location)
.build())
}
}
#[cfg(test)]
mod tests {
use chrono::{TimeZone, Utc};
use iceberg::spec::{
FormatVersion, NestedField, NullOrder, Operation, PrimitiveType, Schema, Snapshot,
SnapshotLog, SortDirection, SortField, SortOrder, Summary, Transform, Type,
UnboundPartitionField, UnboundPartitionSpec,
};
use iceberg::transaction::Transaction;
use mockito::{Mock, Server, ServerGuard};
use serde_json::json;
use std::fs::File;
use std::io::BufReader;
use std::sync::Arc;
use uuid::uuid;
use super::*;
#[tokio::test]
async fn test_update_config() {
let mut server = Server::new_async().await;
let config_mock = server
.mock("GET", "/v1/config")
.with_status(200)
.with_body(
r#"{
"overrides": {
"warehouse": "s3://iceberg-catalog"
},
"defaults": {}
}"#,
)
.create_async()
.await;
let catalog = RestCatalog::new(RestCatalogConfig::builder().uri(server.url()).build());
assert_eq!(
catalog
.context()
.await
.unwrap()
.config
.props
.get("warehouse"),
Some(&"s3://iceberg-catalog".to_string())
);
config_mock.assert_async().await;
}
async fn create_config_mock(server: &mut ServerGuard) -> Mock {
server
.mock("GET", "/v1/config")
.with_status(200)
.with_body(
r#"{
"overrides": {
"warehouse": "s3://iceberg-catalog"
},
"defaults": {}
}"#,
)
.create_async()
.await
}
async fn create_oauth_mock(server: &mut ServerGuard) -> Mock {
create_oauth_mock_with_path(server, "/v1/oauth/tokens").await
}
async fn create_oauth_mock_with_path(server: &mut ServerGuard, path: &str) -> Mock {
server
.mock("POST", path)
.with_status(200)
.with_body(
r#"{
"access_token": "ey000000000000",
"token_type": "Bearer",
"issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
"expires_in": 86400
}"#,
)
.expect(2)
.create_async()
.await
}
#[tokio::test]
async fn test_oauth() {
let mut server = Server::new_async().await;
let oauth_mock = create_oauth_mock(&mut server).await;
let config_mock = create_config_mock(&mut server).await;
let mut props = HashMap::new();
props.insert("credential".to_string(), "client1:secret1".to_string());
let catalog = RestCatalog::new(
RestCatalogConfig::builder()
.uri(server.url())
.props(props)
.build(),
);
let token = catalog.context().await.unwrap().client.token().await;
oauth_mock.assert_async().await;
config_mock.assert_async().await;
assert_eq!(token, Some("ey000000000000".to_string()));
}
#[tokio::test]
async fn test_oauth_with_optional_param() {
let mut props = HashMap::new();
props.insert("credential".to_string(), "client1:secret1".to_string());
props.insert("scope".to_string(), "custom_scope".to_string());
props.insert("audience".to_string(), "custom_audience".to_string());
props.insert("resource".to_string(), "custom_resource".to_string());
let mut server = Server::new_async().await;
let oauth_mock = server
.mock("POST", "/v1/oauth/tokens")
.match_body(mockito::Matcher::Regex("scope=custom_scope".to_string()))
.match_body(mockito::Matcher::Regex(
"audience=custom_audience".to_string(),
))
.match_body(mockito::Matcher::Regex(
"resource=custom_resource".to_string(),
))
.with_status(200)
.with_body(
r#"{
"access_token": "ey000000000000",
"token_type": "Bearer",
"issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
"expires_in": 86400
}"#,
)
.expect(2)
.create_async()
.await;
let config_mock = create_config_mock(&mut server).await;
let catalog = RestCatalog::new(
RestCatalogConfig::builder()
.uri(server.url())
.props(props)
.build(),
);
let token = catalog.context().await.unwrap().client.token().await;
oauth_mock.assert_async().await;
config_mock.assert_async().await;
assert_eq!(token, Some("ey000000000000".to_string()));
}
#[tokio::test]
async fn test_http_headers() {
let server = Server::new_async().await;
let mut props = HashMap::new();
props.insert("credential".to_string(), "client1:secret1".to_string());
let config = RestCatalogConfig::builder()
.uri(server.url())
.props(props)
.build();
let headers: HeaderMap = config.extra_headers().unwrap();
let expected_headers = HeaderMap::from_iter([
(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
),
(
HeaderName::from_static("x-client-version"),
HeaderValue::from_static(ICEBERG_REST_SPEC_VERSION),
),
(
header::USER_AGENT,
HeaderValue::from_str(&format!("iceberg-rs/{}", CARGO_PKG_VERSION)).unwrap(),
),
]);
assert_eq!(headers, expected_headers);
}
#[tokio::test]
async fn test_http_headers_with_custom_headers() {
let server = Server::new_async().await;
let mut props = HashMap::new();
props.insert("credential".to_string(), "client1:secret1".to_string());
props.insert(
"header.content-type".to_string(),
"application/yaml".to_string(),
);
props.insert(
"header.customized-header".to_string(),
"some/value".to_string(),
);
let config = RestCatalogConfig::builder()
.uri(server.url())
.props(props)
.build();
let headers: HeaderMap = config.extra_headers().unwrap();
let expected_headers = HeaderMap::from_iter([
(
header::CONTENT_TYPE,
HeaderValue::from_static("application/yaml"),
),
(
HeaderName::from_static("x-client-version"),
HeaderValue::from_static(ICEBERG_REST_SPEC_VERSION),
),
(
header::USER_AGENT,
HeaderValue::from_str(&format!("iceberg-rs/{}", CARGO_PKG_VERSION)).unwrap(),
),
(
HeaderName::from_static("customized-header"),
HeaderValue::from_static("some/value"),
),
]);
assert_eq!(headers, expected_headers);
}
#[tokio::test]
async fn test_oauth_with_auth_url() {
let mut server = Server::new_async().await;
let config_mock = create_config_mock(&mut server).await;
let mut auth_server = Server::new_async().await;
let auth_server_path = "/some/path";
let oauth_mock = create_oauth_mock_with_path(&mut auth_server, auth_server_path).await;
let mut props = HashMap::new();
props.insert("credential".to_string(), "client1:secret1".to_string());
props.insert(
"rest.authorization-url".to_string(),
format!("{}{}", auth_server.url(), auth_server_path).to_string(),
);
let catalog = RestCatalog::new(
RestCatalogConfig::builder()
.uri(server.url())
.props(props)
.build(),
);
let token = catalog.context().await.unwrap().client.token().await;
oauth_mock.assert_async().await;
config_mock.assert_async().await;
assert_eq!(token, Some("ey000000000000".to_string()));
}
#[tokio::test]
async fn test_config_override() {
let mut server = Server::new_async().await;
let mut redirect_server = Server::new_async().await;
let new_uri = redirect_server.url();
let config_mock = server
.mock("GET", "/v1/config")
.with_status(200)
.with_body(
json!(
{
"overrides": {
"uri": new_uri,
"warehouse": "s3://iceberg-catalog",
"prefix": "ice/warehouses/my"
},
"defaults": {},
}
)
.to_string(),
)
.create_async()
.await;
let list_ns_mock = redirect_server
.mock("GET", "/v1/ice/warehouses/my/namespaces")
.with_body(
r#"{
"namespaces": []
}"#,
)
.create_async()
.await;
let catalog = RestCatalog::new(RestCatalogConfig::builder().uri(server.url()).build());
let _namespaces = catalog.list_namespaces(None).await.unwrap();
config_mock.assert_async().await;
list_ns_mock.assert_async().await;
}
#[tokio::test]
async fn test_list_namespace() {
let mut server = Server::new_async().await;
let config_mock = create_config_mock(&mut server).await;
let list_ns_mock = server
.mock("GET", "/v1/namespaces")
.with_body(
r#"{
"namespaces": [
["ns1", "ns11"],
["ns2"]
]
}"#,
)
.create_async()
.await;
let catalog = RestCatalog::new(RestCatalogConfig::builder().uri(server.url()).build());
let namespaces = catalog.list_namespaces(None).await.unwrap();
let expected_ns = vec![
NamespaceIdent::from_vec(vec!["ns1".to_string(), "ns11".to_string()]).unwrap(),
NamespaceIdent::from_vec(vec!["ns2".to_string()]).unwrap(),
];
assert_eq!(expected_ns, namespaces);
config_mock.assert_async().await;
list_ns_mock.assert_async().await;
}
#[tokio::test]