@verii/batch-issuer 0.0.0-stage → 1.3.0
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/LICENSE +202 -0
- package/NOTICE +1 -0
- package/README.md +296 -2
- package/package.json +50 -3
- package/src/cli.js +190 -0
- package/src/clients/hub-client.js +181 -0
- package/src/clients/init-client.js +40 -0
- package/src/clients/registrar-client.js +37 -0
- package/src/commands/check-rules.js +187 -0
- package/src/commands/exit-codes.js +30 -0
- package/src/commands/load.js +175 -0
- package/src/csv/load-csv.js +113 -0
- package/src/index.js +28 -0
- package/src/load/load-batch.js +313 -0
- package/src/report/count.js +24 -0
- package/src/report/describe-error.js +37 -0
- package/src/report/format-load-report.js +134 -0
- package/src/report/format-report.js +100 -0
- package/src/spec/load-spec.js +193 -0
- package/src/spec/spec-schema.js +109 -0
- package/src/state/state-file.js +212 -0
- package/src/templates/render-template.js +159 -0
- package/src/validation/check-credential-subjects.js +129 -0
- package/src/validation/check-rows.js +193 -0
- package/src/validation/check-service.js +127 -0
- package/src/validation/find-duplicates.js +147 -0
- package/src/validation/match-existing-depots.js +142 -0
- package/src/validation/reasons.js +21 -0
- package/src/validation/validate-batch.js +105 -0
- package/src/values/auth-values.js +130 -0
- package/src/values/convert-value.js +65 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Velocity Team
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const { writeFile } = require('node:fs/promises');
|
|
18
|
+
const path = require('node:path');
|
|
19
|
+
const { stringify } = require('csv-stringify/sync');
|
|
20
|
+
const { isEmpty, map, pick } = require('lodash/fp');
|
|
21
|
+
const { initHubClient } = require('../clients/hub-client');
|
|
22
|
+
const { initRegistrarClient } = require('../clients/registrar-client');
|
|
23
|
+
const {
|
|
24
|
+
summarizeBatch,
|
|
25
|
+
validateBatch,
|
|
26
|
+
} = require('../validation/validate-batch');
|
|
27
|
+
const {
|
|
28
|
+
PRIVATE_FILE_MODE,
|
|
29
|
+
identifyBatch,
|
|
30
|
+
openState,
|
|
31
|
+
readState,
|
|
32
|
+
} = require('../state/state-file');
|
|
33
|
+
const { listLinks, loadBatch, summarizeLoad } = require('../load/load-batch');
|
|
34
|
+
const {
|
|
35
|
+
formatJsonReport,
|
|
36
|
+
formatSummary,
|
|
37
|
+
formatTextReport,
|
|
38
|
+
} = require('../report/format-report');
|
|
39
|
+
const {
|
|
40
|
+
formatFailedNotifications,
|
|
41
|
+
formatJsonLoadReport,
|
|
42
|
+
formatLoadFailure,
|
|
43
|
+
formatLoadReport,
|
|
44
|
+
} = require('../report/format-load-report');
|
|
45
|
+
const { ExitCodes } = require('./exit-codes');
|
|
46
|
+
|
|
47
|
+
const LINK_COLUMNS = ['row', 'userReference', 'redirectUrl'];
|
|
48
|
+
|
|
49
|
+
// The registrar is only needed to check credentials.
|
|
50
|
+
const initClients = ({ endpoint, authToken, registrar }) => ({
|
|
51
|
+
hub: initHubClient({ endpoint, authToken }),
|
|
52
|
+
registrar: registrar == null ? undefined : initRegistrarClient({ registrar }),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// holders.csv gives holders.state.jsonl, in the same directory.
|
|
56
|
+
const besideCsv = (csvFile, extension) => {
|
|
57
|
+
const { dir, name } = path.parse(csvFile);
|
|
58
|
+
return path.join(dir, `${name}${extension}`);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// Validates the batch, with the depots its state file records as its own,
|
|
62
|
+
// and opens the state, which must belong to the batch.
|
|
63
|
+
const validate = async (input, clients, stateFile) => {
|
|
64
|
+
const saved = await readState(stateFile);
|
|
65
|
+
const createdDepotIds = new Set(map('id', saved?.state.depots));
|
|
66
|
+
const { errors, batch } = await validateBatch(
|
|
67
|
+
{ ...input, options: { ...input.options, createdDepotIds } },
|
|
68
|
+
clients,
|
|
69
|
+
);
|
|
70
|
+
if (batch == null) {
|
|
71
|
+
return { errors };
|
|
72
|
+
}
|
|
73
|
+
const batchId = await identifyBatch(input, batch.spec);
|
|
74
|
+
const state = openState(saved, batchId, stateFile);
|
|
75
|
+
return { errors, batch, saved, state, summary: summarizeBatch(batch) };
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const reportValidation = ({ errors, summary }, options, io) => {
|
|
79
|
+
const formatReport = options.json ? formatJsonReport : formatTextReport;
|
|
80
|
+
io.stdout(formatReport({ errors, summary }));
|
|
81
|
+
return isEmpty(errors) ? ExitCodes.OK : ExitCodes.FAILED;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// A finished load whose wallet messages failed exits with ERROR, so that a
|
|
85
|
+
// rerun retries them.
|
|
86
|
+
const reportLoaded = (report, options, io) => {
|
|
87
|
+
const { failedNotifications } = report.load;
|
|
88
|
+
if (options.json) {
|
|
89
|
+
io.stdout(formatJsonLoadReport(report));
|
|
90
|
+
} else {
|
|
91
|
+
io.stdout(formatLoadReport(report));
|
|
92
|
+
io.stderr(formatFailedNotifications(report));
|
|
93
|
+
}
|
|
94
|
+
return isEmpty(failedNotifications) ? ExitCodes.OK : ExitCodes.ERROR;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const reportStopped = (report, options, io) => {
|
|
98
|
+
if (options.json) {
|
|
99
|
+
io.stdout(formatJsonLoadReport(report));
|
|
100
|
+
} else {
|
|
101
|
+
io.stderr(formatLoadFailure(report));
|
|
102
|
+
}
|
|
103
|
+
return ExitCodes.ERROR;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
// A load that stops reports what the state file holds then.
|
|
107
|
+
const load = async (
|
|
108
|
+
{ batch, summary, saved, state, files, hub, options },
|
|
109
|
+
io,
|
|
110
|
+
) => {
|
|
111
|
+
const report = (final, extras) => ({
|
|
112
|
+
summary,
|
|
113
|
+
load: {
|
|
114
|
+
...summarizeLoad(batch.rows, state, final, options),
|
|
115
|
+
...extras,
|
|
116
|
+
state: files.state,
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
try {
|
|
120
|
+
const loaded = await loadBatch(batch, {
|
|
121
|
+
hub,
|
|
122
|
+
state,
|
|
123
|
+
saved,
|
|
124
|
+
stateFile: files.state,
|
|
125
|
+
resolveDeferred: options.resolveDeferred,
|
|
126
|
+
});
|
|
127
|
+
const links = listLinks(batch.rows, loaded.state, loaded.sharedLink);
|
|
128
|
+
await writeFile(
|
|
129
|
+
files.output,
|
|
130
|
+
stringify(links, { header: true, columns: LINK_COLUMNS }),
|
|
131
|
+
{ mode: PRIVATE_FILE_MODE },
|
|
132
|
+
);
|
|
133
|
+
const done = report(loaded.state, {
|
|
134
|
+
link: loaded.sharedLink,
|
|
135
|
+
output: files.output,
|
|
136
|
+
failedNotifications: loaded.failedNotifications,
|
|
137
|
+
});
|
|
138
|
+
return reportLoaded(done, options, io);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
const final = (await readState(files.state))?.state ?? state;
|
|
141
|
+
return reportStopped({ ...report(final), error }, options, io);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* `batch-issuer load <spec> <csv>`: validates a batch and, when it's valid,
|
|
147
|
+
* loads it into the Hub. With `dryrun`, it stops after validating, which is
|
|
148
|
+
* `batch-issuer validate`.
|
|
149
|
+
* @param {{ specFile: string, csvFile: string, options: object }} input the files and the command's options
|
|
150
|
+
* @param {{ stdout: Function, stderr: Function }} io where the reports go
|
|
151
|
+
* @returns {Promise<number>} the exit code
|
|
152
|
+
*/
|
|
153
|
+
const runLoad = async ({ specFile, csvFile, options }, io) => {
|
|
154
|
+
const files = {
|
|
155
|
+
state: options.state ?? besideCsv(csvFile, '.state.jsonl'),
|
|
156
|
+
output: options.output ?? besideCsv(csvFile, '.links.csv'),
|
|
157
|
+
};
|
|
158
|
+
const clients = initClients(options);
|
|
159
|
+
const input = {
|
|
160
|
+
specFile,
|
|
161
|
+
csvFile,
|
|
162
|
+
vars: options.var,
|
|
163
|
+
options: pick(['defaultCountry', 'network', 'reuse'], options),
|
|
164
|
+
};
|
|
165
|
+
const validation = await validate(input, clients, files.state);
|
|
166
|
+
if (!isEmpty(validation.errors) || options.dryrun) {
|
|
167
|
+
return reportValidation(validation, options, io);
|
|
168
|
+
}
|
|
169
|
+
if (!options.json) {
|
|
170
|
+
io.stdout(`The batch is valid: ${formatSummary(validation.summary)}.\n`);
|
|
171
|
+
}
|
|
172
|
+
return load({ ...validation, files, hub: clients.hub, options }, io);
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
module.exports = { runLoad };
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Velocity Team
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const { readFile } = require('node:fs/promises');
|
|
18
|
+
const { CsvError, parse } = require('csv-parse/sync');
|
|
19
|
+
const {
|
|
20
|
+
every,
|
|
21
|
+
filter,
|
|
22
|
+
flow,
|
|
23
|
+
fromPairs,
|
|
24
|
+
isEmpty,
|
|
25
|
+
map,
|
|
26
|
+
size,
|
|
27
|
+
trim,
|
|
28
|
+
zip,
|
|
29
|
+
} = require('lodash/fp');
|
|
30
|
+
|
|
31
|
+
// bom strips a byte order mark, and relax_column_count keeps rows with fewer
|
|
32
|
+
// or more cells than the header, which validation reports. Quoting stays
|
|
33
|
+
// strict: csv-parse refuses a quote that is never closed, which would
|
|
34
|
+
// otherwise take the rest of the file into one cell and lose its rows.
|
|
35
|
+
const PARSE_OPTIONS = { bom: true, relax_column_count: true };
|
|
36
|
+
|
|
37
|
+
const QUOTE_NOT_CLOSED = 'CSV_QUOTE_NOT_CLOSED';
|
|
38
|
+
|
|
39
|
+
const mapWithIndex = map.convert({ cap: false });
|
|
40
|
+
|
|
41
|
+
const parseErrorReason = (error) =>
|
|
42
|
+
error.code === QUOTE_NOT_CLOSED
|
|
43
|
+
? 'opens a quoted cell that is never closed'
|
|
44
|
+
: `can't be parsed: ${error.message}`;
|
|
45
|
+
|
|
46
|
+
// error.records counts the records before the one that failed, the header and
|
|
47
|
+
// blank lines included, so the failed record is row records + 1.
|
|
48
|
+
const toParseError = (error) => ({
|
|
49
|
+
row: error.records + 1,
|
|
50
|
+
reason: parseErrorReason(error),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const parseRecords = (text) => {
|
|
54
|
+
try {
|
|
55
|
+
return { records: parse(text, PARSE_OPTIONS) };
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (!(error instanceof CsvError)) {
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
return { errors: [toParseError(error)] };
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const isCellOfColumn = ([column, cell]) => column != null && cell != null;
|
|
65
|
+
|
|
66
|
+
// The row's cells by column. A row with fewer cells than the header has no
|
|
67
|
+
// value for the remaining columns, rather than an empty one, and cells past
|
|
68
|
+
// the header's columns are left out.
|
|
69
|
+
const toRowData = (headers, cells) =>
|
|
70
|
+
flow(zip(headers), filter(isCellOfColumn), fromPairs)(cells);
|
|
71
|
+
|
|
72
|
+
// Rows are numbered as a spreadsheet numbers them: the header is row 1.
|
|
73
|
+
const toRow = (headers) => (cells, index) => ({
|
|
74
|
+
row: index + 2,
|
|
75
|
+
data: toRowData(headers, cells),
|
|
76
|
+
cells,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const hasCells = ({ cells }) => !every(isEmpty, cells);
|
|
80
|
+
|
|
81
|
+
const withCellCount = ({ cells, ...row }) => ({
|
|
82
|
+
...row,
|
|
83
|
+
cellCount: size(cells),
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
const toCsv = (records) => {
|
|
87
|
+
const [headerRecord = [], ...dataRecords] = records;
|
|
88
|
+
const headers = map(trim, headerRecord);
|
|
89
|
+
const rows = flow(
|
|
90
|
+
mapWithIndex(toRow(headers)),
|
|
91
|
+
filter(hasCells),
|
|
92
|
+
map(withCellCount),
|
|
93
|
+
)(dataRecords);
|
|
94
|
+
return { headers, rows, errors: [] };
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Loads a CSV file whose first line is the header. A byte order mark is
|
|
99
|
+
* stripped, header names are trimmed, and blank lines are skipped. A file that
|
|
100
|
+
* doesn't parse, such as one with a quote that is never closed, gives an error
|
|
101
|
+
* for the row where parsing failed instead of rows.
|
|
102
|
+
* @param {string} fileName the CSV file
|
|
103
|
+
* @returns {Promise<{ headers?: Array<string>, rows?: Array<{ row: number, data: object, cellCount: number }>,
|
|
104
|
+
* errors: Array<{ row: number, reason: string }> }>}
|
|
105
|
+
* @throws when the file can't be read
|
|
106
|
+
*/
|
|
107
|
+
const loadCsv = async (fileName) => {
|
|
108
|
+
const text = await readFile(fileName, 'utf8');
|
|
109
|
+
const { records, errors } = parseRecords(text);
|
|
110
|
+
return errors == null ? toCsv(records) : { errors };
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
module.exports = { loadCsv };
|
package/src/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Copyright 2026 Velocity Team
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const { runCli } = require('./cli');
|
|
19
|
+
|
|
20
|
+
const io = {
|
|
21
|
+
stdout: (text) => process.stdout.write(text),
|
|
22
|
+
stderr: (text) => process.stderr.write(text),
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
runCli(process.argv, io).then((exitCode) => {
|
|
26
|
+
// eslint-disable-next-line better-mutation/no-mutation
|
|
27
|
+
process.exitCode = exitCode;
|
|
28
|
+
});
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Velocity Team
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/* global AggregateError */
|
|
18
|
+
|
|
19
|
+
const {
|
|
20
|
+
chunk,
|
|
21
|
+
filter,
|
|
22
|
+
flatMap,
|
|
23
|
+
flatten,
|
|
24
|
+
flow,
|
|
25
|
+
get,
|
|
26
|
+
has,
|
|
27
|
+
isArray,
|
|
28
|
+
join,
|
|
29
|
+
keyBy,
|
|
30
|
+
map,
|
|
31
|
+
mapValues,
|
|
32
|
+
pick,
|
|
33
|
+
reject,
|
|
34
|
+
size,
|
|
35
|
+
uniqBy,
|
|
36
|
+
zipWith,
|
|
37
|
+
} = require('lodash/fp');
|
|
38
|
+
const { runSequentially } = require('@verii/common-functions');
|
|
39
|
+
const { isInternalVpAuth, isPreauth } = require('../validation/check-service');
|
|
40
|
+
const { appendRecords, startState } = require('../state/state-file');
|
|
41
|
+
const { count } = require('../report/count');
|
|
42
|
+
|
|
43
|
+
// The status of a wallet message that the Hub couldn't send.
|
|
44
|
+
const FAILED_NOTIFICATION = 'failed';
|
|
45
|
+
|
|
46
|
+
// create-many takes up to 1000 credentials, but the Hub limits a request's
|
|
47
|
+
// body to 8 MiB, which 1000 large credentials can exceed.
|
|
48
|
+
const CREDENTIALS_PER_REQUEST = 100;
|
|
49
|
+
|
|
50
|
+
const addToList = (state, key, records) => ({
|
|
51
|
+
...state,
|
|
52
|
+
[key]: [...state[key], ...records],
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// Runs a step for each item, one at a time. The records that a step gives
|
|
56
|
+
// are appended to the state file as soon as it ends, and the records of
|
|
57
|
+
// every step are added to one of the state's lists.
|
|
58
|
+
const inSequence = (append, key, step) => async (state, items) => {
|
|
59
|
+
const recordStep = async (item) => append(key, await step(item));
|
|
60
|
+
const records = await runSequentially(
|
|
61
|
+
map((item) => () => recordStep(item), items),
|
|
62
|
+
);
|
|
63
|
+
return addToList(state, key, flatten(records));
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// Each row's depot id, by row: the existing depot that validation matched it
|
|
67
|
+
// to, or else the depot that this batch created for it, in this run or an
|
|
68
|
+
// earlier one.
|
|
69
|
+
const depotIdsByRow = (rows, state) => ({
|
|
70
|
+
...flow(keyBy('row'), mapValues('id'))(state.depots),
|
|
71
|
+
...flow(
|
|
72
|
+
filter('existingDepot'),
|
|
73
|
+
keyBy('row'),
|
|
74
|
+
mapValues(get(['existingDepot', 'id'])),
|
|
75
|
+
)(rows),
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
// Rows whose depot exists, and wasn't created by this batch.
|
|
79
|
+
const reusedRows = (rows, state) => {
|
|
80
|
+
const createdIds = new Set(map('id', state.depots));
|
|
81
|
+
const isReused = ({ existingDepot }) =>
|
|
82
|
+
existingDepot != null && !createdIds.has(existingDepot.id);
|
|
83
|
+
return filter(isReused, rows);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const rowsWithoutDepots = (rows, state) => {
|
|
87
|
+
const depotIds = depotIdsByRow(rows, state);
|
|
88
|
+
return reject(({ row }) => has([row], depotIds), rows);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// A 409 means that another client created a depot with the row's auth values
|
|
92
|
+
// after validation.
|
|
93
|
+
const refuseDepot = (spec, row) => (error) => {
|
|
94
|
+
if (error.statusCode !== 409) {
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
const rowError = {
|
|
98
|
+
row: row.row,
|
|
99
|
+
column: join(', ', map('column', spec.depot.authValues)),
|
|
100
|
+
reason: `the auth values belong to depot ${get(['body', 'depotId'], error)}, which another client created after validation`,
|
|
101
|
+
};
|
|
102
|
+
throw new AggregateError([rowError], 'depots/create refused a depot');
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const createDepots = ({ spec, hub, append }) =>
|
|
106
|
+
inSequence(append, 'depots', async (row) => {
|
|
107
|
+
const depot = await hub
|
|
108
|
+
.createDepot(spec, row.depot)
|
|
109
|
+
.catch(refuseDepot(spec, row));
|
|
110
|
+
return [{ row: row.row, id: depot.id }];
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
const toItems =
|
|
114
|
+
(depotIds) =>
|
|
115
|
+
({ row, credentials }) =>
|
|
116
|
+
map(
|
|
117
|
+
({ template, credential }) => ({
|
|
118
|
+
row,
|
|
119
|
+
template,
|
|
120
|
+
depotId: get([row], depotIds),
|
|
121
|
+
credential,
|
|
122
|
+
}),
|
|
123
|
+
credentials,
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
// The credentials that no run of this batch has created yet, each with its
|
|
127
|
+
// row's depot, in requests of at most CREDENTIALS_PER_REQUEST.
|
|
128
|
+
const pendingRequests = (rows, state) => {
|
|
129
|
+
const depotIds = depotIdsByRow(rows, state);
|
|
130
|
+
const createdReferences = new Set(
|
|
131
|
+
map('credentialReference', state.credentials),
|
|
132
|
+
);
|
|
133
|
+
const isCreated = ({ credential }) =>
|
|
134
|
+
createdReferences.has(credential.credentialReference);
|
|
135
|
+
return flow(
|
|
136
|
+
flatMap(toItems(depotIds)),
|
|
137
|
+
reject(isCreated),
|
|
138
|
+
chunk(CREDENTIALS_PER_REQUEST),
|
|
139
|
+
)(rows);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// A 400 lists each invalid item by its index in the request. The Hub checks
|
|
143
|
+
// every item before it creates any, so it created none of them.
|
|
144
|
+
const refuseItems = (items) => (error) => {
|
|
145
|
+
const itemErrors = get(['body', 'errors'], error);
|
|
146
|
+
if (error.statusCode !== 400 || !isArray(itemErrors)) {
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
const toRowError = ({ index, message }) => ({
|
|
150
|
+
...pick(['row', 'template'], get([index], items)),
|
|
151
|
+
reason: message,
|
|
152
|
+
});
|
|
153
|
+
const refused = count(size(uniqBy('index', itemErrors)), 'credential');
|
|
154
|
+
throw new AggregateError(
|
|
155
|
+
map(toRowError, itemErrors),
|
|
156
|
+
`credentials/create-many refused ${refused}, so it created none of the ${count(size(items), 'credential')} in its request`,
|
|
157
|
+
);
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const toCredentialRecord = ({ row, depotId, credential }, { id }) => ({
|
|
161
|
+
row,
|
|
162
|
+
credentialReference: credential.credentialReference,
|
|
163
|
+
id,
|
|
164
|
+
depotId,
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const createCredentials = ({ spec, hub, append }) =>
|
|
168
|
+
inSequence(append, 'credentials', async (items) => {
|
|
169
|
+
const credentials = await hub
|
|
170
|
+
.createCredentials(spec, map(pick(['depotId', 'credential']), items))
|
|
171
|
+
.catch(refuseItems(items));
|
|
172
|
+
return zipWith(toCredentialRecord, items, credentials);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
// Reused depots that defer credentials and received some from this batch, in
|
|
176
|
+
// this run or an earlier one, and that no run has resolved yet, with their
|
|
177
|
+
// rows.
|
|
178
|
+
const depotsToResolve = (rows, state) => {
|
|
179
|
+
const receivingIds = new Set(map('depotId', state.credentials));
|
|
180
|
+
const resolvedIds = new Set(state.resolvedDepots);
|
|
181
|
+
const isWaiting = ({ existingDepot: { id, deferredCredentials } }) =>
|
|
182
|
+
deferredCredentials === true &&
|
|
183
|
+
receivingIds.has(id) &&
|
|
184
|
+
!resolvedIds.has(id);
|
|
185
|
+
return flow(
|
|
186
|
+
filter(isWaiting),
|
|
187
|
+
map(({ row, existingDepot }) => ({ row, id: existingDepot.id })),
|
|
188
|
+
)(reusedRows(rows, state));
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
// Resolves each depot, one at a time. A depot whose wallet message failed
|
|
192
|
+
// isn't recorded as resolved, so that a rerun resolves it again.
|
|
193
|
+
const resolveDepots =
|
|
194
|
+
({ spec, hub, append }) =>
|
|
195
|
+
async (state, depots) => {
|
|
196
|
+
const resolveDepot = async ({ row, id }) => {
|
|
197
|
+
const { status, error } = await hub.resolveDeferredCredentials(spec, id);
|
|
198
|
+
return status === FAILED_NOTIFICATION
|
|
199
|
+
? { resolved: [], failed: [{ row, depotId: id, error }] }
|
|
200
|
+
: { resolved: await append('resolvedDepots', [id]), failed: [] };
|
|
201
|
+
};
|
|
202
|
+
const results = await runSequentially(
|
|
203
|
+
map((depot) => () => resolveDepot(depot), depots),
|
|
204
|
+
);
|
|
205
|
+
return {
|
|
206
|
+
state: addToList(state, 'resolvedDepots', flatMap('resolved', results)),
|
|
207
|
+
failedNotifications: flatMap('failed', results),
|
|
208
|
+
};
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
// The depots this batch created that have no link yet. Reused depots are
|
|
212
|
+
// never refreshed: a refresh replaces the depot's pre-authorized code, which
|
|
213
|
+
// breaks the links already sent.
|
|
214
|
+
const depotsToLink = (state) => {
|
|
215
|
+
const linkedRows = new Set(map('row', state.links));
|
|
216
|
+
return reject(({ row }) => linkedRows.has(row), state.depots);
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const linkDepots = ({ spec, hub, append }) =>
|
|
220
|
+
inSequence(append, 'links', async ({ row, id }) => {
|
|
221
|
+
const redirectUrl = await hub.refreshIssueLink(spec, id);
|
|
222
|
+
return [{ row, redirectUrl }];
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Loads a valid batch into the Hub, as the README's Loading section
|
|
227
|
+
* describes. The state file records each depot, credential, resolved depot
|
|
228
|
+
* and link as soon as the Hub confirms it, and what it records is skipped.
|
|
229
|
+
* @param {{ spec: object, service: object, rows: Array<object> }} batch the validated batch
|
|
230
|
+
* @param {{ hub: object, state: object, saved?: object, stateFile: string, resolveDeferred?: boolean }} context
|
|
231
|
+
* saved is what readState read from the state file, if it was there
|
|
232
|
+
* @returns {Promise<{ state: object, sharedLink?: string, failedNotifications: Array<object> }>} the final
|
|
233
|
+
* state, the service's shared link when it uses verifiable_presentation auth, and the depots whose
|
|
234
|
+
* wallet message failed when their deferred credentials were resolved, with their rows and the Hub's error
|
|
235
|
+
* @throws an AggregateError of row errors when the Hub refuses a depot or credentials, or the error of a
|
|
236
|
+
* request that failed. The state file then holds what was created before it
|
|
237
|
+
*/
|
|
238
|
+
const loadBatch = async (
|
|
239
|
+
{ spec, service, rows },
|
|
240
|
+
{ hub, state, saved, stateFile, resolveDeferred },
|
|
241
|
+
) => {
|
|
242
|
+
const context = { spec, hub, append: appendRecords(stateFile) };
|
|
243
|
+
await startState(stateFile, saved, state.batch);
|
|
244
|
+
const withDepots = await createDepots(context)(
|
|
245
|
+
state,
|
|
246
|
+
rowsWithoutDepots(rows, state),
|
|
247
|
+
);
|
|
248
|
+
const withCredentials = await createCredentials(context)(
|
|
249
|
+
withDepots,
|
|
250
|
+
pendingRequests(rows, withDepots),
|
|
251
|
+
);
|
|
252
|
+
const resolution = await resolveDepots(context)(
|
|
253
|
+
withCredentials,
|
|
254
|
+
resolveDeferred ? depotsToResolve(rows, withCredentials) : [],
|
|
255
|
+
);
|
|
256
|
+
const final = await linkDepots(context)(
|
|
257
|
+
resolution.state,
|
|
258
|
+
isPreauth(service) ? depotsToLink(resolution.state) : [],
|
|
259
|
+
);
|
|
260
|
+
const sharedLink = isInternalVpAuth(service)
|
|
261
|
+
? await hub.refreshIssueLink(spec)
|
|
262
|
+
: undefined;
|
|
263
|
+
return {
|
|
264
|
+
state: final,
|
|
265
|
+
sharedLink,
|
|
266
|
+
failedNotifications: resolution.failedNotifications,
|
|
267
|
+
};
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Counts what a load did, from the state before it and after it.
|
|
272
|
+
* @param {Array<object>} rows the batch's rows
|
|
273
|
+
* @param {object} initial the state before the load
|
|
274
|
+
* @param {object} final the state after it, or when it stopped
|
|
275
|
+
* @param {{ resolveDeferred?: boolean }} options
|
|
276
|
+
* @returns {{ depots: object, credentials: object, resolvedDepots?: number }} what this run created, reused
|
|
277
|
+
* and resolved, and what it skipped because an earlier run created it
|
|
278
|
+
*/
|
|
279
|
+
const summarizeLoad = (rows, initial, final, { resolveDeferred }) => {
|
|
280
|
+
const created = (key) => size(final[key]) - size(initial[key]);
|
|
281
|
+
return {
|
|
282
|
+
depots: {
|
|
283
|
+
created: created('depots'),
|
|
284
|
+
reused: size(reusedRows(rows, initial)),
|
|
285
|
+
skipped: size(initial.depots),
|
|
286
|
+
},
|
|
287
|
+
credentials: {
|
|
288
|
+
created: created('credentials'),
|
|
289
|
+
skipped: size(initial.credentials),
|
|
290
|
+
},
|
|
291
|
+
...(resolveDeferred ? { resolvedDepots: created('resolvedDepots') } : {}),
|
|
292
|
+
};
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Lists each row's link: its own, from the depot this batch created for it,
|
|
297
|
+
* or else the service's shared link. Rows without either are left out.
|
|
298
|
+
* @param {Array<object>} rows the batch's rows
|
|
299
|
+
* @param {object} state the final state
|
|
300
|
+
* @param {string} [sharedLink] the service's shared link
|
|
301
|
+
* @returns {Array<{ row: number, userReference: string, redirectUrl: string }>}
|
|
302
|
+
*/
|
|
303
|
+
const listLinks = (rows, state, sharedLink) => {
|
|
304
|
+
const linksByRow = flow(keyBy('row'), mapValues('redirectUrl'))(state.links);
|
|
305
|
+
const toLink = ({ row, depot }) => ({
|
|
306
|
+
row,
|
|
307
|
+
userReference: depot.userReference,
|
|
308
|
+
redirectUrl: get([row], linksByRow) ?? sharedLink,
|
|
309
|
+
});
|
|
310
|
+
return flow(map(toLink), filter('redirectUrl'))(rows);
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
module.exports = { listLinks, loadBatch, summarizeLoad };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Velocity Team
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// A count with thousands separators, such as 49,999.
|
|
18
|
+
const formatNumber = (number) => number.toLocaleString('en-US');
|
|
19
|
+
|
|
20
|
+
// A count and its noun, such as "1 row" or "2,500 rows".
|
|
21
|
+
const count = (number, noun) =>
|
|
22
|
+
`${formatNumber(number)} ${noun}${number === 1 ? '' : 's'}`;
|
|
23
|
+
|
|
24
|
+
module.exports = { count, formatNumber };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Velocity Team
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const { get } = require('lodash/fp');
|
|
18
|
+
|
|
19
|
+
// An HTTP error carries the response's status code and body. Its request
|
|
20
|
+
// headers, which hold the operator token, are never printed.
|
|
21
|
+
const describeResponse = (error) => {
|
|
22
|
+
const message = get(['body', 'message'], error) ?? error.message;
|
|
23
|
+
return error.statusCode == null ? message : `${error.statusCode} ${message}`;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Describes an error that stopped a command, such as an unreadable file or a
|
|
28
|
+
* failed request, without the request's headers.
|
|
29
|
+
* @param {Error} error
|
|
30
|
+
* @returns {string} the description
|
|
31
|
+
*/
|
|
32
|
+
const describeError = (error) =>
|
|
33
|
+
error.url == null
|
|
34
|
+
? error.message
|
|
35
|
+
: `${error.url} failed: ${describeResponse(error)}`;
|
|
36
|
+
|
|
37
|
+
module.exports = { describeError };
|