Browse Source
* Serve pre-compressed UI files from web-ui instead of compressing per request compression 1.8 (pulled in by a CVE fix in 4.2.2.5 / 4.3.1.5) prefers brotli, and browsers always offer it over HTTPS. Brotli-compressing the 8.5 MB main chunk on every cache miss fragments native memory that glibc never returns, so web-ui RSS grows with each traffic burst until the container is OOMKilled. - ui-ngx: write .gz copies for every compressible file of the production build in a post-build step. The esbuild plugin it replaces missed global styles, scripts, polyfills, ace workers and assets/. - web-ui: serve those copies with Content-Encoding: gzip and drop the compression middleware and its dependency. * Run UI compression as a Maven step and ignore aborted downloads in web-ui - build:prod is a plain ng build again; "yarn run compress" runs as its own frontend-maven-plugin execution right after it. - web-ui: like express.static, ignore ECONNABORTED and socket write errors instead of logging a stack trace for every cancelled download, and fall back to the original file if its .gz copy is missing. * Serve pre-built brotli copies of UI files - compress-build.js also writes <file>.br (brotli quality 10). It is 21.5% smaller than gzip -9 on the UI bundle (main chunk 0.96 MiB vs 1.47 MiB). Quality 11 saves only 2% more and takes 3x longer. - It now uses every available core and starts with the largest files: 7 s for .br and .gz together on 6 cores, against 25 s for quality 11 on the default 4 libuv threads. - web-ui serves .br when the client accepts it and .gz otherwise. The server's order wins, because browsers list gzip before br. * Ignore stale pre-compressed copies and warn when there are none - web-ui skips a .br/.gz copy that is older than its original or has no original. Otherwise a file edited after the build, such as a customized locale, would keep being served from its old copy. - Log a warning when the web folder has no pre-compressed files at all, for example a UI built without "yarn run compress". - compress-build.js runs at most 8 threads. - Shorter comments; the pom comment duplicated the script header. * Respect Accept-Encoding q-values and detect edited originals by size - Pick the encoding with negotiator (already in the tree through express, now a direct dependency). The highest q wins as RFC 9110 says, and the server's br-first order only breaks ties. Before, "gzip;q=1, br;q=0.1" still got br. - Check a copy against the uncompressed size gzip stores in its trailer instead of comparing mtimes. Touching or copying the build without preserving timestamps no longer disables compression, and a customized file of a different size still gets served fresh. * Trust pre-compressed copies as built, like nginx, Caddy and Fastify do The web folder is a build artifact that is not edited by hand, so checking copies against their originals at startup only added code. * Load negotiator.d.ts in yarn start and start-prod ts-node only compiles files that are imported, so it ignored the ambient declaration and failed with TS7016. tsc, the Docker image and production were not affected.pull/16740/head
committed by
GitHub
9 changed files with 191 additions and 112 deletions
@ -0,0 +1,12 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
|
|||
// negotiator 1.x ships no types, and @types/negotiator (0.6) lacks the `preferred` option
|
|||
declare module 'negotiator' { |
|||
import { IncomingMessage } from 'http'; |
|||
|
|||
export default class Negotiator { |
|||
constructor(request: IncomingMessage); |
|||
encoding(available: string[], options?: { preferred?: string[] }): string | undefined; |
|||
} |
|||
} |
|||
@ -0,0 +1,82 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
|
|||
// Writes .br and .gz copies of the production build's files, served as-is by the monolith and msa/web-ui.
|
|||
// Not an esbuild plugin: Angular gives custom plugins only the browser code bundle, not polyfills,
|
|||
// global styles/scripts or copied assets.
|
|||
|
|||
const os = require('node:os'); |
|||
|
|||
// zlib runs on the libuv thread pool (4 threads by default), which must be sized before its first use.
|
|||
// More than 8 threads gains nothing: the largest chunk alone takes ~5 s.
|
|||
const concurrency = Math.min(os.availableParallelism(), 8); |
|||
process.env.UV_THREADPOOL_SIZE = String(concurrency); |
|||
|
|||
const fs = require('node:fs'); |
|||
const path = require('node:path'); |
|||
const { promisify } = require('node:util'); |
|||
const zlib = require('node:zlib'); |
|||
|
|||
const gzip = promisify(zlib.gzip); |
|||
const brotliCompress = promisify(zlib.brotliCompress); |
|||
|
|||
const buildDir = path.join(__dirname, 'target', 'generated-resources', 'public'); |
|||
// already-compressed formats (png, webp, woff2, ...) are left out
|
|||
const compressibleExtensions = new Set(['.js', '.mjs', '.css', '.html', '.json', '.svg', '.txt', '.md', '.ttf', '.otf', '.eot']); |
|||
const minSize = 10240; |
|||
|
|||
// brotli quality 11 is only ~2% smaller than 10 but 3x slower; must match precompressedEncodings in msa/web-ui
|
|||
const encoders = [ |
|||
{ |
|||
ext: '.br', |
|||
encode: content => brotliCompress(content, { |
|||
params: { |
|||
[zlib.constants.BROTLI_PARAM_QUALITY]: 10, |
|||
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: content.length |
|||
} |
|||
}) |
|||
}, |
|||
{ |
|||
ext: '.gz', |
|||
encode: content => gzip(content, { level: zlib.constants.Z_BEST_COMPRESSION }) |
|||
} |
|||
]; |
|||
|
|||
function listFiles(dir) { |
|||
return fs.readdirSync(dir, { recursive: true, withFileTypes: true }) |
|||
.filter(entry => entry.isFile()) |
|||
.map(entry => path.join(entry.parentPath, entry.name)); |
|||
} |
|||
|
|||
async function compress(file, { ext, encode }) { |
|||
const content = await fs.promises.readFile(file); |
|||
const compressed = await encode(content); |
|||
if (compressed.length < content.length) { |
|||
await fs.promises.writeFile(file + ext, compressed); |
|||
} |
|||
} |
|||
|
|||
async function main() { |
|||
// largest first, so the main chunk does not start last
|
|||
const files = listFiles(buildDir) |
|||
.map(file => ({ file, size: fs.statSync(file).size })) |
|||
.filter(({ file, size }) => compressibleExtensions.has(path.extname(file).toLowerCase()) && size >= minSize) |
|||
.sort((a, b) => b.size - a.size) |
|||
.map(({ file }) => file); |
|||
const jobs = files.flatMap(file => encoders.map(encoder => () => compress(file, encoder))); |
|||
let next = 0; |
|||
const worker = async () => { |
|||
while (next < jobs.length) { |
|||
await jobs[next++](); |
|||
} |
|||
}; |
|||
const start = Date.now(); |
|||
await Promise.all(Array.from({ length: concurrency }, worker)); |
|||
console.log(`Compressed ${files.length} files (${encoders.map(e => e.ext).join(', ')}) in ${path.relative(__dirname, buildDir)} ` + |
|||
`in ${((Date.now() - start) / 1000).toFixed(1)} s on ${concurrency} threads`); |
|||
} |
|||
|
|||
main().catch(error => { |
|||
console.error(error); |
|||
process.exit(1); |
|||
}); |
|||
Loading…
Reference in new issue