waba-devtools 0.1.0 → 0.2.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/README.md +156 -43
- package/lib/budget.js +275 -0
- package/lib/cli.js +101 -5
- package/lib/commands.js +164 -18
- package/lib/compare.js +1 -1
- package/lib/csv.js +436 -55
- package/lib/errors.js +15 -1
- package/lib/graph.js +78 -1
- package/lib/index.js +8 -0
- package/lib/report.js +110 -11
- package/package.json +1 -1
package/lib/cli.js
CHANGED
|
@@ -13,7 +13,8 @@ import {
|
|
|
13
13
|
import { compareBackups, compareWabas, compareWithLive } from './compare.js';
|
|
14
14
|
import { loadConfig, loadDotenvFile, parseJson } from './config.js';
|
|
15
15
|
import { UsageError } from './errors.js';
|
|
16
|
-
import {
|
|
16
|
+
import { DEFAULT_LIMIT_PERCENT, META_CREATES_PER_HOUR } from './budget.js';
|
|
17
|
+
import { formatReport, nextRetry } from './report.js';
|
|
17
18
|
|
|
18
19
|
/**
|
|
19
20
|
* Exit codes, documented in the README.
|
|
@@ -27,16 +28,17 @@ Usage:
|
|
|
27
28
|
waba import --csv <file> [--json]
|
|
28
29
|
waba deploy <target> [-m <name>…] [--dry-run] [--json] (from the template files)
|
|
29
30
|
waba deploy <source> <target> [-m <name>…] [--dry-run] [--json] (WABA to WABA)
|
|
30
|
-
waba deploy --csv <file> <target> [--dry-run] [--json]
|
|
31
|
+
waba deploy --csv <file> <target> [--stop-on-error] [--dry-run] [--json]
|
|
31
32
|
waba deploy [<source>] <target> --prune [--yes]
|
|
32
33
|
waba deploy … --backup <folder> (snapshot targets first)
|
|
34
|
+
waba deploy … --limit-percent <n> [--wait] (share of Meta's limits)
|
|
33
35
|
waba list <source> | <target> [--json]
|
|
34
36
|
waba check [--stage <stage>] [--json]
|
|
35
37
|
waba discover --token-env <NAME> [--business <id>] [--json]
|
|
36
38
|
waba compare <backup set> <backup set> [--json] (older vs newer, by backup time)
|
|
37
39
|
waba compare <backup set> --live [--waba <id>] [--json] (backup vs the WABA right now)
|
|
38
40
|
waba compare --before-waba <id> --after-waba <id> [--json] (two WABAs right now)
|
|
39
|
-
waba backup --stage <stage> | --waba <id>… --backup <folder> [--json] (
|
|
41
|
+
waba backup --stage <stage> | --waba <id>… --backup <folder> [--json] (manual backup)
|
|
40
42
|
|
|
41
43
|
<source> --from <stage> and/or --from-waba <id>
|
|
42
44
|
<target> --to <stage> and/or --to-waba <id>…
|
|
@@ -60,6 +62,14 @@ Options:
|
|
|
60
62
|
(<wabaId>_<time>_after/).
|
|
61
63
|
--from-dir <folder> Source: template files in this folder instead of templatesDir
|
|
62
64
|
(e.g. a backup set: <backup>/<wabaId>_<time>).
|
|
65
|
+
--limit-percent <n> Share of Meta's limits to use, 1 to 100 (default 80): template creates
|
|
66
|
+
per WABA and hour (Meta allows 100) and Meta's API usage (writing
|
|
67
|
+
stops at this %). More creates are deferred: the report shows
|
|
68
|
+
the batch schedule and when to run the same command again (exit code 1).
|
|
69
|
+
--stop-on-error deploy --csv: when any CSV row has an error, send nothing at all
|
|
70
|
+
(default: rows with errors are left out, the others are sent).
|
|
71
|
+
--wait deploy: keep running and send each batch when its time comes, until
|
|
72
|
+
nothing is deferred. Ctrl+C is safe; rerun the command to continue.
|
|
63
73
|
--token-env <NAME> discover: the environment variable that holds the access token.
|
|
64
74
|
--business <id> discover: the business portfolio whose WABAs to list (needed when Meta
|
|
65
75
|
does not name the WABAs for the token).
|
|
@@ -92,6 +102,9 @@ const OPTIONS = {
|
|
|
92
102
|
'backup-after': { type: 'boolean' },
|
|
93
103
|
expect: { type: 'string' },
|
|
94
104
|
'from-dir': { type: 'string' },
|
|
105
|
+
'limit-percent': { type: 'string' },
|
|
106
|
+
wait: { type: 'boolean' },
|
|
107
|
+
'stop-on-error': { type: 'boolean' },
|
|
95
108
|
prune: { type: 'boolean' },
|
|
96
109
|
yes: { type: 'boolean' },
|
|
97
110
|
'token-env': { type: 'string' },
|
|
@@ -123,6 +136,9 @@ const ALLOWED = new Map([
|
|
|
123
136
|
'backup-after',
|
|
124
137
|
'expect',
|
|
125
138
|
'from-dir',
|
|
139
|
+
'limit-percent',
|
|
140
|
+
'wait',
|
|
141
|
+
'stop-on-error',
|
|
126
142
|
],
|
|
127
143
|
],
|
|
128
144
|
['check', ['stage']],
|
|
@@ -142,6 +158,7 @@ const ALLOWED = new Map([
|
|
|
142
158
|
* @param {(text: string) => void} [io.out]
|
|
143
159
|
* @param {(text: string) => void} [io.err]
|
|
144
160
|
* @param {typeof fetch} [io.fetchImpl]
|
|
161
|
+
* @param {(ms: number) => Promise.<void>} [io.sleep] - Waits for `deploy --wait` (tests).
|
|
145
162
|
* @returns {Promise.<number>}
|
|
146
163
|
*/
|
|
147
164
|
export async function main(argv, io = {}) {
|
|
@@ -151,6 +168,7 @@ export async function main(argv, io = {}) {
|
|
|
151
168
|
out = (text) => process.stdout.write(`${text}\n`),
|
|
152
169
|
err: error = (text) => process.stderr.write(`${text}\n`),
|
|
153
170
|
fetchImpl,
|
|
171
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
154
172
|
} = io;
|
|
155
173
|
let parsed;
|
|
156
174
|
try {
|
|
@@ -254,13 +272,29 @@ export async function main(argv, io = {}) {
|
|
|
254
272
|
}
|
|
255
273
|
case 'deploy': {
|
|
256
274
|
requireOption(values.to ?? values['to-waba'], 'to or --to-waba');
|
|
257
|
-
|
|
275
|
+
if (values.wait && (values['dry-run'] || values.expect)) {
|
|
276
|
+
throw new UsageError('--wait does not work with --dry-run or --expect.');
|
|
277
|
+
}
|
|
278
|
+
const limitPercent =
|
|
279
|
+
values['limit-percent'] === undefined
|
|
280
|
+
? undefined
|
|
281
|
+
: parseCount(values['limit-percent'], 'limit-percent');
|
|
282
|
+
if (limitPercent > DEFAULT_LIMIT_PERCENT) {
|
|
283
|
+
error(
|
|
284
|
+
`Warning: --limit-percent ${limitPercent} leaves little room below Meta's limits ` +
|
|
285
|
+
`(${META_CREATES_PER_HOUR} template creates per WABA and hour, and its API ` +
|
|
286
|
+
'allowance). Templates created and deleted again within the hour are not ' +
|
|
287
|
+
'visible to waba, so Meta may still refuse creates.',
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
const deployOptions = {
|
|
258
291
|
...common,
|
|
259
292
|
to: values.to,
|
|
260
293
|
from: values.from,
|
|
261
294
|
toWabas: values['to-waba'] ?? [],
|
|
262
295
|
fromWaba: values['from-waba'],
|
|
263
296
|
csv: values.csv,
|
|
297
|
+
stopOnRowErrors: values['stop-on-error'] === true,
|
|
264
298
|
names,
|
|
265
299
|
dryRun: values['dry-run'] === true,
|
|
266
300
|
prune: values.prune === true,
|
|
@@ -271,7 +305,16 @@ export async function main(argv, io = {}) {
|
|
|
271
305
|
? readExpectedActions(path.resolve(cwd, values.expect))
|
|
272
306
|
: undefined,
|
|
273
307
|
sourceDir: values['from-dir'] && path.resolve(cwd, values['from-dir']),
|
|
274
|
-
|
|
308
|
+
...(limitPercent !== undefined && { limitPercent }),
|
|
309
|
+
};
|
|
310
|
+
report = await deploy(deployOptions);
|
|
311
|
+
while (values.wait && isOnlyDeferred(report)) {
|
|
312
|
+
if (!values.json) {
|
|
313
|
+
out(formatReport(report).join('\n'));
|
|
314
|
+
}
|
|
315
|
+
await waitUntil(nextRetry(report), { sleep, say: values.json ? error : out });
|
|
316
|
+
report = await deploy(deployOptions);
|
|
317
|
+
}
|
|
275
318
|
break;
|
|
276
319
|
}
|
|
277
320
|
case 'compare': {
|
|
@@ -395,6 +438,59 @@ function readExpectedActions(file) {
|
|
|
395
438
|
return targets;
|
|
396
439
|
}
|
|
397
440
|
|
|
441
|
+
/**
|
|
442
|
+
* True when a deploy report has deferred templates and nothing else went wrong, so `--wait` may go on.
|
|
443
|
+
*
|
|
444
|
+
* @param {object} report - Deploy report.
|
|
445
|
+
* @returns {boolean}
|
|
446
|
+
*/
|
|
447
|
+
function isOnlyDeferred(report) {
|
|
448
|
+
return (
|
|
449
|
+
nextRetry(report) !== undefined &&
|
|
450
|
+
report.rowErrors.length === 0 &&
|
|
451
|
+
report.targets.every(
|
|
452
|
+
(target) =>
|
|
453
|
+
!target.error &&
|
|
454
|
+
target.actions.every(
|
|
455
|
+
(action) => action.result !== 'failed' && action.action !== 'blocked',
|
|
456
|
+
),
|
|
457
|
+
)
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Sleeps until `retryAfter` (plus one second), saying every 10 minutes how long is left.
|
|
463
|
+
*
|
|
464
|
+
* @param {string} retryAfter - ISO time.
|
|
465
|
+
* @param {{sleep: (ms: number) => Promise.<void>, say: (text: string) => void}} io
|
|
466
|
+
* @returns {Promise.<void>}
|
|
467
|
+
*/
|
|
468
|
+
async function waitUntil(retryAfter, { sleep, say }) {
|
|
469
|
+
const until = Date.parse(retryAfter) + 1000;
|
|
470
|
+
say(
|
|
471
|
+
`Waiting for the next batch at ${retryAfter} (Ctrl+C is safe; run the same command later to continue).`,
|
|
472
|
+
);
|
|
473
|
+
let left = until - Date.now();
|
|
474
|
+
while (left > 0) {
|
|
475
|
+
say(` ${Math.ceil(left / 60_000)} min left`);
|
|
476
|
+
const step = Math.min(left, 10 * 60_000);
|
|
477
|
+
await sleep(step);
|
|
478
|
+
left -= step;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* @param {string} value - Option value.
|
|
484
|
+
* @param {string} name - Option name for the message.
|
|
485
|
+
* @returns {number} Whole number of 1 or more.
|
|
486
|
+
*/
|
|
487
|
+
function parseCount(value, name) {
|
|
488
|
+
if (!/^\d+$/.test(value) || Number(value) < 1) {
|
|
489
|
+
throw new UsageError(`--${name} needs a whole number of 1 or more, got "${value}".`);
|
|
490
|
+
}
|
|
491
|
+
return Number(value);
|
|
492
|
+
}
|
|
493
|
+
|
|
398
494
|
/**
|
|
399
495
|
* @param {string|undefined} value - Parsed option value.
|
|
400
496
|
* @param {string} name - Option name for the message.
|
package/lib/commands.js
CHANGED
|
@@ -8,6 +8,17 @@ import {
|
|
|
8
8
|
pickTargetWabas,
|
|
9
9
|
resolveToken,
|
|
10
10
|
} from './config.js';
|
|
11
|
+
import {
|
|
12
|
+
batchTime,
|
|
13
|
+
DEFAULT_LIMIT_PERCENT,
|
|
14
|
+
DEFAULT_THROTTLE_MINUTES,
|
|
15
|
+
planBatches,
|
|
16
|
+
usageStopReason,
|
|
17
|
+
THROTTLED_CODE,
|
|
18
|
+
validateRecentWrites,
|
|
19
|
+
writeBudget,
|
|
20
|
+
writesPerHour,
|
|
21
|
+
} from './budget.js';
|
|
11
22
|
import { readCsvTemplates } from './csv.js';
|
|
12
23
|
import { GraphError, UsageError } from './errors.js';
|
|
13
24
|
import {
|
|
@@ -47,6 +58,18 @@ function clientFor(entry, { config, environment = process.env, fetchImpl }) {
|
|
|
47
58
|
});
|
|
48
59
|
}
|
|
49
60
|
|
|
61
|
+
/**
|
|
62
|
+
* `{usage}` with the highest `X-Business-Use-Case-Usage` values the client saw, or `{}` when Meta
|
|
63
|
+
* sent none (or there is no client).
|
|
64
|
+
*
|
|
65
|
+
* @param {import('./graph.js').GraphClient|undefined} client
|
|
66
|
+
* @returns {{usage?: import('./graph.js').UsageInfo}}
|
|
67
|
+
*/
|
|
68
|
+
function usageOf(client) {
|
|
69
|
+
const usage = client?.usage();
|
|
70
|
+
return usage ? { usage } : {};
|
|
71
|
+
}
|
|
72
|
+
|
|
50
73
|
/**
|
|
51
74
|
* @param {unknown} ex
|
|
52
75
|
* @returns {string}
|
|
@@ -115,7 +138,9 @@ export async function retrieve(options) {
|
|
|
115
138
|
* @returns {Promise.<object>} Report.
|
|
116
139
|
*/
|
|
117
140
|
export async function importCsv({ config, cwd, csv }) {
|
|
118
|
-
const { templates, errors, cleanup, parts } = await readCsvTemplates(
|
|
141
|
+
const { templates, errors, warnings, cleanup, parts } = await readCsvTemplates(
|
|
142
|
+
path.resolve(cwd, csv),
|
|
143
|
+
);
|
|
119
144
|
const files = [];
|
|
120
145
|
for (const template of templates) {
|
|
121
146
|
const existing = await readTemplateFile(config.templatesDir, template);
|
|
@@ -134,6 +159,7 @@ export async function importCsv({ config, cwd, csv }) {
|
|
|
134
159
|
csvCleanup: cleanup,
|
|
135
160
|
files,
|
|
136
161
|
rowErrors: errors,
|
|
162
|
+
rowWarnings: warnings,
|
|
137
163
|
ok: errors.length === 0,
|
|
138
164
|
};
|
|
139
165
|
}
|
|
@@ -147,13 +173,14 @@ export async function importCsv({ config, cwd, csv }) {
|
|
|
147
173
|
async function loadSource(options) {
|
|
148
174
|
const { config, cwd, from, fromWaba, csv } = options;
|
|
149
175
|
if (csv) {
|
|
150
|
-
const { templates, errors, cleanup, parts } = await readCsvTemplates(
|
|
176
|
+
const { templates, errors, warnings, cleanup, parts } = await readCsvTemplates(
|
|
151
177
|
path.resolve(cwd, csv),
|
|
152
178
|
);
|
|
153
179
|
return {
|
|
154
180
|
source: templates.map((template) => ({ template, parts })),
|
|
155
181
|
description: { type: 'csv', csv, cleanup },
|
|
156
182
|
rowErrors: errors,
|
|
183
|
+
rowWarnings: warnings,
|
|
157
184
|
};
|
|
158
185
|
}
|
|
159
186
|
if (from || fromWaba) {
|
|
@@ -184,7 +211,15 @@ async function loadSource(options) {
|
|
|
184
211
|
* onProgress?: (event: object) => void,
|
|
185
212
|
* expectedActions?: {wabaId: string, actions: {name: string, language: string, action: string}[]}[],
|
|
186
213
|
* backupDir?: string, backupBefore?: boolean, backupAfter?: boolean, sourceDir?: string,
|
|
187
|
-
* templateKeys?: string[] - only these templates, as `name::language` (e.g. a selection from a backup)
|
|
214
|
+
* templateKeys?: string[] - only these templates, as `name::language` (e.g. a selection from a backup),
|
|
215
|
+
* limitPercent?: number - share of Meta's limits to use, 1–100 (default 80): creates per
|
|
216
|
+
* target WABA and hour = floor(100 × limitPercent / 100); writing stops when Meta's
|
|
217
|
+
* X-Business-Use-Case-Usage reports any percentage at or above it,
|
|
218
|
+
* recentWrites?: import('./budget.js').RecentWrite[] - creates and updates logged by the caller
|
|
219
|
+
* (creates count when younger than one hour and not visible in the live list; an update keeps
|
|
220
|
+
* that template's recent `last_updated_time` from counting),
|
|
221
|
+
* stopOnRowErrors?: boolean - with `csv`: when any row has an error, send nothing to any target
|
|
222
|
+
* (each target reports why); default false: rows with errors are left out, the others are sent
|
|
188
223
|
* }} options
|
|
189
224
|
* @returns {Promise.<object>} Report.
|
|
190
225
|
*/
|
|
@@ -206,7 +241,12 @@ export async function deploy(options) {
|
|
|
206
241
|
backupBefore = true,
|
|
207
242
|
backupAfter = false,
|
|
208
243
|
templateKeys,
|
|
244
|
+
limitPercent = DEFAULT_LIMIT_PERCENT,
|
|
245
|
+
recentWrites = [],
|
|
246
|
+
stopOnRowErrors = false,
|
|
209
247
|
} = options;
|
|
248
|
+
const maxWritesPerHour = writesPerHour(limitPercent);
|
|
249
|
+
validateRecentWrites(recentWrites);
|
|
210
250
|
if (backupDir && !backupBefore && !backupAfter) {
|
|
211
251
|
throw new UsageError(
|
|
212
252
|
'A backup folder was given, but both before- and after-backups are off.',
|
|
@@ -239,6 +279,8 @@ export async function deploy(options) {
|
|
|
239
279
|
);
|
|
240
280
|
}
|
|
241
281
|
const isFullSet = names.length === 0 && !templateKeys && !csv;
|
|
282
|
+
// With stopOnRowErrors, one bad CSV row blocks every target: nothing is sent at all.
|
|
283
|
+
const isStoppedByRowErrors = stopOnRowErrors === true && loaded.rowErrors.length > 0;
|
|
242
284
|
const results = [];
|
|
243
285
|
const createdAt = new Date().toISOString();
|
|
244
286
|
const backup = backupDir
|
|
@@ -254,6 +296,7 @@ export async function deploy(options) {
|
|
|
254
296
|
live = await client.listTemplates(entry.wabaId);
|
|
255
297
|
} catch (ex) {
|
|
256
298
|
target.error = describeError(ex);
|
|
299
|
+
Object.assign(target, usageOf(client));
|
|
257
300
|
continue;
|
|
258
301
|
}
|
|
259
302
|
const liveById = new Map(live.map((template) => [template.id, template]));
|
|
@@ -265,10 +308,39 @@ export async function deploy(options) {
|
|
|
265
308
|
!isSameSendSet(planned, expectedFor(expectedActions, entry.wabaId));
|
|
266
309
|
if (hasChanged) {
|
|
267
310
|
target.error = 'changed since preview — run the preview again';
|
|
311
|
+
} else if (isStoppedByRowErrors) {
|
|
312
|
+
target.error = `${loaded.rowErrors.length} CSV row(s) have errors — nothing is sent (stop on error)`;
|
|
268
313
|
}
|
|
269
314
|
const total = planned.filter((action) => SENDING.has(action.action)).length;
|
|
270
|
-
|
|
271
|
-
|
|
315
|
+
const now = Date.now();
|
|
316
|
+
const budget = writeBudget({
|
|
317
|
+
limit: maxWritesPerHour,
|
|
318
|
+
live,
|
|
319
|
+
recentWrites: recentWrites.filter((write) => write.wabaId === entry.wabaId),
|
|
320
|
+
now,
|
|
321
|
+
});
|
|
322
|
+
target.budget = {
|
|
323
|
+
limitPercent,
|
|
324
|
+
limit: budget.limit,
|
|
325
|
+
usedLastHour: budget.usedLastHour,
|
|
326
|
+
left: budget.left,
|
|
327
|
+
countedAt: budget.times.map((time) => new Date(time).toISOString()),
|
|
328
|
+
};
|
|
329
|
+
// Creates that the confirmed preview showed as deferred stay deferred.
|
|
330
|
+
const deferredInPreview = new Set(
|
|
331
|
+
(expectedActions === undefined ? [] : expectedFor(expectedActions, entry.wabaId))
|
|
332
|
+
.filter((action) => action.result === 'deferred')
|
|
333
|
+
.map((action) => actionKey(action)),
|
|
334
|
+
);
|
|
335
|
+
const isDeferredUpFront = (action) =>
|
|
336
|
+
COUNTED.has(action.action) && deferredInPreview.has(actionKey(action));
|
|
337
|
+
const counted = planned.filter((action) => COUNTED.has(action.action));
|
|
338
|
+
const willSend =
|
|
339
|
+
total > counted.length ||
|
|
340
|
+
Math.min(counted.filter((action) => !isDeferredUpFront(action)).length, budget.left) >
|
|
341
|
+
0;
|
|
342
|
+
let isBlocked = hasChanged || isStoppedByRowErrors;
|
|
343
|
+
if (backup && backupBefore && !dryRun && !isBlocked && willSend) {
|
|
272
344
|
try {
|
|
273
345
|
target.backup = await backupTarget(backup, {
|
|
274
346
|
stage,
|
|
@@ -281,21 +353,58 @@ export async function deploy(options) {
|
|
|
281
353
|
isBlocked = true;
|
|
282
354
|
}
|
|
283
355
|
}
|
|
356
|
+
target.budget.schedule = planBatches({
|
|
357
|
+
wanted: isBlocked ? 0 : counted.length,
|
|
358
|
+
limit: budget.limit,
|
|
359
|
+
countedAt: budget.times,
|
|
360
|
+
now,
|
|
361
|
+
});
|
|
284
362
|
let done = 0;
|
|
285
363
|
let sent = 0;
|
|
364
|
+
let left = budget.left;
|
|
365
|
+
const overBudget = [];
|
|
286
366
|
for (const plannedAction of planned) {
|
|
287
367
|
const { body, ...action } = plannedAction;
|
|
288
368
|
target.actions.push(action);
|
|
289
|
-
if (
|
|
369
|
+
if (isBlocked || !SENDING.has(action.action)) {
|
|
290
370
|
continue;
|
|
291
371
|
}
|
|
292
|
-
|
|
293
|
-
|
|
372
|
+
const isCounted = COUNTED.has(action.action);
|
|
373
|
+
const usage = client.usage();
|
|
374
|
+
const stopReason = target.throttled ? undefined : usageStopReason(usage, limitPercent);
|
|
375
|
+
if (stopReason) {
|
|
376
|
+
const minutes = usage.regainAccessMinutes || DEFAULT_THROTTLE_MINUTES;
|
|
377
|
+
target.throttled = {
|
|
378
|
+
retryAfter: new Date(Date.now() + minutes * 60_000).toISOString(),
|
|
379
|
+
error: stopReason,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
if (target.throttled) {
|
|
383
|
+
deferAction(action, 'throttled', target.throttled.retryAfter);
|
|
384
|
+
} else if (isCounted && (left <= 0 || isDeferredUpFront(action))) {
|
|
385
|
+
deferAction(action, 'budget');
|
|
386
|
+
overBudget.push(action);
|
|
294
387
|
} else {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
sent++;
|
|
388
|
+
if (isCounted) {
|
|
389
|
+
left--;
|
|
298
390
|
}
|
|
391
|
+
if (dryRun) {
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
if (!yes && action.action === 'delete') {
|
|
395
|
+
action.result = 'not run (add --yes)';
|
|
396
|
+
} else {
|
|
397
|
+
action.at = new Date().toISOString();
|
|
398
|
+
await sendAction(client, entry.wabaId, action, body);
|
|
399
|
+
if (action.result === 'done') {
|
|
400
|
+
sent++;
|
|
401
|
+
} else if (action.result === 'deferred') {
|
|
402
|
+
target.throttled = { retryAfter: action.retryAfter, error: action.error };
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (dryRun) {
|
|
407
|
+
continue;
|
|
299
408
|
}
|
|
300
409
|
done++;
|
|
301
410
|
onProgress?.({
|
|
@@ -310,6 +419,11 @@ export async function deploy(options) {
|
|
|
310
419
|
total,
|
|
311
420
|
});
|
|
312
421
|
}
|
|
422
|
+
const passed = budget.left - left;
|
|
423
|
+
for (const [index, action] of overBudget.entries()) {
|
|
424
|
+
action.retryAfter = batchTime(target.budget.schedule, passed + index);
|
|
425
|
+
}
|
|
426
|
+
Object.assign(target, usageOf(client));
|
|
313
427
|
if (backup && backupAfter && sent > 0) {
|
|
314
428
|
try {
|
|
315
429
|
target.backupAfter = await backupTarget(backup, {
|
|
@@ -329,7 +443,10 @@ export async function deploy(options) {
|
|
|
329
443
|
(target) =>
|
|
330
444
|
!target.error &&
|
|
331
445
|
target.actions.every(
|
|
332
|
-
(action) =>
|
|
446
|
+
(action) =>
|
|
447
|
+
action.result !== 'failed' &&
|
|
448
|
+
action.result !== 'deferred' &&
|
|
449
|
+
action.action !== 'blocked',
|
|
333
450
|
),
|
|
334
451
|
);
|
|
335
452
|
return {
|
|
@@ -337,6 +454,8 @@ export async function deploy(options) {
|
|
|
337
454
|
dryRun,
|
|
338
455
|
source: loaded.description,
|
|
339
456
|
rowErrors: loaded.rowErrors,
|
|
457
|
+
rowWarnings: loaded.rowWarnings ?? [],
|
|
458
|
+
...(isStoppedByRowErrors && { stoppedByRowErrors: true }),
|
|
340
459
|
targets: results,
|
|
341
460
|
ok: isOk,
|
|
342
461
|
};
|
|
@@ -411,6 +530,28 @@ async function backupTarget(backup, { stage, wabaId, live, phase }) {
|
|
|
411
530
|
*/
|
|
412
531
|
const SENDING = new Set(['create', 'update', 'delete']);
|
|
413
532
|
|
|
533
|
+
/**
|
|
534
|
+
* Actions that count against the hourly budget: Meta limits template creates per hour, not edits
|
|
535
|
+
* or deletes.
|
|
536
|
+
*/
|
|
537
|
+
const COUNTED = new Set(['create']);
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Marks a create, update or delete as not sent in this run.
|
|
541
|
+
*
|
|
542
|
+
* @param {object} action - Report entry, updated in place.
|
|
543
|
+
* @param {'budget'|'throttled'} reason - Hourly create budget used up, or Meta throttled the app.
|
|
544
|
+
* @param {string} [retryAfter] - ISO time it can be tried again (set after the loop for `budget`).
|
|
545
|
+
* @returns {void}
|
|
546
|
+
*/
|
|
547
|
+
function deferAction(action, reason, retryAfter) {
|
|
548
|
+
action.result = 'deferred';
|
|
549
|
+
action.deferredReason = reason;
|
|
550
|
+
if (retryAfter) {
|
|
551
|
+
action.retryAfter = retryAfter;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
414
555
|
/**
|
|
415
556
|
* The confirmed preview actions of one target WABA.
|
|
416
557
|
*
|
|
@@ -522,7 +663,12 @@ async function sendAction(client, wabaId, action, body) {
|
|
|
522
663
|
}
|
|
523
664
|
action.result = 'done';
|
|
524
665
|
} catch (ex) {
|
|
525
|
-
|
|
666
|
+
if (ex instanceof GraphError && ex.code === THROTTLED_CODE) {
|
|
667
|
+
const minutes = ex.regainAccessMinutes ?? DEFAULT_THROTTLE_MINUTES;
|
|
668
|
+
deferAction(action, 'throttled', new Date(Date.now() + minutes * 60_000).toISOString());
|
|
669
|
+
} else {
|
|
670
|
+
action.result = 'failed';
|
|
671
|
+
}
|
|
526
672
|
action.error = describeError(ex);
|
|
527
673
|
}
|
|
528
674
|
}
|
|
@@ -551,11 +697,10 @@ export async function listTemplates(options) {
|
|
|
551
697
|
for (const { stage, stages, entry } of entries) {
|
|
552
698
|
const result = { stage, stages, wabaId: entry.wabaId };
|
|
553
699
|
wabas.push(result);
|
|
700
|
+
let client;
|
|
554
701
|
try {
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
SUMMARY_FIELDS,
|
|
558
|
-
);
|
|
702
|
+
client = clientFor(entry, options);
|
|
703
|
+
const live = await client.listTemplates(entry.wabaId, SUMMARY_FIELDS);
|
|
559
704
|
result.templates = live
|
|
560
705
|
.map(({ name, language, category, status }) => ({
|
|
561
706
|
name,
|
|
@@ -569,6 +714,7 @@ export async function listTemplates(options) {
|
|
|
569
714
|
} catch (ex) {
|
|
570
715
|
result.error = describeError(ex);
|
|
571
716
|
}
|
|
717
|
+
Object.assign(result, usageOf(client));
|
|
572
718
|
}
|
|
573
719
|
return { command: 'list', wabas, ok: wabas.every((waba) => !waba.error) };
|
|
574
720
|
}
|
|
@@ -685,7 +831,7 @@ export async function discoverWabas({
|
|
|
685
831
|
}
|
|
686
832
|
|
|
687
833
|
/**
|
|
688
|
-
* Creates
|
|
834
|
+
* Creates manual backups without deploying: one backup set `<wabaId>_<time>_manual` per WABA.
|
|
689
835
|
*
|
|
690
836
|
* @param {CommonOptions & {stage?: string, wabaIds?: string[], backupDir: string}} options
|
|
691
837
|
* @returns {Promise.<object>} Report.
|
package/lib/compare.js
CHANGED
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
|
-
* Compares two backup sets
|
|
22
|
+
* Compares two backup sets. The older one (by `createdAt` in its manifest) is
|
|
23
23
|
* always "before", whatever order they are given in, so a removed template never looks added.
|
|
24
24
|
*
|
|
25
25
|
* @param {string} setA - Backup set folder.
|