-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetrics.ts
More file actions
519 lines (451 loc) · 17.4 KB
/
metrics.ts
File metadata and controls
519 lines (451 loc) · 17.4 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
import type {
CoderWorkspace,
CoderTemplate,
WorkspaceMetrics,
TeamMetrics,
PlatformMetrics,
TemplateMetrics,
ParticipantData,
ActivityStatus,
WorkspaceStatus,
HealthStatus,
DailyEngagement,
} from './types';
// ===== Activity Thresholds =====
const ACTIVITY_THRESHOLDS = {
ACTIVE_DAYS: 7, // 7 days - workspace used recently
INACTIVE_DAYS: 30, // 30 days - workspace not used lately
STALE_DAYS: 30, // 30+ days - workspace abandoned
} as const;
// ===== Utility Functions =====
/**
* Calculate days between two dates
*/
function daysBetween(date1: Date, date2: Date): number {
const diffTime = Math.abs(date2.getTime() - date1.getTime());
return Math.floor(diffTime / (1000 * 60 * 60 * 24));
}
/**
* Calculate hours between two dates
*/
function hoursBetween(date1: Date, date2: Date): number {
const diffTime = Math.abs(date2.getTime() - date1.getTime());
return Math.floor(diffTime / (1000 * 60 * 60));
}
/**
* Get workspace usage hours from pre-calculated field or fallback to latest build
* The collection script calculates total usage across all builds
*/
function getWorkspaceUsageHours(workspace: CoderWorkspace): number {
// Use pre-calculated total_usage_hours from collection script if available
if (workspace.total_usage_hours !== undefined && workspace.total_usage_hours !== null) {
return workspace.total_usage_hours;
}
// Fallback: calculate from latest build only (less accurate)
try {
const resources = workspace.latest_build?.resources || [];
let earliestConnection: Date | null = null;
let latestConnection: Date | null = null;
for (const resource of resources) {
const agents = resource.agents || [];
for (const agent of agents) {
if (agent.first_connected_at) {
const firstConnected = new Date(agent.first_connected_at);
if (!earliestConnection || firstConnected < earliestConnection) {
earliestConnection = firstConnected;
}
}
if (agent.last_connected_at) {
const lastConnected = new Date(agent.last_connected_at);
if (!latestConnection || lastConnected > latestConnection) {
latestConnection = lastConnected;
}
}
}
}
if (earliestConnection && latestConnection) {
return hoursBetween(earliestConnection, latestConnection);
}
return 0;
} catch (error) {
console.warn(`Error calculating usage hours for workspace ${workspace.id}:`, error);
return 0;
}
}
/**
* Get workspace active hours from pre-calculated field
* The collection script fetches this from Coder Insights API
*/
function getWorkspaceActiveHours(workspace: CoderWorkspace): number {
// Use pre-calculated active_hours from collection script
if (workspace.active_hours !== undefined && workspace.active_hours !== null) {
return workspace.active_hours;
}
return 0;
}
/**
* Classify activity status based on days since last active
*/
function classifyActivityStatus(daysSinceActive: number): ActivityStatus {
if (daysSinceActive <= ACTIVITY_THRESHOLDS.ACTIVE_DAYS) {
return 'active';
} else if (daysSinceActive <= ACTIVITY_THRESHOLDS.INACTIVE_DAYS) {
return 'inactive';
} else {
return 'stale';
}
}
/**
* Extract the most recent last_connected_at timestamp from workspace agents
*/
export function getLastActiveTimestamp(workspace: CoderWorkspace): string {
let mostRecent = workspace.created_at;
try {
const resources = workspace.latest_build?.resources || [];
for (const resource of resources) {
const agents = resource.agents || [];
for (const agent of agents) {
if (agent.last_connected_at && agent.last_connected_at > mostRecent) {
mostRecent = agent.last_connected_at;
}
}
}
} catch (error) {
console.warn(`Error extracting last active timestamp for workspace ${workspace.id}:`, error);
}
return mostRecent;
}
/**
* Determine current workspace status from build data
*/
export function getCurrentStatus(workspace: CoderWorkspace): WorkspaceStatus {
try {
const latestBuild = workspace.latest_build;
if (!latestBuild) {
return 'unknown';
}
const jobStatus = latestBuild.job?.status;
const transition = latestBuild.transition;
// Check if build failed
if (jobStatus === 'failed' || jobStatus === 'canceled') {
return 'error';
}
// Check agent status if available
const resources = latestBuild.resources || [];
for (const resource of resources) {
const agents = resource.agents || [];
for (const agent of agents) {
if (agent.status === 'connected' && agent.lifecycle_state === 'ready') {
return 'running';
}
}
}
// Fallback to transition type
if (transition === 'start' && jobStatus === 'succeeded') {
return 'running';
} else if (transition === 'stop' && jobStatus === 'succeeded') {
return 'stopped';
}
return 'unknown';
} catch (error) {
console.warn(`Error determining status for workspace ${workspace.id}:`, error);
return 'unknown';
}
}
/**
* Determine health status from workspace agents
*/
export function getHealthStatus(workspace: CoderWorkspace): HealthStatus {
try {
const resources = workspace.latest_build?.resources || [];
for (const resource of resources) {
const agents = resource.agents || [];
for (const agent of agents) {
const apps = agent.apps || [];
for (const app of apps) {
if (app.health === 'unhealthy') {
return 'unhealthy';
}
}
}
}
// If no unhealthy apps found, consider healthy
return 'healthy';
} catch (error) {
console.warn(`Error determining health for workspace ${workspace.id}:`, error);
return 'unknown';
}
}
// ===== Main Enrichment Functions =====
/**
* Enrich workspace data with team information and calculated metrics
*/
export function enrichWorkspaceData(
workspaces: CoderWorkspace[],
teamMappings: Map<string, ParticipantData>
): WorkspaceMetrics[] {
const now = new Date();
return workspaces.map((workspace) => {
const ownerHandle = workspace.owner_name.toLowerCase();
const participant = teamMappings.get(ownerHandle);
const lastActive = getLastActiveTimestamp(workspace);
const daysSinceActive = daysBetween(new Date(lastActive), now);
const daysSinceCreated = daysBetween(new Date(workspace.created_at), now);
const workspaceHours = getWorkspaceUsageHours(workspace);
const activeHours = getWorkspaceActiveHours(workspace);
// Determine full name
let ownerName = workspace.owner_name;
if (participant?.first_name && participant?.last_name) {
ownerName = `${participant.first_name} ${participant.last_name}`;
}
return {
workspace_id: workspace.id,
workspace_name: workspace.name || `${workspace.owner_name}/workspace`,
owner_github_handle: workspace.owner_name,
owner_name: ownerName,
team_name: participant?.team_name || 'Unassigned',
template_id: workspace.template_id,
template_name: workspace.template_name,
template_display_name: workspace.template_display_name,
current_status: getCurrentStatus(workspace),
health_status: getHealthStatus(workspace),
created_at: workspace.created_at,
last_active: lastActive,
last_build_at: workspace.latest_build.created_at,
days_since_created: daysSinceCreated,
days_since_active: daysSinceActive,
workspace_hours: workspaceHours,
active_hours: activeHours,
total_builds: workspace.latest_build.build_number,
last_build_status: workspace.latest_build.job?.status || 'unknown',
activity_status: classifyActivityStatus(daysSinceActive),
};
});
}
/**
* Aggregate workspace metrics by team
*/
export function aggregateByTeam(workspaces: WorkspaceMetrics[]): TeamMetrics[] {
const teams = new Map<string, WorkspaceMetrics[]>();
// Group workspaces by team
workspaces.forEach((workspace) => {
const teamWorkspaces = teams.get(workspace.team_name) || [];
teamWorkspaces.push(workspace);
teams.set(workspace.team_name, teamWorkspaces);
});
// Calculate metrics for each team
return Array.from(teams.entries()).map(([teamName, teamWorkspaces]) => {
// Template distribution
const templateDistribution: Record<string, number> = {};
teamWorkspaces.forEach((workspace) => {
const count = templateDistribution[workspace.template_display_name] || 0;
templateDistribution[workspace.template_display_name] = count + 1;
});
// Total workspace hours (sum of all workspace lifetime hours)
const totalWorkspaceHours = teamWorkspaces.reduce((sum, w) => sum + w.workspace_hours, 0);
// Total active hours (sum of actual interaction hours from Insights API)
const totalActiveHours = teamWorkspaces.reduce((sum, w) => sum + w.active_hours, 0);
// Average workspace hours
const avgWorkspaceHours =
teamWorkspaces.length > 0 ? totalWorkspaceHours / teamWorkspaces.length : 0;
// Calculate active days (unique dates when workspaces were active)
const activeDates = new Set<string>();
teamWorkspaces.forEach((workspace) => {
// Add creation date
const createdDate = new Date(workspace.created_at).toISOString().split('T')[0];
activeDates.add(createdDate);
// Add last active date if different from created
const lastActiveDate = new Date(workspace.last_active).toISOString().split('T')[0];
if (lastActiveDate !== createdDate) {
activeDates.add(lastActiveDate);
}
});
// Member activity
const memberMap = new Map<string, { workspaces: WorkspaceMetrics[] }>();
teamWorkspaces.forEach((workspace) => {
const member = memberMap.get(workspace.owner_github_handle) || { workspaces: [] };
member.workspaces.push(workspace);
memberMap.set(workspace.owner_github_handle, member);
});
const members = Array.from(memberMap.entries()).map(([githubHandle, data]) => {
const mostRecentWorkspace = data.workspaces.reduce((most, current) =>
new Date(current.last_active) > new Date(most.last_active) ? current : most
);
return {
github_handle: githubHandle,
name: mostRecentWorkspace.owner_name,
workspace_count: data.workspaces.length,
last_active: mostRecentWorkspace.last_active,
activity_status: mostRecentWorkspace.activity_status,
};
});
// Sort members by last active (most recent first)
members.sort((a, b) => new Date(b.last_active).getTime() - new Date(a.last_active).getTime());
// Count unique active users (users with at least one active workspace in last 7 days)
const activeUsers = new Set<string>();
teamWorkspaces.forEach((workspace) => {
if (workspace.activity_status === 'active') {
activeUsers.add(workspace.owner_github_handle);
}
});
return {
team_name: teamName,
total_workspaces: teamWorkspaces.length,
unique_active_users: activeUsers.size,
total_workspace_hours: Math.round(totalWorkspaceHours),
total_active_hours: Math.round(totalActiveHours),
avg_workspace_hours: Math.round(avgWorkspaceHours * 10) / 10,
active_days: activeDates.size,
template_distribution: templateDistribution,
members,
};
});
}
/**
* Calculate platform-wide metrics
*/
export function calculatePlatformMetrics(workspaces: WorkspaceMetrics[]): PlatformMetrics {
const activeWorkspaces = workspaces.filter((w) => w.activity_status === 'active');
const inactiveWorkspaces = workspaces.filter((w) => w.activity_status === 'inactive');
const staleWorkspaces = workspaces.filter((w) => w.activity_status === 'stale');
const healthyWorkspaces = workspaces.filter((w) => w.health_status === 'healthy');
// Unique users
const uniqueUsers = new Set(workspaces.map((w) => w.owner_github_handle));
// Unique teams
const uniqueTeams = new Set(workspaces.map((w) => w.team_name));
// Most popular template
const templateCounts = new Map<string, { name: string; displayName: string; count: number }>();
workspaces.forEach((workspace) => {
const existing = templateCounts.get(workspace.template_name) || {
name: workspace.template_name,
displayName: workspace.template_display_name,
count: 0,
};
existing.count++;
templateCounts.set(workspace.template_name, existing);
});
let mostPopularTemplate = null;
let maxCount = 0;
templateCounts.forEach((data) => {
if (data.count > maxCount) {
maxCount = data.count;
mostPopularTemplate = {
name: data.name,
display_name: data.displayName,
count: data.count,
};
}
});
// Average days since active
const avgDaysSinceActive =
workspaces.length > 0
? workspaces.reduce((sum, w) => sum + w.days_since_active, 0) / workspaces.length
: 0;
// Healthy rate percentage
const healthyRate = workspaces.length > 0 ? (healthyWorkspaces.length / workspaces.length) * 100 : 0;
return {
total_workspaces: workspaces.length,
total_users: uniqueUsers.size,
total_teams: uniqueTeams.size,
active_workspaces: activeWorkspaces.length,
inactive_workspaces: inactiveWorkspaces.length,
stale_workspaces: staleWorkspaces.length,
total_templates: templateCounts.size,
most_popular_template: mostPopularTemplate,
healthy_rate: Math.round(healthyRate * 10) / 10,
avg_days_since_active: Math.round(avgDaysSinceActive * 10) / 10,
};
}
/**
* Calculate template-level metrics
*/
export function calculateTemplateMetrics(
workspaces: WorkspaceMetrics[],
templates: CoderTemplate[]
): TemplateMetrics[] {
// Group workspaces by template
const templateMap = new Map<string, WorkspaceMetrics[]>();
workspaces.forEach((workspace) => {
const existing = templateMap.get(workspace.template_id) || [];
existing.push(workspace);
templateMap.set(workspace.template_id, existing);
});
// Calculate metrics for each template
return templates.map((template) => {
const templateWorkspaces = templateMap.get(template.id) || [];
const activeWorkspaces = templateWorkspaces.filter((w) => w.activity_status === 'active');
// Total workspace hours (sum of all workspace lifetime hours)
const totalWorkspaceHours = templateWorkspaces.reduce((sum, w) => sum + w.workspace_hours, 0);
// Total active hours (sum of actual interaction hours from Insights API)
const totalActiveHours = templateWorkspaces.reduce((sum, w) => sum + w.active_hours, 0);
// Average workspace hours
const avgWorkspaceHours =
templateWorkspaces.length > 0 ? totalWorkspaceHours / templateWorkspaces.length : 0;
// Team distribution
const teamDistribution: Record<string, number> = {};
templateWorkspaces.forEach((workspace) => {
const count = teamDistribution[workspace.team_name] || 0;
teamDistribution[workspace.team_name] = count + 1;
});
// Count unique active users for this template (users with at least one active workspace in last 7 days)
const activeUsers = new Set<string>();
activeWorkspaces.forEach((workspace) => {
activeUsers.add(workspace.owner_github_handle);
});
return {
template_id: template.id,
template_name: template.name,
template_display_name: template.display_name,
total_workspaces: templateWorkspaces.length,
active_workspaces: activeWorkspaces.length,
unique_active_users: activeUsers.size,
total_workspace_hours: Math.round(totalWorkspaceHours),
total_active_hours: Math.round(totalActiveHours),
avg_workspace_hours: Math.round(avgWorkspaceHours * 10) / 10,
team_distribution: teamDistribution,
};
});
}
/**
* Calculate daily user engagement from workspace data
* Returns array of daily unique users and active workspaces for the last 60 days
*/
export function calculateDailyEngagement(workspaces: WorkspaceMetrics[]): DailyEngagement[] {
const now = new Date();
const daysToShow = 60;
// Create a map to store engagement data by date
const engagementMap = new Map<string, Set<string>>();
const workspaceActivityMap = new Map<string, Set<string>>();
// Initialize map for last 60 days
for (let i = 0; i < daysToShow; i++) {
const date = new Date(now);
date.setDate(date.getDate() - i);
const dateStr = date.toISOString().split('T')[0];
engagementMap.set(dateStr, new Set());
workspaceActivityMap.set(dateStr, new Set());
}
// Process each workspace
workspaces.forEach((workspace) => {
const createdDate = new Date(workspace.created_at).toISOString().split('T')[0];
const lastActiveDate = workspace.last_active ? new Date(workspace.last_active).toISOString().split('T')[0] : createdDate;
// Add user to created date
if (engagementMap.has(createdDate)) {
engagementMap.get(createdDate)!.add(workspace.owner_github_handle);
workspaceActivityMap.get(createdDate)!.add(workspace.workspace_id);
}
// Add user to last active date
if (lastActiveDate !== createdDate && engagementMap.has(lastActiveDate)) {
engagementMap.get(lastActiveDate)!.add(workspace.owner_github_handle);
workspaceActivityMap.get(lastActiveDate)!.add(workspace.workspace_id);
}
});
// Convert to array and sort by date
const engagement: DailyEngagement[] = Array.from(engagementMap.entries())
.map(([date, users]) => ({
date,
unique_users: users.size,
active_workspaces: workspaceActivityMap.get(date)?.size || 0,
}))
.sort((a, b) => a.date.localeCompare(b.date));
return engagement;
}