diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index ab79e66ac4..1d55db95ad 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -924,11 +924,9 @@ spring.main.allow-circular-references: "true" # Spring Boot configuration proper spring.freemarker.checkTemplateLocation: "false" # spring freemarker configuration spring.mvc.async.request-timeout: "${SPRING_MVC_ASYNC_REQUEST_TIMEOUT:30000}" # The default timeout for asynchronous requests in milliseconds spring.mvc.pathmatch.matching-strategy: "ANT_PATH_MATCHER" # For endpoints matching in Swagger -spring.resources.chain: - compressed: "true" # This property enables or disables support for serving pre-compressed resources (for example, a .gzip or .br file) - strategy: - content: - enabled: "true" # This property enables or disables the content Version Strategy. This strategy allows Spring to generate a unique version for static resources, which is based on the content of the resource +spring.web.resources.chain: + enabled: "true" # Enables the Spring resource chain explicitly instead of relying on a webjars locator being on the classpath + compressed: "true" # Serve the pre-compressed .br/.gz copies of the UI files built by ui-ngx when the client accepts them spring.servlet.multipart.max-file-size: "${SPRING_SERVLET_MULTIPART_MAX_FILE_SIZE:50MB}" # Total file size cannot exceed 50MB when configuring file uploads spring.servlet.multipart.max-request-size: "${SPRING_SERVLET_MULTIPART_MAX_REQUEST_SIZE:50MB}" # Total request size for a multipart/form-data cannot exceed 50MB diff --git a/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java b/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java new file mode 100644 index 0000000000..954b136c84 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.config; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; +import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration; +import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.GZIPOutputStream; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.http.HttpHeaders.ACCEPT_ENCODING; +import static org.springframework.http.HttpHeaders.CONTENT_ENCODING; +import static org.springframework.http.HttpHeaders.VARY; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Loads the real thingsboard.yml, so the test fails if its static resource chain keys stop binding again. + */ +@SpringBootTest(classes = StaticResourceCompressionTest.WebMvcConfig.class, properties = "spring.config.name=thingsboard") +@AutoConfigureMockMvc(addFilters = false) +public class StaticResourceCompressionTest { + + private static final byte[] JS = "console.log('ThingsBoard');\n".repeat(100).getBytes(StandardCharsets.UTF_8); + private static final byte[] JS_GZ = gzip(JS); + private static final byte[] CSS = "@font-face { src: url(font.woff2); }\n".getBytes(StandardCharsets.UTF_8); + + @TempDir + static Path webRoot; + + @Autowired + private MockMvc mvc; + + @DynamicPropertySource + static void staticLocations(DynamicPropertyRegistry registry) { + registry.add("spring.web.resources.static-locations", () -> webRoot.toUri().toString()); + } + + @BeforeAll + static void createStaticFiles() throws IOException { + Files.write(webRoot.resolve("main.js"), JS); + Files.write(webRoot.resolve("main.js.gz"), JS_GZ); + Files.write(webRoot.resolve("styles.css"), CSS); + Files.write(webRoot.resolve("font.woff2"), new byte[]{1, 2, 3}); + } + + @Test + public void servesPrebuiltGzipWhenClientAcceptsIt() throws Exception { + mvc.perform(get("/main.js").header(ACCEPT_ENCODING, "gzip, deflate, br")) + .andExpect(status().isOk()) + .andExpect(header().string(CONTENT_ENCODING, "gzip")) + .andExpect(header().string(VARY, containsString(ACCEPT_ENCODING))) + .andExpect(content().contentTypeCompatibleWith("text/javascript")) + .andExpect(content().bytes(JS_GZ)); + } + + @Test + public void servesRawFileWhenClientDoesNotAcceptGzip() throws Exception { + mvc.perform(get("/main.js")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(CONTENT_ENCODING)) + .andExpect(content().bytes(JS)); + } + + @Test + public void servesStylesheetUnchanged() throws Exception { + // the content version strategy would rewrite url(font.woff2) to url(font-.woff2) + mvc.perform(get("/styles.css").header(ACCEPT_ENCODING, "gzip")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(CONTENT_ENCODING)) + .andExpect(content().bytes(CSS)); + } + + // not @Configuration: @ComponentScan("org.thingsboard.server") in other tests would pick it up + @ImportAutoConfiguration({DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class}) + static class WebMvcConfig { + } + + private static byte[] gzip(byte[] data) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(out)) { + gzip.write(data); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return out.toByteArray(); + } + +} diff --git a/msa/web-ui/negotiator.d.ts b/msa/web-ui/negotiator.d.ts new file mode 100644 index 0000000000..ffbc4fbf39 --- /dev/null +++ b/msa/web-ui/negotiator.d.ts @@ -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; + } +} diff --git a/msa/web-ui/package.json b/msa/web-ui/package.json index b59b2b267f..2e999547ef 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -13,17 +13,16 @@ "build": "tsc" }, "dependencies": { - "compression": "^1.8.2", "config": "^4.4.2", "connect-history-api-fallback": "^2.0.0", "express": "^5.3.0", "http-proxy": "^1.18.1", "js-yaml": "^4.3.2", + "negotiator": "^1.1.0", "winston": "^3.19.0", "winston-daily-rotate-file": "^5.0.0" }, "devDependencies": { - "@types/compression": "^1.8.1", "@types/connect-history-api-fallback": "1.5.4", "@types/express": "~5.0.6", "@types/http-proxy": "^1.17.17", diff --git a/msa/web-ui/server.ts b/msa/web-ui/server.ts index 4a84a03907..ee856b6a0e 100644 --- a/msa/web-ui/server.ts +++ b/msa/web-ui/server.ts @@ -6,9 +6,10 @@ import { _logger} from './config/logger'; import path from 'path'; import http, { ServerResponse } from 'http'; import httpProxy from 'http-proxy'; -import compression from 'compression'; +import fs from 'fs'; import historyApiFallback from 'connect-history-api-fallback'; import { Socket } from 'net'; +import Negotiator from 'negotiator'; import { RequestHandler } from 'express'; const logger = _logger('main'); @@ -16,6 +17,18 @@ const logger = _logger('main'); let server: http.Server | null; let connections: Socket[] = []; +// in server preference order; must match the encoders in ui-ngx/compress-build.js +const precompressedEncodings = [ + {encoding: 'br', ext: '.br'}, + {encoding: 'gzip', ext: '.gz'} +]; + +interface PrecompressedVariant { + encoding: string; + ext: string; + files: Set; +} + (async() => { try { logger.info('Starting ThingsBoard Web UI Microservice...'); @@ -112,10 +125,18 @@ let connections: Socket[] = []; } app.use(historyApiFallback()); - app.use(compression()); const root = path.join(webDir, 'public'); + // No per-request compression: zlib/brotli fragment native memory that glibc never returns, until OOM + const variants = listPrecompressedFiles(root); + if (variants.some(({files}) => files.size)) { + logger.info('Pre-compressed files: %s', variants.map(({encoding, files}) => `${encoding} ${files.size}`).join(', ')); + } else { + logger.warn('No pre-compressed (.br/.gz) UI files in %s: UI files are served uncompressed', root); + } + app.use(precompressedStatic(root, variants)); + const staticServe = express.static(root); const indexHtmlFallback: RequestHandler = (req, res, next) => { @@ -162,6 +183,57 @@ process.on('exit', async (code: number) => { logger.info(`ThingsBoard Web UI Microservice has been stopped. Exit code: ${code}.`); }); +function listPrecompressedFiles(root: string): PrecompressedVariant[] { + const variants = precompressedEncodings.map(encoding => ({...encoding, files: new Set()})); + if (fs.existsSync(root)) { + for (const file of fs.readdirSync(root, {recursive: true, encoding: 'utf8'})) { + const variant = variants.find(({ext}) => file.endsWith(ext)); + variant?.files.add('/' + file.slice(0, -variant.ext.length).split(path.sep).join('/')); + } + } + return variants; +} + +function precompressedStatic(root: string, variants: PrecompressedVariant[]): RequestHandler { + return (req, res, next) => { + if (req.method !== 'GET' && req.method !== 'HEAD') { + return next(); + } + let filePath: string; + try { + filePath = decodeURIComponent(req.path); + } catch { + return next(); + } + const available = variants.filter(({files}) => files.has(filePath)); + if (!available.length) { + return next(); + } + res.vary('Accept-Encoding'); + // highest q wins; on a tie the server's order does, as browsers list gzip before br + const encodings = available.map(({encoding}) => encoding); + const best = new Negotiator(req).encoding([...encodings, 'identity'], {preferred: encodings}); + const variant = available.find(({encoding}) => encoding === best); + if (!variant) { + return next(); + } + res.setHeader('Content-Encoding', variant.encoding); + res.type(path.extname(filePath)); + res.sendFile(filePath + variant.ext, {root}, (err?: NodeJS.ErrnoException & { status?: number }) => { + // the client went away; express.static ignores these too + if (!err || err.code === 'ECONNABORTED' || err.syscall === 'write') { + return; + } + if (res.headersSent) { + return next(err); + } + res.removeHeader('Content-Encoding'); + // the copy was removed after startup: fall through to the original + next(err.status === 404 ? undefined : err); + }); + }; +} + async function exit(status: number) { logger.info('Exiting with status: %d ...', status); if (server) { diff --git a/msa/web-ui/tsconfig.json b/msa/web-ui/tsconfig.json index b633ffc768..2b3cfdf7e5 100644 --- a/msa/web-ui/tsconfig.json +++ b/msa/web-ui/tsconfig.json @@ -9,5 +9,8 @@ "skipLibCheck": true, "strictPropertyInitialization": false }, - "exclude": ["node_modules", "target"] + "exclude": ["node_modules", "target"], + "ts-node": { + "files": true + } } diff --git a/msa/web-ui/yarn.lock b/msa/web-ui/yarn.lock index b438733025..7be1378496 100644 --- a/msa/web-ui/yarn.lock +++ b/msa/web-ui/yarn.lock @@ -312,14 +312,6 @@ "@types/connect" "*" "@types/node" "*" -"@types/compression@^1.8.1": - version "1.8.1" - resolved "https://registry.yarnpkg.com/@types/compression/-/compression-1.8.1.tgz#57cd1a5c0c585aca56124ab4daef1d254d6f5a7d" - integrity sha512-kCFuWS0ebDbmxs0AXYn6e2r2nrGAb5KwQhknjSPSPgJcGd8+HVSILlUyFhGqML2gk39HcG7D1ydW9/qpYkN00Q== - dependencies: - "@types/express" "*" - "@types/node" "*" - "@types/connect-history-api-fallback@1.5.4": version "1.5.4" resolved "https://registry.yarnpkg.com/@types/connect-history-api-fallback/-/connect-history-api-fallback-1.5.4.tgz#7de71645a103056b48ac3ce07b3520b819c1d5b3" @@ -345,7 +337,7 @@ "@types/range-parser" "*" "@types/send" "*" -"@types/express@*", "@types/express@~5.0.6": +"@types/express@~5.0.6": version "5.0.6" resolved "https://registry.yarnpkg.com/@types/express/-/express-5.0.6.tgz#2d724b2c990dcb8c8444063f3580a903f6d500cc" integrity sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA== @@ -578,7 +570,7 @@ buffer@^5.5.0: base64-js "^1.3.1" ieee754 "^1.1.13" -bytes@3.1.2, bytes@^3.1.2, bytes@~3.1.2: +bytes@^3.1.2, bytes@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.2.tgz#8b0beeb98605adf1b128fa4386403c009e0221a5" integrity sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg== @@ -662,27 +654,6 @@ commander@^9.4.0: resolved "https://registry.yarnpkg.com/commander/-/commander-9.5.0.tgz#bc08d1eb5cedf7ccb797a96199d41c7bc3e60d30" integrity sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ== -compressible@~2.0.18: - version "2.0.18" - resolved "https://registry.yarnpkg.com/compressible/-/compressible-2.0.18.tgz#af53cca6b070d4c3c0750fbd77286a6d7cc46fba" - integrity sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg== - dependencies: - mime-db ">= 1.43.0 < 2" - -compression@^1.8.2: - version "1.8.2" - resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.2.tgz#781397127ae2da00c0c5f7c76bda5b2a9b32a49f" - integrity sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ== - dependencies: - bytes "3.1.2" - compressible "~2.0.18" - debug "2.6.9" - destroy "1.2.0" - negotiator "~0.6.4" - on-headers "~1.1.0" - safe-buffer "5.2.1" - vary "~1.1.2" - config@^4.4.2: version "4.4.2" resolved "https://registry.yarnpkg.com/config/-/config-4.4.2.tgz#adab67a87fcb5f84edcacb3f159ccdb31ad8b901" @@ -725,13 +696,6 @@ create-require@^1.1.0: resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== -debug@2.6.9: - version "2.6.9" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" - integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== - dependencies: - ms "2.0.0" - debug@^4.3.1, debug@^4.4.0, debug@^4.4.3: version "4.4.3" resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.3.tgz#c6ae432d9bd9662582fce08709b038c58e9e3d6a" @@ -756,11 +720,6 @@ depd@^2.0.0, depd@~2.0.0: resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== -destroy@1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" - integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== - detect-libc@^2.0.0: version "2.1.2" resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.1.2.tgz#689c5dcdc1900ef5583a4cb9f6d7b473742074ad" @@ -1214,7 +1173,7 @@ merge-descriptors@^2.0.0: resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-2.0.0.tgz#ea922f660635a2249ee565e0449f951e6b603808" integrity sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g== -"mime-db@>= 1.43.0 < 2", mime-db@^1.54.0: +mime-db@^1.54.0: version "1.54.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.54.0.tgz#cddb3ee4f9c64530dff640236661d42cb6a314f5" integrity sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ== @@ -1258,11 +1217,6 @@ moment@^2.29.1: resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== -ms@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" - integrity sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A== - ms@^2.1.1, ms@^2.1.3: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" @@ -1281,18 +1235,13 @@ napi-build-utils@^2.0.0: resolved "https://registry.yarnpkg.com/napi-build-utils/-/napi-build-utils-2.0.0.tgz#13c22c0187fcfccce1461844136372a47ddc027e" integrity sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA== -negotiator@^1.0.0: +negotiator@^1.0.0, negotiator@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-1.1.0.tgz#16e003d0db4ac24fd9df168edf871625deeae3df" integrity sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg== dependencies: content-type "^2.1.0" -negotiator@~0.6.4: - version "0.6.4" - resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.4.tgz#777948e2452651c570b712dd01c23e262713fff7" - integrity sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w== - node-abi@^3.3.0: version "3.100.0" resolved "https://registry.yarnpkg.com/node-abi/-/node-abi-3.100.0.tgz#31aa9623841051d14f52415557e18101bc0de7ca" @@ -1322,11 +1271,6 @@ on-finished@^2.4.1: dependencies: ee-first "1.1.1" -on-headers@~1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/on-headers/-/on-headers-1.1.0.tgz#59da4f91c45f5f989c6e4bcedc5a3b0aed70ff65" - integrity sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A== - once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" @@ -1508,7 +1452,7 @@ router@^2.2.0: parseurl "^1.3.3" path-to-regexp "^8.0.0" -safe-buffer@5.2.1, safe-buffer@^5.0.1, safe-buffer@~5.2.0: +safe-buffer@^5.0.1, safe-buffer@~5.2.0: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== @@ -1861,7 +1805,7 @@ v8-compile-cache-lib@^3.0.1: resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf" integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg== -vary@^1.1.2, vary@~1.1.2: +vary@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc" integrity sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg== diff --git a/pom.xml b/pom.xml index 1a26c6bfa4..3233daa7b3 100755 --- a/pom.xml +++ b/pom.xml @@ -74,13 +74,14 @@ 10.1.61 5.4.3 1.5.38 - 2.21.7 + 2.21.8 42.7.14 5.34.0 5.6.4 1.5.7-14 2.3.35 1.11.4 + 20260719 2.4.0-b180830.0359 0.12.5 0.10 @@ -1140,6 +1141,13 @@ ${lz4-java.version} + + + org.json + json + ${org.json.version} + + org.springframework.boot spring-boot-dependencies diff --git a/ui-ngx/compress-build.js b/ui-ngx/compress-build.js new file mode 100644 index 0000000000..526a214b41 --- /dev/null +++ b/ui-ngx/compress-build.js @@ -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); +}); diff --git a/ui-ngx/esbuild/tb-esbuild-plugins.ts b/ui-ngx/esbuild/tb-esbuild-plugins.ts index cacd2db7d7..db0f448d69 100644 --- a/ui-ngx/esbuild/tb-esbuild-plugins.ts +++ b/ui-ngx/esbuild/tb-esbuild-plugins.ts @@ -1,10 +1,8 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import type { Plugin, PluginBuild, OutputFile } from 'esbuild'; +import type { Plugin, PluginBuild } from 'esbuild'; import dirTree from 'directory-tree'; import * as packageJson from '../package.json'; -import { gzip } from 'node:zlib'; -import * as path from 'node:path'; const defineTbVariablesPlugin: Plugin = { name: 'tb-define-variables', @@ -36,47 +34,6 @@ const resolveJQueryPlugin: Plugin = { } }; -const compressFileTypes = ['.js', '.css', '.html', '.svg', '.png', '.jpg', '.ttf', '.gif', '.woff', '.woff2', '.eot', '.json']; -const compressThreshold = 10240; - -const compressorPlugin: Plugin = { - name: 'tb-compressor-plugin', - setup(build) { - build.onEnd(async result => { - if (!result.outputFiles || !isProduction()) return; - const outputExt = '.gz'; - const gzippedFiles: OutputFile[] = []; - for (const file of result.outputFiles) { - if (!compressFileTypes.some((ext) => ext === path.extname(file.path))) continue; - if (file.contents.byteLength <= compressThreshold) continue; - const compressedContent = await gzipContent(file.contents); - const compressedFilePath = `${file.path}${outputExt}`; - gzippedFiles.push( - { - path: compressedFilePath, - hash: file.hash, - contents: new Uint8Array(compressedContent), - text: '', - } - ); - } - result.outputFiles.push(...gzippedFiles); - }); - }, -}; - -async function gzipContent(content): Promise { - return new Promise((resolve, reject) => { - gzip(content, (error, result) => { - if (error) { - reject(error); - } else { - resolve(result); - } - }); - }); -} - function isProduction(): boolean { const configurationIndex = process.argv.indexOf('--configuration'); let production = false; @@ -87,4 +44,4 @@ function isProduction(): boolean { return production; } -export default [defineTbVariablesPlugin, resolveJQueryPlugin, compressorPlugin]; +export default [defineTbVariablesPlugin, resolveJQueryPlugin]; diff --git a/ui-ngx/package.json b/ui-ngx/package.json index 2ea76996c1..d9bd060bfc 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -6,6 +6,7 @@ "start": "node --max_old_space_size=8048 ./node_modules/@angular/cli/bin/ng serve --configuration development --host 0.0.0.0 --open", "build": "ng build", "build:prod": "node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build --configuration production", + "compress": "node compress-build.js", "build:types": "node generate-types.js", "build:icon-metadata": "node generate-icon-metadata.js", "lint": "ng lint", diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index e1bae5c390..817d3e935e 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -109,6 +109,15 @@ --mutex network run build:prod + + yarn compress + + yarn + + + run compress + +