perf(core): снизить пиковый heap — стриминговый checkPageCount и потолок растра диаграмм
PR checks / web (pull_request) Successful in 40s
PR checks / java (pull_request) Successful in 1m4s
Main: tests, deploy, autotests / web (push) Successful in 31s
Main: tests, deploy, autotests / images-web (push) Successful in 29s
Main: tests, deploy, autotests / java (push) Successful in 1m24s
Main: tests, deploy, autotests / images-app (push) Successful in 39s
Main: tests, deploy, autotests / deploy (push) Successful in 1m33s
Main: tests, deploy, autotests / autotests (push) Successful in 42s
Main: tests, deploy, autotests / rollback (push) Has been skipped
PR checks / web (pull_request) Successful in 40s
PR checks / java (pull_request) Successful in 1m4s
Main: tests, deploy, autotests / web (push) Successful in 31s
Main: tests, deploy, autotests / images-web (push) Successful in 29s
Main: tests, deploy, autotests / java (push) Successful in 1m24s
Main: tests, deploy, autotests / images-app (push) Successful in 39s
Main: tests, deploy, autotests / deploy (push) Successful in 1m33s
Main: tests, deploy, autotests / autotests (push) Successful in 42s
Main: tests, deploy, autotests / rollback (push) Has been skipped
WordPdfValidator.checkPageCount больше не буферизует word/document.xml, колонтитулы и docProps/app.xml в Map<String,byte[]>: один проход ZipInputStream, счётчики накапливаются на месте (хелпер noClose глушит close() сканеров). Потребление — O(одной части) вместо O(суммы XML-частей). ChartRenderer/SmartArtRenderer: новый потолок MAX_PIXELS = 4096^2 (64 МБ ARGB); при превышении эффективный dpi понижается fitDpi (uniform g.scale — геометрия и безразмерные пропорции не меняются). 24"-график: 208 МБ растра -> 64 МБ (dpi 300 -> 170.7).
This commit was merged in pull request #65.
This commit is contained in:
@@ -9,9 +9,9 @@ import java.io.IOException;
|
|||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayDeque;
|
import java.util.ArrayDeque;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Deque;
|
import java.util.Deque;
|
||||||
import java.util.List;
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipInputStream;
|
import java.util.zip.ZipInputStream;
|
||||||
|
|
||||||
@@ -64,6 +64,12 @@ public final class WordPdfValidator {
|
|||||||
/** Элемент-контейнер body, внутри которого sectPr — межсекционный разрыв. */
|
/** Элемент-контейнер body, внутри которого sectPr — межсекционный разрыв. */
|
||||||
private static final String BODY_ELEMENT = "body";
|
private static final String BODY_ELEMENT = "body";
|
||||||
|
|
||||||
|
/** Кэш Word <Pages>. */
|
||||||
|
private static final String APP_PART = "docProps/app.xml";
|
||||||
|
|
||||||
|
/** Тело документа. */
|
||||||
|
private static final String DOCUMENT_PART = "word/document.xml";
|
||||||
|
|
||||||
private WordPdfValidator() {
|
private WordPdfValidator() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,28 +144,38 @@ public final class WordPdfValidator {
|
|||||||
if (docxBytes == null) {
|
if (docxBytes == null) {
|
||||||
throw new ValidationException("Не указаны байты входного .docx");
|
throw new ValidationException("Не указаны байты входного .docx");
|
||||||
}
|
}
|
||||||
int pages;
|
int cached = 0;
|
||||||
|
BreakScan scan = new BreakScan(0, 0);
|
||||||
|
int hfBreaks = 0;
|
||||||
|
// Дубликаты записей враждебного zip: первая выигрывает (прежняя
|
||||||
|
// map хранила последнюю). Обе оценки нижние, расхождение — только
|
||||||
|
// в сторону отказа на враждебном входе.
|
||||||
|
boolean appSeen = false;
|
||||||
|
boolean docSeen = false;
|
||||||
|
Set<String> hfSeen = new HashSet<>();
|
||||||
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docxBytes))) {
|
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docxBytes))) {
|
||||||
java.util.Map<String, byte[]> parts = new java.util.HashMap<>();
|
|
||||||
List<String> headerFooter = new ArrayList<>();
|
|
||||||
ZipEntry entry;
|
ZipEntry entry;
|
||||||
while ((entry = zip.getNextEntry()) != null) {
|
while ((entry = zip.getNextEntry()) != null) {
|
||||||
String n = entry.getName();
|
String n = entry.getName();
|
||||||
if ("docProps/app.xml".equals(n) || "word/document.xml".equals(n)
|
if (APP_PART.equals(n)) {
|
||||||
|| isHeaderFooterPart(n)) {
|
if (!appSeen) {
|
||||||
parts.put(n, zip.readAllBytes());
|
appSeen = true;
|
||||||
if (isHeaderFooterPart(n)) {
|
cached = cachedPageCount(noClose(zip));
|
||||||
headerFooter.add(n);
|
}
|
||||||
|
} else if (DOCUMENT_PART.equals(n)) {
|
||||||
|
if (!docSeen) {
|
||||||
|
docSeen = true;
|
||||||
|
scan = scanDocument(noClose(zip));
|
||||||
|
}
|
||||||
|
} else if (isHeaderFooterPart(n) && hfSeen.add(n)) {
|
||||||
|
hfBreaks += countBreaksInFlat(noClose(zip));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
pages = pageCountOfZip(name -> {
|
|
||||||
byte[] b = parts.get(name);
|
|
||||||
return b == null ? null : new ByteArrayInputStream(b);
|
|
||||||
}, headerFooter);
|
|
||||||
} catch (IOException | RuntimeException e) {
|
} catch (IOException | RuntimeException e) {
|
||||||
throw new ValidationException("Не удалось разобрать байты .docx", e);
|
throw new ValidationException("Не удалось разобрать байты .docx", e);
|
||||||
}
|
}
|
||||||
|
int pages = Math.max(Math.max(cached, 1 + scan.breaks() + hfBreaks),
|
||||||
|
scan.lastRendered() + 1);
|
||||||
if (pages > maxPages) {
|
if (pages > maxPages) {
|
||||||
throw new ValidationException("Документ длиннее " + maxPages
|
throw new ValidationException("Документ длиннее " + maxPages
|
||||||
+ " страниц: получено не менее " + pages);
|
+ " страниц: получено не менее " + pages);
|
||||||
@@ -184,8 +200,8 @@ public final class WordPdfValidator {
|
|||||||
* декларация документа wordprocessingml (архив без неё — не .docx);
|
* декларация документа wordprocessingml (архив без неё — не .docx);
|
||||||
* zip-бомба отсекается потоковым счётчиком распакованных байт
|
* zip-бомба отсекается потоковым счётчиком распакованных байт
|
||||||
* ({@link WordPdfSettings#MAX_DECOMPRESSED_MB}) и числом записей
|
* ({@link WordPdfSettings#MAX_DECOMPRESSED_MB}) и числом записей
|
||||||
* ({@link WordPdfSettings#MAX_ZIP_ENTRIES}) — до загрузки содержимого
|
* ({@link WordPdfSettings#MAX_ZIP_ENTRIES}) — до разбора содержимого
|
||||||
* в память в {@link #checkPageCount(byte[], int)}. Оба лимита —
|
* в {@link #checkPageCount(byte[], int)}. Оба лимита —
|
||||||
* защитные пороги, {@link ConvertOptions} их не переопределяет.
|
* защитные пороги, {@link ConvertOptions} их не переопределяет.
|
||||||
* Регрессии — {@code WordPdfValidatorTest#validate_plainZipRejected},
|
* Регрессии — {@code WordPdfValidatorTest#validate_plainZipRejected},
|
||||||
* {@code #validate_xlsxRenamedRejected}, {@code #validate_zipBombRejected},
|
* {@code #validate_xlsxRenamedRejected}, {@code #validate_zipBombRejected},
|
||||||
@@ -206,7 +222,7 @@ public final class WordPdfValidator {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Один потоковый проход по zip: суммарный распакованный размер и число
|
* Один потоковый проход по zip: суммарный распакованный размер и число
|
||||||
* записей (защита от zip-бомбы — отсечение ДО {@code readAllBytes}
|
* записей (защита от zip-бомбы — отсечение ДО чтения содержимого
|
||||||
* в {@link #checkPageCount(byte[], int)}) и наличие в
|
* в {@link #checkPageCount(byte[], int)}) и наличие в
|
||||||
* {@code [Content_Types].xml} декларации документа wordprocessingml
|
* {@code [Content_Types].xml} декларации документа wordprocessingml
|
||||||
* (архив без неё — не .docx: обычный zip, переименованный .xlsx/.pptx).
|
* (архив без неё — не .docx: обычный zip, переименованный .xlsx/.pptx).
|
||||||
@@ -276,11 +292,6 @@ public final class WordPdfValidator {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Поставщик потока по имени части zip; null — части нет. */
|
|
||||||
private interface PartStream {
|
|
||||||
InputStream open(String name) throws IOException;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** {@code word/headerN.xml} / {@code word/footerN.xml} (не .rels). */
|
/** {@code word/headerN.xml} / {@code word/footerN.xml} (не .rels). */
|
||||||
private static boolean isHeaderFooterPart(String name) {
|
private static boolean isHeaderFooterPart(String name) {
|
||||||
return (name.startsWith("word/header") || name.startsWith("word/footer"))
|
return (name.startsWith("word/header") || name.startsWith("word/footer"))
|
||||||
@@ -288,21 +299,19 @@ public final class WordPdfValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Лёгкий расчёт числа страниц прямо по zip-пакету .docx, без docx4j.
|
* Обёртка, глушащая {@code close()}: {@code cachedPageCount},
|
||||||
* Максимум кэша {@code docProps/app.xml <Pages>}, явных разрывов и
|
* {@code scanDocument} и {@code countBreaksInFlat} закрывают
|
||||||
* {@code w:lastRenderedPageBreak}. Считаются все колонтитулы
|
* переданный поток в {@code finally}, а закрывать {@code ZipInputStream}
|
||||||
* ({@code word/header*.xml}, {@code word/footer*.xml}) — там Word тоже
|
* в середине обхода нельзя — переход к следующей записи делает цикл
|
||||||
* держит {@code w:br type="page"}.
|
* в {@code checkPageCount}.
|
||||||
*/
|
*/
|
||||||
private static int pageCountOfZip(PartStream parts, List<String> headerFooterParts)
|
private static InputStream noClose(InputStream in) {
|
||||||
throws IOException {
|
return new java.io.FilterInputStream(in) {
|
||||||
int cached = cachedPageCount(parts.open("docProps/app.xml"));
|
@Override
|
||||||
BreakScan scan = scanDocument(parts.open("word/document.xml"));
|
public void close() {
|
||||||
int explicit = 1 + scan.breaks(); // сам документ — минимум одна страница
|
// намеренно не закрываем базовый ZipInputStream
|
||||||
for (String part : headerFooterParts) {
|
|
||||||
explicit += countBreaksInFlat(parts.open(part));
|
|
||||||
}
|
}
|
||||||
return Math.max(Math.max(cached, explicit), scan.lastRendered() + 1);
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Результат разбора word/document.xml: явные разрывы и маркеры. */
|
/** Результат разбора word/document.xml: явные разрывы и маркеры. */
|
||||||
|
|||||||
@@ -33,6 +33,14 @@ final class ChartRenderer {
|
|||||||
/** Разрешение растра: 300 dpi, чтобы подписи не мылились при печати. */
|
/** Разрешение растра: 300 dpi, чтобы подписи не мылились при печати. */
|
||||||
static final int DPI = 300;
|
static final int DPI = 300;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Потолок площади растра: 4096×4096 ARGB = 64 МБ (против 208 МБ при
|
||||||
|
* 24″ × 300 dpi — верхняя граница {@code DrawingPreRenderer.MAX_EXTENT_EMU}).
|
||||||
|
* Превышение — понижение эффективного dpi ({@link #fitDpi}), геометрия
|
||||||
|
* не меняется.
|
||||||
|
*/
|
||||||
|
static final long MAX_PIXELS = 16_777_216L;
|
||||||
|
|
||||||
/** Поля вокруг chartSpace от рамки графика. Auto-layout Word — Word-эмпирика. */
|
/** Поля вокруг chartSpace от рамки графика. Auto-layout Word — Word-эмпирика. */
|
||||||
private static final double PADDING = 4.0;
|
private static final double PADDING = 4.0;
|
||||||
|
|
||||||
@@ -57,10 +65,26 @@ final class ChartRenderer {
|
|||||||
private ChartRenderer() {
|
private ChartRenderer() {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Эффективный dpi растра: {@link #DPI}, либо пониженный так, чтобы
|
||||||
|
* площадь не превысила {@link #MAX_PIXELS}. Понижение uniform — все
|
||||||
|
* размеры в пунктах под одним {@code g.scale}, безразмерные пропорции
|
||||||
|
* рендера сохраняются.
|
||||||
|
*/
|
||||||
|
static double fitDpi(double widthPt, double heightPt) {
|
||||||
|
double w = Math.max(16, Math.round(widthPt * DPI / 72.0));
|
||||||
|
double h = Math.max(16, Math.round(heightPt * DPI / 72.0));
|
||||||
|
if (w * h <= MAX_PIXELS) {
|
||||||
|
return DPI;
|
||||||
|
}
|
||||||
|
return DPI * Math.sqrt(MAX_PIXELS / (w * h));
|
||||||
|
}
|
||||||
|
|
||||||
static BufferedImage render(ChartSpec spec, double widthPt, double heightPt,
|
static BufferedImage render(ChartSpec spec, double widthPt, double heightPt,
|
||||||
DrawMlColor colors) {
|
DrawMlColor colors) {
|
||||||
int w = Math.max(16, (int) Math.round(widthPt * DPI / 72.0));
|
double dpi = fitDpi(widthPt, heightPt);
|
||||||
int h = Math.max(16, (int) Math.round(heightPt * DPI / 72.0));
|
int w = Math.max(16, (int) Math.round(widthPt * dpi / 72.0));
|
||||||
|
int h = Math.max(16, (int) Math.round(heightPt * dpi / 72.0));
|
||||||
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
||||||
Graphics2D g = img.createGraphics();
|
Graphics2D g = img.createGraphics();
|
||||||
try {
|
try {
|
||||||
@@ -70,7 +94,7 @@ final class ChartRenderer {
|
|||||||
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||||
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
|
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
|
||||||
RenderingHints.VALUE_STROKE_PURE);
|
RenderingHints.VALUE_STROKE_PURE);
|
||||||
g.scale(DPI / 72.0, DPI / 72.0);
|
g.scale(dpi / 72.0, dpi / 72.0);
|
||||||
drawFrame(g, spec, widthPt, heightPt);
|
drawFrame(g, spec, widthPt, heightPt);
|
||||||
|
|
||||||
Rectangle2D box = new Rectangle2D.Double(PADDING, PADDING,
|
Rectangle2D box = new Rectangle2D.Double(PADDING, PADDING,
|
||||||
|
|||||||
@@ -79,8 +79,9 @@ final class SmartArtRenderer {
|
|||||||
double widthPt, double heightPt) {
|
double widthPt, double heightPt) {
|
||||||
List<Item> items = new ArrayList<>();
|
List<Item> items = new ArrayList<>();
|
||||||
collect(drawing.getSpTree().getSpOrGrpSp(), new AffineTransform(), items);
|
collect(drawing.getSpTree().getSpOrGrpSp(), new AffineTransform(), items);
|
||||||
int w = Math.max(16, (int) Math.round(widthPt * DPI / 72.0));
|
double dpi = ChartRenderer.fitDpi(widthPt, heightPt);
|
||||||
int h = Math.max(16, (int) Math.round(heightPt * DPI / 72.0));
|
int w = Math.max(16, (int) Math.round(widthPt * dpi / 72.0));
|
||||||
|
int h = Math.max(16, (int) Math.round(heightPt * dpi / 72.0));
|
||||||
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
||||||
Graphics2D g = img.createGraphics();
|
Graphics2D g = img.createGraphics();
|
||||||
try {
|
try {
|
||||||
@@ -90,7 +91,7 @@ final class SmartArtRenderer {
|
|||||||
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||||
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
|
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
|
||||||
RenderingHints.VALUE_STROKE_PURE);
|
RenderingHints.VALUE_STROKE_PURE);
|
||||||
g.scale(DPI / 72.0, DPI / 72.0);
|
g.scale(dpi / 72.0, dpi / 72.0);
|
||||||
if (items.isEmpty()) {
|
if (items.isEmpty()) {
|
||||||
return img;
|
return img;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user