-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.ts
More file actions
461 lines (411 loc) · 18.5 KB
/
engine.ts
File metadata and controls
461 lines (411 loc) · 18.5 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
import factorsData from './factors.json';
import type {
ResourceInput,
EmissionAndCostEstimate,
UpgradeRecommendation,
PlanAnalysisResult,
ConfidenceLevel,
PowerModel,
CloudProvider,
} from './types';
// ---------------------------------------------------------------------------
// Internal types for ledger shape (mirrors factors.json v2.0.0)
// ---------------------------------------------------------------------------
interface LedgerInstance {
architecture: string;
vcpus: number;
memory_gb: number;
power_watts: { idle: number; max: number };
embodied_co2e_grams_per_month: number;
}
interface LedgerRegion {
location: string;
grid_intensity_gco2e_per_kwh: number;
pue: number;
water_intensity_litres_per_kwh: number;
}
interface ProviderLedger {
regions: Record<string, LedgerRegion>;
instances: Record<string, LedgerInstance>;
pricing_usd_per_hour: Record<string, Record<string, number>>;
}
interface Ledger {
metadata: {
ledger_version: string;
assumptions: { default_utilization: { value: number } };
};
aws: ProviderLedger;
azure: ProviderLedger;
gcp: ProviderLedger;
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const HOURS_PER_MONTH = 730;
const GRAMS_PER_KWH = 1000;
/**
* Memory power draw coefficient — CCF standard (0.392W per GB of RAM).
* Applied to all instances with a known memory_gb value.
* Source: Cloud Carbon Footprint methodology v3.
*/
const MEMORY_WATTS_PER_GB = 0.392;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function resolveUtilization(input: ResourceInput, ledger: Ledger): number {
if (input.avgUtilization !== undefined && (input.avgUtilization < 0 || input.avgUtilization > 1)) {
throw new RangeError(`avgUtilization must be between 0 and 1, got ${input.avgUtilization}`);
}
if (input.hoursPerMonth !== undefined && input.hoursPerMonth <= 0) {
throw new RangeError(`hoursPerMonth must be positive, got ${input.hoursPerMonth}`);
}
return input.avgUtilization ?? ledger.metadata.assumptions.default_utilization.value;
}
/**
* Returns total effective watts: CPU interpolation + memory power draw.
* Memory contribution is constant (not utilization-dependent) per CCF methodology.
*/
function effectiveTotalWatts(idle: number, max: number, utilization: number, memoryGb: number): number {
const cpuWatts = idle + (max - idle) * utilization;
const memoryWatts = memoryGb * MEMORY_WATTS_PER_GB;
return cpuWatts + memoryWatts;
}
function wattsToScope2Carbon(watts: number, hours: number, pue: number, gridIntensity: number): number {
return (watts * pue * hours / GRAMS_PER_KWH) * gridIntensity;
}
function wattsToWater(watts: number, hours: number, wue: number): number {
return (watts * hours / GRAMS_PER_KWH) * wue;
}
// ---------------------------------------------------------------------------
// ARM upgrade maps — per provider
// ---------------------------------------------------------------------------
const ARM_UPGRADE_MAP: Record<CloudProvider, Record<string, string>> = {
aws: {
t3: 't4g', t3a: 't4g',
m5: 'm6g', m5a: 'm6g',
c5: 'c6g', c5a: 'c6g',
r5: 'r6g', r5a: 'r6g',
},
azure: {
'Standard_D2s_v3': 'Standard_D2ps_v5',
'Standard_D4s_v3': 'Standard_D4ps_v5',
'Standard_D8s_v3': 'Standard_D8ps_v5',
'Standard_D2s_v4': 'Standard_D2ps_v5',
'Standard_D4s_v4': 'Standard_D4ps_v5',
},
gcp: {
n2: 't2a',
n2d: 't2a',
e2: 't2a',
},
};
function getArmAlternative(instanceType: string, provider: CloudProvider, ledger: Ledger): string | null {
const providerLedger = ledger[provider];
const map = ARM_UPGRADE_MAP[provider];
if (provider === 'azure') {
const candidate = map[instanceType];
return candidate && providerLedger.instances[candidate] ? candidate : null;
}
const [family, size] = instanceType.split('.');
if (!family || !size) return null;
const armFamily = map[family];
if (!armFamily) return null;
const candidate = `${armFamily}.${size}`;
return providerLedger.instances[candidate] ? candidate : null;
}
function getCleanerRegion(currentRegion: string, instanceType: string, provider: CloudProvider, ledger: Ledger): string | null {
const providerLedger = ledger[provider];
const regions = Object.entries(providerLedger.regions)
.filter(([regionId]) => {
if (regionId === currentRegion) return false;
return !!providerLedger.pricing_usd_per_hour[regionId]?.[instanceType];
})
.sort(([, a], [, b]) => a.grid_intensity_gco2e_per_kwh - b.grid_intensity_gco2e_per_kwh);
if (regions.length === 0) return null;
const [cleanestRegionId, cleanestRegion] = regions[0];
const currentIntensity = providerLedger.regions[currentRegion]?.grid_intensity_gco2e_per_kwh ?? Infinity;
if (cleanestRegion.grid_intensity_gco2e_per_kwh >= currentIntensity * 0.9) return null;
return cleanestRegionId;
}
// ---------------------------------------------------------------------------
// Serverless estimation model
// ---------------------------------------------------------------------------
/**
* Parse a serverless instance type string into its parameters.
* Format: "serverless:{memoryMb}mb:{invocations}inv:{durationMs}ms"
*/
function parseServerlessInstanceType(instanceType: string): {
memoryMb: number;
invocationsPerMonth: number;
avgDurationMs: number;
} | null {
if (!instanceType.startsWith('serverless:')) return null;
const match = instanceType.match(/^serverless:(\d+)mb:(\d+)inv:(\d+)ms$/);
if (!match) return null;
return {
memoryMb: parseInt(match[1], 10),
invocationsPerMonth: parseInt(match[2], 10),
avgDurationMs: parseInt(match[3], 10),
};
}
/**
* Calculate emissions for a serverless function.
*
* Model: AWS Lambda Power Model (CCF methodology)
* W = (memory_gb × 0.392W/GB) + CONSTANT_CPU_OVERHEAD
* energy_kwh = W × (avg_duration_seconds × invocations_per_month) / 3_600_000
*
* CPU overhead constant: 0.002W (Lambda micro-VM baseline)
* This is conservative and marked LOW_ASSUMED_DEFAULT because we don't have
* actual invocation telemetry — we use the Terraform-configured memory and defaults.
*
* Embodied carbon: Lambda shares hardware with other tenants — we use
* a minimal prorated allocation (1/48 vCPU equivalent, prorated by duration fraction).
*/
function calculateServerlessBaseline(
input: ResourceInput,
params: { memoryMb: number; invocationsPerMonth: number; avgDurationMs: number },
regionData: LedgerRegion
): EmissionAndCostEstimate {
const { memoryMb, invocationsPerMonth, avgDurationMs } = params;
const memoryGb = memoryMb / 1024;
// Power: memory-proportional + constant CPU overhead
const LAMBDA_CPU_OVERHEAD_W = 0.002;
const powerW = (memoryGb * MEMORY_WATTS_PER_GB) + LAMBDA_CPU_OVERHEAD_W;
// Total compute seconds per month
const computeSecondsPerMonth = (avgDurationMs / 1000) * invocationsPerMonth;
// Energy in kWh (convert W×s to kWh: divide by 3,600,000)
const energyKwh = (powerW * computeSecondsPerMonth) / 3_600_000;
// Scope 2: energy × PUE × grid intensity
const totalCo2eGramsPerMonth = energyKwh * regionData.pue * regionData.grid_intensity_gco2e_per_kwh;
// Scope 3: minimal embodied — prorate by duration fraction of a month
// Assumption: Lambda co-tenancy means ~1/100th of a single-server embodied allocation
const EMBODIED_MONTHLY_SINGLE_SERVER_G = 500; // conservative baseline
const durationFractionOfMonth = computeSecondsPerMonth / (730 * 3600);
const embodiedCo2eGramsPerMonth = EMBODIED_MONTHLY_SINGLE_SERVER_G * durationFractionOfMonth;
const totalLifecycleCo2eGramsPerMonth = totalCo2eGramsPerMonth + embodiedCo2eGramsPerMonth;
// Water
const waterLitresPerMonth = energyKwh * regionData.pue * regionData.water_intensity_litres_per_kwh;
// Cost: AWS Lambda pricing at us-east-1 rates
// $0.0000002/request + $0.0000000167/GB-second
const REQUEST_COST = 0.0000002;
const GB_SECOND_COST = 0.0000000167;
const gbSeconds = memoryGb * (avgDurationMs / 1000) * invocationsPerMonth;
const totalCostUsdPerMonth = (REQUEST_COST * invocationsPerMonth) + (GB_SECOND_COST * gbSeconds);
return {
totalCo2eGramsPerMonth,
embodiedCo2eGramsPerMonth,
totalLifecycleCo2eGramsPerMonth,
waterLitresPerMonth,
totalCostUsdPerMonth,
confidence: 'LOW_ASSUMED_DEFAULT',
scope: 'SCOPE_2_AND_3',
unsupportedReason: `Serverless estimation uses assumed defaults: ${memoryMb}MB memory, ${invocationsPerMonth.toLocaleString()} invocations/month, ${avgDurationMs}ms avg duration. Override via .greenops.yml or resource tags for accuracy.`,
assumptionsApplied: {
utilizationApplied: 1.0, // serverless runs at full allocated memory
gridIntensityApplied: regionData.grid_intensity_gco2e_per_kwh,
powerModelUsed: 'SERVERLESS_INVOCATION',
embodiedCo2ePerVcpuPerMonthApplied: EMBODIED_MONTHLY_SINGLE_SERVER_G,
waterIntensityLitresPerKwhApplied: regionData.water_intensity_litres_per_kwh,
memoryWattsApplied: memoryGb * MEMORY_WATTS_PER_GB,
},
};
}
// ---------------------------------------------------------------------------
// Core Engine
// ---------------------------------------------------------------------------
export function calculateBaseline(
input: ResourceInput,
ledger: Ledger = factorsData as Ledger
): EmissionAndCostEstimate {
const provider: CloudProvider = input.provider ?? 'aws';
const providerLedger = ledger[provider];
const hours = input.hoursPerMonth ?? HOURS_PER_MONTH;
const utilization = resolveUtilization(input, ledger);
const zeroResult = (unsupportedReason: string, gridIntensity = 0, embodied = 0, waterIntensity = 0): EmissionAndCostEstimate => ({
totalCo2eGramsPerMonth: 0,
embodiedCo2eGramsPerMonth: 0,
totalLifecycleCo2eGramsPerMonth: 0,
waterLitresPerMonth: 0,
totalCostUsdPerMonth: 0,
confidence: 'LOW_ASSUMED_DEFAULT',
scope: 'SCOPE_2_AND_3',
unsupportedReason,
assumptionsApplied: {
utilizationApplied: utilization,
gridIntensityApplied: gridIntensity,
powerModelUsed: 'LINEAR_INTERPOLATION',
embodiedCo2ePerVcpuPerMonthApplied: embodied,
waterIntensityLitresPerKwhApplied: waterIntensity,
memoryWattsApplied: 0,
},
});
const regionData = providerLedger.regions[input.region];
if (!regionData) {
return zeroResult(`Region "${input.region}" is not present in the ${provider.toUpperCase()} section of the Open GreenOps Methodology Ledger v${ledger.metadata.ledger_version}.`);
}
// --- Serverless path ---
const serverlessParams = parseServerlessInstanceType(input.instanceType);
if (serverlessParams) {
return calculateServerlessBaseline(input, serverlessParams, regionData);
}
const instanceData = providerLedger.instances[input.instanceType];
if (!instanceData) {
return zeroResult(
`Instance type "${input.instanceType}" is not present in the ${provider.toUpperCase()} section of the Open GreenOps Methodology Ledger v${ledger.metadata.ledger_version}.`,
regionData.grid_intensity_gco2e_per_kwh, 0, regionData.water_intensity_litres_per_kwh
);
}
const pricePerHour = providerLedger.pricing_usd_per_hour[input.region]?.[input.instanceType];
if (pricePerHour === undefined) {
return zeroResult(
`No pricing data for "${input.instanceType}" in "${input.region}" (${provider.toUpperCase()}).`,
regionData.grid_intensity_gco2e_per_kwh,
instanceData.embodied_co2e_grams_per_month,
regionData.water_intensity_litres_per_kwh
);
}
const powerModel: PowerModel = 'LINEAR_INTERPOLATION';
const effectiveWatts = effectiveTotalWatts(
instanceData.power_watts.idle,
instanceData.power_watts.max,
utilization,
instanceData.memory_gb
);
const totalCo2eGramsPerMonth = wattsToScope2Carbon(
effectiveWatts, hours, regionData.pue, regionData.grid_intensity_gco2e_per_kwh
);
const embodiedCo2eGramsPerMonth = instanceData.embodied_co2e_grams_per_month * (hours / HOURS_PER_MONTH);
const waterLitresPerMonth = wattsToWater(effectiveWatts, hours, regionData.water_intensity_litres_per_kwh);
const totalLifecycleCo2eGramsPerMonth = totalCo2eGramsPerMonth + embodiedCo2eGramsPerMonth;
const totalCostUsdPerMonth = pricePerHour * hours;
const confidence: ConfidenceLevel = input.avgUtilization !== undefined ? 'MEDIUM' : 'HIGH';
return {
totalCo2eGramsPerMonth,
embodiedCo2eGramsPerMonth,
totalLifecycleCo2eGramsPerMonth,
waterLitresPerMonth,
totalCostUsdPerMonth,
confidence,
scope: 'SCOPE_2_AND_3',
assumptionsApplied: {
utilizationApplied: utilization,
gridIntensityApplied: regionData.grid_intensity_gco2e_per_kwh,
powerModelUsed: powerModel,
embodiedCo2ePerVcpuPerMonthApplied: instanceData.embodied_co2e_grams_per_month,
waterIntensityLitresPerKwhApplied: regionData.water_intensity_litres_per_kwh,
memoryWattsApplied: instanceData.memory_gb * MEMORY_WATTS_PER_GB,
},
};
}
export function generateRecommendation(
input: ResourceInput,
baseline: EmissionAndCostEstimate,
ledger: Ledger = factorsData as Ledger
): UpgradeRecommendation | null {
if (baseline.confidence === 'LOW_ASSUMED_DEFAULT') return null;
const provider: CloudProvider = input.provider ?? 'aws';
const providerLedger = ledger[provider];
const candidates: UpgradeRecommendation[] = [];
const armAlternative = getArmAlternative(input.instanceType, provider, ledger);
if (armAlternative) {
const armEstimate = calculateBaseline({ ...input, instanceType: armAlternative }, ledger);
if (armEstimate.confidence !== 'LOW_ASSUMED_DEFAULT') {
const co2Delta = armEstimate.totalCo2eGramsPerMonth - baseline.totalCo2eGramsPerMonth;
const costDelta = armEstimate.totalCostUsdPerMonth - baseline.totalCostUsdPerMonth;
const embodiedDelta = armEstimate.embodiedCo2eGramsPerMonth - baseline.embodiedCo2eGramsPerMonth;
if (co2Delta < 0 && costDelta < 0) {
const embodiedNote = embodiedDelta < 0
? ` ARM also reduces embodied (Scope 3) carbon by ${Math.abs(Math.round(embodiedDelta))}g CO2e/month.` : '';
candidates.push({
suggestedInstanceType: armAlternative,
co2eDeltaGramsPerMonth: co2Delta,
costDeltaUsdPerMonth: costDelta,
rationale: `Switching from ${input.instanceType} to ${armAlternative} (ARM) provides identical vCPU and memory at lower power draw, saving ${Math.abs(Math.round(co2Delta))}g CO2e/month and $${Math.abs(costDelta).toFixed(2)}/month.${embodiedNote}`,
});
}
}
}
const cleanerRegion = getCleanerRegion(input.region, input.instanceType, provider, ledger);
if (cleanerRegion) {
const regionEstimate = calculateBaseline({ ...input, region: cleanerRegion }, ledger);
if (regionEstimate.confidence !== 'LOW_ASSUMED_DEFAULT') {
const co2Delta = regionEstimate.totalCo2eGramsPerMonth - baseline.totalCo2eGramsPerMonth;
const costDelta = regionEstimate.totalCostUsdPerMonth - baseline.totalCostUsdPerMonth;
const co2ReductionPct = baseline.totalCo2eGramsPerMonth > 0
? Math.abs(co2Delta) / baseline.totalCo2eGramsPerMonth : 0;
if (co2Delta < 0 && co2ReductionPct > 0.15) {
const regionName = providerLedger.regions[cleanerRegion]?.location ?? cleanerRegion;
const costNote = costDelta > 0
? ` (note: cost increases by $${costDelta.toFixed(2)}/month)`
: ` saving $${Math.abs(costDelta).toFixed(2)}/month`;
const waterDelta = regionEstimate.waterLitresPerMonth - baseline.waterLitresPerMonth;
const waterNote = waterDelta < -0.1
? ` Water consumption also decreases by ${Math.abs(waterDelta).toFixed(1)}L/month.` : '';
candidates.push({
suggestedRegion: cleanerRegion,
co2eDeltaGramsPerMonth: co2Delta,
costDeltaUsdPerMonth: costDelta,
rationale: `Moving ${input.instanceType} from ${input.region} to ${regionName} (${cleanerRegion}) reduces grid carbon intensity from ${providerLedger.regions[input.region]?.grid_intensity_gco2e_per_kwh}g to ${providerLedger.regions[cleanerRegion]?.grid_intensity_gco2e_per_kwh}g CO2e/kWh, saving ${Math.abs(Math.round(co2Delta))}g CO2e/month${costNote}.${waterNote}`,
});
}
}
}
if (candidates.length === 0) return null;
const scored = candidates.map((rec) => {
const co2Pct = baseline.totalCo2eGramsPerMonth > 0
? Math.abs(rec.co2eDeltaGramsPerMonth) / baseline.totalCo2eGramsPerMonth : 0;
const costPct = baseline.totalCostUsdPerMonth > 0
? Math.abs(rec.costDeltaUsdPerMonth) / baseline.totalCostUsdPerMonth : 0;
return { rec, score: co2Pct * 0.6 + costPct * 0.4 };
});
scored.sort((a, b) => b.score - a.score);
return scored[0].rec;
}
export function analysePlan(
resources: ResourceInput[],
skipped: PlanAnalysisResult['skipped'],
planFile: string,
ledger: Ledger = factorsData as Ledger,
unsupportedTypes: string[] = []
): PlanAnalysisResult {
const analysedResources: PlanAnalysisResult['resources'] = resources.map((input) => {
const baseline = calculateBaseline(input, ledger);
const recommendation = generateRecommendation(input, baseline, ledger);
return { input, baseline, recommendation };
});
const totals = analysedResources.reduce(
(acc, { baseline, recommendation }) => {
acc.currentCo2eGramsPerMonth += baseline.totalCo2eGramsPerMonth;
acc.currentEmbodiedCo2eGramsPerMonth += baseline.embodiedCo2eGramsPerMonth;
acc.currentLifecycleCo2eGramsPerMonth += baseline.totalLifecycleCo2eGramsPerMonth;
acc.currentWaterLitresPerMonth += baseline.waterLitresPerMonth;
acc.currentCostUsdPerMonth += baseline.totalCostUsdPerMonth;
if (recommendation) {
acc.potentialCo2eSavingGramsPerMonth += Math.abs(recommendation.co2eDeltaGramsPerMonth);
acc.potentialCostSavingUsdPerMonth += Math.abs(recommendation.costDeltaUsdPerMonth);
}
return acc;
},
{
currentCo2eGramsPerMonth: 0,
currentEmbodiedCo2eGramsPerMonth: 0,
currentLifecycleCo2eGramsPerMonth: 0,
currentWaterLitresPerMonth: 0,
currentCostUsdPerMonth: 0,
potentialCo2eSavingGramsPerMonth: 0,
potentialCostSavingUsdPerMonth: 0,
}
);
const providers = [...new Set(resources.map(r => r.provider ?? 'aws'))] as CloudProvider[];
return {
analysedAt: new Date().toISOString(),
ledgerVersion: ledger.metadata.ledger_version,
planFile,
providers: providers.length > 0 ? providers : ['aws'],
resources: analysedResources,
skipped,
unsupportedTypes,
totals,
};
}