sqlload 0.70.1

SQL data loading tooling.
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
//! Paging through one endpoint with its named paginator.

use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::atomic::Ordering;

use std::collections::VecDeque;

use reqwest::Url;
use serde_json::{Map, Value};
use tokio::sync::mpsc::Sender;
use tokio_util::task::AbortOnDropHandle;

use crate::http_source::_helpers::cells::pivoted_rows;
use crate::http_source::_helpers::fetch::fetch;
use crate::http_source::_helpers::job::request_projection;
use crate::http_source::_helpers::reshaped::{reshapes, wrapped_projection, wrapped_rows};
use crate::http_source::_helpers::selector::{
    missing_path, pointer_text, pointer_value, selected_node, selector,
};
use crate::http_source::_helpers::urls::{redacted, request_url};
use crate::http_source::constants::REPORTED_ERROR_CHARS;
use crate::http_source::models::{
    AheadPage, Calls, CellNames, Fetched, HttpPage, Location, Method, PageCall, Paginator, Request,
    RowContext, SelectMissing, Selector,
};
use crate::python_sources::errors::ReadError;

/// Send every page of `request` at `path` (its placeholders filled) to `pages`, with where its rows are; a page whose selected node is null has no rows and is not sent, and one missing it fails, naming what the response holds, unless the request reads a missing node as no rows (`select_missing`). An offset run that would end after a first page shorter than its limit asks for the next offset once, and fails when rows come back, as the API then caps its pages lower than the limit. With `read_ahead`, offset and page-number pages after a full first page are requested that many at a time (fewer under a memory budget: only as many as pages the size of the largest yet fit in a quarter of each table's share), each through the shared rate limit and retries in a task of its own (so it keeps reading while the pages' receiver holds this loop up, and is aborted when the run ends), and handled strictly in page order, so the run still ends at the first short page, dropping the requests past it. Stops quietly once `pages` closes. A next position (cursor, link or count) already requested for this request fails before it is requested again, naming the value and the page that returned it, and a counted page repeating the previous response fails, rather than loop. With `error_path`, an error a page reports there fails the table before any of that page's rows load.
pub(crate) async fn paginate(
    calls: &Calls,
    (request, context): (&Request, &RowContext),
    path: &str,
    pages: &Sender<HttpPage>,
) -> Result<(), ReadError> {
    let rows = selector(request.select.as_deref())?;
    let reshaped = reshapes(request, &rows);
    let own = request_projection(request)?;
    let projection = match reshaped {
        true => wrapped_projection(request)?,
        false => own.clone(),
    };
    let rows_path = Some(rows.rows.join(".")).filter(|path| !path.is_empty());
    let first = request_url(&calls.endpoint.base_url, path)?;
    let mut call = page_call(request, &first, start_values(&request.paginator))?;
    let mut seen: HashMap<(Url, Option<String>), u64> = HashMap::from([(seen_key(&call), 1)]);
    let mut previous: Option<u64> = None;
    let mut names: Option<CellNames> = None;
    let ahead = read_ahead(&request.paginator);
    let mut in_flight: VecDeque<AbortOnDropHandle<AheadPage>> = VecDeque::new();
    let mut queued: u64 = 1;
    let mut largest: u64 = 0;
    for step in 1_u64.. {
        let shown = redacted(
            &format!("{} {}", call.method.as_str(), call.url),
            &calls.endpoint.current_secrets(),
        );
        let fetched = match (step, ahead) {
            (1, _) | (_, 1) => fetch(calls, &call).await?,
            _ => {
                let fitting = match (calls.source_part, largest) {
                    (Some(part), largest) if largest > 0 => (part / largest).max(1),
                    _ => ahead,
                };
                while queued < step + ahead.min(fitting) - 1 {
                    queued += 1;
                    let ahead_call = counted_call(request, &first, queued)?;
                    let ahead_calls = calls.clone();
                    in_flight.push_back(AbortOnDropHandle::new(tokio::spawn(async move {
                        let fetched = fetch(&ahead_calls, &ahead_call).await;
                        AheadPage {
                            call: ahead_call,
                            fetched,
                        }
                    })));
                }
                let next =
                    match in_flight.pop_front() {
                        Some(handle) => Some(handle.await.map_err(|error| {
                            format!("{shown}: a page read ahead stopped: {error}")
                        })?),
                        None => None,
                    };
                match next {
                    Some(ahead) if ahead.call == call => ahead.fetched?,
                    Some(_) | None => {
                        return Err(format!(
                            "{shown}: the pages read ahead fell out of order with the paginator"
                        )
                        .into());
                    }
                }
            }
        };
        let Some(fetched) = fetched else {
            return Ok(());
        };
        largest = largest.max(fetched.bytes.len() as u64);
        let digest = counted(&request.paginator).then(|| digest(&fetched.bytes));
        if digest.is_some() && previous == digest {
            return Err(format!(
                "{shown}: the response repeats the previous page; the API may ignore the paginator's parameter"
            )
            .into());
        }
        previous = digest;
        let document = parsed(request, &rows, &fetched.bytes)
            .map_err(|error| format!("{shown}: the response is not JSON: {error}"))?;
        if let Some(document) = &document {
            reported_error(request, document, (&shown, calls))?;
            selected_or_allowed(request, (&rows, document), &shown)?;
        }
        let next = next_call(
            request,
            (&first, &call),
            (&fetched, document.as_ref(), step),
        )
        .map_err(|error| format!("{shown}: {error}"))?;
        if let Some((next, position)) = &next
            && let Some(earlier) = seen.insert(seen_key(next), step + 1)
        {
            let position = redacted(position, &calls.endpoint.current_secrets());
            return Err(format!(
                "{shown}: {position} repeated after page {step}, so paging would read page {earlier} again; check the paginator's pointer"
            )
            .into());
        }
        match (step, &next, &document) {
            (1, None, Some(document)) => {
                capped_pages(calls, request, (&first, document), &shown).await?
            }
            (_, Some(_), _) if matches!(request.paginator, Paginator::Offset { .. }) => {
                calls.full_page_seen.store(true, Ordering::Relaxed);
            }
            _ => {}
        }
        let has_rows = document.as_ref().is_none_or(|document| {
            selected_node(document, &rows).is_some_and(|node| !node.is_null())
        });
        let (bytes, path) = match (&request.cells, document.as_ref()) {
            (Some(cells), Some(document)) => {
                let (text, used) = pivoted_rows(document, (&rows, cells), names.take())
                    .map_err(|error| format!("{shown}: cells: {error}"))?;
                names = used;
                (text.into_bytes(), None)
            }
            (None, Some(document)) if reshaped => (
                wrapped_rows(
                    (document, &fetched.bytes),
                    &rows,
                    (request, own.as_ref()),
                    context,
                )
                .map_err(|error| format!("{shown}: {error}"))?
                .into_bytes(),
                None,
            ),
            (Some(_), None) | (None, _) => (fetched.bytes, rows_path.clone()),
        };
        let page = HttpPage {
            bytes,
            path,
            source: shown,
            projection: projection.clone(),
            number: step,
            key: context.key.clone(),
        };
        if has_rows && pages.send(page).await.is_err() {
            return Ok(());
        }
        match next {
            Some((next, _)) => call = next,
            None => return Ok(()),
        }
    }
    Ok(())
}

