diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 98939c3a55..be1959f081 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1214,6 +1214,9 @@ spring.freemarker.checkTemplateLocation: "false" # spring freemarker configurati 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.http.converters.preferred-json-mapper: "jackson2" # JSON mapper for HTTP message conversion; ThingsBoard uses Jackson 2 +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..46101efa07 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java @@ -0,0 +1,116 @@ +// 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.BeforeEach; +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.http.converter.autoconfigure.HttpMessageConvertersAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.autoconfigure.DispatcherServletAutoConfiguration; +import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.WebApplicationContext; + +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; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +/** + * 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") +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 WebApplicationContext webApplicationContext; + + 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}); + } + + @BeforeEach + void setUpMockMvc() { + mvc = webAppContextSetup(webApplicationContext).build(); + } + + @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/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index a81368450c..27a75dbcd4 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -467,6 +467,7 @@ class DefaultIotHubServiceTest { profile.setDefaultDashboardId(dashboard.getId()); Integration integration = new Integration(new IntegrationId(UUID.randomUUID())); Converter converter = new Converter(new ConverterId(UUID.randomUUID())); + converter.setTenantId(tenantId); // The profile and the integration listed first: in reverse order of creation, the dashboard would go before the // profile that refers to it, and the converter before the integration that uses it. IotHubInstalledItem deleted = devicePackage(profile.getId(), dashboard.getId(), integration.getId(), converter.getId()); @@ -604,6 +605,7 @@ class DefaultIotHubServiceTest { mockTenant(); IntegrationId integrationId = new IntegrationId(UUID.randomUUID()); Converter converter = new Converter(new ConverterId(UUID.randomUUID())); + converter.setTenantId(tenantId); when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter); IotHubInstalledItem deleted = devicePackage(converter.getId(), integrationId); // The converter and the integration steps shared the name: the integration's state replaced the converter's diff --git a/msa/web-report/chromium.js b/msa/web-report/chromium.js new file mode 100644 index 0000000000..cd9acc9f14 --- /dev/null +++ b/msa/web-report/chromium.js @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +// The Chromium builds shipped with the packages. They must be the Chromium release that playwright-core is released with, +// which install.js checks, so a Playwright upgrade needs new builds here. The Docker image has the chromium package of +// Debian instead: see docker/Dockerfile. +// +// The Chromium project publishes builds of the main branch only, so these are the builds from where the release was +// branched off, without the fixes made on the release branch later. The Debian package of the image has those fixes. +// +// To update after a Playwright upgrade, for the version that the error of install.js names: +// 1. Find where the release was branched off: chromium_main_branch_position in +// https://chromiumdash.appspot.com/fetch_version?version= +// 2. For Linux_x64 and for Win_x64, take the highest snapshot build that is not above that position. Builds are listed by +// the start of their number, so shorten the start until one appears: +// https://www.googleapis.com/storage/v1/b/chromium-browser-snapshots/o?delimiter=/&fields=prefixes&prefix=Linux_x64/ +// 3. Set the version (the release from the error, ending in .0) and the two paths, and build the module. It fails with +// the SHA-256 of an archive: put it in the sha256 of that platform and build again, until both pass. +// install.js also fails if an unpacked build is not the version set here. +module.exports = { + // The packages: snapshot builds of the open source code, published by the Chromium project. + // exclude: glob patterns of the files that are not packaged + // strip: glob patterns of the executables to strip of their symbols, when GNU strip is installed + snapshot: { + version: '156.0.8078.0', + baseUrl: 'https://commondatastorage.googleapis.com/chromium-browser-snapshots', + // The .pak.info files, 70 MB, are left from the build of the translations; the browser does not read them + linux: { path: 'Linux_x64/1706520/chrome-linux.zip', sha256: '6b62846a868ea3ee675f77600790877a428dfb2428c940f8eff99db1038f9815', + exclude: ['locales/*.pak.info'], + // The Linux builds come with their symbols, 180 MB + strip: ['chrome', 'chrome_crashpad_handler', 'chrome_sandbox', '*.so*'] }, + // interactive_ui_tests.exe is a test program of 348 MB that the service does not need + windows: { path: 'Win_x64/1706509/chrome-win.zip', sha256: '6bdfecb33dbfa7159e5666798bdc28c76347bef913573e899cb43930b78d26cc', + exclude: ['interactive_ui_tests.exe'] } + } +}; diff --git a/msa/web-report/docker/Dockerfile b/msa/web-report/docker/Dockerfile index 9e1d9404e3..17457c153c 100644 --- a/msa/web-report/docker/Dockerfile +++ b/msa/web-report/docker/Dockerfile @@ -10,7 +10,8 @@ ARG DEBIAN_FRONTEND=noninteractive ENV NODE_ENV production ENV DOCKER_MODE true -ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright +# The browser is the chromium package of Debian, installed below +ENV CHROME_EXECUTABLE=/usr/bin/chromium COPY start-web-report.sh /tmp/ @@ -26,17 +27,13 @@ COPY src/config ./config COPY src/inspectorShim.js src/server.js ./ RUN apt-get update \ - && apt-get install -yq --no-install-recommends fonts-noto-cjk-extra fonts-roboto fonts-noto-color-emoji fonts-unifont libfreetype6 xfonts-scalable fonts-liberation \ - fonts-ipafont-gothic fonts-wqy-zenhei fonts-tlwg-loma-otf fonts-freefont-ttf fontconfig libasound2 libatk-bridge2.0-0 libatk1.0-0 libatspi2.0-0 \ - libcairo2 libcups2 libdbus-1-3 libdrm2 libgbm1 libglib2.0-0 libnspr4 libnss3 libpango-1.0-0 libwayland-client0 libx11-6 libxcb1 libxcomposite1 \ - libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 \ + && apt-get install -yq --no-install-recommends chromium fontconfig fonts-noto-cjk-extra fonts-roboto fonts-noto-color-emoji fonts-unifont \ + xfonts-scalable fonts-liberation fonts-ipafont-gothic fonts-wqy-zenhei fonts-tlwg-loma-otf fonts-freefont-ttf \ && rm -rf /var/lib/apt/lists/* \ && chmod a+x /tmp/*.sh \ && mv /tmp/start-web-report.sh /usr/bin \ && chown -R node:node ${pkg.installFolder} \ - && mkdir /ms-playwright \ - && yarn install --production --non-interactive --network-concurrency 4 --network-timeout 100000 --mutex network && yarn cache clean --all \ - && chmod -R 777 /ms-playwright + && yarn install --production --non-interactive --network-concurrency 4 --network-timeout 100000 --mutex network && yarn cache clean --all USER node diff --git a/msa/web-report/docker/start-web-report.sh b/msa/web-report/docker/start-web-report.sh index 390c77e2d7..6b2a050558 100755 --- a/msa/web-report/docker/start-web-report.sh +++ b/msa/web-report/docker/start-web-report.sh @@ -14,7 +14,5 @@ source "${CONF_FOLDER}/${configfile}" cd ${pkg.installFolder} -export CHROME_EXECUTABLE=$(node -e "console.log(require('playwright-chromium').chromium.executablePath());") - # This will forward this PID 1 to the node.js and forward SIGTERM for graceful shutdown as well exec node server.js diff --git a/msa/web-report/install.js b/msa/web-report/install.js index 842978aaec..64312b6333 100644 --- a/msa/web-report/install.js +++ b/msa/web-report/install.js @@ -1,46 +1,149 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +const fs = require('fs'); const fse = require('fs-extra'); const path = require('path'); -const { execFileSync } = require('child_process'); +const crypto = require('crypto'); +const { execFile, execFileSync } = require('child_process'); +const { promisify } = require('util'); +const { Transform } = require('stream'); +const { pipeline } = require('stream/promises'); +// The helpers that Playwright downloads its browsers with: httpRequest follows HTTPS_PROXY and redirects, extractZip needs no unzip tool +const { httpRequest, extractZip } = require('playwright-core/lib/coreBundle').utils; +const { snapshot } = require('./chromium'); + +const DOWNLOAD_ATTEMPTS = 3; -// Chromium builds packaged with the service, downloaded by the Playwright CLI as if it ran on the target platform. const PLATFORMS = { - linux: { hostPlatform: 'ubuntu24.04-x64', downloadDir: 'chromiumLinux', chromeDir: 'chrome-linux64', binary: 'tb-web-report', pkgOutput: 'thingsboard-web-report-linux' }, - windows: { hostPlatform: 'win64', downloadDir: 'chromiumWin', chromeDir: 'chrome-win64', binary: 'tb-web-report.exe', pkgOutput: 'thingsboard-web-report-win.exe' } + linux: { + ...snapshot.linux, binary: 'tb-web-report', pkgOutput: 'thingsboard-web-report-linux', + // The version is written into the executable + hasVersion: dir => fileContains(path.join(dir, 'chrome'), snapshot.version) + }, + windows: { + ...snapshot.windows, binary: 'tb-web-report.exe', pkgOutput: 'thingsboard-web-report-win.exe', + hasVersion: dir => fse.pathExists(path.join(dir, `${snapshot.version}.manifest`)) + } }; (async() => { - for (const [targetDir, platform] of Object.entries(PLATFORMS)) { - const downloadDir = path.join(projectRoot(), 'target', platform.downloadDir); - installChromium(platform.hostPlatform, downloadDir); - const chromiumDir = path.join(targetPackageDir(targetDir), 'chromium'); - await fse.emptyDir(chromiumDir); - await fse.copy(path.join(downloadDir, chromiumRevisionDir(), platform.chromeDir), chromiumDir); + checkPlaywrightVersion(); + await Promise.all(Object.entries(PLATFORMS).map(async ([targetDir, platform]) => { + await installChromium(platform, path.join(projectRoot(), 'target', 'chromium-' + targetDir), + path.join(targetPackageDir(targetDir), 'chromium')); await fse.move(path.join(projectRoot(), 'target', platform.pkgOutput), path.join(targetPackageDir(targetDir), 'bin', platform.binary), {overwrite: true}); - } + })); })().catch(e => { console.error(e); process.exit(1); }); -function installChromium(hostPlatform, downloadDir) { - execFileSync(process.execPath, [path.join(path.dirname(require.resolve('playwright-core/package.json')), 'cli.js'), 'install', '--no-shell', 'chromium'], { - stdio: 'inherit', - env: { - ...process.env, - PLAYWRIGHT_HOST_PLATFORM_OVERRIDE: hostPlatform, - PLAYWRIGHT_BROWSERS_PATH: downloadDir, - PLAYWRIGHT_SKIP_BROWSER_GC: '1' +function checkPlaywrightVersion() { + const browsers = fse.readJsonSync(path.join(path.dirname(require.resolve('playwright-core/package.json')), 'browsers.json')).browsers; + const chromium = browsers.find(browser => browser.name === 'chromium'); + if (!chromium) { + throw new Error('playwright-core/browsers.json does not list chromium'); + } + // The release is the first three numbers; the last one counts the fixes on its branch and differs between builds + const build = version => version.split('.').slice(0, 3).join('.'); + if (build(chromium.browserVersion) !== build(snapshot.version)) { + throw new Error(`playwright-core expects Chromium ${chromium.browserVersion}, the snapshot build in chromium.js is ${snapshot.version}`); + } +} + +async function installChromium(platform, downloadDir, chromiumDir) { + await fse.emptyDir(downloadDir); + const archive = path.join(downloadDir, 'chromium.zip'); + await download(`${snapshot.baseUrl}/${platform.path}`, archive, platform.sha256); + await extractZip(archive, { dir: downloadDir }); + const unpacked = path.join(downloadDir, path.basename(platform.path, '.zip')); + for await (const excluded of fs.promises.glob(platform.exclude || [], { cwd: unpacked })) { + await fse.remove(path.join(unpacked, excluded)); + } + if (platform.strip) { + await stripExecutables(unpacked, platform.strip); + } + if (!await platform.hasVersion(unpacked)) { + throw new Error(`${platform.path} is not Chromium ${snapshot.version}; check the build number in chromium.js`); + } + await fse.move(unpacked, chromiumDir, { overwrite: true }); + await fse.remove(downloadDir); +} + +// Fails unless the SHA-256 of the downloaded file is the expected one. Tries again when the connection or the server +// fails, but not for an answer such as 404, which would be the same again. +async function download(url, file, sha256) { + let actual; + for (let attempt = 1; actual === undefined; attempt++) { + try { + actual = await downloadOnce(url, file); + } catch (e) { + if (e.statusCode < 500 || attempt === DOWNLOAD_ATTEMPTS) { + throw e; + } + console.warn(`${e.message}; trying again`); } + } + if (actual !== sha256) { + throw new Error(`${url} has SHA-256 ${actual}, expected ${sha256}`); + } +} + +// Writes the file while it is downloaded, and gives its SHA-256 +function downloadOnce(url, file) { + return new Promise((resolve, reject) => { + const fail = (reason, statusCode) => reject(Object.assign(new Error(`Cannot download ${url}: ${reason}`), { statusCode })); + httpRequest({ url, socketTimeout: 60000 }, response => { + if (response.statusCode !== 200) { + response.resume(); + fail(`HTTP ${response.statusCode}`, response.statusCode); + return; + } + const hash = crypto.createHash('sha256'); + const hashing = new Transform({ + transform(chunk, encoding, callback) { + hash.update(chunk); + callback(null, chunk); + } + }); + pipeline(response, hashing, fs.createWriteStream(file)).then(() => resolve(hash.digest('hex')), e => fail(e.message)); + }, e => fail(e.message)); }); } -function chromiumRevisionDir() { - const browsers = fse.readJsonSync(path.join(projectRoot(), 'node_modules', 'playwright-core', 'browsers.json')).browsers; - return 'chromium-' + browsers.find(b => b.name === 'chromium').revision; +// Strips the symbols with GNU strip, which reads the Linux executables on any build machine. Without it, as on macOS +// or where binutils is not installed, the executables are packaged as they are. +async function stripExecutables(dir, patterns) { + if (!hasGnuStrip()) { + console.warn('strip not found, Linux Chromium left unstripped (+~180 MB); install GNU binutils to strip it'); + return; + } + for await (const file of fs.promises.glob(patterns, { cwd: dir })) { + await promisify(execFile)('strip', ['--strip-unneeded', path.join(dir, file)]); + } +} + +function hasGnuStrip() { + try { + return execFileSync('strip', ['--version'], { encoding: 'utf8' }).includes('GNU strip'); + } catch { + return false; + } +} + +async function fileContains(file, text) { + const needle = Buffer.from(text); + let tail = Buffer.alloc(0); + for await (const chunk of fs.createReadStream(file)) { + const data = Buffer.concat([tail, chunk]); + if (data.includes(needle)) { + return true; + } + tail = data.subarray(data.length - needle.length + 1); + } + return false; } function projectRoot() { diff --git a/msa/web-report/package.json b/msa/web-report/package.json index 169548ffc0..e247cdde62 100644 --- a/msa/web-report/package.json +++ b/msa/web-report/package.json @@ -18,7 +18,6 @@ "config": "~4.4.2", "express": "~5.3.0", "js-yaml": "^4.3.2", - "playwright-chromium": "~1.64.1", "playwright-core": "~1.64.1", "winston": "~3.19.0", "winston-daily-rotate-file": "~5.0.0" diff --git a/msa/web-report/pom.xml b/msa/web-report/pom.xml index 7bba753b18..fc1264adb9 100644 --- a/msa/web-report/pom.xml +++ b/msa/web-report/pom.xml @@ -321,15 +321,16 @@ application - chrome-for-testing + chromium ${chromium.version} - Chrome for Testing build downloaded by Playwright, used to render reports. - pkg:generic/google/chrome-for-testing@${chromium.version}?os=linux + Chromium snapshot build of the Chromium project, used to render reports. + pkg:generic/chromium/chromium@${chromium.version}?os=linux cpe:2.3:a:google:chrome:${chromium.version}:*:*:*:*:*:*:* + BSD-3-Clause - Google LLC + The Chromium Authors - https://googlechromelabs.github.io/chrome-for-testing/ + https://www.chromium.org ${pkg.linux.dist}/chromium/chrome @@ -340,15 +341,16 @@ application - chrome-for-testing + chromium ${chromium.version} - Chrome for Testing build downloaded by Playwright, used to render reports. - pkg:generic/google/chrome-for-testing@${chromium.version}?os=windows + Chromium snapshot build of the Chromium project, used to render reports. + pkg:generic/chromium/chromium@${chromium.version}?os=windows cpe:2.3:a:google:chrome:${chromium.version}:*:*:*:*:*:*:* + BSD-3-Clause - Google LLC + The Chromium Authors - https://googlechromelabs.github.io/chrome-for-testing/ + https://www.chromium.org ${pkg.win.dist}/chromium/chrome.exe @@ -367,48 +369,6 @@ ${project.build.directory}/sbom/tb-web-report.cdx.json ${pkg.installFolder} - - application - chrome-for-testing - ${chromium.version} - Chrome for Testing build downloaded by Playwright to /ms-playwright, used to render reports. - pkg:generic/google/chrome-for-testing@${chromium.version}?os=linux&arch=@{architecture} - cpe:2.3:a:google:chrome:${chromium.version}:*:*:*:*:*:*:* - - Google LLC - - https://googlechromelabs.github.io/chrome-for-testing/ - - - - - application - chrome-headless-shell - ${chromium-headless-shell.version} - Chrome Headless Shell build downloaded by Playwright to /ms-playwright. - pkg:generic/google/chrome-headless-shell@${chromium-headless-shell.version}?os=linux&arch=@{architecture} - cpe:2.3:a:google:chrome:${chromium-headless-shell.version}:*:*:*:*:*:*:* - - Google LLC - - https://googlechromelabs.github.io/chrome-for-testing/ - - - - - application - playwright-ffmpeg - ${ffmpeg.revision} - FFmpeg build by Playwright (revision ${ffmpeg.revision}), downloaded to /ms-playwright. - pkg:generic/microsoft/playwright-ffmpeg@${ffmpeg.revision}?os=linux&arch=@{architecture} - LGPL-2.1-or-later - - Microsoft Corporation - - https://playwright.dev - - - diff --git a/msa/web-report/sbom-check.js b/msa/web-report/sbom-check.js index cd4d3f76df..3f2723cea6 100644 --- a/msa/web-report/sbom-check.js +++ b/msa/web-report/sbom-check.js @@ -12,7 +12,7 @@ const BASE_BINARY = /fetched-v(\d+\.\d+\.\d+)-/; (() => { const listed = listedPackages(JSON.parse(fs.readFileSync(SBOM_FILE, 'utf8'))); - const versions = playwrightVersions(); + const versions = { 'chromium.version': require('./chromium').snapshot.version }; for (const [os, log] of Object.entries(PKG_LOGS)) { const output = fs.readFileSync(path.join(TARGET_DIR, log), 'utf8').replace(/\x1b\[[0-9;]*m/g, ''); const baseBinary = BASE_BINARY.exec(output); @@ -74,20 +74,3 @@ function packageDir(file) { } return parts.slice(0, index + (scoped ? 3 : 2)).join(path.sep); } - -function playwrightVersions() { - const browsers = JSON.parse(fs.readFileSync(path.join(path.dirname(require.resolve('playwright-core/package.json')), 'browsers.json'), 'utf8')).browsers; - const browser = name => { - const found = browsers.find(candidate => candidate.name === name); - if (!found) { - throw new Error(`playwright-core/browsers.json does not list ${name}`); - } - return found; - }; - return { - 'chromium.version': browser('chromium').browserVersion, - 'chromium-headless-shell.version': browser('chromium-headless-shell').browserVersion, - 'ffmpeg.revision': browser('ffmpeg').revision - }; -} - diff --git a/msa/web-report/server.ts b/msa/web-report/server.ts index e000c860c4..758f016cb2 100644 --- a/msa/web-report/server.ts +++ b/msa/web-report/server.ts @@ -5,8 +5,7 @@ import express from 'express'; import bodyParser from 'body-parser'; import config from 'config'; import { _logger } from './config/logger'; -import { chromium } from 'playwright-chromium'; -import { Browser, LaunchOptions } from 'playwright-core'; +import { Browser, chromium, LaunchOptions } from 'playwright-core'; import { route } from './api/routes/tbWebReportRoutes'; import { TbWebReportPageQueue } from './api/controllers/tbWebReportPageQueue'; diff --git a/msa/web-report/yarn.lock b/msa/web-report/yarn.lock index 82f160bb5d..61a026c6d0 100644 --- a/msa/web-report/yarn.lock +++ b/msa/web-report/yarn.lock @@ -1307,14 +1307,7 @@ picomatch@^4.0.2, picomatch@^4.0.4: resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.7.tgz#6313360034ccb36b3dc61ecbdff78121f90fe21f" integrity sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA== -playwright-chromium@~1.64.1: - version "1.64.1" - resolved "https://registry.yarnpkg.com/playwright-chromium/-/playwright-chromium-1.64.1.tgz#81aec8925514050c0ac5bc08fa231ed189ab0e86" - integrity sha512-lvAzvvIRtbHaeLwl7XoUkhSNuWHKshbrYv2sjqYgLQS4SsTTwgSTlg9BwU5LeGxYkHxBXTnKtNDEQdZSOj/01g== - dependencies: - playwright-core "1.64.1" - -playwright-core@1.64.1, playwright-core@~1.64.1: +playwright-core@~1.64.1: version "1.64.1" resolved "https://registry.yarnpkg.com/playwright-core/-/playwright-core-1.64.1.tgz#ca9ec82d7da6ced1b2326ec59ef097aaa9a29f94" integrity sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ== diff --git a/msa/web-ui/negotiator.d.ts b/msa/web-ui/negotiator.d.ts new file mode 100644 index 0000000000..c98d111f40 --- /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 3053dbe185..bfcb04bb7d 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -14,18 +14,17 @@ "sbom": "node ../../tools/src/main/javascript/yarn-sbom.js target/sbom/tb-web-ui.cdx.json application --all-platforms" }, "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": { "@cyclonedx/cyclonedx-library": "10.3.0", - "@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 9aa316e78f..59cb9dec9d 100644 --- a/msa/web-ui/server.ts +++ b/msa/web-ui/server.ts @@ -1,14 +1,16 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import express from 'express'; import config from 'config'; 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 +18,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...'); @@ -115,12 +129,20 @@ let connections: Socket[] = []; } app.use(historyApiFallback()); - if (compressionEnabled) { - app.use(compression()); - } const root = path.join(webDir, 'public'); + // No per-request compression: zlib/brotli fragment native memory that glibc never returns, until OOM + if (compressionEnabled) { + 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) => { @@ -167,6 +189,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 70dce9222f..de9d88afe3 100644 --- a/msa/web-ui/yarn.lock +++ b/msa/web-ui/yarn.lock @@ -317,14 +317,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" @@ -350,7 +342,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== @@ -588,7 +580,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== @@ -672,27 +664,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" @@ -735,13 +706,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" @@ -766,11 +730,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" @@ -1236,7 +1195,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== @@ -1280,11 +1239,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" @@ -1303,18 +1257,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" @@ -1353,11 +1302,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" @@ -1544,7 +1488,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== @@ -1939,7 +1883,7 @@ validate-npm-package-license@^3.0.4: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" -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 a54a2ff9a7..6afe3dee4d 100755 --- a/pom.xml +++ b/pom.xml @@ -87,7 +87,7 @@ 4.2.19.Final 2.0.84.Final 11.0.27 - 2.21.7 + 2.21.8 42.7.14 1.11.4 5.34.0 @@ -151,7 +151,7 @@ 8.10.1 3.5.3 0.15.12 - 20250517 + 20260719 3.1.2 1.11.4 1.12.701 diff --git a/tools/src/main/python/license-headers/curations.json b/tools/src/main/python/license-headers/curations.json index 0c8aff5941..4bf0cbe1bf 100644 --- a/tools/src/main/python/license-headers/curations.json +++ b/tools/src/main/python/license-headers/curations.json @@ -1157,7 +1157,7 @@ "path": "msa/web-report/pom.xml", "header": "busl", "reason": "Build descriptor of the PE-only web-report module; CE has no web-report module. The only CE version is an empty file (blob e69de29bb2d) added by stray commit 2b1c5d92f3a, pushed to fix/maven-node-lts-4.3 after #16417 merged and carried into lts-4.4 via #16419; it never reached CE lts-4.3 and is not the origin of this file.", - "contentHash": "sha256:48ee3956937386c95ebb2b95a4981506203c00ce276aa6003fecfc0ddaf04218" + "contentHash": "sha256:9ddddeec7898c7232abc7b16c696fdad4f3825d15d3810369f621609f2678f65" }, { "path": "report/src/main/conf/logback.xml", diff --git a/ui-ngx/compress-build.js b/ui-ngx/compress-build.js new file mode 100644 index 0000000000..a81d7f610f --- /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 acf7ffcfeb..50f07f8bd5 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 1a7a15c765..0364996e3c 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -6,6 +6,7 @@ "start": "node --max_old_space_size=8192 ./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=8192 ./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", "sbom": "node ../tools/src/main/javascript/yarn-sbom.js target/generated-resources/META-INF/sbom/ui-ngx.cdx.json library", diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index 7758fa08fc..aa9013d9b6 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -127,6 +127,15 @@ --mutex network run build:prod + + yarn compress + + yarn + + + run compress + + diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html index 3d4b515a28..fcf1625c81 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html @@ -93,7 +93,7 @@ } @case (FormFieldType.SELECT) { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} @@ -110,7 +110,7 @@ } @case (FormFieldType.STRING_AUTOCOMPLETE) { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} } @case (FormFieldType.PASSWORD) { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} } @case (FormFieldType.INTEGER) { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} } @default { - {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} { - if ($event) { - $event.stopPropagation(); - } - return this.dialog.open(ImportDashboardFileDialogComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - dashboard - } - }).afterClosed(); - } - public selectOwner($event: Event, selectOwnerTitle: string, confirmSelectTitle: string, placeholderText: string, notFoundText: string, requiredText: string, onOwnerSelected?: (targetOwnerId: EntityId) => Observable, diff --git a/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts b/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts index ec56f4b220..4b6e7a93f0 100644 --- a/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts +++ b/ui-ngx/src/app/modules/home/pages/dashboard/dashboard-group-config.factory.ts @@ -254,7 +254,10 @@ export class DashboardGroupConfigFactory implements EntityGroupStateConfigFactor } importDashboardFile($event: Event, dashboard: DashboardInfo, config: GroupEntityTableConfig) { - this.homeDialogs.importDashboardFile($event, dashboard).subscribe( + if ($event) { + $event.stopPropagation(); + } + this.importExport.importDashboardVersion(dashboard, this.editMissingAliases.bind(this)).subscribe( (res) => { if (res) { config.updateData(); diff --git a/ui-ngx/src/app/modules/home/pages/dashboard/dashboard.module.ts b/ui-ngx/src/app/modules/home/pages/dashboard/dashboard.module.ts index 10c0b1b2f5..4388b15cf5 100644 --- a/ui-ngx/src/app/modules/home/pages/dashboard/dashboard.module.ts +++ b/ui-ngx/src/app/modules/home/pages/dashboard/dashboard.module.ts @@ -12,14 +12,12 @@ import { DASHBOARD_GROUP_CONFIG_FACTORY } from '@home/models/group/group-entitie import { DashboardGroupConfigFactory } from '@home/pages/dashboard/dashboard-group-config.factory'; import { DashboardRoutingModule } from '@home/pages/dashboard/dashboard-routing.module'; import { DashboardTableHeaderComponent } from '@home/pages/dashboard/dashboard-table-header.component'; -import { ImportDashboardFileDialogComponent } from "@home/pages/dashboard/import-dashboard-file-dialog.component"; @NgModule({ declarations: [ DashboardFormComponent, DashboardTableHeaderComponent, - PublicDashboardLinkDialogComponent, - ImportDashboardFileDialogComponent + PublicDashboardLinkDialogComponent ], imports: [ CommonModule, diff --git a/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts index 2432a7bbea..c63b23a9ce 100644 --- a/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/pages/dashboard/dashboards-table-config.resolver.ts @@ -286,7 +286,10 @@ export class DashboardsTableConfigResolver { } importDashboardFile($event: Event, dashboard: DashboardInfo, config: EntityTableConfig) { - this.homeDialogs.importDashboardFile($event, dashboard).subscribe( + if ($event) { + $event.stopPropagation(); + } + this.importExport.importDashboardVersion(dashboard, this.editMissingAliases.bind(this)).subscribe( (res) => { if (res) { config.updateData(); diff --git a/ui-ngx/src/app/modules/home/pages/dashboard/import-dashboard-file-dialog.component.html b/ui-ngx/src/app/modules/home/pages/dashboard/import-dashboard-file-dialog.component.html deleted file mode 100644 index 298014fa74..0000000000 --- a/ui-ngx/src/app/modules/home/pages/dashboard/import-dashboard-file-dialog.component.html +++ /dev/null @@ -1,50 +0,0 @@ - -
- -

