fix(images): ship Linux codecs and preserve original-image fallback

Vendor the locked sharp Linux runtime and verify it during Docker builds. Add complete image response lengths and persistent frontend fallbacks, with real-codec HTTP and isolated release regression tests. Refresh tested API, admin and customer release artifacts.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
mahmood
2026-11-26 18:12:21 +03:30
co-authored by Claude Code
parent a085c279f8
commit 3e9f532c6c
346 changed files with 33359 additions and 240 deletions
+52 -1
View File
@@ -10,8 +10,11 @@ const {
cpSync,
realpathSync,
readdirSync,
readFileSync,
writeFileSync,
} = require('fs');
const path = require('path');
const { createRequire } = require('module');
// Only this engine ships to Docker; see apps/api/Dockerfile (bookworm/OpenSSL 3).
const RUNTIME_ENGINE = 'libquery_engine-debian-openssl-3.0.x.so.node';
@@ -52,7 +55,7 @@ function copyPrismaIntoRelease() {
// Drop engines for other platforms (local Windows dll, stale musl builds) so the
// committed artifact stays small.
for (const name of readdirSync(prismaEngineDest)) {
const isEngine = name.endsWith('.so.node') || name.endsWith('.dll.node');
const isEngine = /^(?:lib)?query_engine-/.test(name) || name.endsWith('.so.node') || name.endsWith('.dll.node');
if (isEngine && name !== RUNTIME_ENGINE) {
rmSync(path.join(prismaEngineDest, name), { force: true });
}
@@ -65,6 +68,52 @@ function copyPrismaIntoRelease() {
}
}
// Copy the locked runtime closure, not Windows binaries or pnpm's symlinks.
// Both native packages must remain siblings: sharp's ELF RUNPATH finds libvips
// relative to @img/sharp-linux-x64. Runtime installation is deliberately offline.
function copySharpIntoRelease() {
const versions = {};
function copyPackage(name, from) {
let source;
try {
// sharp 0.35 hides package.json behind exports; packaging must locate
// the installed manifest without loading a native binary on Windows.
const search = createRequire(path.join(from, 'package.json')).resolve.paths(name) ?? [];
const manifest = search.map((dir) => path.join(dir, name, 'package.json')).find(existsSync);
if (!manifest) throw new Error('Package not installed');
source = realpathSync(path.dirname(manifest));
} catch {
throw new Error(`Missing image runtime package ${name}. Run pnpm install with the workspace supportedArchitectures settings before building release.`);
}
const pkg = JSON.parse(readFileSync(path.join(source, 'package.json'), 'utf8'));
if (versions[name]) {
if (versions[name] !== pkg.version) throw new Error(`Conflicting image runtime versions for ${name}`);
return;
}
versions[name] = pkg.version;
const dest = path.join(vendorDir, name);
mkdirSync(path.dirname(dest), { recursive: true });
cpSync(source, dest, { recursive: true, dereference: true });
for (const dependency of Object.keys(pkg.dependencies ?? {})) copyPackage(dependency, source);
if (name === 'sharp') {
copyPackage('@img/sharp-linux-x64', source);
copyPackage('@img/sharp-libvips-linux-x64', source);
}
}
copyPackage('sharp', root);
for (const [name, extension] of [
['@img/sharp-linux-x64', '.node'],
['@img/sharp-libvips-linux-x64', '.so'],
]) {
const lib = path.join(vendorDir, name, 'lib');
if (!existsSync(lib) || !readdirSync(lib).some((file) => file.includes(extension))) {
throw new Error(`Incomplete Linux image runtime: ${name}`);
}
}
writeFileSync(path.join(releaseDir, 'image-runtime.json'), JSON.stringify({ platform: 'linux', arch: 'x64', versions }, null, 2) + '\n');
cpSync(path.join(__dirname, 'verify-release-images.cjs'), path.join(releaseDir, 'verify-release-images.cjs'));
}
async function main() {
const entry = config.entryPoints[0];
const fallbackEntry = path.join(root, 'dist', 'src', 'main.js');
@@ -82,6 +131,7 @@ async function main() {
await esbuild.build(config);
copyPrismaIntoRelease();
copySharpIntoRelease();
// SQL migrations are read at runtime by src/prisma/migrate.ts
cpSync(path.join(root, 'prisma', 'migrations'), path.join(releaseDir, 'migrations'), {
@@ -97,6 +147,7 @@ async function main() {
console.log('نوشت:', config.outfile);
console.log('Prisma client در release/vendor کپی شد.');
console.log('sharp و وابستگی‌های native لینوکس در release/vendor کپی شدند.');
console.log('migrations و seed.js در release کپی شدند.');
}
+84
View File
@@ -0,0 +1,84 @@
// Bundle this test entry with the release esbuild externals, then run it beside
// release/vendor in an isolated Linux container. No real DB/app bootstrap.
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const sharp = require('sharp');
const request = require('supertest');
const { Module } = require('@nestjs/common');
const { NestFactory } = require('@nestjs/core');
const { ImageVariantService } = require('../dist/modules/admin-uploads/image-variants.service');
const { AdminUploadsService } = require('../dist/modules/admin-uploads/admin-uploads.service');
const { PublicImagesController } = require('../dist/modules/admin-uploads/public-images.controller');
const { PublicUploadsController } = require('../dist/modules/admin-uploads/public-uploads.controller');
async function main() {
assert.equal(process.platform, 'linux');
assert.ok(require.resolve('sharp').startsWith('/app/vendor/'), 'Must load the shipped codec, not development dependencies');
const input = await fs.readFile(process.argv[2]);
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'release-image-'));
process.env.UPLOAD_DIR = dir;
const variants = new ImageVariantService();
let app;
let stored;
try {
const persistence = { uploadedFile: { create: async ({ data }) => data } };
stored = await new AdminUploadsService(persistence, variants).store(
{ originalname: 'fixture.jpg', mimetype: 'image/jpeg', size: input.length, buffer: input }, 'test', null,
);
assert.equal(stored.mimeType, 'image/webp');
assert.ok(stored.sizeBytes < 500 * 1024);
console.log('Stored:', JSON.stringify({ url: stored.url, mimeType: stored.mimeType, bytes: stored.sizeBytes }));
await Promise.all([200, 400, 600, 1600].map((w) => variants.resolve(path.basename(stored.url), w)));
await fs.writeFile(path.join(dir, 'original.jpg'), input);
class ImageTestModule {}
Module({ controllers: [PublicImagesController, PublicUploadsController], providers: [{ provide: ImageVariantService, useValue: variants }] })(ImageTestModule);
app = await NestFactory.create(ImageTestModule, { logger: false });
app.setGlobalPrefix('api');
app.useStaticAssets(dir, { prefix: '/uploads/', dotfiles: 'deny' });
await app.init();
async function check(url, mime) {
const res = await request(app.getHttpServer()).get(url).timeout({ deadline: 15000 }).expect(200);
assert.ok(res.headers['content-type'].includes(mime));
assert.equal(Number(res.headers['content-length']), res.body.length);
const meta = await sharp(res.body).metadata();
await sharp(res.body).raw().toBuffer();
console.log('HTTP:', JSON.stringify({ url, status: res.status, bytes: res.body.length, mime, width: meta.width, height: meta.height }));
return { res, meta };
}
const { meta } = await check(stored.url, 'image/webp');
assert.ok(Math.max(meta.width, meta.height) <= 2000);
await check(`/api/uploads/${path.basename(stored.url)}`, 'image/webp');
for (const w of [200, 400, 600, 1600]) {
const url = `/api/img/${path.basename(stored.url)}?w=${w}`;
const result = await check(url, 'image/webp');
assert.equal(result.meta.width, Math.min(w, meta.width));
const head = await request(app.getHttpServer()).head(url).expect(200);
assert.equal(Number(head.headers['content-length']), result.res.body.length);
}
// Previously uploaded large JPEGs must work without uploading them again.
// Use a separate name so the no-codec checks below cannot hit this cache.
await fs.writeFile(path.join(dir, 'legacy.jpg'), input);
for (const w of [200, 400, 600, 1600]) {
const { res, meta: legacy } = await check(`/api/img/legacy.jpg?w=${w}`, 'image/webp');
assert.equal(legacy.width, w);
assert.ok(res.body.length < input.length);
assert.ok(res.headers['cache-control'].includes('immutable'));
}
variants.sharp = null;
for (const url of ['/uploads/original.jpg', '/api/uploads/original.jpg', '/api/img/original.jpg?w=1600']) {
const { res } = await check(url, 'image/jpeg');
assert.ok(res.body.equals(input));
}
for (const url of ['/api/img/missing.jpg?w=400', '/api/uploads/missing.jpg']) {
await request(app.getHttpServer()).get(url).timeout({ deadline: 15000 }).expect(404);
}
console.log('PASS: isolated Linux release upload, all previews, large-original fallback, Content-Length, HEAD and 404');
} finally {
if (stored) await Promise.all([200, 400, 600, 1600].map((w) => variants.resolve(path.basename(stored.url), w)));
if (app) await app.close();
await fs.rm(dir, { recursive: true, force: true, maxRetries: 5 });
}
}
main().catch((err) => { console.error(err); process.exitCode = 1; });
+54
View File
@@ -0,0 +1,54 @@
// Usage: node scripts/test-release-images.cjs <JPEG fixture> [Node 20 Bookworm image]
// Run after build:release. Copies the artifact into a disposable isolated tree;
// neither the application database nor the production environment is started.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const esbuild = require('esbuild');
async function main() {
assert.ok(process.argv[2], 'Supply a local JPEG fixture path');
const input = fs.realpathSync(process.argv[2]);
const image = process.argv[3] || 'node:20-bookworm';
const root = path.resolve(__dirname, '..');
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'release-image-test-'));
const artifact = path.join(scratch, 'artifact');
const tests = path.join(scratch, 'tests');
try {
fs.cpSync(path.join(root, 'release'), artifact, { recursive: true, dereference: true });
fs.mkdirSync(tests);
await esbuild.build({
...require('../esbuild.release.config.cjs'),
entryPoints: [path.join(__dirname, 'image-http-smoke.cjs')],
outfile: path.join(tests, 'http-smoke.cjs'),
});
const common = ['run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
'--mount', `type=bind,source=${artifact},target=/app,readonly`,
'--mount', `type=bind,source=${tests},target=/test,readonly`,
'--mount', `type=bind,source=${input},target=/input/fixture.jpg,readonly`,
'-e', 'NODE_PATH=/app/vendor', '-w', '/app', image, 'node'];
function run(entry, args = [], expectedFailure = false) {
const result = spawnSync('docker', [...common, entry, ...args], { encoding: 'utf8', timeout: 180000 });
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
if (result.error) throw result.error;
if (expectedFailure) {
assert.equal(result.status, 1, 'Broken artifact must fail the codec verifier, not Docker startup');
assert.match(result.stderr, /sharp|MODULE_NOT_FOUND/);
} else assert.equal(result.status, 0, `Linux artifact test failed: ${entry}`);
}
run('/app/verify-release-images.cjs');
run('/test/http-smoke.cjs', ['/input/fixture.jpg']);
const lib = path.join(artifact, 'vendor/@img/sharp-linux-x64/lib');
const native = fs.readdirSync(lib).find((name) => name.endsWith('.node'));
assert.ok(native, 'Native Linux module must exist before negative test');
fs.rmSync(path.join(lib, native)); // Only the disposable copy is changed.
run('/app/verify-release-images.cjs', [], true);
console.log('PASS: omitted native module is rejected; no silent codec fallback');
} finally {
fs.rmSync(scratch, { recursive: true, force: true, maxRetries: 5, retryDelay: 250 });
}
}
main().catch((err) => { console.error(err); process.exitCode = 1; });
@@ -0,0 +1,31 @@
// Copied beside app.js. No Nest bootstrap, environment files, database or network.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { createRequire } = require('node:module');
async function main() {
const root = __dirname;
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'image-runtime.json'), 'utf8'));
assert.equal(process.platform, manifest.platform, 'Validate native images on the target Linux runtime');
assert.equal(process.arch, manifest.arch, 'Image artifact targets Linux x64');
const vendor = fs.realpathSync(path.join(root, 'vendor'));
// Use absolute package paths so a developer's node_modules cannot mask an
// incomplete artifact. Also check every dependency against the build manifest.
for (const [name, version] of Object.entries(manifest.versions)) {
const packagePath = path.join(vendor, name, 'package.json');
const real = fs.realpathSync(packagePath);
assert.ok(real.startsWith(vendor + path.sep), `Dependency escapes artifact: ${name}`);
assert.equal(JSON.parse(fs.readFileSync(real, 'utf8')).version, version, name);
}
const sharp = createRequire(path.join(vendor, 'sharp', 'package.json'))(path.join(vendor, 'sharp'));
assert.equal(sharp.versions.sharp, manifest.versions.sharp);
const encoded = await sharp({ create: { width: 32, height: 24, channels: 3, background: '#557799' } }).webp().toBuffer();
const decoded = await sharp(encoded).raw().toBuffer({ resolveWithObject: true });
assert.equal(decoded.info.width, 32);
assert.equal(decoded.info.height, 24);
assert.equal((await sharp(encoded).metadata()).format, 'webp');
console.log(`Image runtime OK: sharp ${sharp.versions.sharp}, libvips ${sharp.versions.vips}, ${encoded.length} byte WebP`);
}
main().catch((err) => { console.error(err); process.exitCode = 1; });