/// What identifies a request among those a paginator sent: its URL and body.
fn seen_key(call: &PageCall) -> (Url, Option<String>) {
    (call.url.clone(), call.body.as_ref().map(Value::to_string))
}

/// Fails when the response `document` to `shown` holds an error at the request's `error_path`: any value there but null, false, `""`, `[]` or `{}`, shown as text (a string as itself, else as JSON), its secrets hidden, cut short.
fn reported_error(
    request: &Request,
    document: &Value,
    (shown, calls): (&str, &Calls),
) -> Result<(), ReadError> {
    let Some(path) = &request.error_path else {
        return Ok(());
    };
    let text = match selected_node(document, &selector(Some(path))?) {
        Some(Value::String(text)) => text.clone(),
        Some(Value::Null | Value::Bool(false)) | None => String::new(),
        Some(Value::Array(items)) if items.is_empty() => String::new(),
        Some(Value::Object(fields)) if fields.is_empty() => String::new(),
        Some(other) => other.to_string(),
    };
    if text.is_empty() {
        return Ok(());
    }
    let text: String = redacted(&text, &calls.endpoint.current_secrets())
        .chars()
        .take(REPORTED_ERROR_CHARS)
        .collect();
    Err(format!("{shown}: the API reported an error at {path}: {text}").into())
}