{{ 'dashboard.update-new-version' | translate }}

- - -
- @if (isLoading$ | async) { - - - } @else { -
- } -
- - -
- -
- - -
-
diff --git a/ui-ngx/src/app/modules/home/pages/dashboard/import-dashboard-file-dialog.component.ts b/ui-ngx/src/app/modules/home/pages/dashboard/import-dashboard-file-dialog.component.ts deleted file mode 100644 index 1b76ca539f..0000000000 --- a/ui-ngx/src/app/modules/home/pages/dashboard/import-dashboard-file-dialog.component.ts +++ /dev/null @@ -1,77 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { Component, Inject, OnInit } from '@angular/core'; -import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { FormBuilder, FormGroup } from '@angular/forms'; -import { DashboardService } from '@core/http/dashboard.service'; -import { DashboardInfo } from '@app/shared/models/dashboard.models'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; -import { DialogComponent } from '@shared/components/dialog.component'; -import { Router } from '@angular/router'; - -export interface DashboardInfoDialogData { - dashboard: DashboardInfo; -} - -@Component({ - selector: 'tb-import-dashboard-file-dialog', - templateUrl: './import-dashboard-file-dialog.component.html', - styleUrls: [], - standalone: false -}) -export class ImportDashboardFileDialogComponent extends DialogComponent implements OnInit { - - private dashboard: DashboardInfo; - currentFileName: string = ''; - uploadFileFormGroup: FormGroup; - - constructor(protected store: Store, - protected router: Router, - @Inject(MAT_DIALOG_DATA) public data: DashboardInfoDialogData, - private dashboardService: DashboardService, - protected dialogRef: MatDialogRef, - private fb: FormBuilder) { - super(store, router, dialogRef); - this.dashboard = data.dashboard; - } - - ngOnInit(): void { - this.uploadFileFormGroup = this.fb.group({ - file: [null] - }); - } - - cancel(): void { - this.dialogRef.close(); - } - - save() { - const fileControl = this.uploadFileFormGroup.get('file'); - if (!fileControl || !fileControl.value) { - return; - } - - const dashboardContent = { - ...fileControl.value, - description: this.dashboard.configuration.description - }; - this.dashboard.configuration = dashboardContent; - - this.dashboardService.saveDashboard(this.dashboard).subscribe(() => { - this.dialogRef.close(true); - }) - } - - loadDataFromJsonContent(content: string): any { - try { - const importData = JSON.parse(content); - return importData ? importData['configuration'] : importData; - } catch (err) { - this.store.dispatch(new ActionNotificationShow({message: err.message, type: 'error'})); - return null; - } - } -} diff --git a/ui-ngx/src/app/shared/import-export/import-export.service.ts b/ui-ngx/src/app/shared/import-export/import-export.service.ts index 38b4ab0ce4..888a267071 100644 --- a/ui-ngx/src/app/shared/import-export/import-export.service.ts +++ b/ui-ngx/src/app/shared/import-export/import-export.service.ts @@ -7,9 +7,9 @@ import { TranslateService } from '@ngx-translate/core'; import { select, Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { ActionNotificationShow } from '@core/notification/notification.actions'; -import { BreakpointId, Dashboard, DashboardLayoutId } from '@shared/models/dashboard.models'; +import { BreakpointId, Dashboard, DashboardInfo, DashboardLayoutId } from '@shared/models/dashboard.models'; import { DatePipe } from '@angular/common'; -import { deepClone, guid, isDate, isDefined, isNotEmptyStr, isNumber, isObject, isString, isUndefined, unwrapModule } from '@core/utils'; +import { deepClone, guid, isDate, isDefined, isNotEmptyStr, isObject, isString, isUndefined, unwrapModule } from '@core/utils'; import { AliasesInfo, @@ -22,7 +22,8 @@ import { import { MatDialog } from '@angular/material/dialog'; import { ImportDialogComponent, ImportDialogData } from '@shared/import-export/import-dialog.component'; import { forkJoin, Observable, of, Subject } from 'rxjs'; -import { catchError, map, mergeMap, switchMap, take, tap } from 'rxjs/operators'; +import { catchError, defaultIfEmpty, map, mergeMap, switchMap, take, tap } from 'rxjs/operators'; +import { HttpErrorResponse, HttpStatusCode } from '@angular/common/http'; import { DashboardUtilsService } from '@core/services/dashboard-utils.service'; import { EntityService } from '@core/http/entity.service'; import { ExportRow, Widget, WidgetActionsMap, WidgetActionType, WidgetSize, WidgetTypeDetails } from '@shared/models/widget.models'; @@ -266,48 +267,33 @@ export class ImportExportService { onEditMissingAliases: editMissingAliasesFunction, entityGroupId?: string): Observable { return this.openImportDialog('dashboard.import', 'dashboard.dashboard-file').pipe( mergeMap((dashboard: Dashboard) => { - if (!this.validateImportedDashboard(dashboard)) { - this.store.dispatch(new ActionNotificationShow( - {message: this.translate.instant('dashboard.invalid-dashboard-file-error'), - type: 'error'})); - throw new Error('Invalid dashboard file'); - } else { - dashboard = this.prepareImport(dashboard); - dashboard = this.dashboardUtils.validateAndUpdateDashboard(dashboard); - dashboard.customerId = customerId; - let aliasIds = null; - const entityAliases = dashboard.configuration.entityAliases; - if (entityAliases) { - aliasIds = Object.keys(entityAliases); - } - if (aliasIds && aliasIds.length > 0) { - return this.processEntityAliases(entityAliases, aliasIds).pipe( - mergeMap((missingEntityAliases) => { - if (Object.keys(missingEntityAliases).length > 0) { - return onEditMissingAliases(this.dashboardUtils.getWidgetsArray(dashboard), - false, 'dashboard.dashboard-import-missing-aliases-title', - missingEntityAliases).pipe( - mergeMap((updatedEntityAliases) => { - for (const aliasId of Object.keys(updatedEntityAliases)) { - entityAliases[aliasId] = updatedEntityAliases[aliasId]; - } - return this.saveImportedDashboard(dashboard, entityGroupId); - }) - ); - } else { - return this.saveImportedDashboard(dashboard, entityGroupId); - } - } - )); - } else { - return this.saveImportedDashboard(dashboard, entityGroupId); - } - } + dashboard = this.prepareImportedDashboard(dashboard); + dashboard.customerId = customerId; + return this.resolveMissingAliases(dashboard, onEditMissingAliases); }), + mergeMap((dashboard) => this.saveImportedDashboard(dashboard, entityGroupId)), catchError(() => of(null)) ); } + public importDashboardVersion(dashboard: DashboardInfo, + onEditMissingAliases: editMissingAliasesFunction): Observable { + return this.openImportDialog('dashboard.update-new-version', 'dashboard.upload-file-to-update').pipe( + mergeMap((imported: Dashboard) => + this.resolveMissingAliases(this.prepareImportedDashboard(imported), onEditMissingAliases)), + mergeMap((imported) => this.dashboardService.saveDashboard({ + ...dashboard, + configuration: {...imported.configuration, description: dashboard.configuration?.description}, + resources: imported.resources + }).pipe( + map(() => true), + defaultIfEmpty(true), + catchError((err) => of(err instanceof HttpErrorResponse && err.status === HttpStatusCode.Conflict)) + )), + catchError(() => of(false)) + ); + } + public exportWidget(dashboard: Dashboard, sourceState: string, sourceLayout: DashboardLayoutId, widget: Widget, widgetTitle: string, breakpoint: BreakpointId) { const widgetItem = this.itembuffer.prepareWidgetItem(dashboard, sourceState, sourceLayout, widget, breakpoint); @@ -1315,10 +1301,40 @@ export class ImportExportService { } private validateImportedDashboard(dashboard: Dashboard): boolean { - if (isUndefined(dashboard.title) || isUndefined(dashboard.configuration)) { - return false; + return isObject(dashboard) && !Array.isArray(dashboard) && isDefined(dashboard.title) + && isObject(dashboard.configuration) && !Array.isArray(dashboard.configuration); + } + + private prepareImportedDashboard(dashboard: Dashboard): Dashboard { + if (!this.validateImportedDashboard(dashboard)) { + this.store.dispatch(new ActionNotificationShow( + {message: this.translate.instant('dashboard.invalid-dashboard-file-error'), + type: 'error'})); + throw new Error('Invalid dashboard file'); } - return true; + return this.dashboardUtils.validateAndUpdateDashboard(this.prepareImport(dashboard)); + } + + private resolveMissingAliases(dashboard: Dashboard, onEditMissingAliases: editMissingAliasesFunction): Observable { + const entityAliases = dashboard.configuration.entityAliases; + const aliasIds = entityAliases ? Object.keys(entityAliases) : []; + if (!aliasIds.length) { + return of(dashboard); + } + return this.processEntityAliases(entityAliases, aliasIds).pipe( + mergeMap((missingEntityAliases) => { + if (!Object.keys(missingEntityAliases).length) { + return of(dashboard); + } + return onEditMissingAliases(this.dashboardUtils.getWidgetsArray(dashboard), + false, 'dashboard.dashboard-import-missing-aliases-title', missingEntityAliases).pipe( + map((updatedEntityAliases) => { + Object.assign(entityAliases, updatedEntityAliases); + return dashboard; + }) + ); + }) + ); } private validateImportedWidget(widgetItem: WidgetItem): boolean {