-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathls.ts
303 lines (260 loc) · 8.2 KB
/
ls.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import type { ACTOR_JOB_STATUSES } from '@apify/consts';
import { Flags } from '@oclif/core';
import { Time } from '@sapphire/duration';
import type { Actor, ActorRunListItem, ActorTaggedBuild, PaginatedList } from 'apify-client';
import chalk from 'chalk';
import { ApifyCommand } from '../../lib/apify_command.js';
import { prettyPrintStatus } from '../../lib/commands/pretty-print-status.js';
import { CompactMode, kSkipColumn, ResponsiveTable } from '../../lib/commands/responsive-table.js';
import { info, simpleLog } from '../../lib/outputs.js';
import {
DateOnlyTimestampFormatter,
getLoggedClientOrThrow,
MultilineTimestampFormatter,
ShortDurationFormatter,
} from '../../lib/utils.js';
const statusMap: Record<(typeof ACTOR_JOB_STATUSES)[keyof typeof ACTOR_JOB_STATUSES], string> = {
'TIMED-OUT': chalk.gray('after'),
'TIMING-OUT': chalk.gray('after'),
ABORTED: chalk.gray('after'),
ABORTING: chalk.gray('after'),
FAILED: chalk.gray('after'),
READY: chalk.gray('for'),
RUNNING: chalk.gray('for'),
SUCCEEDED: chalk.gray('after'),
};
const recentlyUsedTable = new ResponsiveTable({
allColumns: ['Name', 'Runs', 'Last run started at', 'Last run status', 'Last run duration', '_Small_LastRunText'],
mandatoryColumns: ['Name', 'Runs', 'Last run status', 'Last run duration'],
columnAlignments: {
'Runs': 'right',
'Last run duration': 'right',
Name: 'left',
'Last run status': 'center',
},
hiddenColumns: ['_Small_LastRunText'],
breakpointOverrides: {
small: {
'Last run status': {
label: 'Last run',
valueFrom: '_Small_LastRunText',
},
},
},
});
const myRecentlyUsedTable = new ResponsiveTable({
allColumns: [
'Name',
'Modified at',
'Builds',
'Default build',
'Runs',
'Last run',
'Last run status',
'Last run duration',
'_Small_LastRunText',
],
mandatoryColumns: ['Name', 'Runs', 'Last run', 'Last run duration'],
hiddenColumns: ['_Small_LastRunText'],
columnAlignments: {
'Builds': 'right',
'Runs': 'right',
'Last run duration': 'right',
Name: 'left',
'Last run status': 'center',
},
breakpointOverrides: {
small: {
'Last run': {
label: 'Last run',
valueFrom: '_Small_LastRunText',
},
},
},
});
interface HydratedListData {
id: string;
createdAt: Date;
modifiedAt: Date;
name: string;
username: string;
title: string;
stats: {
totalRuns: number;
lastRunStartedAt: string | null;
};
actor: Actor | null;
lastRun: ActorRunListItem | null;
}
export class ActorsLsCommand extends ApifyCommand<typeof ActorsLsCommand> {
static override description = 'Prints a list of recently executed Actors or Actors you own.';
static override flags = {
my: Flags.boolean({
description: 'Whether to list Actors made by the logged in user.',
default: false,
}),
offset: Flags.integer({
description: 'Number of Actors that will be skipped.',
default: 0,
}),
limit: Flags.integer({
description: 'Number of Actors that will be listed.',
default: 20,
}),
desc: Flags.boolean({
description: 'Sort Actors in descending order.',
default: false,
}),
};
static override enableJsonFlag = true;
async run() {
const { desc, limit, offset, my, json } = this.flags;
const client = await getLoggedClientOrThrow();
const rawActorList = await client.actors().list({ limit, offset, desc, my });
if (rawActorList.count === 0) {
if (json) {
return rawActorList;
}
info({
message: my ? "You don't have any Actors yet!" : 'There are no recent Actors used by you.',
stdout: true,
});
return;
}
// Fetch the last run for actors
const actorList: PaginatedList<HydratedListData> = {
...rawActorList,
items: await Promise.all(
rawActorList.items.map(async (actorData) => {
const actor = await client.actor(actorData.id).get();
const runs = await client
.actor(actorData.id)
.runs()
.list({ desc: true, limit: 1 })
// Throws an error if the returned actor changed publicity status
.catch(
() =>
({
count: 0,
desc: true,
items: [],
limit: 1,
offset: 0,
total: 0,
}) satisfies PaginatedList<ActorRunListItem>,
);
return {
...actorData,
actor: actor ?? null,
lastRun: (runs.items[0] ?? null) as ActorRunListItem | null,
} as HydratedListData;
}),
),
};
actorList.items = my ? this.sortByModifiedAt(actorList.items) : this.sortByLastRun(actorList.items);
if (json) {
return actorList;
}
const table = my ? myRecentlyUsedTable : recentlyUsedTable;
const longestActorTitleLength =
actorList.items.reduce((acc, curr) => {
const title = `${curr.username}/${curr.name}`;
if (title.length > acc) {
return title.length;
}
return acc;
}, 0) +
// Padding left right of the name column
2 +
// Runs column minimum size with padding
6;
for (const item of actorList.items) {
const lastRunDisplayedTimestamp = item.stats.lastRunStartedAt
? MultilineTimestampFormatter.display(item.stats.lastRunStartedAt)
: '';
const lastRunDuration = item.lastRun
? (() => {
if (item.lastRun.finishedAt) {
return ShortDurationFormatter.format(
item.lastRun.finishedAt.getTime() - item.lastRun.startedAt.getTime(),
);
}
const duration = Date.now() - item.lastRun.startedAt.getTime();
return `${ShortDurationFormatter.format(duration)}…`;
})()
: '';
const defaultBuild = item.actor
? (() => {
const buildVersionToTag = Object.entries(
(item.actor.taggedBuilds ?? {}) as Record<string, ActorTaggedBuild>,
).find(
([tag, data]) =>
data.buildNumber === item.actor!.defaultRunOptions.build ||
tag === item.actor!.defaultRunOptions.build,
);
if (buildVersionToTag) {
return `${chalk.yellow(buildVersionToTag[0])} / ${chalk.cyan(buildVersionToTag[1].buildNumber ?? item.actor.defaultRunOptions.build)}`;
}
return chalk.gray('Unknown');
})()
: chalk.gray('Unknown');
const runStatus = (() => {
if (item.lastRun) {
const status = prettyPrintStatus(item.lastRun.status);
const stringParts = [status];
if (lastRunDuration) {
stringParts.push(statusMap[item.lastRun.status], chalk.cyan(lastRunDuration));
}
if (item.lastRun.finishedAt) {
const diff = Date.now() - item.lastRun.finishedAt.getTime();
if (diff < Time.Week) {
stringParts.push('\n', chalk.gray(`${ShortDurationFormatter.format(diff)} ago`));
} else {
stringParts.push(
'\n',
chalk.gray('On', DateOnlyTimestampFormatter.display(item.lastRun.finishedAt)),
);
}
}
return stringParts.join(' ');
}
return '';
})();
table.pushRow({
Name: `${item.title}\n${chalk.gray(`${item.username}/${item.name}`)}`,
// Completely arbitrary number, but its enough for a very specific edge case where a full actor identifier could be very long, but only on small terminals
Runs:
ResponsiveTable.isSmallTerminal() && longestActorTitleLength >= 56
? kSkipColumn
: chalk.cyan(`${item.stats?.totalRuns ?? 0}`),
'Last run started at': lastRunDisplayedTimestamp,
'Last run': lastRunDisplayedTimestamp,
'Last run status': item.lastRun ? prettyPrintStatus(item.lastRun.status) : '',
'Modified at': MultilineTimestampFormatter.display(item.modifiedAt),
Builds: item.actor ? chalk.cyan(item.actor.stats.totalBuilds) : chalk.gray('Unknown'),
'Last run duration': ResponsiveTable.isSmallTerminal() ? kSkipColumn : chalk.cyan(lastRunDuration),
'Default build': defaultBuild,
_Small_LastRunText: runStatus,
});
}
simpleLog({
message: table.render(CompactMode.WebLikeCompact),
stdout: true,
});
return undefined;
}
private sortByModifiedAt(items: HydratedListData[]) {
return items.sort((a, b) => {
const aDate = new Date(a.modifiedAt);
const bDate = new Date(b.modifiedAt);
return bDate.getTime() - aDate.getTime();
});
}
private sortByLastRun(items: HydratedListData[]) {
return items.sort((a, b) => {
const aDate = new Date(a.stats?.lastRunStartedAt ?? '1970-01-01T00:00Z');
const bDate = new Date(b.stats?.lastRunStartedAt ?? '1970-01-01T00:00Z');
return bDate.getTime() - aDate.getTime();
});
}
}