/// For offset paging whose first page (`document`, from the request `shown`) held some rows but fewer than its limit: the page at the next offset, which an API capping its pages below the limit fills, so rows there fail with the page size to set. An empty or missing page is the real end, and so are the first page's rows again, from an API that rounds the offset down to a page boundary. Skipped once a page of the request held its whole limit in this job, which shows the API does not cap it (see `Calls::full_page_seen`).
async fn capped_pages(
    calls: &Calls,
    request: &Request,
    (first, document): (&Url, &Value),
    shown: &str,
) -> Result<(), ReadError> {
    let Paginator::Offset {
        param,
        limit_param,
        limit,
        ..
    } = &request.paginator
    else {
        return Ok(());
    };
    let read = page_rows(document, request).map_err(|error| format!("{shown}: {error}"))?;
    if read == 0 || read >= *limit || calls.full_page_seen.load(Ordering::Relaxed) {
        return Ok(());
    }
    let probe = page_call(
        request,
        first,
        vec![
            (param.clone(), Value::from(read)),
            (limit_param.clone(), Value::from(*limit)),
        ],
    )?;
    let Some(fetched) = fetch(calls, &probe).await? else {
        return Ok(());
    };
    let probed = redacted(
        &format!("{} {}", probe.method.as_str(), probe.url),
        &calls.endpoint.current_secrets(),
    );
    let rows = selector(request.select.as_deref())?;
    let more = match parsed(request, &rows, &fetched.bytes)
        .map_err(|error| format!("{probed}: the response is not JSON: {error}"))?
    {
        Some(next) if selected_node(&next, &rows) == selected_node(document, &rows) => 0,
        Some(next) => {
            reported_error(request, &next, (&probed, calls))?;
            selected_or_allowed(request, (&rows, &next), &probed)?;
            page_rows(&next, request).map_err(|error| format!("{probed}: {error}"))?
        }
        None => 0,
    };
    match more {
        0 => Ok(()),
        _ => Err(format!(
            "{shown}: the first page held {read} rows, fewer than limit {limit}, but the API returned {more} more at offset {read}, so it caps its pages at {read} rows; set limit={read}"
        )
        .into()),
    }
}

/// Fails when the response `document` to `shown` lacks the `rows` path, naming what it holds, unless the request reads a missing path as no rows (`select_missing`).
fn selected_or_allowed(
    request: &Request,
    (rows, document): (&Selector, &Value),
    shown: &str,
) -> Result<(), ReadError> {
    match request.select_missing == SelectMissing::Fail && missing_path(document, rows) {
        true => Err(format!(
            "{shown}: select {:?} is not in the response, which holds {}; an API can answer an error with a 200 status, so check the response. For an API that leaves an empty list out, set select_missing=\"empty\" to read such a page as no rows",
            request.select.clone().unwrap_or_default(),
            top_level(document)
        )
        .into()),
        false => Ok(()),
    }
}

/// What a response holds at its top level, for an error: its keys, or the kind of value it is.
fn top_level(document: &Value) -> String {
    match document {
        Value::Object(fields) if fields.is_empty() => "an empty object".to_owned(),
        Value::Object(fields) => {
            let keys: Vec<&str> = fields.keys().map(String::as_str).collect();
            format!("the keys {}", keys.join(", "))
        }
        Value::Array(_) => "a list".to_owned(),
        Value::String(_) => "text".to_owned(),
        Value::Number(_) => "a number".to_owned(),
        Value::Bool(_) => "true or false".to_owned(),
        Value::Null => "null".to_owned(),
    }
}

/// The response as JSON when the selector, the paginator, the cells or `error_path` read it, else `None`.
fn parsed(request: &Request, rows: &Selector, bytes: &[u8]) -> Result<Option<Value>, String> {
    let reads_body = match &request.paginator {
        Paginator::Single | Paginator::LinkHeader => !rows.rows.is_empty(),
        Paginator::NextLink { .. }
        | Paginator::Cursor { .. }
        | Paginator::Offset { .. }
        | Paginator::PageNumber { .. } => true,
    } || request.cells.is_some()
        || request.error_path.is_some()
        || reshapes(request, rows);
    match reads_body {
        true => serde_json::from_slice(bytes)
            .map(Some)
            .map_err(|error| error.to_string()),
        false => Ok(None),
    }
}

