@xeplr/ui-utils 1.1.9 → 1.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -8
- package/package.json +1 -1
- package/src/fileUpload/uploadFile.js +38 -0
- package/src/imports/designs/ImportsSample.jsx +2 -2
- package/src/imports/importsApi.js +131 -6
- package/src/imports/useImportsController.js +35 -20
- package/src/index.js +5 -2
package/README.md
CHANGED
|
@@ -120,7 +120,7 @@ export default function SelectCompany() {
|
|
|
120
120
|
| `useNumberFieldController(props)` | NumberFieldPage props | `type, raw, numeric, error, placeholder, disabled, decimals, formatDisplay, affix {list, selected, position, labelKey, valueKey} \| null, handleNumberChange, handleAffixChange, handleBlur` |
|
|
121
121
|
| `useTextFieldController(props)` | TextFieldPage props | `type, raw, error, remaining, placeholder, disabled, required, maxLength, rows, label, help, handleChange, handleBlur, handleKeyDown, handleClear` |
|
|
122
122
|
| `useFileUploadController(options)` | FileUploadPage props | `files, uploading, progress, error, result, dragOver, inputRef, handleChange, handleDragOver, handleDragLeave, handleDrop, handleUpload, openFilePicker, removeFile(i), clear, allowedTypes, maxSize, maxFiles` |
|
|
123
|
-
| `useImportsController(props)` | ImportsPage props | `targets, targetsError, connectionId, dbInfoId, databases, chooseConnection, chooseDatabase, importing, progressText, stop, historyVersion, importProps, historyProps` |
|
|
123
|
+
| `useImportsController(props)` | ImportsPage props | `targets, targetsError, connectionId, dbInfoId, databases, chooseConnection, chooseDatabase, importing` (`{ runId, kind: 'check' \| 'import', startedAt, progress }`), `progressText, stop, historyVersion, importProps, historyProps` |
|
|
124
124
|
| `useDataImportController(options)` | DataImportPage props | `file, inspecting, uploadPercent, inspected, mappings, committing, results, error, handleFileChange, updateMapping(i, patch), setFix(i, key, on), checksOf(part), modes, setMode(i, mode), problems (per mapping), checking, blocked, handleCommit, reset, accept, targetLabel` |
|
|
125
125
|
| `useImportHistoryController(options)` | ImportHistoryPage props | `jobs, loading, error, rollingBackId, deletingId, reload, handleRollback(job), handleDelete(job)` |
|
|
126
126
|
| `useDroppedRowsController(options)` | `onLoadDropped`, `onDownloadDropped` | `job, data, table {columns, rows}, summary {heading, note}, loading, error, copied, downloading, canCopy, canDownload, canView(job), open(job), close, copy, download` |
|
|
@@ -152,7 +152,8 @@ export default function SelectCompany() {
|
|
|
152
152
|
| `toggleBranch`, `decorateTree` | `(open, parentKey, key) → open`, `(nodes, open) → nodes` | Which branch of a settings tree is open at each level; `open` is `{ [parentKey]: key }`, the root's parent `''` |
|
|
153
153
|
| `filterGridRows`, `sortGridRows` | `(rows, query, fields)`, `(rows, field, 'asc'\|'desc')` | Grid search and sort. An array field matches if any entry matches. |
|
|
154
154
|
| `sanitizeTargetName`, `buildInitialMappings`, `checksFor` | `(name) → string`, `({ parts?, originalName?, checks? }) → [{ part, target, include, fixes }]`, `(inspectResult, part) → checks[]` | Data import mapping |
|
|
155
|
-
| `configureUpload`, `uploadFile` | `({ url, headers, getHeaders })`, `(files, { url, fieldName, extraData, onProgress }) → Promise` | Multipart upload over XHR |
|
|
155
|
+
| `configureUpload`, `uploadFile` | `({ url, headers, getHeaders, renew })`, `(files, { url, fieldName, extraData, onProgress }) → Promise` | Multipart upload over XHR. **Give `renew`** (`async () => boolean`, e.g. `@xeplr/ui-account`'s `renewSession`): on a 401 the upload renews the sign-in once and sends the file again. Without it, a token that ran out while the person sat on the page failed the upload with "token expired" while every other request renewed. |
|
|
156
|
+
| `signedFetch`, `renewSignIn` | `(url, init) → Response`, `() → boolean` | `fetch` with the upload headers and the same one renewal on a 401 — what the Imports page's JSON calls use |
|
|
156
157
|
| `attachProgressSource`, `progressSourceAttached`, `subscribeToProgress`, `describeProgress`, `describeComplete` | `(subscribe)`, `() → boolean`, `(key, handler) → unsubscribe`, `(data, noun?)`, `(data, noun?)` | The progress event source and its sentences |
|
|
157
158
|
|
|
158
159
|
### Imperative helpers, theme, data
|
|
@@ -297,7 +298,7 @@ The search type shows a ✕ only when there is text, and clearing calls `onChang
|
|
|
297
298
|
```jsx
|
|
298
299
|
import { configureUpload, FileUploadPage } from '@xeplr/ui-utils'
|
|
299
300
|
|
|
300
|
-
configureUpload({ url: '/uploads', getHeaders: () => ({ Authorization: 'Bearer ' + getToken() }) })
|
|
301
|
+
configureUpload({ url: '/uploads', getHeaders: () => ({ Authorization: 'Bearer ' + getToken() }), renew: renewSession })
|
|
301
302
|
|
|
302
303
|
<FileUploadPage allowedTypes={['image/*', 'application/pdf']} maxSize={10 * 1024 * 1024} maxFiles={3}
|
|
303
304
|
onSuccess={(res) => raiseSnackbar('Uploaded', { design: 'success' })} />
|
|
@@ -320,27 +321,29 @@ configureUpload({ url: '/uploads', getHeaders: () => ({ Authorization: 'Bearer '
|
|
|
320
321
|
The whole import feature, against [`@xeplr/imports`](https://www.npmjs.com/package/@xeplr/imports)' routes. An app that mounts that router adds one route here and nothing else:
|
|
321
322
|
|
|
322
323
|
```jsx
|
|
323
|
-
configureUpload({ url: API_BASE + '/imports/files', getHeaders }) // once, at startup — the headers every call carries
|
|
324
|
+
configureUpload({ url: API_BASE + '/imports/files', getHeaders, renew: renewSession }) // once, at startup — the headers every call carries, and how an expired sign-in renews
|
|
324
325
|
<Route path="/upload" element={<ImportsPage basePath={API_BASE + '/imports'} />} />
|
|
325
326
|
```
|
|
326
327
|
|
|
327
328
|
| prop | type | meaning |
|
|
328
329
|
|---|---|---|
|
|
329
330
|
| `basePath` | `string` | Where the app mounted the router, as the browser sees it (default `'/imports'`) |
|
|
330
|
-
| `
|
|
331
|
+
| `events` | `{ subscribe(handler) → unsubscribe, isLive?() → boolean }` | Optional, recommended: the app's event stream (SSE), on which `@xeplr/imports` (its `publish` option) tells each check and import as it moves and when it ends. With it the page **waits on the stream**: it asks `GET /runs/:id` once after a run starts (it may have ended before its id came back), and again only every 15 s as a safety net, or every `pollMs` while `isLive()` is false. `handler` gets each event's data; anything but `type: 'import-run'` is ignored. Pass the same object on every render. Xeplr BI passes `{ subscribe: subscribeToRunEvents, isLive: streamIsLive }` on topic `user:me:imports` |
|
|
332
|
+
| `pollMs` | `number` | How often a running check or import is asked how far it has got when there is no stream, or it is down (default 1000) |
|
|
331
333
|
| `upload` | `(file, onProgress(percent), { standard }) => Promise<{ filePath }>` | Optional: the app's own way to send a file. It decides per file — `standard(file, onProgress)` is the usual one request to `/files`; a file too big for one request can be sent another way (in pieces, say) into the tenant's `uploads/` folder, and the answer's `filePath` is imported like any other. Xeplr BI sends files over 200 MB in chunks this way, on Pro and up (`importsApi.js` `uploaderFor`) |
|
|
332
334
|
| `accept` | `string` | The file input's `accept` (default `ACCEPT`: `.csv,.json,.xlsx,.xls,.parquet`) |
|
|
333
335
|
|
|
334
336
|
It shows three things:
|
|
335
337
|
|
|
336
338
|
1. **The database picker**, filled from `GET /targets`.
|
|
337
|
-
2. **The import itself.** This is `DataImportPage`: its checks, the New table / Append / Replace modes with the file checked against the typed table, the upload percentage, and the dropped rows. While an import runs, its progress shows with its running time and
|
|
339
|
+
2. **The import itself.** This is `DataImportPage`: its checks, the New table / Append / Replace modes with the file checked against the typed table, the upload percentage, and the dropped rows. **The check runs in the background** (`POST /inspect` with `background: true`): it reads every row of a CSV, which on a file of gigabytes takes minutes, past a proxy's wait (nginx's 60 s gave a 504). While the check or an import runs, its progress shows with its running time and ✕ — for the check "Checking the file · 1.2 GB of 3.0 GB (40%) · 412,000 rows". Needs `@xeplr/imports` 2.0.2+; an older server answers the check at once and is used as before.
|
|
338
340
|
3. **The history.** This is `ImportHistoryPage`, with dropped rows, rollback (none for a Replace) and delete.
|
|
339
341
|
|
|
340
342
|
Requests carry the headers `configureUpload` was given (`uploadHeaders()`), so sign-in and tenancy need no second setup. The model is `importsApi.js`:
|
|
341
343
|
|
|
342
344
|
- `createImportsApi(basePath)` makes every route call.
|
|
343
|
-
-
|
|
345
|
+
- `createRunWatcher({ api, events?, pollMs? })` → `{ wait(runId, onProgress) → Promise<run>, close() }`: waits for a check or an import as described under `events`, without React. A run whose `GET /runs/:id` fails (with several API processes it may be held by another one) is still heard ending on the stream.
|
|
346
|
+
- Pure helpers: `importProgressText`, `checkProgressText`, `runResults`, `checkResult` (a finished check in `onInspect`'s shape, or its error), `historyJob`, `databasesOf`, `fileNameOf`, `uploaderFor(api, upload)` (how a picked file is sent), `ACCEPT` (exported as `IMPORT_ACCEPT`: the files it reads, Parquet among them).
|
|
344
347
|
|
|
345
348
|
A custom design receives the controller's values plus `importSection` and `historySection` as elements.
|
|
346
349
|
|
|
@@ -665,7 +668,7 @@ npm test
|
|
|
665
668
|
|
|
666
669
|
This runs each `test/*.test.js` with plain `node` and stops at the first failing file. The tests cover the date range model, the range field model, the text field model with `inputStyleVars`, the colour, expander and settings-tree models, and the design rules of the date range, colour picker, expanders and settings tree. CI runs the same files with `node --test` and coverage.
|
|
667
670
|
|
|
668
|
-
`test/importsApi.test.js` runs the imports model against the real `@xeplr/imports` router: a real Express app, real Postgres and a throwaway `xeplr_configs`. It runs when `PG_HOST`, `PG_PORT`, `PG_USER`, `PG_PASSWORD` and `PG_DATABASE` are set and `XEPLR_IMPORTS_DIR` names the package's folder; otherwise it is skipped. The upload itself uses XMLHttpRequest, so it only runs in a browser, where BI's screen is driven.
|
|
671
|
+
`test/importsApi.test.js` runs the imports model against the real `@xeplr/imports` router: a real Express app, real Postgres and a throwaway `xeplr_configs`. It runs when `PG_HOST`, `PG_PORT`, `PG_USER`, `PG_PASSWORD` and `PG_DATABASE` are set and `XEPLR_IMPORTS_DIR` names the package's folder; otherwise it is skipped. It also opens a real event stream (`@xeplr/base-apis` `sse` over HTTP, the router publishing to it) and checks that a 400,000-row check is heard on it, asked about once instead of every 50 ms, with its progress; that a run another process holds is still heard ending; that a stopped check says so; and that with the stream down it is asked about again. The upload itself uses XMLHttpRequest, so it only runs in a browser, where BI's screen is driven.
|
|
669
672
|
|
|
670
673
|
## License
|
|
671
674
|
|
package/package.json
CHANGED
|
@@ -7,6 +7,31 @@ export function configureUpload(config = {}) {
|
|
|
7
7
|
if (config.url) _config.url = config.url;
|
|
8
8
|
if (config.headers) _config.headers = config.headers;
|
|
9
9
|
if (config.getHeaders) _config.getHeaders = config.getHeaders;
|
|
10
|
+
// renew: async () => boolean — get a fresh sign-in token (the app's own
|
|
11
|
+
// refresh, e.g. @xeplr/ui-account's renewSession). Without it an upload sent
|
|
12
|
+
// with an expired token just failed with "token expired", while every other
|
|
13
|
+
// request in the app renewed and carried on.
|
|
14
|
+
if (config.renew) _config.renew = config.renew;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Ask the app for a fresh token, once. true when it got one. */
|
|
18
|
+
export async function renewSignIn() {
|
|
19
|
+
if (typeof _config.renew !== 'function') return false;
|
|
20
|
+
try { return Boolean(await _config.renew()); } catch (e) { return false; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* fetch with the upload headers, renewing the sign-in once on a 401 and
|
|
25
|
+
* asking again — the same rule the app's own authFetch follows. `init.headers`
|
|
26
|
+
* are added on top of the upload headers.
|
|
27
|
+
*/
|
|
28
|
+
export async function signedFetch(url, init) {
|
|
29
|
+
var opts = init || {};
|
|
30
|
+
var send = function() {
|
|
31
|
+
return fetch(url, Object.assign({}, opts, { headers: Object.assign(uploadHeaders(), opts.headers || {}) }));
|
|
32
|
+
};
|
|
33
|
+
var res = await send();
|
|
34
|
+
return (await renewAndRetry(res.status, false, send)) || res;
|
|
10
35
|
}
|
|
11
36
|
|
|
12
37
|
/**
|
|
@@ -19,6 +44,16 @@ export function uploadHeaders() {
|
|
|
19
44
|
return Object.assign({}, _config.getHeaders ? _config.getHeaders() : _config.headers);
|
|
20
45
|
}
|
|
21
46
|
|
|
47
|
+
/**
|
|
48
|
+
* After a request answered `status`: when it was a 401 not yet retried, renew
|
|
49
|
+
* the sign-in once and `retry()` — its promise; otherwise null (keep the
|
|
50
|
+
* answer). Shared by signedFetch and uploadFile, so both follow one rule.
|
|
51
|
+
*/
|
|
52
|
+
export function renewAndRetry(status, retried, retry) {
|
|
53
|
+
if (status !== 401 || retried) return null;
|
|
54
|
+
return renewSignIn().then(function(ok) { return ok ? retry() : null; });
|
|
55
|
+
}
|
|
56
|
+
|
|
22
57
|
/**
|
|
23
58
|
* Upload files to the server.
|
|
24
59
|
* @param {File[]} files - Files to upload
|
|
@@ -65,6 +100,9 @@ export function uploadFile(files, options = {}) {
|
|
|
65
100
|
}
|
|
66
101
|
|
|
67
102
|
xhr.onload = function() {
|
|
103
|
+
// A token that ran out while the page sat open: renew once, send again.
|
|
104
|
+
var again = renewAndRetry(xhr.status, options.renewed, function() { return uploadFile(files, Object.assign({}, options, { renewed: true })); });
|
|
105
|
+
if (again) return again.then(function(r) { return r === null ? reject(new Error('Upload failed: sign-in expired')) : resolve(r); }, reject);
|
|
68
106
|
try {
|
|
69
107
|
var response = JSON.parse(xhr.responseText);
|
|
70
108
|
if (xhr.status >= 200 && xhr.status < 300) {
|
|
@@ -45,7 +45,7 @@ export default function ImportsSample({
|
|
|
45
45
|
<p className="xeplr-imports-progress">
|
|
46
46
|
{progressText}
|
|
47
47
|
<RunClock startedAt={importing.startedAt} />
|
|
48
|
-
<button type="button" className="xeplr-imports-stop" title=
|
|
48
|
+
<button type="button" className="xeplr-imports-stop" title={importing.kind === 'check' ? 'Stop this check' : 'Stop this import'} onClick={stop}>✕</button>
|
|
49
49
|
</p>
|
|
50
50
|
)}
|
|
51
51
|
{importSection}
|
|
@@ -60,7 +60,7 @@ export default function ImportsSample({
|
|
|
60
60
|
);
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
/** "12 s", "3 min 4 s" — how long the import has been running. */
|
|
63
|
+
/** "12 s", "3 min 4 s" — how long the check or import has been running. */
|
|
64
64
|
function RunClock({ startedAt }) {
|
|
65
65
|
var [now, setNow] = useState(Date.now());
|
|
66
66
|
useEffect(function() {
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// '/imports', or '/api/imports' behind a proxy prefix. Requests carry the
|
|
6
6
|
// headers configureUpload was given (uploadHeaders): sign-in and tenancy.
|
|
7
7
|
|
|
8
|
-
import { uploadFile,
|
|
8
|
+
import { uploadFile, signedFetch } from '../fileUpload/uploadFile.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* How a picked file is sent: the app's own `upload` when it gives one —
|
|
@@ -28,9 +28,9 @@ export function createImportsApi(basePath) {
|
|
|
28
28
|
var base = String(basePath || '/imports').replace(/\/+$/, '');
|
|
29
29
|
|
|
30
30
|
async function call(method, path, body) {
|
|
31
|
-
var headers =
|
|
32
|
-
|
|
33
|
-
var res = await
|
|
31
|
+
var headers = body ? { 'content-type': 'application/json' } : {};
|
|
32
|
+
// signedFetch: the upload headers, and one renewal of an expired sign-in.
|
|
33
|
+
var res = await signedFetch(base + path, { method: method, headers: headers, body: body ? JSON.stringify(body) : undefined });
|
|
34
34
|
var data = await res.json().catch(function() { return {}; });
|
|
35
35
|
if (!res.ok) throw new Error(data.error || ('The request failed (' + res.status + ')'));
|
|
36
36
|
return data;
|
|
@@ -38,7 +38,8 @@ export function createImportsApi(basePath) {
|
|
|
38
38
|
|
|
39
39
|
return {
|
|
40
40
|
upload: function(file, onProgress) { return uploadFile(file, { url: base + '/files', onProgress: onProgress }); },
|
|
41
|
-
|
|
41
|
+
// In the background: on a big CSV the check reads every row, for minutes.
|
|
42
|
+
inspect: function(filePath) { return call('POST', '/inspect', { filePath: filePath, background: true }); },
|
|
42
43
|
checkTarget: function(body) { return call('POST', '/check-target', body); },
|
|
43
44
|
commit: function(body) { return call('POST', '/commit', body); },
|
|
44
45
|
run: function(runId) { return call('GET', '/runs/' + encodeURIComponent(runId)); },
|
|
@@ -50,7 +51,7 @@ export function createImportsApi(basePath) {
|
|
|
50
51
|
remove: function(id) { return call('POST', '/history/' + encodeURIComponent(id) + '/delete'); },
|
|
51
52
|
/** The dropped rows as a file: { blob, name } — saving it is the page's job. */
|
|
52
53
|
droppedFile: async function(id) {
|
|
53
|
-
var res = await
|
|
54
|
+
var res = await signedFetch(base + '/history/' + encodeURIComponent(id) + '/dropped/file');
|
|
54
55
|
if (!res.ok) {
|
|
55
56
|
var data = await res.json().catch(function() { return {}; });
|
|
56
57
|
throw new Error(data.error || ('The download failed (' + res.status + ')'));
|
|
@@ -69,6 +70,130 @@ export function fileNameOf(disposition, fallback) {
|
|
|
69
70
|
return plain ? plain[1] : fallback;
|
|
70
71
|
}
|
|
71
72
|
|
|
73
|
+
// ── WAITING FOR A RUN ──────────────────────────────────────────────────
|
|
74
|
+
//
|
|
75
|
+
// A check and an import both run in the background on the server and answer
|
|
76
|
+
// with a run id. How the page hears how far one has got and how it ended:
|
|
77
|
+
//
|
|
78
|
+
// On the app's event stream, when it gives one (`events`): the server tells
|
|
79
|
+
// each run as it moves and once when it ends (@xeplr/imports' `publish`).
|
|
80
|
+
// The stream is listened to from the moment the watcher is made, so an event
|
|
81
|
+
// is not missed for want of a listener; after a run starts it is asked about
|
|
82
|
+
// ONCE (it may have ended before its id came back), then waited for. While
|
|
83
|
+
// the stream is live it is asked again only every LIVE_ASK_MS — a safety net
|
|
84
|
+
// for a lost event, not the way the answer comes.
|
|
85
|
+
//
|
|
86
|
+
// Without a stream, or while it is down (`events.isLive()` false): asked
|
|
87
|
+
// every pollMs, as before.
|
|
88
|
+
//
|
|
89
|
+
// events = { subscribe(handler) → unsubscribe, isLive?() → boolean }
|
|
90
|
+
// handler gets each event's data: { type: 'import-run', runId, kind, status,
|
|
91
|
+
// progress, result, error }; anything else is ignored.
|
|
92
|
+
|
|
93
|
+
export var LIVE_ASK_MS = 15000;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* @param {object} opts - { api, events?, pollMs? }
|
|
97
|
+
* @returns {{ wait(runId, onProgress) → Promise<run>, close() }} the run as GET /runs/:id gives it, once it ended
|
|
98
|
+
*/
|
|
99
|
+
export function createRunWatcher(opts) {
|
|
100
|
+
var api = opts.api;
|
|
101
|
+
var events = opts.events && typeof opts.events.subscribe === 'function' ? opts.events : null;
|
|
102
|
+
var pollMs = opts.pollMs || 1000;
|
|
103
|
+
var waiting = new Map(); // runId → { onProgress, done }
|
|
104
|
+
var closed = false;
|
|
105
|
+
|
|
106
|
+
function heard(run) {
|
|
107
|
+
var w = waiting.get(run.runId || run.id);
|
|
108
|
+
if (!w) return;
|
|
109
|
+
if (run.status === 'running') { if (w.onProgress) w.onProgress(run.progress || null); return; }
|
|
110
|
+
w.done(run);
|
|
111
|
+
}
|
|
112
|
+
var unsubscribe = events ? events.subscribe(function(e) {
|
|
113
|
+
if (e && e.type === 'import-run' && e.runId) heard(e);
|
|
114
|
+
}) : null;
|
|
115
|
+
|
|
116
|
+
function live() {
|
|
117
|
+
if (!events) return false;
|
|
118
|
+
try { return typeof events.isLive === 'function' ? Boolean(events.isLive()) : true; } catch (e) { return false; }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function wait(runId, onProgress) {
|
|
122
|
+
return new Promise(function(resolve, reject) {
|
|
123
|
+
var timer = null;
|
|
124
|
+
var over = false;
|
|
125
|
+
function done(run) {
|
|
126
|
+
if (over) return;
|
|
127
|
+
over = true;
|
|
128
|
+
waiting.delete(runId);
|
|
129
|
+
if (timer) clearTimeout(timer);
|
|
130
|
+
resolve(Object.assign({}, run, { id: runId }));
|
|
131
|
+
}
|
|
132
|
+
function fail(err) {
|
|
133
|
+
if (over) return;
|
|
134
|
+
over = true;
|
|
135
|
+
waiting.delete(runId);
|
|
136
|
+
if (timer) clearTimeout(timer);
|
|
137
|
+
reject(err);
|
|
138
|
+
}
|
|
139
|
+
waiting.set(runId, { onProgress: onProgress, done: done });
|
|
140
|
+
async function ask() {
|
|
141
|
+
timer = null;
|
|
142
|
+
if (over || closed) return;
|
|
143
|
+
try {
|
|
144
|
+
var run = await api.run(runId);
|
|
145
|
+
if (over) return;
|
|
146
|
+
if (run.status !== 'running') return done(run);
|
|
147
|
+
if (onProgress) onProgress(run.progress || null);
|
|
148
|
+
} catch (err) {
|
|
149
|
+
// With a stream the run may be on another API process, which does
|
|
150
|
+
// not know it: the stream still carries its ending.
|
|
151
|
+
if (!events) return fail(err);
|
|
152
|
+
}
|
|
153
|
+
if (!over && !closed) timer = setTimeout(ask, live() ? LIVE_ASK_MS : pollMs);
|
|
154
|
+
}
|
|
155
|
+
ask();
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
wait: wait,
|
|
161
|
+
close: function() {
|
|
162
|
+
closed = true;
|
|
163
|
+
if (unsubscribe) { try { unsubscribe(); } catch (e) { /* gone already */ } }
|
|
164
|
+
waiting.clear();
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** What a finished check found, in onInspect's shape — or the error it ended with. */
|
|
170
|
+
export function checkResult(run) {
|
|
171
|
+
if (run.status === 'error') throw new Error(run.error || 'The check failed');
|
|
172
|
+
if (run.status === 'stopped') throw new Error(run.error === 'Stopped' || !run.error ? 'The check was stopped.' : run.error);
|
|
173
|
+
var found = run.result || {};
|
|
174
|
+
return { format: found.format, parts: found.sheets, checks: found.checks };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** "Checking the file · 1.2 GB of 3.0 GB (40%) · 412,000 rows" — how far a check has got. */
|
|
178
|
+
export function checkProgressText(p) {
|
|
179
|
+
if (!p) return 'Checking the file…';
|
|
180
|
+
var parts = [];
|
|
181
|
+
if (p.parts > 1) parts.push('sheet ' + p.part + ' of ' + p.parts + (p.sheet ? ' (' + p.sheet + ')' : ''));
|
|
182
|
+
if (p.bytesRead != null && p.bytes) {
|
|
183
|
+
parts.push(sizeText(p.bytesRead) + ' of ' + sizeText(p.bytes) + ' (' + Math.min(100, Math.floor((p.bytesRead / p.bytes) * 100)) + '%)');
|
|
184
|
+
}
|
|
185
|
+
if (p.rowsRead != null) parts.push(Number(p.rowsRead).toLocaleString() + ' rows');
|
|
186
|
+
return 'Checking the file' + (parts.length ? ' · ' + parts.join(' · ') : '…');
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 512 KB, 340 MB, 2.4 GB. */
|
|
190
|
+
export function sizeText(bytes) {
|
|
191
|
+
var mb = bytes / 1024 / 1024;
|
|
192
|
+
if (mb >= 1024) return (mb / 1024).toFixed(1) + ' GB';
|
|
193
|
+
if (mb >= 1) return Math.round(mb) + ' MB';
|
|
194
|
+
return Math.max(1, Math.round(bytes / 1024)) + ' KB';
|
|
195
|
+
}
|
|
196
|
+
|
|
72
197
|
/** "Sheet 2 of 3 (Orders) · 412,000 rows read · 400,000 written" — how far an import has got. */
|
|
73
198
|
export function importProgressText(p) {
|
|
74
199
|
if (!p) return 'Importing — reading the file…';
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
createImportsApi, importProgressText, checkProgressText, runResults, checkResult, historyJob, databasesOf, uploaderFor,
|
|
4
|
+
createRunWatcher
|
|
5
|
+
} from './importsApi.js';
|
|
3
6
|
|
|
4
7
|
/**
|
|
5
8
|
* The whole import screen against @xeplr/imports' routes: which database,
|
|
@@ -9,18 +12,23 @@ import { createImportsApi, importProgressText, runResults, historyJob, databases
|
|
|
9
12
|
*
|
|
10
13
|
* @param {object} props
|
|
11
14
|
* @param {string} [props.basePath='/imports'] - where the app mounted the router, as the browser sees it
|
|
12
|
-
* @param {number} [props.pollMs=1000] - how often a running import is asked how far it has got
|
|
15
|
+
* @param {number} [props.pollMs=1000] - how often a running check or import is asked how far it has got, when there is no event stream
|
|
13
16
|
* @param {(file, onProgress, { standard }) => Promise<{ filePath }>} [props.upload] - the app's own way to send a file (see uploaderFor)
|
|
17
|
+
* @param {{ subscribe: Function, isLive?: Function }} [props.events] - the app's event stream, so a run is heard rather
|
|
18
|
+
* than asked about (see createRunWatcher). Keep the object the same between renders.
|
|
14
19
|
*/
|
|
15
20
|
export function useImportsController(props = {}) {
|
|
16
21
|
var api = useMemo(function() { return createImportsApi(props.basePath); }, [props.basePath]);
|
|
17
22
|
var pollMs = props.pollMs || 1000;
|
|
23
|
+
var events = props.events;
|
|
24
|
+
var watcher = useMemo(function() { return createRunWatcher({ api: api, events: events, pollMs: pollMs }); }, [api, events, pollMs]);
|
|
25
|
+
useEffect(function() { return function() { watcher.close(); }; }, [watcher]);
|
|
18
26
|
|
|
19
27
|
var [targets, setTargets] = useState([]);
|
|
20
28
|
var [targetsError, setTargetsError] = useState('');
|
|
21
29
|
var [connectionId, setConnectionId] = useState('');
|
|
22
30
|
var [dbInfoId, setDbInfoId] = useState('');
|
|
23
|
-
// The import running now: { runId, startedAt, progress }.
|
|
31
|
+
// The check or import running now: { runId, kind: 'check' | 'import', startedAt, progress }.
|
|
24
32
|
var [importing, setImporting] = useState(null);
|
|
25
33
|
// Bumped to make the history list read itself again.
|
|
26
34
|
var [historyVersion, setHistoryVersion] = useState(0);
|
|
@@ -46,10 +54,26 @@ export function useImportsController(props = {}) {
|
|
|
46
54
|
var upload = props.upload;
|
|
47
55
|
var onUpload = useMemo(function() { return uploaderFor(api, upload); }, [api, upload]);
|
|
48
56
|
|
|
57
|
+
/** Wait for a run, showing how far it has got on the progress line. */
|
|
58
|
+
var follow = useCallback(async function(runId, kind) {
|
|
59
|
+
setImporting({ runId: runId, kind: kind, startedAt: Date.now(), progress: null });
|
|
60
|
+
try {
|
|
61
|
+
return await watcher.wait(runId, function(progress) {
|
|
62
|
+
if (mounted.current) setImporting(function(cur) { return cur && cur.runId === runId ? Object.assign({}, cur, { progress: progress }) : cur; });
|
|
63
|
+
});
|
|
64
|
+
} finally {
|
|
65
|
+
if (mounted.current) setImporting(function(cur) { return cur && cur.runId === runId ? null : cur; });
|
|
66
|
+
}
|
|
67
|
+
}, [watcher]);
|
|
68
|
+
|
|
69
|
+
// The check reads every row — minutes on a big CSV — so it runs in the
|
|
70
|
+
// background like the import. A server before @xeplr/imports 2.0.2 answers
|
|
71
|
+
// at once, without a run.
|
|
49
72
|
var onInspect = useCallback(async function(filePath) {
|
|
50
73
|
var found = await api.inspect(filePath);
|
|
51
|
-
return { format: found.format, parts: found.sheets, checks: found.checks };
|
|
52
|
-
|
|
74
|
+
if (!found.runId) return { format: found.format, parts: found.sheets, checks: found.checks };
|
|
75
|
+
return checkResult(await follow(found.runId, 'check'));
|
|
76
|
+
}, [api, follow]);
|
|
53
77
|
|
|
54
78
|
// Bound to the chosen database, so choosing another asks again.
|
|
55
79
|
var onCheckTarget = useCallback(function(filePath, part) {
|
|
@@ -57,8 +81,8 @@ export function useImportsController(props = {}) {
|
|
|
57
81
|
return api.checkTarget({ filePath: filePath, sheet: part.part, connectionId: connectionId, dbInfoId: dbInfoId, targetTable: part.target });
|
|
58
82
|
}, [api, connectionId, dbInfoId]);
|
|
59
83
|
|
|
60
|
-
// STARTS the import, then
|
|
61
|
-
//
|
|
84
|
+
// STARTS the import, then follows it until it ends. The request answers at
|
|
85
|
+
// once with a run id, so no gateway timeout applies.
|
|
62
86
|
var onCommit = useCallback(async function(filePath, mappings, meta) {
|
|
63
87
|
if (!connectionId || !dbInfoId) throw new Error('Choose a database to import into first');
|
|
64
88
|
var started = await api.commit({
|
|
@@ -67,22 +91,13 @@ export function useImportsController(props = {}) {
|
|
|
67
91
|
return { sheet: m.part, targetTable: m.target, mode: m.mode, repairPastedRows: Boolean(m.fixes && m.fixes.pastedRows) };
|
|
68
92
|
})
|
|
69
93
|
});
|
|
70
|
-
setImporting({ runId: started.runId, startedAt: Date.now(), progress: null });
|
|
71
94
|
setHistoryVersion(function(v) { return v + 1; }); // in the history from its first row
|
|
72
95
|
try {
|
|
73
|
-
|
|
74
|
-
await new Promise(function(r) { setTimeout(r, pollMs); });
|
|
75
|
-
var run = await api.run(started.runId);
|
|
76
|
-
if (run.status !== 'running') return { results: runResults(run) };
|
|
77
|
-
if (mounted.current) setImporting(function(cur) { return cur && cur.runId === run.id ? Object.assign({}, cur, { progress: run.progress }) : cur; });
|
|
78
|
-
}
|
|
96
|
+
return { results: runResults(await follow(started.runId, 'import')) };
|
|
79
97
|
} finally {
|
|
80
|
-
if (mounted.current) {
|
|
81
|
-
setImporting(null);
|
|
82
|
-
setHistoryVersion(function(v) { return v + 1; });
|
|
83
|
-
}
|
|
98
|
+
if (mounted.current) setHistoryVersion(function(v) { return v + 1; });
|
|
84
99
|
}
|
|
85
|
-
}, [api, connectionId, dbInfoId,
|
|
100
|
+
}, [api, connectionId, dbInfoId, follow]);
|
|
86
101
|
|
|
87
102
|
function stop() {
|
|
88
103
|
if (importing) api.stop(importing.runId).catch(function() {});
|
|
@@ -115,7 +130,7 @@ export function useImportsController(props = {}) {
|
|
|
115
130
|
chooseConnection: chooseConnection,
|
|
116
131
|
chooseDatabase: setDbInfoId,
|
|
117
132
|
importing: importing,
|
|
118
|
-
progressText: importing ?
|
|
133
|
+
progressText: !importing ? '' : importing.kind === 'check' ? checkProgressText(importing.progress) : importProgressText(importing.progress),
|
|
119
134
|
stop: stop,
|
|
120
135
|
historyVersion: historyVersion,
|
|
121
136
|
// What the two built-in pages take.
|
package/src/index.js
CHANGED
|
@@ -59,12 +59,15 @@ export { DroppedRowsPage } from './dataImport/pages.jsx';
|
|
|
59
59
|
// Imports — the whole import screen against @xeplr/imports' routes: database
|
|
60
60
|
// picker, import (DataImportPage), progress with ✕, history (ImportHistoryPage).
|
|
61
61
|
// <ImportsPage basePath="/api/imports" /> is all an app adds.
|
|
62
|
-
export {
|
|
62
|
+
export {
|
|
63
|
+
createImportsApi, importProgressText, checkProgressText, runResults, checkResult, createRunWatcher, historyJob, databasesOf,
|
|
64
|
+
fileNameOf, uploaderFor, ACCEPT as IMPORT_ACCEPT
|
|
65
|
+
} from './imports/importsApi.js';
|
|
63
66
|
export { useImportsController } from './imports/useImportsController.js';
|
|
64
67
|
export { IMPORTS_RULES } from './imports/validateDesign.js';
|
|
65
68
|
export { ImportsSample } from './imports/designs/index.js';
|
|
66
69
|
export { ImportsPage } from './imports/pages.jsx';
|
|
67
|
-
export { uploadHeaders } from './fileUpload/uploadFile.js';
|
|
70
|
+
export { uploadHeaders, signedFetch, renewSignIn, renewAndRetry } from './fileUpload/uploadFile.js';
|
|
68
71
|
|
|
69
72
|
// NumberField — model
|
|
70
73
|
export {
|