11 changed files with 306 additions and 120 deletions
@ -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-<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,12 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||
|
|
||||
|
// negotiator 1.x ships no types, and @types/negotiator (0.6) lacks the `preferred` option
|
||||
|
declare module 'negotiator' { |
||||
|
import { IncomingMessage } from 'http'; |
||||
|
|
||||
|
export default class Negotiator { |
||||
|
constructor(request: IncomingMessage); |
||||
|
encoding(available: string[], options?: { preferred?: string[] }): string | undefined; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,82 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||
|
|
||||
|
// Writes .br and .gz copies of the production build's files, served as-is by the monolith and msa/web-ui.
|
||||
|
// Not an esbuild plugin: Angular gives custom plugins only the browser code bundle, not polyfills,
|
||||
|
// global styles/scripts or copied assets.
|
||||
|
|
||||
|
const os = require('node:os'); |
||||
|
|
||||
|
// zlib runs on the libuv thread pool (4 threads by default), which must be sized before its first use.
|
||||
|
// More than 8 threads gains nothing: the largest chunk alone takes ~5 s.
|
||||
|
const concurrency = Math.min(os.availableParallelism(), 8); |
||||
|
process.env.UV_THREADPOOL_SIZE = String(concurrency); |
||||
|
|
||||
|
const fs = require('node:fs'); |
||||
|
const path = require('node:path'); |
||||
|
const { promisify } = require('node:util'); |
||||
|
const zlib = require('node:zlib'); |
||||
|
|
||||
|
const gzip = promisify(zlib.gzip); |
||||
|
const brotliCompress = promisify(zlib.brotliCompress); |
||||
|
|
||||
|
const buildDir = path.join(__dirname, 'target', 'generated-resources', 'public'); |
||||
|
// already-compressed formats (png, webp, woff2, ...) are left out
|
||||
|
const compressibleExtensions = new Set(['.js', '.mjs', '.css', '.html', '.json', '.svg', '.txt', '.md', '.ttf', '.otf', '.eot']); |
||||
|
const minSize = 10240; |
||||
|
|
||||
|
// brotli quality 11 is only ~2% smaller than 10 but 3x slower; must match precompressedEncodings in msa/web-ui
|
||||
|
const encoders = [ |
||||
|
{ |
||||
|
ext: '.br', |
||||
|
encode: content => brotliCompress(content, { |
||||
|
params: { |
||||
|
[zlib.constants.BROTLI_PARAM_QUALITY]: 10, |
||||
|
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: content.length |
||||
|
} |
||||
|
}) |
||||
|
}, |
||||
|
{ |
||||
|
ext: '.gz', |
||||
|
encode: content => gzip(content, { level: zlib.constants.Z_BEST_COMPRESSION }) |
||||
|
} |
||||
|
]; |
||||
|
|
||||
|
function listFiles(dir) { |
||||
|
return fs.readdirSync(dir, { recursive: true, withFileTypes: true }) |
||||
|
.filter(entry => entry.isFile()) |
||||
|
.map(entry => path.join(entry.parentPath, entry.name)); |
||||
|
} |
||||
|
|
||||
|
async function compress(file, { ext, encode }) { |
||||
|
const content = await fs.promises.readFile(file); |
||||
|
const compressed = await encode(content); |
||||
|
if (compressed.length < content.length) { |
||||
|
await fs.promises.writeFile(file + ext, compressed); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
async function main() { |
||||
|
// largest first, so the main chunk does not start last
|
||||
|
const files = listFiles(buildDir) |
||||
|
.map(file => ({ file, size: fs.statSync(file).size })) |
||||
|
.filter(({ file, size }) => compressibleExtensions.has(path.extname(file).toLowerCase()) && size >= minSize) |
||||
|
.sort((a, b) => b.size - a.size) |
||||
|
.map(({ file }) => file); |
||||
|
const jobs = files.flatMap(file => encoders.map(encoder => () => compress(file, encoder))); |
||||
|
let next = 0; |
||||
|
const worker = async () => { |
||||
|
while (next < jobs.length) { |
||||
|
await jobs[next++](); |
||||
|
} |
||||
|
}; |
||||
|
const start = Date.now(); |
||||
|
await Promise.all(Array.from({ length: concurrency }, worker)); |
||||
|
console.log(`Compressed ${files.length} files (${encoders.map(e => e.ext).join(', ')}) in ${path.relative(__dirname, buildDir)} ` + |
||||
|
`in ${((Date.now() - start) / 1000).toFixed(1)} s on ${concurrency} threads`); |
||||
|
} |
||||
|
|
||||
|
main().catch(error => { |
||||
|
console.error(error); |
||||
|
process.exit(1); |
||||
|
}); |
||||
Loading…
Reference in new issue