Browse Source
# Conflicts: # application/src/main/resources/thingsboard.yml # pom.xmlpull/16341/head
31 changed files with 573 additions and 430 deletions
@ -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-<md5>.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(); |
|||
} |
|||
|
|||
} |
|||
@ -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=<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/<start of the position>
|
|||
// 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'] } |
|||
} |
|||
}; |
|||
@ -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); |
|||
}); |
|||
@ -1,50 +0,0 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors |
|||
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 |
|||
|
|||
--> |
|||
<form [formGroup]="uploadFileFormGroup" (ngSubmit)="save()" style="width: 800px;"> |
|||
<mat-toolbar color="tb-primary" class="tb-bottom-border"> |
|||
<h2>{{ 'dashboard.update-new-version' | translate }}</h2> |
|||
<span class="flex-1"></span> |
|||
<button mat-icon-button |
|||
(click)="cancel()" |
|||
type="button"> |
|||
<mat-icon class="material-icons">close</mat-icon> |
|||
</button> |
|||
</mat-toolbar> |
|||
@if (isLoading$ | async) { |
|||
<mat-progress-bar color="warn" mode="indeterminate"> |
|||
</mat-progress-bar> |
|||
} @else { |
|||
<div style="height: 4px;"></div> |
|||
} |
|||
<div mat-dialog-content> |
|||
<tb-file-input [contentConvertFunction]="loadDataFromJsonContent" |
|||
[existingFileName]="currentFileName" |
|||
(fileNameChanged)="currentFileName = $event" |
|||
label="{{'dashboard.upload-file-to-update' | translate}}" |
|||
formControlName="file" |
|||
dropLabel="{{ 'import.drop-json-file-or' | translate }}" |
|||
accept=".json,application/json" |
|||
allowedExtensions="json"> |
|||
</tb-file-input> |
|||
</div> |
|||
|
|||
<div mat-dialog-actions class="flex flex-row items-center justify-end"> |
|||
<button mat-button color="primary" |
|||
type="button" |
|||
[disabled]="(isLoading$ | async)" |
|||
(click)="cancel()" cdkFocusInitial> |
|||
{{ 'action.cancel' | translate }} |
|||
</button> |
|||
<button mat-raised-button color="primary" |
|||
type="submit" |
|||
[disabled]="(isLoading$ | async) || uploadFileFormGroup.invalid |
|||
|| !uploadFileFormGroup.dirty"> |
|||
{{ 'action.save' | translate }} |
|||
</button> |
|||
</div> |
|||
</form> |
|||
@ -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<ImportDashboardFileDialogComponent> implements OnInit { |
|||
|
|||
private dashboard: DashboardInfo; |
|||
currentFileName: string = ''; |
|||
uploadFileFormGroup: FormGroup; |
|||
|
|||
constructor(protected store: Store<AppState>, |
|||
protected router: Router, |
|||
@Inject(MAT_DIALOG_DATA) public data: DashboardInfoDialogData, |
|||
private dashboardService: DashboardService, |
|||
protected dialogRef: MatDialogRef<ImportDashboardFileDialogComponent>, |
|||
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; |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue