Skip to content

Commit ce12527

Browse files
committed
build: payload github status
* Show payload deta on PRs using the Github Statuses API.
1 parent aafa6b0 commit ce12527

File tree

3 files changed

+103
-18
lines changed

3 files changed

+103
-18
lines changed

tools/gulp/tasks/payload.ts

Lines changed: 89 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
import {task} from 'gulp';
22
import {join} from 'path';
33
import {statSync} from 'fs';
4-
import {spawnSync} from 'child_process';
5-
import {isTravisMasterBuild} from '../util/travis-ci';
4+
import {isTravisBuild, isTravisMasterBuild} from '../util/travis-ci';
65
import {openFirebaseDashboardApp} from '../util/firebase';
76
import {buildConfig} from '../packaging/build-config';
87

8+
// These imports lack of type definitions.
9+
const request = require('request');
10+
911
/** Path to the directory where all bundles are living. */
1012
const bundlesDir = join(buildConfig.outputDir, 'bundles');
1113

1214
/** Task which runs test against the size of material. */
13-
task('payload', ['material:clean-build'], () => {
15+
task('payload', ['material:clean-build'], async () => {
1416

15-
let results = {
17+
const results = {
1618
timestamp: Date.now(),
1719
// Material bundles
1820
material_umd: getBundleSize('material.umd.js'),
@@ -29,9 +31,21 @@ task('payload', ['material:clean-build'], () => {
2931
// Print the results to the console, so we can read it from the CI.
3032
console.log('Payload Results:', JSON.stringify(results, null, 2));
3133

32-
// Publish the results to firebase when it runs on Travis and not as a PR.
33-
if (isTravisMasterBuild()) {
34-
return publishResults(results);
34+
if (isTravisBuild()) {
35+
// Open a connection to Firebase. For PRs the connection will be established as a guest.
36+
const firebaseApp = openFirebaseDashboardApp(!isTravisMasterBuild());
37+
const database = firebaseApp.database();
38+
const currentSha = process.env['TRAVIS_PULL_REQUEST_SHA'] || process.env['TRAVIS_COMMIT'];
39+
40+
// Upload the payload results and calculate the payload diff in parallel. Otherwise the
41+
// payload task will take much more time inside of Travis builds.
42+
await Promise.all([
43+
uploadPayloadResults(database, currentSha, results),
44+
calculatePayloadDiff(database, currentSha, results)
45+
]);
46+
47+
// Disconnect database connection because Firebase otherwise prevents Gulp from exiting.
48+
firebaseApp.delete();
3549
}
3650

3751
});
@@ -46,14 +60,73 @@ function getFilesize(filePath: string) {
4660
return statSync(filePath).size / 1000;
4761
}
4862

49-
/** Publishes the given results to the firebase database. */
50-
function publishResults(results: any) {
51-
const latestSha = spawnSync('git', ['rev-parse', 'HEAD']).stdout.toString().trim();
52-
const dashboardApp = openFirebaseDashboardApp();
53-
const database = dashboardApp.database();
63+
/**
64+
* Calculates the difference between the last and current library payload.
65+
* The results will be published as a commit status on Github.
66+
*/
67+
async function calculatePayloadDiff(database: any, currentSha: string, currentPayload: any) {
68+
const authToken = process.env['FIREBASE_ACCESS_TOKEN'];
69+
70+
if (!authToken) {
71+
console.error('Cannot calculate Payload diff because there is no "FIREBASE_ACCESS_TOKEN" ' +
72+
'environment variable set.');
73+
return;
74+
}
75+
76+
const previousPayload = await getLastPayloadResults(database);
77+
78+
// Calculate library sizes by combining the CDK and Material FESM 2015 bundles.
79+
const previousSize = previousPayload.cdk_fesm_2015 + previousPayload.material_fesm_2015;
80+
const currentSize = currentPayload.cdk_fesm_2015 + currentPayload.material_fesm_2015;
81+
const deltaSize = currentSize - previousSize;
82+
83+
// Update the Github status of the current commit by sending a request to the dashboard
84+
// firebase http trigger function.
85+
await updateGithubStatus(currentSha, deltaSize, authToken);
86+
}
87+
88+
/**
89+
* Updates the Github status of a given commit by sending a request to a Firebase function of
90+
* the dashboard. The function has access to the Github repository and can set status for PRs too.
91+
*/
92+
async function updateGithubStatus(commitSha: string, payloadDiff: number, authToken: string) {
93+
const options = {
94+
url: 'https://us-central1-material2-dashboard.cloudfunctions.net/payloadGithubStatus',
95+
headers: {
96+
'User-Agent': 'Material2/PayloadTask',
97+
'auth-token': authToken,
98+
'commit-sha': commitSha,
99+
'commit-payload-diff': payloadDiff
100+
}
101+
};
102+
103+
return new Promise((resolve, reject) => {
104+
request(options, (err: any, response: any, body: string) => {
105+
if (err) {
106+
reject(`Dashboard Error ${err.toString()}`);
107+
} else {
108+
console.info('Dashboard Response: ', JSON.parse(body).message);
109+
resolve(response.statusCode);
110+
}
111+
});
112+
});
113+
}
114+
115+
/** Uploads the current payload results to the Dashboard database. */
116+
async function uploadPayloadResults(database: any, currentSha: string, currentPayload: any) {
117+
if (isTravisMasterBuild()) {
118+
await database.ref('payloads').child(currentSha).set(currentPayload);
119+
}
120+
}
121+
122+
/** Gets the last payload uploaded from previous Travis builds. */
123+
async function getLastPayloadResults(database: admin.database.Database) {
124+
const snapshot = await database.ref('payloads')
125+
.orderByChild('timestamp')
126+
.limitToLast(1)
127+
.once('value');
54128

55-
// Write the results to the payloads object with the latest Git SHA as key.
56-
return database.ref('payloads').child(latestSha).set(results)
57-
.catch((err: any) => console.error(err))
58-
.then(() => dashboardApp.delete());
129+
// The value of the DataSnapshot is an object with the SHA as a key. Only return the
130+
// value of the object because the SHA is not necessary.
131+
return snapshot.val()[Object.keys(snapshot.val())[0]];
59132
}

tools/gulp/util/firebase.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,26 @@ const cloudStorage = require('@google-cloud/storage');
66
const screenshotFirebaseConfig = require('../../screenshot-test/functions/config.json');
77

88
/** Opens a connection to the Firebase dashboard app. */
9-
export function openFirebaseDashboardApp() {
9+
export function openFirebaseDashboardApp(asGuest = false) {
10+
const databaseURL = 'https://material2-board.firebaseio.com';
11+
12+
// In some situations the service account credentials are not available and authorizing as
13+
// a guest works fine. For example in Pull Requests the payload task just wants to read data.
14+
if (asGuest) {
15+
return firebase.initializeApp({ databaseURL });
16+
}
17+
1018
// Initialize the Firebase application with firebaseAdmin credentials.
1119
// Credentials need to be for a Service Account, which can be created in the Firebase console.
1220
return firebaseAdmin.initializeApp({
21+
databaseURL,
1322
credential: firebaseAdmin.credential.cert({
1423
project_id: 'material2-board',
1524
client_email: '[email protected]',
1625
// In Travis CI the private key will be incorrect because the line-breaks are escaped.
1726
// The line-breaks need to persist in the service account private key.
1827
private_key: decode(process.env['MATERIAL2_BOARD_FIREBASE_SERVICE_KEY'])
1928
}),
20-
databaseURL: 'https://material2-board.firebaseio.com'
2129
});
2230
}
2331

tools/gulp/util/travis-ci.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,7 @@
22
export function isTravisMasterBuild() {
33
return process.env['TRAVIS_PULL_REQUEST'] === 'false';
44
}
5+
6+
export function isTravisBuild() {
7+
return process.env['TRAVIS'] === 'true';
8+
}

0 commit comments

Comments
 (0)