-
-
Notifications
You must be signed in to change notification settings - Fork 628
Expand file tree
/
Copy pathindex.js
More file actions
266 lines (239 loc) · 8.1 KB
/
Copy pathindex.js
File metadata and controls
266 lines (239 loc) · 8.1 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
import { resolve, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import fs from 'node:fs';
import zlib from 'node:zlib';
import { promisify } from 'node:util';
import intel from 'intel';
import { co2, hosting } from '@tgwf/co2';
import { SitespeedioPlugin } from '@sitespeed.io/plugin';
import { Aggregator } from './aggregator.js';
import {
getDirtiestResources,
perParty,
perContentType,
perPage,
perDomain
} from './helper.js';
const fsp = fs.promises;
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const packageJson = JSON.parse(
await fsp.readFile(resolve(join(__dirname, '..', '..', '..', 'package.json')))
);
const co2Version = packageJson.dependencies['@tgwf/co2'];
const gunzip = promisify(zlib.gunzip);
const log = intel.getLogger('sitespeedio.plugin.sustainable');
const DEFAULT_METRICS_PAGE_SUMMARY = [
'co2PerPageView',
'totalCO2',
'co2FirstParty',
'co2ThirdParty'
];
async function streamToString(stream) {
return new Promise((resolve, reject) => {
const chunks = [];
stream.on('error', reject);
stream.on('data', chunk => chunks.push(chunk));
stream.on('end', () => resolve(Buffer.concat(chunks)));
});
}
async function getGzippedFileAsJson(jsonPath) {
const readStream = fs.createReadStream(jsonPath);
const text = await streamToString(readStream);
const unzipped = await gunzip(text);
return unzipped.toString();
}
async function loadJSON(jsonPath) {
const jsonBuffer = jsonPath.endsWith('.gz')
? await getGzippedFileAsJson(jsonPath)
: await fsp.readFile(jsonPath);
return JSON.parse(jsonBuffer);
}
export default class SustainablePlugin extends SitespeedioPlugin {
constructor(options, context, queue) {
super({ name: 'sustainable', options, context, queue });
}
async open(context, options) {
this.storageManager = context.storageManager;
this.options = options;
this.sustainableOptions = options.sustainable || {};
this.make = context.messageMaker('sustainable').make;
this.pug = await fsp.readFile(
resolve(__dirname, 'pug', 'index.pug'),
'utf8'
);
this.aggregator = new Aggregator(options);
this.firstRunsData = {};
context.filterRegistry.registerFilterForType(
DEFAULT_METRICS_PAGE_SUMMARY,
'sustainable.pageSummary'
);
}
async processMessage(message, queue) {
const make = this.make;
const aggregator = this.aggregator;
switch (message.type) {
// When sitespeed.io starts, it sends a setup message on the queue
// That way, we can tell other plugins we exist (sustainable.setup)
// so others could build upon our data
// ... and we also register the pug file(s) for the HTML output
case 'sitespeedio.setup': {
queue.postMessage(make('sustainable.setup'));
// Add the HTML pugs
queue.postMessage(
make('html.pug', {
id: 'sustainable',
name: 'Sustainable Web',
pug: this.pug,
type: 'pageSummary'
})
);
queue.postMessage(
make('html.pug', {
id: 'sustainable',
name: 'Sustainable Web',
pug: this.pug,
type: 'run'
})
);
log.info(
'Use the sustainable web plugin with model %s',
this.sustainableOptions.model
);
break;
}
case 'pagexray.run': {
// We got data for a URL, lets calculate co2, check green servers etc
const listOfDomains = Object.keys(message.data.domains);
const greenDomainJSONpath = join(
__dirname,
'data',
'url2green.json.gz'
);
let hostingGreenCheck;
if (this.sustainableOptions.disableHosting === true) {
hostingGreenCheck = [];
} else {
hostingGreenCheck =
this.sustainableOptions.useGreenWebHostingAPI === true
? await hosting.check(listOfDomains)
: await hosting.check(
listOfDomains,
await loadJSON(greenDomainJSONpath)
);
}
const CO2 = new co2(this.sustainableOptions.model);
const co2PerDomain = perDomain(message.data, hostingGreenCheck, CO2);
const baseDomain = message.data.baseDomain;
const hostingInfo = {
green: false,
url: baseDomain
};
// is the base domain in our list of green domains?
if (hostingGreenCheck.includes(baseDomain)) {
hostingInfo.green = true;
}
const co2PerParty = perParty(message.data, hostingGreenCheck, CO2);
// Fetch the resources with the largest CO2 impact. ie,
// the resources to optimise, host somewhere green, or contact
// a supplier about
const dirtiestResources = getDirtiestResources(
message.data,
hostingGreenCheck,
CO2
);
const co2PerContentType = perContentType(
message.data,
hostingGreenCheck,
CO2
);
const co2PerPageView = perPage(message.data, hostingGreenCheck, CO2);
const totalCO2 = this.sustainableOptions.pageViews
? this.sustainableOptions.pageViews * co2PerPageView
: co2PerPageView;
const transferPerPage = message.data.transferSize;
const firstPartyTransferPerPage = message.data.firstParty.transferSize;
const thirdPartyTransferPerPage = message.data.thirdParty.transferSize;
// adding these to make the link between data and CO2 clearer
// and also so we can give an idea how big this is compared to
// the norm
// let transfer1stParty, transfer3rdParty;
if (message.iteration === 1) {
this.firstRunsData[message.url] = {
co2PerDomain,
co2PerContentType,
dirtiestResources,
hostingGreenCheck
};
}
// We get data per run, so we want to aggregate that per page (multiple runs per page)
// and per group/domain
aggregator.addStats(
{
co2PerDomain,
co2PerPageView,
co2PerParty,
hostingInfo,
totalCO2,
transferPerPage,
firstPartyTransferPerPage,
thirdPartyTransferPerPage
},
message.group,
message.url
);
// We pass on the data we have, so the that HTML plugin can generate the HTML tab
// per run
queue.postMessage(
make(
'sustainable.run',
{
co2PerPageView,
totalCO2,
hostingInfo,
co2PerDomain,
totalTransfer: transferPerPage,
firstPartyTransferPerPage,
thirdPartyTransferPerPage,
co2FirstParty: co2PerParty.firstParty,
co2ThirdParty: co2PerParty.thirdParty,
hostingGreenCheck,
dirtiestResources,
co2PerContentType,
co2Version
},
{
url: message.url,
group: message.group,
runIndex: message.runIndex
}
)
); // Here we put the data that we got from that run
break;
}
case 'sitespeedio.summarize': {
// All URLs has been tested, now calculate the min/median/max c02 per page
// and push that info on the queue
const summaries = aggregator.summarize();
// Send each URL
for (let url of Object.keys(summaries.urls)) {
const extras = this.firstRunsData[url];
// Attach first run so we can show that extra data that we don't collect stats for
summaries.urls[url].firstRun = extras;
summaries.urls[url].co2Version = co2Version;
queue.postMessage(
make('sustainable.pageSummary', summaries.urls[url], {
url: url,
group: summaries.urlToGroup[url]
})
);
}
queue.postMessage(
make('sustainable.summary', summaries.groups['total'], {
group: 'total'
})
);
break;
}
}
}
}