@fishawack/lab-env 5.7.0-beta.1 → 5.7.0-beta.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/CHANGELOG.md +128 -0
- package/_Ai/lab-env-@.md +3 -3
- package/_Scripts/post-release.sh +1 -1
- package/_Test/boilerplate-adonis.js +1 -1
- package/_Test/boilerplate-craftcms.js +1 -1
- package/_Test/boilerplate-drupal.js +1 -1
- package/_Test/boilerplate-laravel.js +1 -1
- package/_Test/boilerplate-python.js +1 -1
- package/_Test/boilerplate-wordpress.js +1 -1
- package/_Test/boilerplate.js +1 -1
- package/_Test/provision.js +4 -9
- package/_Test/prune.js +8 -5
- package/adonis/0/docker-compose.yml +1 -1
- package/bitbucket-pipelines.yml +2 -2
- package/cli.js +1 -0
- package/commands/create/cmds/dekey.js +13 -9
- package/commands/create/cmds/deprovision.js +36 -0
- package/commands/create/cmds/diagnose.js +10 -0
- package/commands/create/cmds/key.js +74 -41
- package/commands/create/cmds/provision.js +573 -69
- package/commands/create/cmds/rekey.js +283 -0
- package/commands/create/cmds/sync-secrets.js +2 -1
- package/commands/create/libs/aws-cloudfront-response.js +11 -0
- package/commands/create/libs/output-credentials.js +59 -0
- package/commands/create/libs/parallel-runner.js +296 -0
- package/commands/create/libs/resolve-operator.js +59 -0
- package/commands/create/libs/utilities.js +75 -8
- package/commands/create/libs/vars.js +124 -143
- package/commands/create/services/aws/acm.js +61 -0
- package/commands/create/services/aws/cloudfront.js +51 -45
- package/commands/create/services/aws/ec2.js +675 -48
- package/commands/create/services/aws/elasticache.js +159 -0
- package/commands/create/services/aws/elasticbeanstalk.js +155 -57
- package/commands/create/services/aws/iam.js +420 -86
- package/commands/create/services/aws/index.js +1401 -260
- package/commands/create/services/aws/opensearch.js +155 -0
- package/commands/create/services/aws/rds.js +98 -35
- package/commands/create/services/aws/s3.js +52 -31
- package/commands/create/services/aws/secretsmanager.js +21 -12
- package/commands/create/services/aws/ses.js +203 -0
- package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/cron.config +45 -0
- package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/queue-worker.config +29 -0
- package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/software.config +12 -0
- package/commands/create/templates/elasticbeanstalk/.ebextensions/misc/setvars.config +2 -16
- package/commands/create/templates/elasticbeanstalk/.platform/confighooks/postdeploy/restart_queue.sh +4 -0
- package/commands/create/templates/elasticbeanstalk/.platform/confighooks/postdeploy/rewrite-flush.sh +1 -1
- package/commands/create/templates/elasticbeanstalk/.platform/confighooks/prebuild/setvars.sh +19 -0
- package/commands/create/templates/elasticbeanstalk/.platform/hooks/postdeploy/restart_queue.sh +4 -0
- package/commands/create/templates/elasticbeanstalk/.platform/hooks/prebuild/setvars.sh +19 -0
- package/commands/scan.js +1 -1
- package/core/1/CHANGELOG.md +41 -0
- package/core/1/Dockerfile +3 -3
- package/core/1/bitbucket-pipelines.yml +5 -5
- package/core/1/package.json +1 -1
- package/drupal/9/docker-compose.yml +1 -2
- package/globals.js +4 -0
- package/laravel/10/docker-compose.yml +1 -1
- package/laravel/9/docker-compose.yml +1 -1
- package/package.json +7 -2
- package/wordpress/1/docker-compose.yml +1 -2
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
const _ = require("../../../globals.js");
|
|
2
|
+
const inquirer = require("inquirer");
|
|
3
|
+
const aws = require("../services/aws/index.js");
|
|
4
|
+
const outputCredentials = require("../libs/output-credentials.js");
|
|
5
|
+
const { misc } = require("../libs/vars.js");
|
|
6
|
+
const {
|
|
7
|
+
setAWSClientDefaults,
|
|
8
|
+
} = require("../../../commands/create/services/aws/misc.js");
|
|
9
|
+
const parallelRunner = require("../libs/parallel-runner.js");
|
|
10
|
+
const resolveOperator = require("../libs/resolve-operator.js");
|
|
11
|
+
|
|
12
|
+
module.exports = [
|
|
13
|
+
"rekey",
|
|
14
|
+
_.config.preset === "devops"
|
|
15
|
+
? "Rotates AWS access keys and credentials"
|
|
16
|
+
: false,
|
|
17
|
+
() => {},
|
|
18
|
+
async () => {
|
|
19
|
+
let operator = await resolveOperator();
|
|
20
|
+
|
|
21
|
+
let users = [];
|
|
22
|
+
let clients = [];
|
|
23
|
+
let sendEmail = false;
|
|
24
|
+
|
|
25
|
+
let answer = await inquirer.prompt([
|
|
26
|
+
{
|
|
27
|
+
type: "confirm",
|
|
28
|
+
name: "check",
|
|
29
|
+
message: `Rotate keys for all users`,
|
|
30
|
+
default: "Y",
|
|
31
|
+
},
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
if (answer.check) {
|
|
35
|
+
users = _.config.users.map((d) => d.username);
|
|
36
|
+
} else {
|
|
37
|
+
answer = await inquirer.prompt([
|
|
38
|
+
{
|
|
39
|
+
type: "checkbox",
|
|
40
|
+
name: "users",
|
|
41
|
+
message: "Select users",
|
|
42
|
+
choices: _.config.users.map((d) => d.username),
|
|
43
|
+
},
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
users = answer.users;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
answer = await inquirer.prompt([
|
|
50
|
+
{
|
|
51
|
+
type: "confirm",
|
|
52
|
+
name: "check",
|
|
53
|
+
message: `Rotate keys for all clients`,
|
|
54
|
+
default: "Y",
|
|
55
|
+
},
|
|
56
|
+
]);
|
|
57
|
+
|
|
58
|
+
if (answer.check) {
|
|
59
|
+
clients = aws.clients;
|
|
60
|
+
} else {
|
|
61
|
+
answer = await inquirer.prompt([
|
|
62
|
+
{
|
|
63
|
+
type: "checkbox",
|
|
64
|
+
name: "clients",
|
|
65
|
+
message: "Select clients",
|
|
66
|
+
choices: aws.clients,
|
|
67
|
+
},
|
|
68
|
+
]);
|
|
69
|
+
|
|
70
|
+
clients = answer.clients;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
answer = await inquirer.prompt([
|
|
74
|
+
{
|
|
75
|
+
type: "confirm",
|
|
76
|
+
name: "check",
|
|
77
|
+
message: `Would you like to email out the credentials after creation (requires office365 credentials in ~/targets/misc.json)?`,
|
|
78
|
+
default: "Y",
|
|
79
|
+
},
|
|
80
|
+
]);
|
|
81
|
+
|
|
82
|
+
sendEmail = answer.check;
|
|
83
|
+
|
|
84
|
+
// Check for SES email credentials if user wants to send emails
|
|
85
|
+
if (sendEmail && !misc.nodemailer?.AWSSES?.username) {
|
|
86
|
+
answer = await inquirer.prompt([
|
|
87
|
+
{
|
|
88
|
+
type: "confirm",
|
|
89
|
+
name: "check",
|
|
90
|
+
message:
|
|
91
|
+
"No email credentials found, create them via AWS SES?",
|
|
92
|
+
default: "Y",
|
|
93
|
+
},
|
|
94
|
+
]);
|
|
95
|
+
|
|
96
|
+
if (answer.check) {
|
|
97
|
+
try {
|
|
98
|
+
let creds = await aws.ses.ensureOperatorSESCredentials(
|
|
99
|
+
operator.username,
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
if (!creds) {
|
|
103
|
+
answer = await inquirer.prompt([
|
|
104
|
+
{
|
|
105
|
+
type: "confirm",
|
|
106
|
+
name: "check",
|
|
107
|
+
message:
|
|
108
|
+
"SES IAM user exists but secret is not stored locally. Rotate credentials to recapture?",
|
|
109
|
+
default: "Y",
|
|
110
|
+
},
|
|
111
|
+
]);
|
|
112
|
+
|
|
113
|
+
if (answer.check) {
|
|
114
|
+
creds = await aws.ses.rotateOperatorSESCredentials(
|
|
115
|
+
operator.username,
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (creds) {
|
|
121
|
+
aws.ses.updateMiscNodemailer(creds);
|
|
122
|
+
console.log(
|
|
123
|
+
"\n \u2713 SES email credentials saved to misc.json\n",
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
} catch (err) {
|
|
127
|
+
console.log(
|
|
128
|
+
`\n \u26a0 Failed to create SES credentials: ${err.message}\n`,
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Separate users into: regular, runners, operator
|
|
135
|
+
// Processing order: regular users → runners → operator (last)
|
|
136
|
+
let runners = users.filter((u) => {
|
|
137
|
+
let config = _.config.users.find((d) => d.username === u);
|
|
138
|
+
return (
|
|
139
|
+
u !== operator.username &&
|
|
140
|
+
config &&
|
|
141
|
+
(config.runner || u === "aws-runner")
|
|
142
|
+
);
|
|
143
|
+
});
|
|
144
|
+
let nonOperatorUsers = users.filter(
|
|
145
|
+
(u) => u !== operator.username && !runners.includes(u),
|
|
146
|
+
);
|
|
147
|
+
let includeOperator = users.includes(operator.username);
|
|
148
|
+
|
|
149
|
+
let credentials = {};
|
|
150
|
+
|
|
151
|
+
// Process non-operator users in parallel
|
|
152
|
+
if (nonOperatorUsers.length) {
|
|
153
|
+
const batches = clients.map((client) => ({
|
|
154
|
+
users: nonOperatorUsers,
|
|
155
|
+
client,
|
|
156
|
+
fn: async (user) => {
|
|
157
|
+
setAWSClientDefaults(client);
|
|
158
|
+
|
|
159
|
+
await aws.iam.removeIAMUser(`fw-automation-${user}`);
|
|
160
|
+
|
|
161
|
+
return aws.iam.createFWIAMUser(
|
|
162
|
+
`fw-automation-${user}`,
|
|
163
|
+
_.config.users.find((d) => d.username === user)
|
|
164
|
+
.permissions,
|
|
165
|
+
);
|
|
166
|
+
},
|
|
167
|
+
}));
|
|
168
|
+
|
|
169
|
+
const resultsMap = await parallelRunner(batches, {
|
|
170
|
+
concurrency: 5,
|
|
171
|
+
verb: "Rotate credentials",
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
for (const [user, entries] of resultsMap) {
|
|
175
|
+
credentials[user] = {};
|
|
176
|
+
|
|
177
|
+
for (const { client, res } of entries) {
|
|
178
|
+
credentials[user][client] = {
|
|
179
|
+
key:
|
|
180
|
+
(res.AccessKey && res.AccessKey.AccessKeyId) ||
|
|
181
|
+
res.AccessKeyMetadata[0].AccessKeyId,
|
|
182
|
+
secret:
|
|
183
|
+
(res.AccessKey && res.AccessKey.SecretAccessKey) ||
|
|
184
|
+
"** secret **",
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Process runner users as a group (after regular, before operator)
|
|
191
|
+
if (runners.length) {
|
|
192
|
+
const runnerBatches = clients.map((client) => ({
|
|
193
|
+
users: runners,
|
|
194
|
+
client,
|
|
195
|
+
fn: async (user) => {
|
|
196
|
+
setAWSClientDefaults(client);
|
|
197
|
+
|
|
198
|
+
await aws.iam.removeIAMUser(`fw-automation-${user}`);
|
|
199
|
+
|
|
200
|
+
return aws.iam.createFWIAMUser(
|
|
201
|
+
`fw-automation-${user}`,
|
|
202
|
+
_.config.users.find((d) => d.username === user)
|
|
203
|
+
.permissions,
|
|
204
|
+
);
|
|
205
|
+
},
|
|
206
|
+
}));
|
|
207
|
+
|
|
208
|
+
const runnerResults = await parallelRunner(runnerBatches, {
|
|
209
|
+
concurrency: 5,
|
|
210
|
+
verb: "Rotate runner credentials",
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
for (const [user, entries] of runnerResults) {
|
|
214
|
+
credentials[user] = {};
|
|
215
|
+
|
|
216
|
+
for (const { client, res } of entries) {
|
|
217
|
+
credentials[user][client] = {
|
|
218
|
+
key:
|
|
219
|
+
(res.AccessKey && res.AccessKey.AccessKeyId) ||
|
|
220
|
+
res.AccessKeyMetadata[0].AccessKeyId,
|
|
221
|
+
secret:
|
|
222
|
+
(res.AccessKey && res.AccessKey.SecretAccessKey) ||
|
|
223
|
+
"** secret **",
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Rotate SES email credentials BEFORE rotating the operator's AWS key.
|
|
230
|
+
// The SES client uses fromIni({ profile: 'fishawack' }) which reads the
|
|
231
|
+
// operator's key from ~/.aws/credentials — once that key is rotated below
|
|
232
|
+
// the profile becomes stale and the SES call would fail.
|
|
233
|
+
if (misc.nodemailer?.AWSSES?.username) {
|
|
234
|
+
try {
|
|
235
|
+
const creds = await aws.ses.rotateOperatorSESCredentials(
|
|
236
|
+
operator.username,
|
|
237
|
+
);
|
|
238
|
+
aws.ses.updateMiscNodemailer(creds);
|
|
239
|
+
console.log(
|
|
240
|
+
"\n \u2713 SES email credentials rotated and saved to misc.json\n",
|
|
241
|
+
);
|
|
242
|
+
} catch (err) {
|
|
243
|
+
console.log(
|
|
244
|
+
`\n \u26a0 Failed to rotate SES credentials: ${err.message}\n`,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Process operator sequentially — must be last per account
|
|
250
|
+
if (includeOperator) {
|
|
251
|
+
const operatorBatches = clients.map((client) => ({
|
|
252
|
+
users: [operator.username],
|
|
253
|
+
client,
|
|
254
|
+
fn: async (user) => {
|
|
255
|
+
setAWSClientDefaults(client);
|
|
256
|
+
|
|
257
|
+
return aws.iam.rotateFWIAMUser(
|
|
258
|
+
`fw-automation-${user}`,
|
|
259
|
+
operator.permissions,
|
|
260
|
+
);
|
|
261
|
+
},
|
|
262
|
+
}));
|
|
263
|
+
|
|
264
|
+
const operatorResults = await parallelRunner(operatorBatches, {
|
|
265
|
+
concurrency: 1,
|
|
266
|
+
verb: "Rotate operator credentials",
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
for (const [user, entries] of operatorResults) {
|
|
270
|
+
credentials[user] = {};
|
|
271
|
+
|
|
272
|
+
for (const { client, res } of entries) {
|
|
273
|
+
credentials[user][client] = {
|
|
274
|
+
key: res.AccessKey.AccessKeyId,
|
|
275
|
+
secret: res.AccessKey.SecretAccessKey,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
await outputCredentials(credentials, sendEmail);
|
|
282
|
+
},
|
|
283
|
+
];
|
|
@@ -4,6 +4,7 @@ const aws = require("../services/aws/index.js");
|
|
|
4
4
|
const { setAWSClientDefaults } = require("../services/aws/misc.js");
|
|
5
5
|
const utilities = require("../libs/utilities");
|
|
6
6
|
const { client, region } = require("../libs/prompts.js");
|
|
7
|
+
const { secretGroups } = require("../libs/vars.js");
|
|
7
8
|
|
|
8
9
|
const SECRETS_NAMESPACE = "aws:elasticbeanstalk:application:environmentsecrets";
|
|
9
10
|
|
|
@@ -72,7 +73,7 @@ module.exports = [
|
|
|
72
73
|
|
|
73
74
|
// Build expected environmentsecrets from Secrets Manager
|
|
74
75
|
const expectedSettings = [];
|
|
75
|
-
const groups =
|
|
76
|
+
const groups = secretGroups;
|
|
76
77
|
|
|
77
78
|
for (const group of groups) {
|
|
78
79
|
const secretName = `${slug}-${group}`;
|
|
@@ -24,5 +24,16 @@ function handler(event) {
|
|
|
24
24
|
headers["x-frame-options"] = { value: "sameorigin" };
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
// Ensure html files aren't cached by browser
|
|
28
|
+
var contentType =
|
|
29
|
+
(headers["content-type"] && headers["content-type"].value) || "";
|
|
30
|
+
var isHtml = contentType.includes("text/html");
|
|
31
|
+
|
|
32
|
+
if (isHtml) {
|
|
33
|
+
headers["cache-control"] = {
|
|
34
|
+
value: "no-cache, no-store, must-revalidate",
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
27
38
|
return response;
|
|
28
39
|
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const _ = require("../../../globals.js");
|
|
2
|
+
const utilities = require("../libs/utilities");
|
|
3
|
+
const email = require("../services/email.js");
|
|
4
|
+
const { readFileSync } = require("fs");
|
|
5
|
+
const htmlEmail = readFileSync(`${__dirname}/../templates/credentials.html`, {
|
|
6
|
+
encoding: "utf8",
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
module.exports = async function outputCredentials(credentials, sendEmail) {
|
|
10
|
+
let output = "";
|
|
11
|
+
|
|
12
|
+
for (var user in credentials) {
|
|
13
|
+
output += utilities.colorize(`\n${user}\n`, "title");
|
|
14
|
+
|
|
15
|
+
let outputUser = "";
|
|
16
|
+
for (var client in credentials[user]) {
|
|
17
|
+
outputUser += `\n[${client}]\n`;
|
|
18
|
+
outputUser += `aws_access_key_id = ${credentials[user][client].key}\n`;
|
|
19
|
+
outputUser += `aws_secret_access_key = ${credentials[user][client].secret}\n`;
|
|
20
|
+
}
|
|
21
|
+
output += outputUser;
|
|
22
|
+
|
|
23
|
+
if (sendEmail) {
|
|
24
|
+
await email.send(
|
|
25
|
+
_.config.users.find((d) => d.username === user).email,
|
|
26
|
+
"New AWS Keys",
|
|
27
|
+
`${htmlEmail}<pre><code>${outputUser.replace(/\n/g, "<br>")}</code></pre>`,
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
console.log(output);
|
|
33
|
+
|
|
34
|
+
// Output base64-encoded credentials for the CI runner user
|
|
35
|
+
let runner =
|
|
36
|
+
_.config.users.find((d) => d.runner) ||
|
|
37
|
+
_.config.users.find((d) => d.username === "aws-runner");
|
|
38
|
+
|
|
39
|
+
if (runner && credentials[runner.username]) {
|
|
40
|
+
let runnerCreds = "";
|
|
41
|
+
|
|
42
|
+
for (var c in credentials[runner.username]) {
|
|
43
|
+
runnerCreds += `[${c}]\n`;
|
|
44
|
+
runnerCreds += `aws_access_key_id = ${credentials[runner.username][c].key}\n`;
|
|
45
|
+
runnerCreds += `aws_secret_access_key = ${credentials[runner.username][c].secret}\n\n`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let base64 = Buffer.from(runnerCreds.trim()).toString("base64");
|
|
49
|
+
|
|
50
|
+
console.log(
|
|
51
|
+
utilities.colorize("\n CI Runner Base64 Credentials\n", "title"),
|
|
52
|
+
);
|
|
53
|
+
console.log(
|
|
54
|
+
" Use this base64 string as the CI variable for pipeline AWS authentication.\n",
|
|
55
|
+
);
|
|
56
|
+
console.log(base64);
|
|
57
|
+
console.log("");
|
|
58
|
+
}
|
|
59
|
+
};
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
const logUpdate = require("log-update");
|
|
2
|
+
const chalk = require("chalk");
|
|
3
|
+
const { Spinner } = require("./utilities");
|
|
4
|
+
|
|
5
|
+
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
6
|
+
const MAX_RETRIES = 15;
|
|
7
|
+
const INITIAL_DELAY = 2000;
|
|
8
|
+
const MAX_DELAY = 60000;
|
|
9
|
+
const TASK_TIMEOUT = 120000; // 2 min hard timeout per attempt — prevents hung TCP connections
|
|
10
|
+
|
|
11
|
+
const RETRYABLE_ERRORS = [
|
|
12
|
+
"Throttling",
|
|
13
|
+
"ThrottlingException",
|
|
14
|
+
"TooManyRequestsException",
|
|
15
|
+
"RequestLimitExceeded",
|
|
16
|
+
"ServiceUnavailable",
|
|
17
|
+
"InternalFailure",
|
|
18
|
+
"RequestTimeout",
|
|
19
|
+
"RequestTimeoutException",
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
function isRetryable(err) {
|
|
23
|
+
if (
|
|
24
|
+
RETRYABLE_ERRORS.includes(err.name) ||
|
|
25
|
+
RETRYABLE_ERRORS.includes(err.Code)
|
|
26
|
+
) {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const statusCode = err.$metadata?.httpStatusCode;
|
|
31
|
+
|
|
32
|
+
return statusCode === 429 || statusCode === 503 || statusCode === 500;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function formatElapsed(ms) {
|
|
36
|
+
const secs = Math.floor(ms / 1000);
|
|
37
|
+
if (secs < 60) return `${secs}s`;
|
|
38
|
+
const mins = Math.floor(secs / 60);
|
|
39
|
+
return `${mins}m${secs % 60}s`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Runs batches of tasks sequentially (one batch per client/account) with
|
|
44
|
+
* parallel execution within each batch. Users are processed in groups of
|
|
45
|
+
* `concurrency` — each group completes all batches before the next starts.
|
|
46
|
+
*
|
|
47
|
+
* @param {Array<{ users: string[], client: string, fn: (user: string) => Promise<any> }>} batches
|
|
48
|
+
* @param {{ concurrency?: number, verb?: string }} options
|
|
49
|
+
* @returns {Promise<Map<string, Array<{ client: string, res: any }>>>} results keyed by user
|
|
50
|
+
*/
|
|
51
|
+
module.exports = async function parallelRunner(
|
|
52
|
+
batches,
|
|
53
|
+
{ concurrency = 5, verb = "Processing" } = {},
|
|
54
|
+
) {
|
|
55
|
+
const allUsers = [...new Set(batches.flatMap((b) => b.users))];
|
|
56
|
+
const totalBatches = batches.length;
|
|
57
|
+
const results = new Map(allUsers.map((u) => [u, []]));
|
|
58
|
+
const startTime = Date.now();
|
|
59
|
+
let frame = 0;
|
|
60
|
+
let throttleCount = 0;
|
|
61
|
+
|
|
62
|
+
// Silence Spinner.prototype.simple — track throttling via slow calls
|
|
63
|
+
const originalSimple = Spinner.prototype.simple;
|
|
64
|
+
Spinner.prototype.simple = async (_message, action) => {
|
|
65
|
+
const t0 = Date.now();
|
|
66
|
+
const res = await action();
|
|
67
|
+
// If a single API call took > 3s it likely hit a retry/backoff
|
|
68
|
+
if (Date.now() - t0 > 3000) {
|
|
69
|
+
throttleCount++;
|
|
70
|
+
}
|
|
71
|
+
return res;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// Chunk users into groups of `concurrency`
|
|
75
|
+
const groups = [];
|
|
76
|
+
for (let i = 0; i < allUsers.length; i += concurrency) {
|
|
77
|
+
groups.push(allUsers.slice(i, i + concurrency));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Track state for users (populated as groups start)
|
|
81
|
+
const groupStates = new Map();
|
|
82
|
+
const errors = [];
|
|
83
|
+
|
|
84
|
+
// Render loop — header + one line per user
|
|
85
|
+
const render = setInterval(() => {
|
|
86
|
+
frame = (frame + 1) % SPINNER_FRAMES.length;
|
|
87
|
+
const elapsed = formatElapsed(Date.now() - startTime);
|
|
88
|
+
|
|
89
|
+
// Header line with timing and throttle info
|
|
90
|
+
let header = chalk.dim(` ${elapsed} elapsed`);
|
|
91
|
+
if (throttleCount > 0) {
|
|
92
|
+
header += chalk.yellow(
|
|
93
|
+
` │ ⚠ ${throttleCount} throttled call${throttleCount > 1 ? "s" : ""} (retrying automatically)`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const lines = [header];
|
|
98
|
+
|
|
99
|
+
for (const user of allUsers) {
|
|
100
|
+
const state = groupStates.get(user);
|
|
101
|
+
|
|
102
|
+
if (!state) {
|
|
103
|
+
lines.push(
|
|
104
|
+
chalk.dim(` - ${verb}: ${user} (0/${totalBatches})`),
|
|
105
|
+
);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (state.status === "retrying") {
|
|
110
|
+
const remaining = Math.max(
|
|
111
|
+
0,
|
|
112
|
+
Math.ceil(
|
|
113
|
+
(state.retryDelay - (Date.now() - state.retryStart)) /
|
|
114
|
+
1000,
|
|
115
|
+
),
|
|
116
|
+
);
|
|
117
|
+
lines.push(
|
|
118
|
+
chalk.yellow(
|
|
119
|
+
` ↻ ${verb}: ${user} - ${state.client} (${state.batchesDone + 1}/${totalBatches}) retry ${state.retryAttempt}/${MAX_RETRIES} ${remaining}s`,
|
|
120
|
+
),
|
|
121
|
+
);
|
|
122
|
+
} else if (state.status === "active") {
|
|
123
|
+
const taskElapsed = Date.now() - state.taskStart;
|
|
124
|
+
let suffix = "";
|
|
125
|
+
if (taskElapsed > 5000) {
|
|
126
|
+
suffix = chalk.yellow(` ${formatElapsed(taskElapsed)}`);
|
|
127
|
+
}
|
|
128
|
+
lines.push(
|
|
129
|
+
chalk.cyan(
|
|
130
|
+
` ${SPINNER_FRAMES[frame]} ${verb}: ${user} - ${state.client} (${state.batchesDone + 1}/${totalBatches})`,
|
|
131
|
+
) + suffix,
|
|
132
|
+
);
|
|
133
|
+
} else if (state.status === "error") {
|
|
134
|
+
lines.push(
|
|
135
|
+
chalk.red(
|
|
136
|
+
` ✖ ${verb}: ${user} - ${state.client} (${state.batchesDone}/${totalBatches}) ${state.errorMsg}`,
|
|
137
|
+
),
|
|
138
|
+
);
|
|
139
|
+
} else if (state.batchesDone === totalBatches) {
|
|
140
|
+
lines.push(
|
|
141
|
+
chalk.green(
|
|
142
|
+
` ✓ ${verb}: ${user} (${totalBatches}/${totalBatches})`,
|
|
143
|
+
),
|
|
144
|
+
);
|
|
145
|
+
} else {
|
|
146
|
+
lines.push(
|
|
147
|
+
chalk.dim(
|
|
148
|
+
` - ${verb}: ${user} (${state.batchesDone}/${totalBatches})`,
|
|
149
|
+
),
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
logUpdate(lines.join("\n"));
|
|
155
|
+
}, 80);
|
|
156
|
+
|
|
157
|
+
// Process each group to full completion before starting the next
|
|
158
|
+
for (const group of groups) {
|
|
159
|
+
for (const u of group) {
|
|
160
|
+
groupStates.set(u, {
|
|
161
|
+
client: "",
|
|
162
|
+
status: "pending",
|
|
163
|
+
batchesDone: 0,
|
|
164
|
+
taskStart: 0,
|
|
165
|
+
hasError: false,
|
|
166
|
+
errorMsg: "",
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
for (const batch of batches) {
|
|
171
|
+
const groupUsers = group.filter((u) => batch.users.includes(u));
|
|
172
|
+
|
|
173
|
+
await Promise.all(
|
|
174
|
+
groupUsers.map(async (user, userIndex) => {
|
|
175
|
+
const state = groupStates.get(user);
|
|
176
|
+
state.client = batch.client;
|
|
177
|
+
state.taskStart = Date.now();
|
|
178
|
+
|
|
179
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
180
|
+
state.status = "active";
|
|
181
|
+
state.taskStart = Date.now();
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
let timeoutHandle;
|
|
185
|
+
const res = await Promise.race([
|
|
186
|
+
batch.fn(user),
|
|
187
|
+
new Promise((_, reject) => {
|
|
188
|
+
timeoutHandle = setTimeout(
|
|
189
|
+
() =>
|
|
190
|
+
reject(
|
|
191
|
+
Object.assign(
|
|
192
|
+
new Error(
|
|
193
|
+
"Request timed out after 2 minutes — will retry",
|
|
194
|
+
),
|
|
195
|
+
{ name: "RequestTimeout" },
|
|
196
|
+
),
|
|
197
|
+
),
|
|
198
|
+
TASK_TIMEOUT,
|
|
199
|
+
);
|
|
200
|
+
}),
|
|
201
|
+
]).finally(() => clearTimeout(timeoutHandle));
|
|
202
|
+
results
|
|
203
|
+
.get(user)
|
|
204
|
+
.push({ client: batch.client, res });
|
|
205
|
+
state.status = "done";
|
|
206
|
+
state.retryAttempt = 0;
|
|
207
|
+
break;
|
|
208
|
+
} catch (err) {
|
|
209
|
+
if (!isRetryable(err) || attempt === MAX_RETRIES) {
|
|
210
|
+
state.status = "error";
|
|
211
|
+
state.hasError = true;
|
|
212
|
+
state.errorMsg = err.message || String(err);
|
|
213
|
+
errors.push({
|
|
214
|
+
user,
|
|
215
|
+
client: batch.client,
|
|
216
|
+
error: err,
|
|
217
|
+
});
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
let delay = Math.min(
|
|
222
|
+
INITIAL_DELAY * Math.pow(2, attempt),
|
|
223
|
+
MAX_DELAY,
|
|
224
|
+
);
|
|
225
|
+
// Stagger retries per user to avoid thundering herd
|
|
226
|
+
delay +=
|
|
227
|
+
Math.floor(Math.random() * delay * 0.3) +
|
|
228
|
+
userIndex * 1000;
|
|
229
|
+
|
|
230
|
+
state.status = "retrying";
|
|
231
|
+
state.retryAttempt = attempt + 1;
|
|
232
|
+
state.retryDelay = delay;
|
|
233
|
+
state.retryStart = Date.now();
|
|
234
|
+
throttleCount++;
|
|
235
|
+
|
|
236
|
+
await new Promise((resolve) =>
|
|
237
|
+
setTimeout(resolve, delay),
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
state.batchesDone++;
|
|
243
|
+
}),
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
clearInterval(render);
|
|
249
|
+
|
|
250
|
+
// Final render
|
|
251
|
+
const elapsed = formatElapsed(Date.now() - startTime);
|
|
252
|
+
let header = chalk.dim(` ${elapsed} elapsed`);
|
|
253
|
+
if (throttleCount > 0) {
|
|
254
|
+
header += chalk.yellow(
|
|
255
|
+
` │ ⚠ ${throttleCount} throttled call${throttleCount > 1 ? "s" : ""}`,
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const lines = [header];
|
|
260
|
+
for (const user of allUsers) {
|
|
261
|
+
const state = groupStates.get(user);
|
|
262
|
+
if (state.hasError) {
|
|
263
|
+
lines.push(
|
|
264
|
+
chalk.red(
|
|
265
|
+
` ✖ ${verb}: ${user} (${state.batchesDone}/${totalBatches}) ${state.errorMsg}`,
|
|
266
|
+
),
|
|
267
|
+
);
|
|
268
|
+
} else {
|
|
269
|
+
lines.push(
|
|
270
|
+
chalk.green(
|
|
271
|
+
` ✓ ${verb}: ${user} (${totalBatches}/${totalBatches})`,
|
|
272
|
+
),
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
logUpdate(lines.join("\n"));
|
|
277
|
+
logUpdate.done();
|
|
278
|
+
|
|
279
|
+
// Restore spinner
|
|
280
|
+
Spinner.prototype.simple = originalSimple;
|
|
281
|
+
|
|
282
|
+
if (errors.length) {
|
|
283
|
+
const summary = errors
|
|
284
|
+
.map(
|
|
285
|
+
(e) => `${e.user} (${e.client}): ${e.error.message || e.error}`,
|
|
286
|
+
)
|
|
287
|
+
.join("\n");
|
|
288
|
+
const err = new Error(
|
|
289
|
+
`${errors.length} task${errors.length > 1 ? "s" : ""} failed:\n${summary}`,
|
|
290
|
+
);
|
|
291
|
+
err.errors = errors;
|
|
292
|
+
throw err;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
return results;
|
|
296
|
+
};
|