-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathhttp.rs
More file actions
1683 lines (1492 loc) · 55.4 KB
/
http.rs
File metadata and controls
1683 lines (1492 loc) · 55.4 KB
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
use arrow::error::ArrowError;
use datafusion::error::DataFusionError;
use std::fmt::Debug;
use std::io::Write;
use std::time::Instant;
use std::{net::SocketAddr, sync::Arc};
use warp::{hyper, Rejection};
use arrow::json::writer::{LineDelimited, WriterBuilder};
use arrow::record_batch::RecordBatch;
#[cfg(feature = "frontend-arrow-flight")]
use arrow_flight::flight_service_client::FlightServiceClient;
use arrow_schema::SchemaRef;
use bytes::Buf;
use datafusion::datasource::DefaultTableSource;
use datafusion::physical_plan::ExecutionPlan;
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion, TreeNodeVisitor};
use datafusion_expr::logical_plan::{LogicalPlan, TableScan};
use deltalake::parquet::data_type::AsBytes;
use deltalake::DeltaTable;
use futures::{future, Future, StreamExt};
use hex::encode;
use metrics::counter;
use percent_encoding::{percent_decode_str, utf8_percent_encode, NON_ALPHANUMERIC};
use serde::Deserialize;
use serde_json::json;
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;
use tracing::{debug, info, warn};
use warp::http::HeaderValue;
use warp::log::Info;
use warp::multipart::{FormData, Part};
use warp::reply::{with_header, Response};
use warp::{hyper::header, hyper::StatusCode, Filter, Reply};
use super::http_utils::{handle_rejection, into_response, ApiError};
use crate::auth::{token_to_principal, AccessPolicy, Action, UserContext};
use crate::catalog::DEFAULT_DB;
use crate::config::context::HTTP_REQUESTS;
use crate::config::schema::{AccessSettings, HttpFrontend, MEBIBYTES};
use crate::{
config::schema::str_to_hex_hash,
context::logical::{is_read_only, is_statement_read_only},
context::SeafowlContext,
};
const QUERY_HEADER: &str = "X-Seafowl-Query";
const BEARER_PREFIX: &str = "Bearer ";
// We have a very lax CORS on this, so we don't mind browsers
// caching it for as long as possible.
const CORS_MAXAGE: u32 = 86400;
const QUERY_TIME_HEADER: &str = "X-Seafowl-Query-Time";
// Vary on Origin, as warp's CORS responds with Access-Control-Allow-Origin: [origin],
// so we can't cache the response in the browser if the origin changes.
// NB: Cloudflare doesn't take the vary values into account in caching decisions:
// https://developers.cloudflare.com/cache/about/cache-control/#other
const VARY: &str = "Authorization, Content-Type, Origin, X-Seafowl-Query";
#[derive(Default)]
struct ETagBuilderVisitor {
table_versions: Vec<u8>,
}
impl TreeNodeVisitor<'_> for ETagBuilderVisitor {
type Node = LogicalPlan;
fn f_down(
&mut self,
plan: &LogicalPlan,
) -> Result<TreeNodeRecursion, DataFusionError> {
if let LogicalPlan::TableScan(TableScan { source, .. }) = plan {
// TODO handle external Parquet tables too
if let Some(default_table_source) =
source.as_any().downcast_ref::<DefaultTableSource>()
{
if let Some(table) = default_table_source
.table_provider
.as_any()
.downcast_ref::<DeltaTable>()
{
self.table_versions
.extend(table.table_uri().as_bytes().to_vec());
self.table_versions
.extend(table.version().as_bytes().to_vec());
}
}
}
Ok(TreeNodeRecursion::Continue)
}
}
fn plan_to_etag(plan: &LogicalPlan) -> String {
let mut visitor = ETagBuilderVisitor::default();
plan.visit(&mut visitor).unwrap();
debug!("Extracted table versions: {:?}", visitor.table_versions);
let mut hasher = Sha256::new();
hasher.update(json!(visitor.table_versions).to_string());
encode(hasher.finalize())
}
// Construct a content-type header value that also includes schema information.
fn content_type_with_schema(schema: SchemaRef) -> HeaderValue {
let schema_string = serde_json::to_string(&schema).unwrap();
let output = utf8_percent_encode(&schema_string, NON_ALPHANUMERIC);
HeaderValue::from_str(format!("application/json; arrow-schema={output}").as_str())
.unwrap_or_else(|e| {
// Seems silly to error out here if the query itself succeeded.
warn!(
"Couldn't generate content type header for output schema {output}: {e:?}"
);
HeaderValue::from_static("application/json")
})
}
#[derive(Debug, Deserialize)]
struct QueryBody {
query: String,
}
/// Convert rows from a `RecordBatch` to their JSON Lines byte representation, with newlines at the end
fn batch_to_json(
maybe_batch: Result<RecordBatch, DataFusionError>,
) -> Result<Vec<u8>, ArrowError> {
let batch = maybe_batch?;
let mut buf = Vec::new();
let mut writer = WriterBuilder::new()
.with_explicit_nulls(true)
.build::<_, LineDelimited>(&mut buf);
writer.write(&batch)?;
Ok(buf)
}
// Execute the plan and stream the results
async fn plan_to_response(
context: Arc<SeafowlContext>,
plan: Arc<dyn ExecutionPlan>,
) -> Result<Response, DataFusionError> {
let stream = context.execute_stream(plan).await?.map(|maybe_batch| {
batch_to_json(maybe_batch)
// Seems like at this point wrap/hyper don't really handle the stream error well,
// i.e. the status code returned is 200 even when stream fails.
// To at least make this more transparent convert the error message to payload,
// otherwise the client just gets an opaque empty reply.
.or_else(|e| Ok::<Vec<u8>, ArrowError>(e.to_string().into_bytes()))
});
let body = hyper::Body::wrap_stream(stream);
Ok(Response::new(body))
}
/// POST /q or /[database_name]/q
pub async fn uncached_read_write_query(
database_name: String,
user_context: UserContext,
query: String,
mut context: Arc<SeafowlContext>,
) -> Result<Response, ApiError> {
let timer = Instant::now();
// If a specific DB name was used as a parameter in the route, scope the context to it,
// effectively making it the default DB for the duration of the session.
if database_name != context.default_catalog {
context = context.scope_to_catalog(database_name);
}
let statements = context.parse_query(&query).await?;
// We assume that there's at least one statement throughout the rest of this function
if statements.is_empty() {
return Err(ApiError::EmptyMultiStatement);
};
let reads = statements
.iter()
.filter(|s| is_statement_read_only(s))
.count();
// Check for authorization
if !user_context.can_perform_action(if reads == statements.len() {
Action::Read
} else {
Action::Write
}) {
return Err(ApiError::WriteForbidden);
};
// If we have a read statement, make sure it's the last and only one (that's the only one
// we'll return actual results for)
if (reads > 1)
|| (reads == 1
&& !is_statement_read_only(
statements
.last()
.expect("at least one statement in the list"),
))
{
return Err(ApiError::InvalidMultiStatement);
}
// Execute all statements up until the last one.
let mut plan_to_output = None;
for statement in statements {
let logical = context
.create_logical_plan_from_statement(statement)
.await?;
plan_to_output = Some(context.create_physical_plan(&logical).await?);
}
// Stream output for the last statement
let plan = plan_to_output.expect("at least one statement in the list");
let schema = plan.schema();
let mut response = plan_to_response(context, plan).await?;
if reads > 0 {
response
.headers_mut()
.insert(header::CONTENT_TYPE, content_type_with_schema(schema));
}
let elapsed = timer.elapsed().as_millis().to_string();
response
.headers_mut()
.insert(QUERY_TIME_HEADER, elapsed.parse().unwrap());
Ok(response)
}
fn header_to_user_context(
header: Option<String>,
policy: &AccessPolicy,
) -> Result<UserContext, ApiError> {
let token = header
.map(|h| {
if h.starts_with(BEARER_PREFIX) {
Ok(h.trim_start_matches(BEARER_PREFIX).to_string())
} else {
Err(ApiError::InvalidAuthorizationHeader)
}
})
.transpose()?;
token_to_principal(token, policy).map(|principal| UserContext {
principal,
policy: policy.clone(),
})
}
pub fn with_auth(
policy: AccessPolicy,
) -> impl Filter<Extract = (UserContext,), Error = Rejection> + Clone {
warp::header::optional::<String>(header::AUTHORIZATION.as_str()).and_then(
move |header: Option<String>| {
future::ready(
header_to_user_context(header, &policy).map_err(warp::reject::custom),
)
},
)
}
// Disable the cached GET endpoint if the reads are disabled. Otherwise extract the principal and
// check whether it is allowed to perform reads.
pub fn cached_read_query_authz(
policy: AccessPolicy,
) -> impl Filter<Extract = (), Error = Rejection> + Clone {
warp::any()
.and(with_auth(policy.clone()))
.and_then(move |user_context: UserContext| match policy.read {
AccessSettings::Off => {
future::err(warp::reject::custom(ApiError::ReadOnlyEndpointDisabled))
}
_ => {
if user_context.can_perform_action(Action::Read) {
future::ok(())
} else {
future::err(warp::reject::custom(ApiError::ReadForbidden))
}
}
})
.untuple_one()
}
/// Supports either one of:
///
/// 1. GET /q/[query]
/// 2. GET /q/[query hash] {"query": "[query]"}
/// 3. GET -H "X-Seafowl-Query: [query]" /q/[query hash]
///
/// In all cases the path can have an optional prefix parameter in order do specify a non-default
/// database as target, e.g. /[database_name]/q/[query]
pub async fn cached_read_query(
database_name: String,
query_or_hash: String,
maybe_raw_query: Option<String>,
if_none_match: Option<String>,
mut context: Arc<SeafowlContext>,
) -> Result<Response, ApiError> {
let timer = Instant::now();
// Ignore dots at the end
let query_or_hash = query_or_hash.split('.').next().unwrap();
let decoded_query = if let Some(raw_query) = maybe_raw_query {
// If we managed to extract the query from the body or the header, the string from the path
// parameter is supposed to be the query hash; decode the query and validate
let query_hash = query_or_hash;
let decoded_query = percent_decode_str(&raw_query).decode_utf8()?;
let hash_str = str_to_hex_hash(&decoded_query);
debug!(
"Received query: {}, URL hash {}, actual hash {}",
decoded_query, query_hash, hash_str
);
// Verify the query hash matches the query
if query_hash != hash_str {
return Err(ApiError::HashMismatch(hash_str, query_hash.to_string()));
};
decoded_query.to_string()
} else {
// Otherwise, the query itself is passed as the path param
percent_decode_str(query_or_hash).decode_utf8()?.to_string()
};
// If a specific DB name was used as a parameter in the route, scope the context to it,
// effectively making it the default DB for the duration of the session.
if database_name != context.default_catalog {
context = context.scope_to_catalog(database_name);
}
// Plan the query
let plan = context.create_logical_plan(&decoded_query).await?;
debug!("Query plan: {:?}", plan);
// Write queries should come in as POST requests
if !is_read_only(&plan) {
return Err(ApiError::NotReadOnlyQuery);
};
// Pre-execution check: if ETags match, we don't need to re-execute the query
let etag = plan_to_etag(&plan);
debug!("ETag: {}, if-none-match header: {:?}", etag, if_none_match);
if let Some(if_none_match) = if_none_match {
if etag == if_none_match {
return Ok(warp::reply::with_status(
"NOT_MODIFIED",
StatusCode::NOT_MODIFIED,
)
.into_response());
}
}
// Guess we'll have to actually run the query
let physical = context.create_physical_plan(&plan).await?;
let schema = physical.schema().clone();
let mut response = plan_to_response(context, physical).await?;
let elapsed = timer.elapsed().as_millis().to_string();
response
.headers_mut()
.insert(QUERY_TIME_HEADER, elapsed.parse().unwrap());
response
.headers_mut()
.insert(header::ETAG, etag.parse().unwrap());
response
.headers_mut()
.insert(header::CONTENT_TYPE, content_type_with_schema(schema));
Ok(response)
}
/// POST /upload/[schema]/[table] or /[database]/upload/[schema]/[table]
pub async fn upload(
database_name: String,
schema_name: String,
table_name: String,
user_context: UserContext,
mut form: FormData,
mut context: Arc<SeafowlContext>,
) -> Result<Response, ApiError> {
if !user_context.can_perform_action(Action::Write) {
return Err(ApiError::WriteForbidden);
};
if database_name != context.default_catalog {
context = context.scope_to_catalog(database_name.clone());
}
let mut has_header = true;
let mut schema: Option<SchemaRef> = None;
let mut filename = String::new();
let mut file_type = String::new();
let mut temp_path = String::new();
let mut temp_file: NamedTempFile;
while let Some(maybe_part) = form.next().await {
let mut part = maybe_part.map_err(ApiError::UploadBodyLoadError)?;
if part.name() == "has_header" {
let value_bytes = load_part(part).await?;
has_header = String::from_utf8(value_bytes)
.map_err(|_| ApiError::UploadHasHeaderParseError)?
.starts_with("true");
debug!("Form part has_header is: {}", has_header);
} else if part.name() == "schema" {
let value_bytes = load_part(part).await?;
schema = Some(Arc::new(
serde_json::from_str(
&String::from_utf8(value_bytes)
.map_err(ApiError::UploadSchemaDeserializationError)?,
)
.map_err(ApiError::UploadSchemaParseError)?,
));
} else if part.name() == "data" || part.name() == "file" {
filename = part
.filename()
.ok_or(ApiError::UploadMissingFile)?
.to_string();
if filename.is_empty() {
return Err(ApiError::UploadMissingFile);
}
file_type = filename
.split('.')
.last()
.ok_or_else(|| {
ApiError::UploadMissingFilenameExtension(filename.clone())
})?
.to_string();
temp_file = tempfile::Builder::new()
.suffix(&format!(".{file_type}"))
.tempfile()?;
temp_path = temp_file.path().display().to_string();
// Write out the incoming bytes into the temporary file
while let Some(maybe_bytes) = part.data().await {
temp_file.write_all(
maybe_bytes.map_err(ApiError::UploadBodyLoadError)?.chunk(),
)?;
}
}
}
if file_type != "csv" && file_type != "parquet" {
return Err(ApiError::UploadUnsupportedFileFormat(filename));
};
// Execute the plan and persist objects as well as table/partition metadata
let table = context
.file_to_table(
temp_path,
&file_type,
schema,
has_header,
schema_name.clone(),
table_name.clone(),
)
.await?;
Ok(warp::reply::with_status(
Ok::<String, ApiError>(format!(
"{filename} appended to table {table_name} version {}\n",
table.version()
)),
StatusCode::OK,
)
.into_response())
}
async fn load_part(mut part: Part) -> Result<Vec<u8>, ApiError> {
let mut bytes: Vec<u8> = vec![];
while let Some(maybe_bytes) = part.data().await {
bytes.extend(maybe_bytes.map_err(ApiError::UploadBodyLoadError)?.chunk())
}
Ok(bytes)
}
/// GET /healthz or /readyz
pub async fn health_endpoint(context: Arc<SeafowlContext>) -> Result<Response, ApiError> {
#[cfg(feature = "frontend-arrow-flight")]
if let Some(flight) = &context.config.frontend.flight {
// TODO: run SELECT 1 or something similar?
if let Err(err) = FlightServiceClient::connect(format!(
"http://{}:{}",
flight.bind_host, flight.bind_port
))
.await
{
warn!(%err, "Arrow Flight client can't connect, health check failed");
return Ok(warp::reply::with_status(
"not_ready",
StatusCode::SERVICE_UNAVAILABLE,
)
.into_response());
};
};
Ok(warp::reply::with_status("ready", StatusCode::OK).into_response())
}
pub fn filters(
context: Arc<SeafowlContext>,
config: HttpFrontend,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
let access_policy = AccessPolicy::from_config(&config);
let cors = warp::cors()
.allow_any_origin()
.allow_headers(vec![
"X-Seafowl-Query",
header::AUTHORIZATION.as_str(),
header::CONTENT_TYPE.as_str(),
])
.allow_methods(vec!["GET", "POST"])
.max_age(CORS_MAXAGE);
let log = warp::log::custom(|info: Info<'_>| {
let path = info.path();
{
let route = if path.contains("/upload/") {
"/upload".to_string()
} else if path.contains("/q") {
"/q".to_string()
} else {
path.to_string()
};
counter!(
HTTP_REQUESTS,
"method" => info.method().as_str().to_string(),
// Omit a potential db prefix or url-encoded query from the path
"route" => route,
"status" => info.status().as_u16().to_string(),
)
.increment(1);
}
info!(
target: module_path!(),
"{} \"{} {} {:?}\" {} \"{}\" \"{}\" {:?}",
info.remote_addr().map(|addr| addr.to_string()).unwrap_or("-".to_string()),
info.method(),
path,
info.version(),
info.status().as_u16(),
info.referer().unwrap_or("-"),
info.user_agent().unwrap_or("-"),
info.elapsed(),
);
});
// Cached read query
let ctx = context.clone();
let cached_read_query_route = warp::path!(String / "q" / String)
.or(warp::any()
.map(move || DEFAULT_DB.to_string())
.and(warp::path!("q" / String)))
.and(warp::path::end())
.and(warp::get())
.unify()
.and(cached_read_query_authz(access_policy.clone()))
.and(
// Extract the query either from the JSON body or the header
warp::body::json()
.map(|b: QueryBody| Some(b.query))
.or(warp::header::optional::<String>(QUERY_HEADER))
.unify(),
)
.and(warp::header::optional::<String>(
header::IF_NONE_MATCH.as_str(),
))
.and(warp::any().map(move || ctx.clone()))
.then(cached_read_query)
.map(move |r: Result<Response, ApiError>| {
if let Ok(response) = r {
with_header(
response,
header::CACHE_CONTROL,
config.cache_control.clone(),
)
.into_response()
} else {
into_response(r)
}
});
// Uncached read/write query
let ctx = context.clone();
let uncached_read_write_query_route = warp::path!(String / "q")
.or(warp::any()
.map(move || DEFAULT_DB.to_string())
.and(warp::path!("q")))
.and(warp::path::end())
.and(warp::post())
.unify()
.and(with_auth(access_policy.clone()))
.and(
// Extract the query from the JSON body
warp::body::json().map(|b: QueryBody| b.query).or_else(|r| {
future::err(warp::reject::custom(ApiError::QueryParsingError(r)))
}),
)
.and(warp::any().map(move || ctx.clone()))
.then(uncached_read_write_query)
.map(into_response);
// Upload endpoint
let ctx = context.clone();
let upload_route = warp::path!(String / "upload" / String / String)
.or(warp::any()
.map(move || DEFAULT_DB.to_string())
.and(warp::path!("upload" / String / String)))
.and(warp::post())
.unify()
.and(with_auth(access_policy))
.and(
warp::multipart::form().max_length(config.upload_data_max_length * MEBIBYTES),
)
.and(warp::any().map(move || ctx.clone()))
.then(upload)
.map(into_response);
// Health-check/readiness probe
let ctx = context;
let health_route = warp::path!("healthz")
.or(warp::path!("readyz"))
.and(warp::path::end())
.and(warp::get())
.unify()
.and(warp::any().map(move || ctx.clone()))
.then(health_endpoint)
.map(into_response);
cached_read_query_route
.or(uncached_read_write_query_route)
.or(upload_route)
.or(health_route)
.with(cors)
.with(log)
.map(|r| with_header(r, header::VARY, VARY))
.recover(handle_rejection)
}
pub async fn run_server(
context: Arc<SeafowlContext>,
config: HttpFrontend,
shutdown: impl Future<Output = ()> + Send + 'static,
) {
let filters = filters(context, config.clone());
let socket_addr: SocketAddr = format!("{}:{}", config.bind_host, config.bind_port)
.parse()
.expect("Error parsing the listen address");
let (_, future) =
warp::serve(filters).bind_with_graceful_shutdown(socket_addr, shutdown);
future.await
}
#[cfg(test)]
pub mod tests {
use bytes::Bytes;
use itertools::Itertools;
use std::fmt::Display;
use std::{collections::HashMap, sync::Arc};
use std::cell::RefCell;
thread_local!(static UUID_SEED: RefCell<u128> = const { RefCell::new(0) });
use rstest::rstest;
use uuid::Uuid;
use warp::{Filter, Rejection, Reply};
use warp::http::Response;
use warp::hyper::header;
use warp::{
hyper::{header::IF_NONE_MATCH, StatusCode},
test::request,
};
use crate::auth::AccessPolicy;
use crate::catalog::DEFAULT_DB;
use crate::config::schema::{str_to_hex_hash, HttpFrontend};
use crate::testutils::{assert_header_is_float, schema_from_header};
use crate::{
context::{test_utils::in_memory_context, SeafowlContext},
frontend::http::{filters, QUERY_HEADER, QUERY_TIME_HEADER},
};
fn http_config_from_access_policy_and_cache_control(
access_policy: AccessPolicy,
cache_control: Option<&str>,
) -> HttpFrontend {
if cache_control.is_none() {
return http_config_from_access_policy(access_policy);
}
HttpFrontend {
read_access: access_policy.read,
write_access: access_policy.write,
cache_control: cache_control.unwrap().to_string(),
..HttpFrontend::default()
}
}
fn http_config_from_access_policy(access_policy: AccessPolicy) -> HttpFrontend {
HttpFrontend {
read_access: access_policy.read,
write_access: access_policy.write,
..HttpFrontend::default()
}
}
/// Build an in-memory context with a single table
/// We implicitly assume here that this table is the only one in this context
/// and has version ID 1 (otherwise the hashes won't match).
async fn in_memory_context_with_single_table(
new_db: Option<&str>,
) -> Arc<SeafowlContext> {
let mut context = Arc::new(in_memory_context().await);
if let Some(db_name) = new_db {
context
.plan_query(&format!("CREATE DATABASE IF NOT EXISTS {db_name}"))
.await
.unwrap();
context = context.scope_to_catalog(db_name.to_string());
}
context
.plan_query("CREATE TABLE test_table(col_1 INT)")
.await
.unwrap();
context
.plan_query("INSERT INTO test_table VALUES (1)")
.await
.unwrap();
if new_db.is_some() {
// Re-scope to the original DB
return context.scope_to_catalog(DEFAULT_DB.to_string());
}
context
}
async fn in_memory_context_with_modified_table(
new_db: Option<&str>,
) -> Arc<SeafowlContext> {
let mut context = in_memory_context_with_single_table(new_db).await;
if let Some(db_name) = new_db {
context = context.scope_to_catalog(db_name.to_string());
}
context
.plan_query("INSERT INTO test_table VALUES (2)")
.await
.unwrap();
if new_db.is_some() {
// Re-scope to the original DB
return context.scope_to_catalog(DEFAULT_DB.to_string());
}
context
}
fn free_for_all() -> AccessPolicy {
AccessPolicy::free_for_all()
}
fn make_uri(path: impl Display, db_prefix: Option<&str>) -> String {
match db_prefix {
None => path.to_string(),
Some(db_name) => format!("/{db_name}{path}"),
}
}
const SELECT_QUERY: &str = "SELECT COUNT(*) AS c FROM test_table";
const PERCENT_ENCODED_SELECT_QUERY: &str =
"SELECT%20COUNT(*)%20AS%20c%20FROM%20test_table";
const BAD_PERCENT_ENCODED_SELECT_QUERY: &str =
"%99SELECT%0A%20%20COUNT(*)%20AS%20c%0AFROM%20test_table";
const INSERT_QUERY: &str = "INSERT INTO test_table VALUES (2)";
const CREATE_QUERY: &str = "CREATE TABLE other_test_table(col_1 INT)";
const SELECT_QUERY_HASH: &str =
"7fbbf7dddfd330d03e5e08cc5885ad8ca823e1b56e7cbadd156daa0e21c288f6";
const V1_ETAG: &str =
"37ff2380efb2e1ba86ad7204998cb7541b32196f4604c85e03cf74f6f9fd75b0";
const V2_ETAG: &str =
"35a334f8ea79ff5e8c79ed3c8083ec2910a9404d56b71cf853b44f979fc0b7fa";
pub fn deterministic_uuid() -> Uuid {
// A crude hack to get reproducible bytes as source for table UUID generation, to enable
// transparent etag asserts
UUID_SEED.with(|uuid_seed| {
let mut seed = uuid_seed.borrow_mut();
*seed += 1;
Uuid::from_u128(*seed)
})
}
async fn query_cached_endpoint<R, H>(
handler: &H,
path: &str,
maybe_body: Option<HashMap<&'_ str, &'_ str>>,
maybe_headers: Option<Vec<(&'_ str, &'_ str)>>,
) -> Response<Bytes>
where
R: Reply,
H: Filter<Extract = R, Error = Rejection> + Clone + 'static,
{
let mut builder = request().method("GET").path(path);
if let Some(body) = maybe_body {
builder = builder.json(&body);
}
if let Some(headers) = maybe_headers {
for (key, value) in headers {
builder = builder.header(key, value);
}
}
builder.reply(handler).await
}
async fn query_uncached_endpoint<R, H>(
handler: &H,
query: &'_ str,
path_prefix: Option<&str>,
token: Option<&str>,
) -> Response<Bytes>
where
R: Reply,
H: Filter<Extract = R, Error = Rejection> + Clone + 'static,
{
let mut builder = request()
.method("POST")
.path(make_uri("/q", path_prefix).as_str())
.json(&HashMap::from([("query", query)]));
if let Some(t) = token {
builder = builder.header(header::AUTHORIZATION, format!("Bearer {t}"));
}
builder.reply(handler).await
}
#[rstest]
#[tokio::test]
async fn test_get_cached_hash_mismatch(
#[values(None, Some("test_db"))] new_db: Option<&str>,
) {
let context = in_memory_context_with_single_table(new_db).await;
let handler = filters(context, http_config_from_access_policy(free_for_all()));
let resp = request()
.method("GET")
.path(make_uri("/q/wrong-hash", new_db).as_str())
.header(QUERY_HEADER, SELECT_QUERY)
.reply(&handler)
.await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[rstest]
#[tokio::test]
async fn test_cors(#[values(None, Some("test_db"))] new_db: Option<&str>) {
let context = in_memory_context_with_single_table(new_db).await;
let handler = filters(context, http_config_from_access_policy(free_for_all()));
let resp = request()
.method("OPTIONS")
.path(make_uri("/q/somehash", new_db).as_str())
.header("Access-Control-Request-Method", "GET")
.header("Access-Control-Request-Headers", "x-seafowl-query")
.header("Origin", "https://example.org")
.reply(&handler)
.await;
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get("Access-Control-Allow-Origin").unwrap(),
"https://example.org"
);
assert_eq!(
resp.headers()
.get("Access-Control-Allow-Methods")
.unwrap()
.to_str()
.unwrap()
.split(',')
.map(|s| s.trim())
.sorted()
.collect::<Vec<&str>>(),
vec!["GET", "POST"]
);
}
#[rstest]
#[tokio::test]
async fn test_get_cached_write_query_error(
#[values(None, Some("test_db"))] new_db: Option<&str>,
) {
let context = in_memory_context_with_single_table(new_db).await;
let handler = filters(context, http_config_from_access_policy(free_for_all()));
let resp = request()
.method("GET")
.path(
make_uri(format!("/q/{}", str_to_hex_hash(CREATE_QUERY)), new_db)
.as_str(),
)
.header(QUERY_HEADER, CREATE_QUERY)
.reply(&handler)
.await;
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
assert_eq!(resp.body(), "NOT_READ_ONLY_QUERY");
}
#[rstest]
#[case::query_in_path(PERCENT_ENCODED_SELECT_QUERY, None, None)]
#[case::query_in_body(
SELECT_QUERY_HASH,
Some(HashMap::from([("query", SELECT_QUERY)])),
None,
)]
#[case::query_in_header(
SELECT_QUERY_HASH,
None,
Some(vec![(QUERY_HEADER, SELECT_QUERY)]),
)]
#[case::encoded_query_in_header(
SELECT_QUERY_HASH,
None,
Some(vec![(QUERY_HEADER, PERCENT_ENCODED_SELECT_QUERY)]),
)]
#[tokio::test]
async fn test_get_cached_no_etag(
#[case] query_param: &str,
#[case] maybe_body: Option<HashMap<&'_ str, &'_ str>>,
#[case] maybe_headers: Option<Vec<(&'_ str, &'_ str)>>,
#[values(None, Some("test_db"))] new_db: Option<&str>,
#[values("", ".bin")] extension: &str,
#[values(None, Some("private, max-age=86400"))] cache_control: Option<&str>,
) {
let context = in_memory_context_with_single_table(new_db).await;
let handler = filters(
context,
http_config_from_access_policy_and_cache_control(
free_for_all(),
cache_control,
),
);
let resp = query_cached_endpoint(
&handler,
make_uri(format!("/q/{query_param}{extension}"), new_db).as_str(),
maybe_body,
maybe_headers,
)
.await;
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body(), "{\"c\":1}\n");
assert_eq!(
resp.headers().get(header::ETAG).unwrap().to_str().unwrap(),
V1_ETAG
);
assert_eq!(
resp.headers()
.get(header::CACHE_CONTROL)
.unwrap()
.to_str()
.unwrap(),
cache_control.unwrap_or("max-age=43200, public")
);
}
#[rstest]
#[tokio::test]
async fn test_get_cached_hash_no_query(
#[values(None, Some("test_db"))] new_db: Option<&str>,
) {