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/lib/graph.js CHANGED
@@ -4,8 +4,11 @@ export const GRAPH_BASE_URL = 'https://graph.facebook.com';
4
4
 
5
5
  /**
6
6
  * Fields requested when listing templates, so normalization always sees the same shape.
7
+ * `last_updated_time` only feeds the hourly write budget of `deploy`; normalization drops it, so it
8
+ * is never compared or written to template files.
7
9
  */
8
- export const TEMPLATE_FIELDS = 'id,name,language,category,status,parameter_format,components';
10
+ export const TEMPLATE_FIELDS =
11
+ 'id,name,language,category,status,parameter_format,components,last_updated_time';
9
12
 
10
13
  /**
11
14
  * Fields for a template overview (no components): enough to pick templates and spot overwrites.
@@ -25,6 +28,8 @@ export const SUMMARY_FIELDS = 'id,name,language,category,status';
25
28
  * @property {(wabaId: string) => Promise.<object[]>} listPhoneNumbers - Sender phone numbers.
26
29
  * @property {(businessId: string) => Promise.<object[]>} listBusinessWabas - WABAs a business
27
30
  * portfolio owns or has access to as a client.
31
+ * @property {() => UsageInfo|undefined} usage - Highest `X-Business-Use-Case-Usage` values seen in
32
+ * this client's responses so far (`undefined` when Meta sent none).
28
33
  */
29
34
 
30
35
  /**
@@ -60,6 +65,66 @@ export function redact(text, token) {
60
65
  return withoutToken.replaceAll(TOKEN_PATTERN, '[token removed]');
61
66
  }
62
67
 
68
+ /**
69
+ * @typedef {object} UsageInfo
70
+ * @property {number} callCount - `call_count`, percent of the hourly allowance used.
71
+ * @property {number} totalCputime - `total_cputime`, percent.
72
+ * @property {number} totalTime - `total_time`, percent.
73
+ * @property {number} regainAccessMinutes - `estimated_time_to_regain_access` (0 = not throttled).
74
+ */
75
+
76
+ const USAGE_FIELDS = [
77
+ ['callCount', 'call_count'],
78
+ ['totalCputime', 'total_cputime'],
79
+ ['totalTime', 'total_time'],
80
+ ['regainAccessMinutes', 'estimated_time_to_regain_access'],
81
+ ];
82
+
83
+ /**
84
+ * Highest of each value in two usage readings.
85
+ *
86
+ * @param {UsageInfo|undefined} a
87
+ * @param {UsageInfo|undefined} b
88
+ * @returns {UsageInfo|undefined}
89
+ */
90
+ export function maxUsage(a, b) {
91
+ return a && b
92
+ ? Object.fromEntries(USAGE_FIELDS.map(([key]) => [key, Math.max(a[key], b[key])]))
93
+ : (a ?? b);
94
+ }
95
+
96
+ /**
97
+ * Meta's business use case usage from the `X-Business-Use-Case-Usage` header of a response: the
98
+ * highest value of each field over all its entries, or `undefined` when the header is missing.
99
+ *
100
+ * @param {Headers|undefined} headers
101
+ * @returns {UsageInfo|undefined}
102
+ */
103
+ export function parseUsage(headers) {
104
+ const raw = headers?.get?.('x-business-use-case-usage');
105
+ if (!raw) {
106
+ return;
107
+ }
108
+ let usage;
109
+ try {
110
+ usage = JSON.parse(raw);
111
+ } catch {
112
+ return;
113
+ }
114
+ const entries = Object.values(usage ?? {})
115
+ .flat()
116
+ .filter((entry) => entry && typeof entry === 'object');
117
+ if (entries.length === 0) {
118
+ return;
119
+ }
120
+ return Object.fromEntries(
121
+ USAGE_FIELDS.map(([key, field]) => [
122
+ key,
123
+ Math.max(0, ...entries.map((entry) => Number(entry[field])).filter(Number.isFinite)),
124
+ ]),
125
+ );
126
+ }
127
+
63
128
  /**
64
129
  * Thin Graph API client for one access token. The token is sent as a bearer header only.
65
130
  *
@@ -72,6 +137,12 @@ export function redact(text, token) {
72
137
  */