/// Whether the paginator moves by a counter whatever the response says, so only a repeated body reveals an API ignoring it; the others follow the response, and the seen URLs catch their loops.
fn counted(paginator: &Paginator) -> bool {
    match paginator {
        Paginator::Offset { .. } | Paginator::PageNumber { .. } => true,
        Paginator::Single
        | Paginator::NextLink { .. }
        | Paginator::LinkHeader
        | Paginator::Cursor { .. } => false,
    }
}

fn digest(bytes: &[u8]) -> u64 {
    let mut hasher = DefaultHasher::new();
    bytes.hash(&mut hasher);
    hasher.finish()
}

/// How many pages an offset or page-number paginator keeps in flight: its `read_ahead`, else 1, as every other paginator reads one page at a time.
fn read_ahead(paginator: &Paginator) -> u64 {
    match paginator {
        Paginator::Offset { read_ahead, .. } | Paginator::PageNumber { read_ahead, .. } => {
            read_ahead.map_or(1, |pages| pages.max(1))
        }
        Paginator::Single
        | Paginator::NextLink { .. }
        | Paginator::LinkHeader
        | Paginator::Cursor { .. } => 1,
    }
}

/// The request for the `step`th page of an offset or page-number paginator, which `next_call` reaches from the page before it: offset `(step - 1) * limit`, or page `start + step - 1`.
fn counted_call(request: &Request, first: &Url, step: u64) -> Result<PageCall, String> {
    let values = match &request.paginator {
        Paginator::Offset {
            param,
            limit_param,
            limit,
            ..
        } => vec![
            (param.clone(), Value::from((step - 1) * limit)),
            (limit_param.clone(), Value::from(*limit)),
        ],
        Paginator::PageNumber { param, start, .. } => {
            vec![(param.clone(), Value::from(start + step - 1))]
        }
        Paginator::Single
        | Paginator::NextLink { .. }
        | Paginator::LinkHeader
        | Paginator::Cursor { .. } => start_values(&request.paginator),
    };
    page_call(request, first, values)
}

/// The paginator's values on the first request.
fn start_values(paginator: &Paginator) -> Vec<(String, Value)> {
    match paginator {
        Paginator::Offset {
            param,
            limit_param,
            limit,
            ..
        } => vec![
            (param.clone(), Value::from(0_u64)),
            (limit_param.clone(), Value::from(*limit)),
        ],
        Paginator::PageNumber { param, start, .. } => vec![(param.clone(), Value::from(*start))],
        Paginator::Single
        | Paginator::NextLink { .. }
        | Paginator::LinkHeader
        | Paginator::Cursor { .. } => Vec::new(),
    }
}

/// Where the paginator's values go.
fn location(paginator: &Paginator) -> Location {
    match paginator {
        Paginator::Offset { location, .. }
        | Paginator::PageNumber { location, .. }
        | Paginator::Cursor { location, .. } => *location,
        Paginator::Single | Paginator::NextLink { .. } | Paginator::LinkHeader => Location::Query,
    }
}

/// The request at `url` with the paginator's `values`: in the query after `params`, or at their paths in a fresh copy of `json_body`, which is never changed itself. A `POST` without `json_body` starts from `{}`.
fn page_call(
    request: &Request,
    url: &Url,
    values: Vec<(String, Value)>,
) -> Result<PageCall, String> {
    let (query, in_body) = match location(&request.paginator) {
        Location::Query => (values, Vec::new()),
        Location::Body => (Vec::new(), values),
    };
    let query: Vec<(String, String)> = query
        .into_iter()
        .map(|(name, value)| (name, param_text(&value)))
        .collect();
    let body = match request.method {
        Method::Get => None,
        Method::Post => {
            let mut body = request
                .json_body
                .clone()
                .unwrap_or_else(|| Value::Object(Map::new()));
            for (path, value) in in_body {
                set_at(&mut body, &path, value)?;
            }
            Some(body)
        }
    };
    Ok(PageCall {
        method: request.method,
        url: with_params(url, &request.params, &query),
        body,
    })
}

