- main
- manifest
- deps
- main
- Install
- Run
import { Backend } from "fastly:backend";
addEventListener("fetch", event => event.respondWith(handleRequest(event)))
async function handleRequest(event) {
const req = event.request;
const backendNames = ["origin_0", "origin_1"];
shuffle(backendNames)
let backend = null;
for (const backendName of backendNames) {
let theBackend = Backend.fromName(backendName);
if (theBackend.health() == "healthy") {
console.log(`Found healthy backend: ${backendName}`);
backend = theBackend;
break;
}
console.log(`Backend ${backendName} is not explicitly healthy, trying next...`);
}
if (backend == null) {
console.log("All backends are unhealthy or unknown!");
return new Response("Service Unavailable: No healthy backends available.", {
status: 503,
});
}
console.log("Sending request...");
return await fetch(req, {
backend,
});
}
function shuffle(array) {
let i = array.length, j, temp;
while (--i > 0) {
j = Math.floor(Math.random () * (i+1));
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}