73
138
  export function createGraphClient({ token, version, fetchImpl = fetch, baseUrl = GRAPH_BASE_URL }) {
74
139
  const root = `${baseUrl}/${version}/`;
140
+ /**
141
+ * Highest usage seen in this client's responses.
142
+ *
143
+ * @type {UsageInfo|undefined}
144
+ */
145
+ let peakUsage;
75
146
 
76
147
  /**
77
148
  * @param {string} method
@@ -99,6 +170,8 @@ export function createGraphClient({ token, version, fetchImpl = fetch, baseUrl =
99
170
  },
100
171
  ...(body && { body: JSON.stringify(body) }),
101
172
  });
173
+ const usage = parseUsage(response.headers);
174
+ peakUsage = maxUsage(peakUsage, usage);
102
175
  const text = await response.text();
103
176
  let data = {};
104
177
  if (text) {
@@ -118,6 +191,7 @@ export function createGraphClient({ token, version, fetchImpl = fetch, baseUrl =
118
191
  userTitle: redact(error.error_user_title, token),
119
192
  userMessage: redact(error.error_user_msg, token),
120
193
  traceId: error.fbtrace_id,
194
+ regainAccessMinutes: usage?.regainAccessMinutes || undefined,
121
195
  });
122
196
  }
123
197
  return data;
@@ -142,6 +216,9 @@ export function createGraphClient({ token, version, fetchImpl = fetch, baseUrl =
142
216
  }
143
217
 
144
218
  return {
219
+ usage() {
220
+ return peakUsage && { ...peakUsage };
221
+ },
145
222
  listTemplates(wabaId, fields = TEMPLATE_FIELDS) {
146
223
  return listAll(`${encodeURIComponent(wabaId)}/message_templates`, fields);
147
224
  },
package/lib/index.js CHANGED
@@ -16,6 +16,14 @@ export {
16
16
  stripBom,
17
17
  validateConfig,
18
18
  } from './config.js';
19
+ export {
20
+ DEFAULT_LIMIT_PERCENT,
21
+ META_CREATES_PER_HOUR,
22
+ planBatches,
23
+ writeBudget,
24
+ writesPerHour,
25
+ } from './budget.js';
26
+ export { templatesToCsv } from './csv.js';
19
27
  export { GraphError, UsageError } from './errors.js';
20
28
  export { createGraphClient } from './graph.js';
21
29
  export { formatReport } from './report.js';
package/lib/report.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { DEFAULT_LIMIT_PERCENT, USAGE_WARN_PERCENT } from './budget.js';
2
+
1
3
  /**
2
4
  * Human-readable report lines. `--json` prints the report object instead.
3
5
  *
@@ -17,7 +19,7 @@ export function formatReport(report) {
17
19
  `Imported ${report.files.length} row(s) from ${report.csv}:`,
18
20
  ...cleanupLines(report.csvCleanup),
19
21
  ...report.files.map((file) => ` ${file.result.padEnd(9)} ${file.path}`),
20
- ...rowErrorLines(report.rowErrors),
22
+ ...rowErrorLines(report.rowErrors, report.rowWarnings),
21
23
  ];
22
24
  }
23
25
  case 'deploy': {
@@ -26,6 +28,7 @@ export function formatReport(report) {
26
28
  case 'list': {
27
29
  return report.wabas.flatMap((waba) => [
28
30
  `${waba.stage} — WABA ${waba.wabaId}:`,
31
+ ...usageLines(waba.usage),
29
32
  ...(waba.error
30
33
  ? [` FAILED ${waba.error}`]
31
34
  : [
@@ -163,16 +166,25 @@ function cleanupLines(cleanup) {
163
166
  }
164
167
 
165
168
  /**
166
- * @param {{row: number, message: string}[]} rowErrors
169
+ * @param {{row: number, message: string}[]} [rowErrors] - Rows left out.
170
+ * @param {{row: number, message: string}[]} [rowWarnings] - Rows read, something ignored.
171
+ * @param {boolean} [isStopped] - deploy --stop-on-error stopped because of them.
167
172
  * @returns {string[]}
168
173
  */
169
- function rowErrorLines(rowErrors = []) {
170
- if (rowErrors.length === 0) {
171
- return [];
172
- }
174
+ function rowErrorLines(rowErrors = [], rowWarnings = [], isStopped = false) {
173
175
  return [
174
- `CSV rows with errors (${rowErrors.length}):`,
175
- ...rowErrors.map((error) => ` row ${error.row}: ${error.message}`),
176
+ ...(rowErrors.length > 0
177
+ ? [
178
+ `CSV rows with errors, ${isStopped ? 'so nothing is sent' : 'left out'} (${rowErrors.length}):`,
179
+ ...rowErrors.map((error) => ` row ${error.row}: ${error.message}`),
180
+ ]
181
+ : []),
182
+ ...(rowWarnings.length > 0
183
+ ? [
184
+ `CSV rows with warnings (${rowWarnings.length}):`,
185
+ ...rowWarnings.map((warning) => ` row ${warning.row}: ${warning.message}`),
186
+ ]
187
+ : []),
176
188
  ];
177
189
  }
178
190
 
@@ -205,11 +217,29 @@ function deployLines(report) {
205
217
  lines.push(` ${label}: ${value}`);
206
218
  }
207
219
  }
220
+ lines.push(...usageLines(target.usage, target.budget?.limitPercent));
221
+ if (target.budget) {
222
+ const { limitPercent, limit, usedLastHour, left, schedule = [] } = target.budget;
223
+ lines.push(
224
+ ` hourly budget (${limitPercent} %): ${usedLastHour} of ${limit} creates in the last hour, ${left} left`,
225
+ );
226
+ if (schedule.length > 1) {
227
+ lines.push(` schedule: ${scheduleText(schedule)}`);
228
+ }
229
+ }
230
+ if (target.throttled) {
231
+ lines.push(
232
+ ` STOPPED Meta throttles this WABA; the rest is deferred until ${target.throttled.retryAfter}`,
233
+ );
234
+ }
208
235
  for (const action of target.actions) {
209
236
  const status = action.status ? ` [${action.status}]` : '';
210
237
  const after = action.statusAfter ? ` → ${action.statusAfter}` : '';
211
- const result = action.result ? ` ${action.result}${after}` : '';
212
- const detail = action.error ?? action.note;
238
+ const retry = action.retryAfter ? ` until ${action.retryAfter}` : '';
239
+ const result = action.result ? ` ${action.result}${after}${retry}` : '';
240
+ const detail =
241
+ action.error ??
242
+ (action.deferredReason === 'budget' ? 'hourly create limit used up' : action.note);
213
243
  lines.push(
214
244
  ` ${action.action.padEnd(9)} ${action.name} (${action.language})${status}${result}` +
215
245
  (detail ? ` — ${detail}` : ''),
@@ -224,6 +254,75 @@ function deployLines(report) {
224
254
  .join(', ');
225
255
  lines.push(` = ${summary || 'nothing to do'}`);
226
256
  }
227
- lines.push(...rowErrorLines(report.rowErrors));
257
+ lines.push(...rowErrorLines(report.rowErrors, report.rowWarnings, report.stoppedByRowErrors));
258
+ const retry = nextRetry(report);
259
+ if (retry) {
260
+ lines.push(
261
+ `Deferred templates: run the same command again after ${clockTime(retry)} (${retry}) — ` +
262
+ 'only what is still missing or different is sent.',
263
+ );
264
+ }
228
265
  return lines;
229
266
  }
267
+
268
+ /**
269
+ * Earliest time a deferred template of a deploy report can be sent, or `undefined`.
270
+ *
271
+ * @param {object} report - Deploy report.
272
+ * @returns {string|undefined} ISO time.
273
+ */
274
+ export function nextRetry(report) {
275
+ const times = (report.targets ?? [])
276
+ .flatMap((target) => target.actions ?? [])
277
+ .filter((action) => action.result === 'deferred' && action.retryAfter)
278
+ .map((action) => action.retryAfter)
279
+ .toSorted((a, b) => Date.parse(a) - Date.parse(b));
280
+ return times[0];
281
+ }
282
+
283
+ /**
284
+ * Local `HH:MM` of an ISO time.
285
+ *
286
+ * @param {string} iso
287
+ * @returns {string}
288
+ */
289
+ function clockTime(iso) {
290
+ const date = new Date(iso);
291
+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
292
+ }
293
+
294
+ /**
295
+ * E.g. `3 batches: 100 now, 100 at 15:05, 50 at 16:05` (the first batch is "now").
296
+ *
297
+ * @param {{at: string, count: number}[]} schedule
298
+ * @returns {string}
299
+ */
300
+ function scheduleText(schedule) {
301
+ const parts = schedule.map(
302
+ (batch, index) => `${batch.count} ${index === 0 ? 'now' : `at ${clockTime(batch.at)}`}`,
303
+ );
304
+ return `${schedule.length} batches: ${parts.join(', ')}`;
305
+ }
306
+
307
+ /**
308
+ * Meta's API usage for a WABA, with a warning from `USAGE_WARN_PERCENT` (or the limit, when lower) on.
309
+ *
310
+ * @param {import('./graph.js').UsageInfo} [usage]
311
+ * @param {number} [limitPercent] - Where `deploy` stops writing.
312
+ * @returns {string[]}
313
+ */
314
+ function usageLines(usage, limitPercent = DEFAULT_LIMIT_PERCENT) {
315
+ if (!usage) {
316
+ return [];
317
+ }
318
+ const peak = Math.max(usage.callCount, usage.totalCputime, usage.totalTime);
319
+ const text =
320
+ `Meta API usage this hour: calls ${usage.callCount} %, CPU ${usage.totalCputime} %, ` +
321
+ `time ${usage.totalTime} %` +
322
+ (usage.regainAccessMinutes > 0 ? `, throttled for ${usage.regainAccessMinutes} min` : '');
323
+ const isHigh =
324
+ peak >= Math.min(USAGE_WARN_PERCENT, limitPercent) || usage.regainAccessMinutes > 0;
325
+ return [
326
+ ` ${isHigh ? 'WARNING ' : ''}${text}${isHigh ? ` — waba stops writing at ${limitPercent} %` : ''}`,
327
+ ];
328
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "waba-devtools",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "WABA DevTools (waba) — retrieve, import from CSV and deploy WhatsApp Business message templates across WABAs and pipeline stages",
5
5
  "author": "Jörn Berkefeld <joern.berkefeld@gmail.com>",
6
6
  "license": "MIT",