/// `body` with `value` at `path` (such as `$.page.cursor`), adding objects on the way.
pub(crate) fn set_at(body: &mut Value, path: &str, value: Value) -> Result<(), String> {
    let names = selector(Some(path))?.rows;
    let Some((last, parents)) = names.split_last() else {
        return Err(format!("body path {path:?} names no field"));
    };
    let mut node = body;
    for name in parents {
        node = node
            .as_object_mut()
            .ok_or_else(|| format!("json_body has no object to set {path} in"))?
            .entry(name.clone())
            .or_insert_with(|| Value::Object(Map::new()));
    }
    node.as_object_mut()
        .ok_or_else(|| format!("json_body has no object to set {path} in"))?
        .insert(last.clone(), value);
    Ok(())
}

/// A value as a query parameter: text as itself, anything else as JSON.
fn param_text(value: &Value) -> String {
    match value {
        Value::String(text) => text.clone(),
        other => other.to_string(),
    }
}

/// The request after `fetched` (the `step`th page, sent as `current`) with the position it goes to, such as `cursor abc`, or `None` at the end; links resolve against the URL the response came from, after any redirect, and keep the current body; `document` is the parsed response whenever the paginator reads the body.
fn next_call(
    request: &Request,
    (first, current): (&Url, &PageCall),
    (fetched, document, step): (&Fetched, Option<&Value>, u64),
) -> Result<Option<(PageCall, String)>, String> {
    let body = || document.ok_or_else(|| "the paginator needs a JSON response".to_owned());
    let joined = |link: String, what: &str| {
        fetched
            .url
            .join(&link)
            .map(|url| {
                Some((
                    PageCall {
                        url,
                        ..current.clone()
                    },
                    format!("{what} {link}"),
                ))
            })
            .map_err(|error| format!("next page {link} is not a URL: {error}"))
    };
    let next = |values: Vec<(String, Value)>, position: String| {
        page_call(request, first, values).map(|call| Some((call, position)))
    };
    match &request.paginator {
        Paginator::Single => Ok(None),
        Paginator::LinkHeader => fetched
            .next_link
            .clone()
            .map_or(Ok(None), |link| joined(link, "Link header next")),
        Paginator::NextLink { pointer } => pointer_text(body()?, &selector(Some(pointer))?)
            .map_or(Ok(None), |link| joined(link, "next link")),
        Paginator::Cursor { pointer, param, .. } => {
            match pointer_value(body()?, &selector(Some(pointer))?) {
                Some(token) => {
                    let position = format!("cursor {}", param_text(&token));
                    next(vec![(param.clone(), token)], position)
                }
                None => Ok(None),
            }
        }
        Paginator::Offset {
            param,
            limit_param,
            limit,
            ..
        } => match page_rows(body()?, request)? >= *limit {
            true => next(
                vec![
                    (param.clone(), Value::from(step * limit)),
                    (limit_param.clone(), Value::from(*limit)),
                ],
                format!("offset {}", step * limit),
            ),
            false => Ok(None),
        },
        Paginator::PageNumber { param, start, .. } => match page_rows(body()?, request)? > 0 {
            true => next(
                vec![(param.clone(), Value::from(start + step))],
                format!("page number {}", start + step),
            ),
            false => Ok(None),
        },
    }
}

/// How many rows a page holds for offset and page-number paging: its selected list's length, 0 when missing or null; anything else is an error, since a counted object would never end the paging.
fn page_rows(document: &Value, request: &Request) -> Result<u64, String> {
    match selected_node(document, &selector(request.select.as_deref())?) {
        Some(Value::Array(items)) => Ok(items.len() as u64),
        Some(Value::Null) | None => Ok(0),
        Some(_) => Err(format!(
            "offset and page-number paging count the rows in a list, but select {:?} is not one; point select at the page's list of rows",
            request.select.clone().unwrap_or_else(|| "$".to_owned())
        )),
    }
}

/// `url` with `params` (nulls left out) and then `extra` appended to its query.
fn with_params(url: &Url, params: &Map<String, Value>, extra: &[(String, String)]) -> Url {
    let mut url = url.clone();
    let pairs = params.iter().filter_map(|(name, value)| match value {
        Value::Null => None,
        Value::String(text) => Some((name.clone(), text.clone())),
        other => Some((name.clone(), other.to_string())),
    });
    let pairs: Vec<(String, String)> = pairs.chain(extra.iter().cloned()).collect();
    if !pairs.is_empty() {
        url.query_pairs_mut().extend_pairs(pairs);
    }
    url
}