2021-05-13 18:03:56 -07:00
|
|
|
/**
|
|
|
|
* /api/outfitImage returns an image of an outfit!
|
|
|
|
*
|
|
|
|
* Parameters:
|
2021-05-14 19:54:18 -07:00
|
|
|
* - size: Must be "150", "300", or "600", to indicate the image size you'd
|
|
|
|
* like back. (For example, "150" will return a 150x150 image.)
|
2021-05-13 18:03:56 -07:00
|
|
|
* - layerUrls: A comma-separated list of URLs to render, in order from
|
|
|
|
* bottom to top. This is a sorta "independent" render mode,
|
|
|
|
* not bound to any saved outfit. The URLs must match a known
|
2021-05-26 19:44:35 -07:00
|
|
|
* layer URL format. This mode will return a long-term cache
|
|
|
|
* header, so the client and our CDN cache can cache the
|
|
|
|
* requested URL forever. (NOTE: The Vercel cache seems pretty
|
|
|
|
* quick to eject them, though...)
|
2021-05-13 18:03:56 -07:00
|
|
|
* - id: Instead of `layerUrls`, you can instead provide an outfit ID, which
|
2021-05-26 19:44:35 -07:00
|
|
|
* will load the outfit data and render it directly. By default, this
|
|
|
|
* will return a 10-minute cache header, to keep individual users from
|
|
|
|
* re-loading the image from scratch too often, while still keeping it
|
|
|
|
* relatively fresh. (If you provide `updatedAt` too, we cache it for
|
|
|
|
* longer!)
|
|
|
|
* - updatedAt: If you provide an `id`, you may also provide `updatedAt`:
|
2021-05-13 18:03:56 -07:00
|
|
|
* the UNIX timestamp for when the outfit was last updated. This
|
2021-05-26 19:44:35 -07:00
|
|
|
* has no effect on image output, but it enables us to return a
|
|
|
|
* long-term cache header, so the client and our CDN cache can
|
|
|
|
* cache the requested URL forever. (NOTE: The Vercel cache
|
|
|
|
* seems pretty quick to eject them, though...)
|
2021-05-13 18:03:56 -07:00
|
|
|
*/
|
2021-01-03 20:21:34 -08:00
|
|
|
const beeline = require("honeycomb-beeline")({
|
|
|
|
writeKey: process.env["HONEYCOMB_WRITE_KEY"],
|
|
|
|
dataset:
|
|
|
|
process.env["NODE_ENV"] === "production"
|
|
|
|
? "Dress to Impress (2020)"
|
|
|
|
: "Dress to Impress (2020, dev)",
|
|
|
|
serviceName: "impress-2020-gql-server",
|
Apply sampling rates to Honeycomb events
Oops, we get a _lot_ of outfit image requests, and it's pushing the limits of our free Honeycomb plan! But I don't really need all that much detail, because there's so many.
So, we here apply sampling! `api/outfitImage` is getting a 1/10 rate, and for GraphQL, `ApiOutfitImage` is getting 1/10, and `SearchPanel` is getting 1/5.
I had to add a `addTraceContext` call, to give all the child events awareness of what operation they're being called in, too!
I haven't actually tested that this is working-working, just that the endpoints still return good data. We'll see how it shakes out in prod!
But I did add `console.log(sampleRate, shouldSample, data);` to the `samplerHook` briefly, to see the data flow through, and I reloaded a `SearchPanel` request a few times and observed a plausibly 20% success rate.
2021-05-26 18:50:19 -07:00
|
|
|
sampleRate: 10,
|
2021-01-03 20:21:34 -08:00
|
|
|
});
|
|
|
|
|
2021-05-13 18:03:56 -07:00
|
|
|
import gql from "graphql-tag";
|
2021-11-12 21:53:07 -08:00
|
|
|
import { ApolloServer } from "apollo-server";
|
|
|
|
import { createTestClient } from "apollo-server-testing";
|
2021-05-13 18:03:56 -07:00
|
|
|
|
2021-11-03 17:07:25 -07:00
|
|
|
import connectToDb from "../../src/server/db";
|
2021-11-12 21:53:07 -08:00
|
|
|
import { config as graphqlConfig } from "../../src/server";
|
2021-11-03 17:07:25 -07:00
|
|
|
import { renderOutfitImage } from "../../src/server/outfit-images";
|
2021-05-13 18:03:56 -07:00
|
|
|
import getVisibleLayers, {
|
|
|
|
petAppearanceFragmentForGetVisibleLayers,
|
|
|
|
itemAppearanceFragmentForGetVisibleLayers,
|
2021-11-03 17:07:25 -07:00
|
|
|
} from "../../src/shared/getVisibleLayers";
|
2021-01-03 20:21:34 -08:00
|
|
|
|
2022-08-03 15:06:38 -07:00
|
|
|
// We're overly cautious about what image URLs we're willing to download and
|
|
|
|
// layer together for our output! We'll only accept `layerUrls` that match one
|
|
|
|
// of the following patterns:
|
2021-01-03 21:58:19 -08:00
|
|
|
const VALID_LAYER_URLS = [
|
2022-08-03 15:06:38 -07:00
|
|
|
// Some layers are converted from SWF to PNG by Classic DTI, living on S3.
|
2022-08-03 15:12:42 -07:00
|
|
|
/^https:\/\/(impress-asset-images\.openneo\.net|impress-asset-images\.s3\.amazonaws\.com)\/(biology|object)\/[0-9]{3}\/[0-9]{3}\/[0-9]{3}\/[0-9]+\/(150x150|300x300|600x600)\.png(\?[a-zA-Z0-9_-]+)?$/,
|
2022-08-03 15:06:38 -07:00
|
|
|
|
|
|
|
// Some layers are converted to PNG or SVG by Neopets themselves, extracted
|
|
|
|
// from the manifest file.
|
|
|
|
// TODO: I don't think we serve the `http://` variant of this layer URL
|
|
|
|
// anymore, we could disallow that someday, but I'm keeping it for
|
|
|
|
// compatibility with any potential old caches for now!
|
|
|
|
/^https?:\/\/images\.neopets\.com\/cp\/(bio|object|items)\/data\/[0-9]{3}\/[0-9]{3}\/[0-9]{3}\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+\.(svg|png)(\?.*)?$/,
|
|
|
|
|
|
|
|
// Some layers are converted from HTML5 movie to PNG, by our new system.
|
|
|
|
// NOTE: We don't validate the layer's libraryUrl, because we're expecting
|
|
|
|
// the assetImage endpoint to have its own validation!
|
2021-09-03 13:38:37 -07:00
|
|
|
/^https:\/\/impress-2020\.openneo\.net\/api\/assetImage\?libraryUrl=[^&]+(&size=(150|300|600))?$/,
|
2021-01-03 21:58:19 -08:00
|
|
|
];
|
|
|
|
|
2021-01-03 20:21:34 -08:00
|
|
|
async function handle(req, res) {
|
2021-01-04 00:10:35 -08:00
|
|
|
const size = parseInt(req.query.size);
|
2021-05-14 19:54:18 -07:00
|
|
|
if (size !== 150 && size !== 300 && size !== 600) {
|
|
|
|
return reject(res, `Size must be 150, 300, or 600`);
|
2021-05-13 18:03:56 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
let layerUrls;
|
|
|
|
if (req.query.layerUrls) {
|
|
|
|
layerUrls = req.query.layerUrls.split(",");
|
2021-05-27 18:33:04 -07:00
|
|
|
} else if (req.query.id && req.query.updatedAt) {
|
2021-05-13 18:03:56 -07:00
|
|
|
const outfitId = req.query.id;
|
|
|
|
try {
|
|
|
|
layerUrls = await loadLayerUrlsForSavedOutfit(outfitId, size);
|
|
|
|
} catch (e) {
|
|
|
|
console.error(e);
|
|
|
|
return reject(
|
|
|
|
res,
|
|
|
|
`Error loading data for outfit ${outfitId}: ${e.message}`,
|
|
|
|
500
|
|
|
|
);
|
|
|
|
}
|
2021-05-27 18:33:04 -07:00
|
|
|
} else if (req.query.id) {
|
|
|
|
// If there's an outfit ID, but no `updatedAt`, redirect to the URL with
|
|
|
|
// `updatedAt` added. (NOTE: Our Fastly config will try to handle this
|
|
|
|
// redirect internally, instead of making the user do a round-trip! That
|
|
|
|
// way, we load the version cached at the CDN instead of regenerating it,
|
|
|
|
// if possible.)
|
|
|
|
const outfitId = req.query.id;
|
|
|
|
let updatedAt;
|
|
|
|
try {
|
|
|
|
updatedAt = await loadUpdatedAtForSavedOutfit(outfitId);
|
|
|
|
} catch (e) {
|
|
|
|
return reject(
|
|
|
|
res,
|
|
|
|
`Error loading data for outfit ${outfitId}: ${e.message}`,
|
|
|
|
500
|
|
|
|
);
|
|
|
|
}
|
2021-05-26 19:44:35 -07:00
|
|
|
|
2021-05-27 18:33:04 -07:00
|
|
|
const updatedAtTimestamp = Math.floor(updatedAt.getTime() / 1000);
|
|
|
|
const urlWithUpdatedAt =
|
|
|
|
`/outfits` +
|
|
|
|
`/${encodeURIComponent(outfitId)}` +
|
|
|
|
`/v/${encodeURIComponent(updatedAtTimestamp)}` +
|
|
|
|
`/${encodeURIComponent(req.query.size)}.png`;
|
|
|
|
|
|
|
|
// Cache this result for 10 minutes, so individual users don't wait on
|
|
|
|
// image reloads too much, but it's still always relatively fresh!
|
|
|
|
res.setHeader("Cache-Control", "public, max-age=600");
|
|
|
|
return res.redirect(urlWithUpdatedAt);
|
2021-05-13 18:03:56 -07:00
|
|
|
} else {
|
|
|
|
return reject(res, `Missing required parameter: layerUrls`);
|
2021-01-04 00:10:35 -08:00
|
|
|
}
|
|
|
|
|
2021-01-03 21:58:19 -08:00
|
|
|
for (const layerUrl of layerUrls) {
|
|
|
|
if (!VALID_LAYER_URLS.some((pattern) => layerUrl.match(pattern))) {
|
2021-05-13 18:03:56 -07:00
|
|
|
return reject(res, `Unexpected layer URL format: ${layerUrl}`);
|
2021-01-03 21:58:19 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let imageResult;
|
|
|
|
try {
|
2021-01-04 00:10:35 -08:00
|
|
|
imageResult = await renderOutfitImage(layerUrls, size);
|
2021-01-03 21:58:19 -08:00
|
|
|
} catch (e) {
|
|
|
|
console.error(e);
|
2021-05-13 18:03:56 -07:00
|
|
|
return reject(res, `Error rendering image: ${e.message}`);
|
2021-01-03 21:58:19 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
const { image, status } = imageResult;
|
|
|
|
|
2021-05-27 18:33:04 -07:00
|
|
|
if (status === "success") {
|
|
|
|
// This image is ready, and it either used `layerUrls` or `updatedAt`, so
|
|
|
|
// it shouldn't change much, if ever. Send a long-term cache header!
|
2021-05-26 19:44:35 -07:00
|
|
|
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
|
|
|
res.status(200);
|
2021-01-03 21:58:19 -08:00
|
|
|
} else {
|
|
|
|
// On partial failure, we still send the image, but with a 500 status. We
|
2021-05-26 19:44:35 -07:00
|
|
|
// send a one-week cache header, but in such a way that the user can
|
2021-01-03 21:58:19 -08:00
|
|
|
// refresh the page to try again. (`private` means the CDN won't cache it,
|
|
|
|
// and we don't send `immutable`, which would save it even across reloads.)
|
|
|
|
// The 500 won't really affect the client, which will still show the image
|
|
|
|
// without feedback to the user - but it's a helpful debugging hint.
|
2021-01-03 22:58:09 -08:00
|
|
|
res.setHeader("Cache-Control", "private, max-age=604800");
|
|
|
|
res.status(500);
|
2021-01-03 21:58:19 -08:00
|
|
|
}
|
|
|
|
|
2021-01-03 22:58:09 -08:00
|
|
|
res.setHeader("Content-Type", "image/png");
|
|
|
|
return res.send(image);
|
2021-01-03 20:21:34 -08:00
|
|
|
}
|
|
|
|
|
2021-11-12 21:53:07 -08:00
|
|
|
// Check out this scrappy way of making a query against server code ^_^`
|
|
|
|
const graphqlClient = createTestClient(new ApolloServer(graphqlConfig));
|
2021-05-13 18:03:56 -07:00
|
|
|
|
|
|
|
async function loadLayerUrlsForSavedOutfit(outfitId, size) {
|
2021-11-12 21:53:07 -08:00
|
|
|
const { errors, data } = await graphqlClient.query({
|
|
|
|
query: gql`
|
|
|
|
query ApiOutfitImage($outfitId: ID!, $size: LayerImageSize) {
|
|
|
|
outfit(id: $outfitId) {
|
|
|
|
petAppearance {
|
|
|
|
layers {
|
|
|
|
id
|
|
|
|
imageUrl(size: $size)
|
|
|
|
}
|
|
|
|
...PetAppearanceForGetVisibleLayers
|
|
|
|
}
|
|
|
|
itemAppearances {
|
|
|
|
layers {
|
|
|
|
id
|
|
|
|
imageUrl(size: $size)
|
|
|
|
}
|
|
|
|
...ItemAppearanceForGetVisibleLayers
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
${petAppearanceFragmentForGetVisibleLayers}
|
|
|
|
${itemAppearanceFragmentForGetVisibleLayers}
|
|
|
|
`,
|
|
|
|
variables: { outfitId, size: `SIZE_${size}` },
|
|
|
|
});
|
2021-05-13 18:03:56 -07:00
|
|
|
|
|
|
|
if (errors && errors.length > 0) {
|
|
|
|
throw new Error(
|
|
|
|
`GraphQL Error: ${errors.map((e) => e.message).join(", ")}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-05-27 17:01:20 -07:00
|
|
|
if (!data.outfit) {
|
|
|
|
throw new Error(`outfit ${outfitId} not found`);
|
|
|
|
}
|
|
|
|
|
2021-05-13 18:03:56 -07:00
|
|
|
const { petAppearance, itemAppearances } = data.outfit;
|
|
|
|
const visibleLayers = getVisibleLayers(petAppearance, itemAppearances);
|
2021-09-03 13:23:19 -07:00
|
|
|
|
|
|
|
for (const layer of visibleLayers) {
|
|
|
|
if (!layer.imageUrl) {
|
|
|
|
throw new Error(`layer ${layer.id} has no imageUrl for size ${size}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-13 18:03:56 -07:00
|
|
|
return visibleLayers
|
|
|
|
.sort((a, b) => a.depth - b.depth)
|
|
|
|
.map((layer) => layer.imageUrl);
|
|
|
|
}
|
|
|
|
|
2021-05-27 18:33:04 -07:00
|
|
|
async function loadUpdatedAtForSavedOutfit(outfitId) {
|
|
|
|
const db = await connectToDb();
|
|
|
|
const [rows] = await db.query(`SELECT updated_at FROM outfits WHERE id = ?`, [
|
|
|
|
outfitId,
|
|
|
|
]);
|
|
|
|
const row = rows[0];
|
|
|
|
if (!row) {
|
|
|
|
throw new Error(`outfit ${outfitId} not found`);
|
|
|
|
}
|
|
|
|
return row.updated_at;
|
|
|
|
}
|
|
|
|
|
2021-05-13 18:03:56 -07:00
|
|
|
function reject(res, message, status = 400) {
|
2021-11-12 21:17:20 -08:00
|
|
|
res.setHeader("Content-Type", "text/plain; charset=utf8");
|
2021-05-13 18:03:56 -07:00
|
|
|
return res.status(status).send(message);
|
|
|
|
}
|
|
|
|
|
2021-05-13 01:13:21 -07:00
|
|
|
async function handleWithBeeline(req, res) {
|
2021-04-23 12:31:41 -07:00
|
|
|
beeline.withTrace(
|
|
|
|
{ name: "api/outfitImage", operation_name: "api/outfitImage" },
|
|
|
|
() => handle(req, res)
|
|
|
|
);
|
2021-05-13 01:13:21 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
export default handleWithBeeline;
|