-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathapi_response.rs
More file actions
526 lines (480 loc) · 16.5 KB
/
Copy pathapi_response.rs
File metadata and controls
526 lines (480 loc) · 16.5 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
// 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.
//! REST API response types for Paimon.
//!
//! This module contains all response structures used in REST API calls.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::catalog::{Function, FunctionDefinition, ViewSchema};
use crate::spec::{DataField, Schema};
/// Error response from REST API calls.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorResponse {
/// The type of resource that caused the error.
pub resource_type: Option<String>,
/// The name of the resource that caused the error.
pub resource_name: Option<String>,
/// The error message.
pub message: Option<String>,
/// The error code.
pub code: Option<i32>,
}
impl ErrorResponse {
/// Create a new ErrorResponse.
pub fn new(
resource_type: Option<String>,
resource_name: Option<String>,
message: Option<String>,
code: Option<i32>,
) -> Self {
Self {
resource_type,
resource_name,
message,
code,
}
}
}
/// Base response containing audit information.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditRESTResponse {
/// The owner of the resource.
pub owner: Option<String>,
/// Timestamp when the resource was created.
pub created_at: Option<i64>,
/// User who created the resource.
pub created_by: Option<String>,
/// Timestamp when the resource was last updated.
pub updated_at: Option<i64>,
/// User who last updated the resource.
pub updated_by: Option<String>,
}
impl AuditRESTResponse {
/// Create a new AuditRESTResponse.
pub fn new(
owner: Option<String>,
created_at: Option<i64>,
created_by: Option<String>,
updated_at: Option<i64>,
updated_by: Option<String>,
) -> Self {
Self {
owner,
created_at,
created_by,
updated_at,
updated_by,
}
}
/// Put audit options into the provided dictionary.
pub fn put_audit_options_to(&self, options: &mut HashMap<String, String>) {
if let Some(owner) = &self.owner {
options.insert("owner".to_string(), owner.clone());
}
if let Some(created_by) = &self.created_by {
options.insert("createdBy".to_string(), created_by.clone());
}
if let Some(created_at) = self.created_at {
options.insert("createdAt".to_string(), created_at.to_string());
}
if let Some(updated_by) = &self.updated_by {
options.insert("updatedBy".to_string(), updated_by.clone());
}
if let Some(updated_at) = self.updated_at {
options.insert("updatedAt".to_string(), updated_at.to_string());
}
}
}
/// Response for getting a table.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetTableResponse {
/// Audit information.
#[serde(flatten)]
pub audit: AuditRESTResponse,
/// The unique identifier of the table.
pub id: Option<String>,
/// The name of the table.
pub name: Option<String>,
/// The path to the table.
pub path: Option<String>,
/// Whether the table is external.
pub is_external: Option<bool>,
/// The schema ID of the table.
pub schema_id: Option<i64>,
/// The schema of the table.
pub schema: Option<Schema>,
}
/// Response for getting a persistent view.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetViewResponse {
/// Audit information.
#[serde(flatten)]
pub audit: AuditRESTResponse,
/// The unique identifier of the view.
pub id: Option<String>,
/// The name of the view.
pub name: Option<String>,
/// Stored view schema and SQL representations.
pub schema: ViewSchema,
}
/// Response for getting a persistent function.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetFunctionResponse {
/// Audit information.
#[serde(flatten)]
pub audit: AuditRESTResponse,
/// The unique identifier of the function.
pub uuid: Option<String>,
/// The name of the function.
pub name: Option<String>,
/// Declared input parameters.
pub input_params: Option<Vec<DataField>>,
/// Declared return parameters.
pub return_params: Option<Vec<DataField>>,
/// Whether the function is deterministic.
pub deterministic: bool,
/// Engine-specific function definitions.
pub definitions: HashMap<String, FunctionDefinition>,
/// Optional function comment.
pub comment: Option<String>,
/// Function options.
#[serde(default)]
pub options: HashMap<String, String>,
}
impl GetFunctionResponse {
/// Create a response from a catalog function.
pub fn from_function(function: &Function, audit: AuditRESTResponse) -> Self {
Self {
audit,
uuid: None,
name: Some(function.name().to_string()),
input_params: function.input_params().map(<[DataField]>::to_vec),
return_params: function.return_params().map(<[DataField]>::to_vec),
deterministic: function.is_deterministic(),
definitions: function.definitions().clone(),
comment: function.comment().map(ToString::to_string),
options: function.options().clone(),
}
}
}
impl GetViewResponse {
/// Create a new get-view response.
pub fn new(
id: Option<String>,
name: Option<String>,
schema: ViewSchema,
audit: AuditRESTResponse,
) -> Self {
Self {
audit,
id,
name,
schema,
}
}
}
impl GetTableResponse {
/// Create a new GetTableResponse.
#[allow(clippy::too_many_arguments)]
pub fn new(
id: Option<String>,
name: Option<String>,
path: Option<String>,
is_external: Option<bool>,
schema_id: Option<i64>,
schema: Option<Schema>,
audit: AuditRESTResponse,
) -> Self {
Self {
audit,
id,
name,
path,
is_external,
schema_id,
schema,
}
}
}
/// Response for getting a database.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetDatabaseResponse {
/// Audit information.
#[serde(flatten)]
pub audit: AuditRESTResponse,
/// The unique identifier of the database.
pub id: Option<String>,
/// The name of the database.
pub name: Option<String>,
/// The location of the database.
pub location: Option<String>,
/// Configuration options for the database.
pub options: HashMap<String, String>,
}
impl GetDatabaseResponse {
/// Create a new GetDatabaseResponse.
pub fn new(
id: Option<String>,
name: Option<String>,
location: Option<String>,
options: HashMap<String, String>,
audit: AuditRESTResponse,
) -> Self {
Self {
audit,
id,
name,
location,
options,
}
}
}
/// Response containing configuration defaults.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfigResponse {
/// Default configuration values.
pub defaults: HashMap<String, String>,
}
impl ConfigResponse {
/// Create a new ConfigResponse.
pub fn new(defaults: HashMap<String, String>) -> Self {
Self { defaults }
}
/// Merge these defaults with the provided Options.
/// User options take precedence over defaults.
pub fn merge_options(&self, options: &crate::common::Options) -> crate::common::Options {
let mut merged = self.defaults.clone();
merged.extend(options.to_map().clone());
crate::common::Options::from_map(merged)
}
/// Convert to Options struct.
pub fn to_options(&self) -> crate::common::Options {
crate::common::Options::from_map(self.defaults.clone())
}
}
/// Response for listing databases.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListDatabasesResponse {
/// List of database names.
pub databases: Vec<String>,
/// Token for the next page.
pub next_page_token: Option<String>,
}
impl ListDatabasesResponse {
/// Create a new ListDatabasesResponse.
pub fn new(databases: Vec<String>, next_page_token: Option<String>) -> Self {
Self {
databases,
next_page_token,
}
}
}
/// Response for listing tables.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListTablesResponse {
/// List of table names.
pub tables: Option<Vec<String>>,
/// Token for the next page.
pub next_page_token: Option<String>,
}
/// Response for listing persistent views.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListViewsResponse {
/// View names.
pub views: Option<Vec<String>>,
/// Token for the next page.
pub next_page_token: Option<String>,
}
/// Response for listing persistent functions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListFunctionsResponse {
/// Function names.
pub functions: Option<Vec<String>>,
/// Token for the next page.
pub next_page_token: Option<String>,
}
impl ListFunctionsResponse {
/// Create a list-functions response.
pub fn new(functions: Vec<String>, next_page_token: Option<String>) -> Self {
Self {
functions: Some(functions),
next_page_token,
}
}
}
impl ListViewsResponse {
/// Create a list-views response.
pub fn new(views: Vec<String>, next_page_token: Option<String>) -> Self {
Self {
views: Some(views),
next_page_token,
}
}
}
impl ListTablesResponse {
/// Create a new ListTablesResponse.
pub fn new(tables: Option<Vec<String>>, next_page_token: Option<String>) -> Self {
Self {
tables,
next_page_token,
}
}
}
/// Response for listing partitions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListPartitionsResponse {
/// List of partitions.
pub partitions: Option<Vec<crate::spec::Partition>>,
/// Token for the next page.
pub next_page_token: Option<String>,
}
impl ListPartitionsResponse {
/// Create a new ListPartitionsResponse.
pub fn new(
partitions: Option<Vec<crate::spec::Partition>>,
next_page_token: Option<String>,
) -> Self {
Self {
partitions,
next_page_token,
}
}
}
/// A paginated list of elements with an optional next page token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PagedList<T> {
/// The list of elements on this page.
pub elements: Vec<T>,
/// Token to retrieve the next page, if available.
pub next_page_token: Option<String>,
}
impl<T> PagedList<T> {
/// Create a new PagedList.
pub fn new(elements: Vec<T>, next_page_token: Option<String>) -> Self {
Self {
elements,
next_page_token,
}
}
}
/// Response for getting table token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetTableTokenResponse {
/// Token key-value pairs (e.g. access_key_id, access_key_secret, etc.)
pub token: HashMap<String, String>,
/// Token expiration time in milliseconds since epoch.
pub expires_at_millis: Option<i64>,
}
/// Response for auth table query: the per-user row filter and column masking the
/// client must enforce at read time for a `query-auth.enabled` table.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthTableQueryResponse {
/// JSON-serialized row-filter predicates, ANDed together. Empty/None = no filter.
pub filter: Option<Vec<String>>,
/// column name -> JSON-serialized masking transform. Empty/None = no masking.
pub column_masking: Option<HashMap<String, String>>,
}
impl AuthTableQueryResponse {
/// True when the server imposes no row filter and no column masking.
pub fn is_unrestricted(&self) -> bool {
self.filter.as_ref().is_none_or(|f| f.is_empty())
&& self.column_masking.as_ref().is_none_or(|m| m.is_empty())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_auth_table_query_response_deserialization() {
// A restricted grant: pin the exact wire field names. A drift in either
// (`filter` / `columnMasking`) would deserialize to None and silently
// skip authorization, so this test fails closed against that.
let resp: AuthTableQueryResponse =
serde_json::from_str(r#"{"filter":["p0","p1"],"columnMasking":{"ssn":"m0"}}"#).unwrap();
assert_eq!(resp.filter, Some(vec!["p0".to_string(), "p1".to_string()]));
assert_eq!(
resp.column_masking,
Some(HashMap::from([("ssn".to_string(), "m0".to_string())]))
);
assert!(!resp.is_unrestricted());
// The real server sends `{}` for an unrestricted grant (both fields are
// `@JsonInclude(NON_NULL)` in Java); it must parse to an empty grant.
let empty: AuthTableQueryResponse = serde_json::from_str("{}").unwrap();
assert_eq!(empty, AuthTableQueryResponse::default());
assert!(empty.is_unrestricted());
// Present-but-empty collections are also unrestricted.
let blank: AuthTableQueryResponse =
serde_json::from_str(r#"{"filter":[],"columnMasking":{}}"#).unwrap();
assert!(blank.is_unrestricted());
}
#[test]
fn test_error_response_serialization() {
let resp = ErrorResponse::new(
Some("table".to_string()),
Some("test_table".to_string()),
Some("Table not found".to_string()),
Some(404),
);
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains("\"resourceType\":\"table\""));
assert!(json.contains("\"resourceName\":\"test_table\""));
assert!(json.contains("\"message\":\"Table not found\""));
assert!(json.contains("\"code\":404"));
}
#[test]
fn test_list_databases_response_serialization() {
let resp = ListDatabasesResponse::new(
vec!["db1".to_string(), "db2".to_string()],
Some("token123".to_string()),
);
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains("\"databases\":[\"db1\",\"db2\"]"));
assert!(json.contains("\"nextPageToken\":\"token123\""));
}
#[test]
fn test_audit_response_options() {
let audit = AuditRESTResponse::new(
Some("owner1".to_string()),
Some(1000),
Some("creator".to_string()),
Some(2000),
Some("updater".to_string()),
);
let mut options = HashMap::new();
audit.put_audit_options_to(&mut options);
assert_eq!(options.get("owner"), Some(&"owner1".to_string()));
assert_eq!(options.get("createdBy"), Some(&"creator".to_string()));
assert_eq!(options.get("createdAt"), Some(&"1000".to_string()));
assert_eq!(options.get("updatedBy"), Some(&"updater".to_string()));
assert_eq!(options.get("updatedAt"), Some(&"2000".to_string()));
}
}