scratch-www/bin/configure-fastly.js

292 lines
12 KiB
JavaScript
Raw Permalink Normal View History

2024-01-17 15:40:27 -05:00
const async = require('async');
const defaults = require('lodash.defaults');
const fastlyConfig = require('./lib/fastly-config-methods');
const languages = require('scratch-l10n').default;
2024-01-17 15:40:27 -05:00
const routeJson = require('../src/routes.json');
const FASTLY_SERVICE_ID = process.env.FASTLY_SERVICE_ID || '';
const S3_BUCKET_NAME = process.env.S3_BUCKET_NAME || '';
const RADISH_URL = process.env.RADISH_URL || '';
2024-01-17 15:40:27 -05:00
const fastly = require('./lib/fastly-extended')(process.env.FASTLY_API_KEY, FASTLY_SERVICE_ID);
2024-01-17 15:40:27 -05:00
const extraAppRoutes = [
// Homepage with querystring.
// TODO: Should this be added for every route?
'/\\?',
// View html
'/[^/]*.html$'
];
const routeJsonPreProcessed = routeJson.map(
2024-05-20 23:12:17 -04:00
route => {
if (route.redirect) {
2024-05-21 00:31:38 -04:00
process.stdout.write(`Updating: ${route.redirect} to `);
2024-05-21 01:00:50 -04:00
route.redirect = route.redirect.replace('RADISH_URL', RADISH_URL);
2024-05-21 00:31:38 -04:00
process.stdout.write(`${route.redirect}\n`);
}
return route;
}
);
const routes = routeJsonPreProcessed.map(
2024-01-17 15:40:27 -05:00
route => defaults({}, {pattern: fastlyConfig.expressPatternToRegex(route.pattern)}, route)
);
async.auto({
2016-04-18 14:07:27 -04:00
version: function (cb) {
2024-01-17 15:40:27 -05:00
fastly.getLatestActiveVersion((err, response) => {
if (err) return cb(err);
// Validate latest version before continuing
2016-04-19 13:04:45 -04:00
if (response.active || response.locked) {
2024-01-17 15:40:27 -05:00
fastly.cloneVersion(response.number, (e, resp) => {
if (e) return cb(`Failed to clone latest version: ${e}`);
cb(null, resp.number);
2016-04-19 13:04:45 -04:00
});
} else {
cb(null, response.number);
}
});
},
recvCustomVCL: ['version', function (results, cb) {
// For all the routes in routes.json, construct a varnish-style regex that matches
// on any of those route conditions.
2024-01-17 15:40:27 -05:00
const notPassStatement = fastlyConfig.getAppRouteCondition('../build/*', routes, extraAppRoutes, __dirname);
// For a non-pass condition, point backend at s3
2024-01-17 15:40:27 -05:00
const recvCondition = `${'' +
'if ('}${notPassStatement}) {\n` +
` set req.backend = F_s3;\n` +
` set req.http.host = "${S3_BUCKET_NAME}";\n` +
`} else {\n` +
` if (!req.http.Fastly-FF) {\n` +
` if (req.http.X-Forwarded-For) {\n` +
` set req.http.Fastly-Temp-XFF = req.http.X-Forwarded-For ", " client.ip;\n` +
` } else {\n` +
` set req.http.Fastly-Temp-XFF = client.ip;\n` +
` }\n` +
` } else {\n` +
` set req.http.Fastly-Temp-XFF = req.http.X-Forwarded-For;\n` +
` }\n` +
` set req.grace = 60s;\n` +
` if (req.http.Cookie:scratchlanguage) {\n` +
` set req.http.Accept-Language = req.http.Cookie:scratchlanguage;\n` +
` } else {\n` +
` set req.http.Accept-Language = accept.language_lookup("${
Object.keys(languages).join(':')}", ` +
`"en", ` +
`std.tolower(req.http.Accept-Language)` +
`);\n` +
` }\n` +
` if (req.url ~ "^(/projects/|/fragment/account-nav.json|/session/)" && ` +
`!req.http.Cookie:scratchsessionsid) {\n` +
` set req.http.Cookie = "scratchlanguage=" req.http.Cookie:scratchlanguage;\n` +
` } else {\n` +
` return(pass);\n` +
` }\n` +
`}\n`;
fastly.setCustomVCL(
results.version,
'recv-condition',
recvCondition,
cb
);
}],
fetchCustomVCL: ['version', function (results, cb) {
2024-01-17 15:40:27 -05:00
const passStatement = fastlyConfig.negateConditionStatement(
fastlyConfig.getAppRouteCondition('../build/*', routes, extraAppRoutes, __dirname)
);
2024-01-17 15:40:27 -05:00
const ttlCondition = fastlyConfig.setResponseTTL(passStatement);
fastly.setCustomVCL(results.version, 'fetch-condition', ttlCondition, cb);
}],
appRouteRequestConditions: ['version', function (results, cb) {
2024-01-17 15:40:27 -05:00
const conditions = {};
async.forEachOf(routes, (route, id, cb2) => {
const condition = {
name: fastlyConfig.getConditionNameForRoute(route, 'request'),
2024-01-17 15:40:27 -05:00
statement: `req.url.path ~ "${route.pattern}"`,
type: 'REQUEST',
// Priority needs to be > 1 to not interact with http->https redirect
priority: 10 + id
};
2024-01-17 15:40:27 -05:00
fastly.setCondition(results.version, condition, (err, response) => {
if (err) return cb2(err);
conditions[id] = response;
cb2(null, response);
});
2024-01-17 15:40:27 -05:00
}, err => {
if (err) return cb(err);
cb(null, conditions);
});
}],
appRouteHeaders: ['version', 'appRouteRequestConditions', function (results, cb) {
2024-01-17 15:40:27 -05:00
const headers = {};
async.forEachOf(routes, (route, id, cb2) => {
2016-04-19 18:42:03 -04:00
if (route.redirect) {
async.auto({
responseCondition: function (cb3) {
2024-01-17 15:40:27 -05:00
const condition = {
name: fastlyConfig.getConditionNameForRoute(route, 'response'),
2024-01-17 15:40:27 -05:00
statement: `req.url.path ~ "${route.pattern}"`,
2016-04-19 18:42:03 -04:00
type: 'RESPONSE',
priority: id
};
fastly.setCondition(results.version, condition, cb3);
},
responseObject: function (cb3) {
2024-01-17 15:40:27 -05:00
const responseObject = {
name: fastlyConfig.getResponseNameForRoute(route),
2016-04-19 18:42:03 -04:00
status: 301,
response: 'Moved Permanently',
request_condition: fastlyConfig.getConditionNameForRoute(route, 'request')
2016-04-19 18:42:03 -04:00
};
fastly.setResponseObject(results.version, responseObject, cb3);
},
redirectHeader: ['responseCondition', function (redirectResults, cb3) {
2024-01-17 15:40:27 -05:00
const header = {
name: fastlyConfig.getHeaderNameForRoute(route),
2016-04-19 18:42:03 -04:00
action: 'set',
ignore_if_set: 0,
type: 'RESPONSE',
dst: 'http.Location',
2024-01-17 15:40:27 -05:00
src: `"${route.redirect}"`,
2016-04-19 18:42:03 -04:00
response_condition: redirectResults.responseCondition.name
};
fastly.setFastlyHeader(results.version, header, cb3);
}]
2024-01-17 15:40:27 -05:00
}, (err, redirectResults) => {
2016-04-19 18:42:03 -04:00
if (err) return cb2(err);
headers[id] = redirectResults.redirectHeader;
cb2(null, redirectResults);
});
} else {
2024-01-17 15:40:27 -05:00
const header = {
name: fastlyConfig.getHeaderNameForRoute(route, 'request'),
2016-04-19 18:42:03 -04:00
action: 'set',
ignore_if_set: 0,
type: 'REQUEST',
dst: 'url',
2024-01-17 15:40:27 -05:00
src: `"/${route.name}.html"`,
2016-04-19 18:42:03 -04:00
request_condition: results.appRouteRequestConditions[id].name,
priority: 10
};
2024-01-17 15:40:27 -05:00
fastly.setFastlyHeader(results.version, header, (err, response) => {
2016-04-19 18:42:03 -04:00
if (err) return cb2(err);
headers[id] = response;
cb2(null, response);
});
}
2024-01-17 15:40:27 -05:00
}, err => {
if (err) return cb(err);
cb(null, headers);
2016-04-18 14:07:27 -04:00
});
}],
tipbarRedirectHeaders: ['version', function (results, cb) {
async.auto({
requestCondition: function (cb2) {
2024-01-17 15:40:27 -05:00
const condition = {
name: 'routes/?tip_bar= (request)',
statement: 'req.url ~ "\\?tip_bar="',
type: 'REQUEST',
priority: 10
};
fastly.setCondition(results.version, condition, cb2);
},
responseCondition: function (cb2) {
2024-01-17 15:40:27 -05:00
const condition = {
name: 'routes/?tip_bar= (response)',
statement: 'req.url ~ "\\?tip_bar="',
type: 'RESPONSE',
priority: 10
};
fastly.setCondition(results.version, condition, cb2);
},
responseObject: ['requestCondition', function (redirectResults, cb2) {
2024-01-17 15:40:27 -05:00
const responseObject = {
name: 'redirects/?tip_bar=',
status: 301,
response: 'Moved Permanently',
request_condition: redirectResults.requestCondition.name
};
fastly.setResponseObject(results.version, responseObject, cb2);
}],
redirectHeader: ['responseCondition', function (redirectResults, cb2) {
2024-01-17 15:40:27 -05:00
const header = {
name: 'redirects/?tip_bar=',
action: 'set',
ignore_if_set: 0,
type: 'RESPONSE',
dst: 'http.Location',
src: 'regsub(req.url, "tip_bar=", "tutorial=")',
response_condition: redirectResults.responseCondition.name
};
fastly.setFastlyHeader(results.version, header, cb2);
}]
2024-01-17 15:40:27 -05:00
}, (err, redirectResults) => {
if (err) return cb(err);
cb(null, redirectResults);
});
}],
embedRedirectHeaders: ['version', function (results, cb) {
async.auto({
requestCondition: function (cb2) {
2024-01-17 15:40:27 -05:00
const condition = {
name: 'routes/projects/embed (request)',
statement: 'req.url.path ~ "^/projects/embed/(\\d+)"',
type: 'REQUEST',
priority: 10
};
fastly.setCondition(results.version, condition, cb2);
},
responseCondition: function (cb2) {
2024-01-17 15:40:27 -05:00
const condition = {
name: 'routes/projects/embed (response)',
statement: 'req.url.path ~ "^/projects/embed/(\\d+)"',
type: 'RESPONSE',
priority: 10
};
fastly.setCondition(results.version, condition, cb2);
},
responseObject: ['requestCondition', function (redirectResults, cb2) {
2024-01-17 15:40:27 -05:00
const responseObject = {
name: 'redirects/projects/embed',
status: 301,
response: 'Moved Permanently',
request_condition: redirectResults.requestCondition.name
};
fastly.setResponseObject(results.version, responseObject, cb2);
}],
redirectHeader: ['responseCondition', function (redirectResults, cb2) {
2024-01-17 15:40:27 -05:00
const header = {
name: 'redirects/projects/embed',
action: 'set',
ignore_if_set: 0,
type: 'RESPONSE',
dst: 'http.Location',
src: '"/projects/" + re.group.1 + "/embed"',
response_condition: redirectResults.responseCondition.name
};
fastly.setFastlyHeader(results.version, header, cb2);
}]
2024-01-17 15:40:27 -05:00
}, (err, redirectResults) => {
if (err) return cb(err);
cb(null, redirectResults);
});
}]
2024-01-17 15:40:27 -05:00
}, (err, results) => {
if (err) throw new Error(err);
if (process.env.FASTLY_ACTIVATE_CHANGES) {
2024-01-17 15:40:27 -05:00
fastly.activateVersion(results.version, (e, resp) => {
if (e) throw new Error(e);
2024-01-17 15:40:27 -05:00
process.stdout.write(`Successfully configured and activated version ${resp.number}\n`);
2021-05-14 19:17:22 -04:00
// purge static-assets using surrogate key
2024-01-17 15:40:27 -05:00
fastly.purgeKey(FASTLY_SERVICE_ID, 'static-assets', error => {
if (error) throw new Error(error);
process.stdout.write('Purged static assets.\n');
});
});
}
});