vantage-api-client 2.2.2

Vantage extension for REST and GraphQL HTTP API backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use async_trait::async_trait;
use ciborium::Value as CborValue;
use indexmap::IndexMap;
use vantage_core::error;
use vantage_dataset::traits::{ReadableValueSet, Result};
use vantage_expressions::Expression;
use vantage_expressions::traits::associated_expressions::AssociatedExpression;
use vantage_expressions::traits::datasource::DataSource;
use vantage_expressions::traits::expressive::ExpressiveEnum;
use vantage_table::column::core::{Column, ColumnType};
use vantage_table::table::Table;
use vantage_table::traits::table_source::TableSource;
use vantage_types::{Entity, Record};

use vantage_expressions::traits::datasource::ExprDataSource;
use vantage_expressions::traits::expressive::DeferredFn;

use crate::RestApi;
use crate::rest::api::Order;

/// The error every write and server-side aggregate returns.
fn unsupported(method: &'static str) -> vantage_core::VantageError {
    error!("REST data source supports reads only", method = method).mark_unsupported()
}

/// A CBOR expression as text, the way `Expression::preview` renders
/// display types (which `CborValue` isn't): text values quoted, other
/// scalars spelled out, deferred parts as a placeholder.
fn cbor_preview(expr: &Expression<CborValue>) -> String {
    let mut parts = expr.template.split("{}");
    let mut out = String::from(parts.next().unwrap_or(""));
    for param in &expr.parameters {
        match param {
            ExpressiveEnum::Scalar(CborValue::Text(s)) => out.push_str(&format!("{s:?}")),
            ExpressiveEnum::Scalar(v) => out.push_str(&vantage_vista::operand_text(v)),
            ExpressiveEnum::Nested(e) => out.push_str(&cbor_preview(e)),
            ExpressiveEnum::Deferred(_) => out.push_str("**deferred()"),
        }
        out.push_str(parts.next().unwrap_or(""));
    }
    out
}

/// Extract the id field name from a table's column flags.
fn id_field_name<E: Entity<CborValue>>(table: &Table<RestApi, E>) -> Option<String> {
    table.id_field().map(|col| col.name().to_string())
}

impl RestApi {
    /// The rows of `table` under its conditions and pagination, with `order`
    /// sent as the ordering param when the API declares one.
    pub(crate) async fn list_ordered<E: Entity<CborValue>>(
        &self,
        table: &Table<RestApi, E>,
        order: Order<'_>,
    ) -> Result<IndexMap<String, Record<CborValue>>> {
        self.fetch_records(
            table.table_name(),
            id_field_name(table).as_deref(),
            &row_fields(table),
            table.pagination(),
            order,
            table.conditions(),
        )
        .await
    }
}

/// The fields a returned row carries: the table's
/// [`row_fields`](Table::row_fields), less the endpoint's `{placeholder}`s,
/// whose values fill the URL path and needn't come back in the rows.
pub(crate) fn row_fields<E: Entity<CborValue>>(table: &Table<RestApi, E>) -> Vec<String> {
    let placeholders: Vec<&str> = crate::rest::placeholders(table.table_name()).collect();
    let mut fields = table.row_fields();
    fields.retain(|name| !placeholders.contains(&name.as_str()));
    fields
}

impl ExprDataSource<CborValue> for RestApi {
    /// A bare template is its own text. A lone `{}` around one value — a
    /// deferred read such as `column_table_values_expr` — evaluates to that
    /// value. Anything else has no REST meaning and is null.
    async fn execute(&self, expr: &Expression<CborValue>) -> vantage_core::Result<CborValue> {
        if expr.parameters.is_empty() {
            return Ok(CborValue::Text(expr.template.clone()));
        }
        if expr.template == "{}" && expr.parameters.len() == 1 {
            let resolved = expr.resolve_deferred().await?;
            if let Some(ExpressiveEnum::Scalar(value)) = resolved.parameters.into_iter().next() {
                return Ok(value);
            }
        }
        Ok(CborValue::Null)
    }

    fn defer(&self, expr: Expression<CborValue>) -> DeferredFn<CborValue> {
        let api = self.clone();
        DeferredFn::new(move || {
            let api = api.clone();
            let expr = expr.clone();
            Box::pin(async move {
                let result = api.execute(&expr).await?;
                Ok(ExpressiveEnum::Scalar(result))
            })
        })
    }
}

impl DataSource for RestApi {}

#[async_trait]
impl TableSource for RestApi {
    type Column<Type>
        = Column<Type>
    where
        Type: ColumnType;
    type AnyType = CborValue;
    type Value = CborValue;
    type Id = String;
    type Condition = vantage_expressions::Expression<Self::Value>;
    type Source = String;

    /// Build a stringy `field == value` eq-condition. Stringy callers
    /// (the model-driven CLI) only have text on hand; values arrive as
    /// `String` and become CBOR text scalars here. The peeling code
    /// in `condition_to_query_param` renders all scalar variants the
    /// same way so the URL still reads correctly.
    fn eq_condition(field: &str, value: &str) -> Result<Self::Condition> {
        Ok(crate::eq_condition(field, value.to_string()))
    }

    /// Typed-value sibling of `eq_condition`. Used by `Reference::resolve_from_row`
    /// to push a row-derived join value onto a child table without a
    /// string round-trip.
    fn eq_value_condition(&self, field: &str, value: Self::Value) -> Result<Self::Condition> {
        Ok(crate::eq_condition(field, value))
    }

    /// A REST endpoint takes one value per filter param, so a single value
    /// becomes the same `field = value` as `eq_value_condition`. Any other
    /// list is refused: an `IN` the URL can't carry would be dropped from the
    /// request and widen the set.
    fn in_values_condition(
        &self,
        field: &str,
        values: Vec<Self::Value>,
    ) -> Result<Self::Condition> {
        match <[CborValue; 1]>::try_from(values) {
            Ok([value]) => Ok(crate::eq_condition(field, value)),
            Err(values) => Err(error!(
                "a REST filter takes exactly one value",
                field = field,
                values = values.len()
            )
            .mark_unsupported()),
        }
    }

    fn describe_condition(&self, condition: &Self::Condition) -> String {
        cbor_preview(condition)
    }

    fn condition_column(&self, condition: &Self::Condition) -> Option<String> {
        vantage_table::conditions::condition_column_of(condition)
    }

    fn create_column<Type: ColumnType>(&self, name: &str) -> Self::Column<Type> {
        Column::new(name)
    }

    fn to_any_column<Type: ColumnType>(
        &self,
        column: Self::Column<Type>,
    ) -> Self::Column<Self::AnyType> {
        Column::from_column(column)
    }

    fn convert_any_column<Type: ColumnType>(
        &self,
        any_column: Self::Column<Self::AnyType>,
    ) -> Option<Self::Column<Type>> {
        Some(Column::from_column(any_column))
    }

    fn expr(
        &self,
        template: impl Into<String>,
        parameters: Vec<ExpressiveEnum<Self::Value>>,
    ) -> Expression<Self::Value> {
        Expression::new(template, parameters)
    }

    fn search_table_condition<E>(
        &self,
        _table: &Table<Self, E>,
        search_value: &str,
    ) -> Expression<Self::Value>
    where
        E: Entity<Self::Value>,
    {
        Expression::new(format!("SEARCH '{}'", search_value), vec![])
    }

    async fn list_table_values<E>(
        &self,
        table: &Table<Self, E>,
    ) -> Result<IndexMap<Self::Id, Record<Self::Value>>>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        self.list_ordered(table, None).await
    }

    async fn get_table_value<E>(
        &self,
        table: &Table<Self, E>,
        id: &Self::Id,
    ) -> Result<Option<Record<Self::Value>>>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        let records = self.list_table_values(table).await?;
        Ok(records.get(id).cloned())
    }

    async fn get_table_some_value<E>(
        &self,
        table: &Table<Self, E>,
    ) -> Result<Option<(Self::Id, Record<Self::Value>)>>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        let records = self.list_table_values(table).await?;
        Ok(records.into_iter().next())
    }

    async fn get_table_count<E>(&self, table: &Table<Self, E>) -> Result<i64>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        let records = self.list_table_values(table).await?;
        Ok(records.len() as i64)
    }

    async fn get_table_sum<E>(
        &self,
        _table: &Table<Self, E>,
        _column: &Self::Column<Self::AnyType>,
    ) -> Result<Self::Value>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        Err(unsupported("get_table_sum"))
    }

    async fn get_table_max<E>(
        &self,
        _table: &Table<Self, E>,
        _column: &Self::Column<Self::AnyType>,
    ) -> Result<Self::Value>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        Err(unsupported("get_table_max"))
    }

    async fn get_table_min<E>(
        &self,
        _table: &Table<Self, E>,
        _column: &Self::Column<Self::AnyType>,
    ) -> Result<Self::Value>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        Err(unsupported("get_table_min"))
    }

    async fn insert_table_value<E>(
        &self,
        _table: &Table<Self, E>,
        _id: &Self::Id,
        _record: &Record<Self::Value>,
    ) -> Result<Record<Self::Value>>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        Err(unsupported("insert_table_value"))
    }

    async fn replace_table_value<E>(
        &self,
        _table: &Table<Self, E>,
        _id: &Self::Id,
        _record: &Record<Self::Value>,
    ) -> Result<Record<Self::Value>>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        Err(unsupported("replace_table_value"))
    }

    async fn patch_table_value<E>(
        &self,
        _table: &Table<Self, E>,
        _id: &Self::Id,
        _partial: &Record<Self::Value>,
    ) -> Result<Record<Self::Value>>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        Err(unsupported("patch_table_value"))
    }

    async fn delete_table_value<E>(&self, _table: &Table<Self, E>, _id: &Self::Id) -> Result<()>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        Err(unsupported("delete_table_value"))
    }

    async fn delete_table_all_values<E>(&self, _table: &Table<Self, E>) -> Result<()>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        Err(unsupported("delete_table_all_values"))
    }

    async fn insert_table_return_id_value<E>(
        &self,
        _table: &Table<Self, E>,
        _record: &Record<Self::Value>,
    ) -> Result<Self::Id>
    where
        E: Entity<Self::Value>,
        Self: Sized,
    {
        Err(unsupported("insert_table_return_id_value"))
    }

    /// Build a child condition for `with_many` / `with_one` traversal.
    ///
    /// REST APIs can't run subqueries, so this resolves on two paths:
    ///
    /// * **Sync peek** — if the parent already carries an eq-condition
    ///   on `source_column`, we re-key its value onto `target_field`
    ///   and we're done. Covers the common `with_many` case where
    ///   `source_column` is the parent's id field (narrowed via
    ///   `id=N` or `[N]`).
    /// * **Deferred read** — otherwise (the `with_one` case, where
    ///   `source_column` is a foreign-key field that lives in the
    ///   parent's record, not its conditions), we wrap the resolution
    ///   in a `DeferredFn` that fetches the parent at request time and
    ///   pulls the field out of the row. `fetch_records` resolves
    ///   deferreds before peeling conditions into query params.
    fn related_in_condition<SourceE: Entity<Self::Value> + 'static>(
        &self,
        target_field: &str,
        source_table: &Table<Self, SourceE>,
        source_column: &str,
    ) -> Self::Condition
    where
        Self: Sized,
    {
        for cond in source_table.conditions() {
            if let Some((field, value)) = crate::condition_to_query_param(cond)
                && field == source_column
            {
                let cbor_value: CborValue = if let Ok(i) = value.parse::<i64>() {
                    CborValue::Integer(i.into())
                } else if let Ok(f) = value.parse::<f64>() {
                    CborValue::Float(f)
                } else {
                    CborValue::Text(value)
                };
                return crate::eq_condition(target_field, cbor_value);
            }
        }

        let parent = source_table.clone();
        let column = source_column.to_string();
        let parent_name = source_table.table_name().to_string();
        let deferred = DeferredFn::new(move || {
            let parent = parent.clone();
            let column = column.clone();
            let parent_name = parent_name.clone();
            Box::pin(async move {
                let records = parent.list_values().await?;
                let value = records
                    .values()
                    .next()
                    .and_then(|r| r.get(&column))
                    .cloned()
                    .ok_or_else(|| {
                        error!(
                            "Deferred FK resolve: parent yielded no row or column missing",
                            table = parent_name,
                            column = column
                        )
                    })?;
                Ok(ExpressiveEnum::Scalar(value))
            })
        });

        Expression::new(
            "{} = {}",
            vec![
                ExpressiveEnum::Nested(Expression::new(target_field.to_string(), vec![])),
                ExpressiveEnum::Nested(Expression::new(
                    "{}",
                    vec![ExpressiveEnum::Deferred(deferred)],
                )),
            ],
        )
    }

    /// A REST API runs no subqueries, so the column's values are read by
    /// listing the table when the expression is resolved and taking
    /// `column` from each row (rows without it are skipped). Resolves to a
    /// CBOR array.
    fn column_table_values_expr<'a, E, Type: ColumnType>(
        &'a self,
        table: &Table<Self, E>,
        column: &Self::Column<Type>,
    ) -> AssociatedExpression<'a, Self, Self::Value, Vec<Type>>
    where
        E: Entity<Self::Value> + 'static,
        Self: Sized,
    {
        let api = self.clone();
        let table = table.clone();
        let column = column.name().to_string();
        let values = DeferredFn::new(move || {
            let (api, table, column) = (api.clone(), table.clone(), column.clone());
            Box::pin(async move {
                let records = api.list_table_values(&table).await?;
                let values = records
                    .values()
                    .filter_map(|r| r.get(&column).cloned())
                    .collect();
                Ok(ExpressiveEnum::Scalar(CborValue::Array(values)))
            })
        });
        let expr = Expression::new("{}", vec![ExpressiveEnum::Deferred(values)]);
        AssociatedExpression::new(expr, self)
    }
}