Log DICOM series sizes and exact volume limit failures
This commit is contained in:
1 parent
68a6801690
commit
86dc0e8d95
6 files changed
+149
-10
No files matched your search
@@ -20,6 +20,8 @@
|
||||
|
||||
Ограничения: до 2048 файлов, 64 МиБ на исходный файл, 1 ГиБ суммарной загрузки и 1 ГиБ Float32-вокселей. Это лимит массива объёма, а не всей памяти браузера: сборка и GPU требуют дополнительной памяти. Файлы читаются последовательно только после нажатия кнопки, загрузку можно отменить. При закрытии удаляются движок, GPU-ресурсы и принадлежащие просмотру записи кеша.
|
||||
|
||||
При запуске 3D в консоль браузера выводятся сообщения `[DICOM 3D]`: число файлов, общий и максимальный исходный размер, а после декодирования первого среза — размеры сетки и оценка Float32-объёма. При превышении лимита выводятся конкретная причина, фактическое значение и порог. Размеры указаны в байтах и ГиБ; пути, токены и медицинские теги не логируются.
|
||||
|
||||
Для приватных файлов используются обычные авторизованные API; для публичных — только API текущей ссылки с её токеном. Публичная ссылка на отдельный файл не запрашивает содержимое его родительской папки.
|
||||
|
||||
В сборщике `xmlbuilder2` направлен на официальный браузерный bundle: серверный entry зависимости VTK требует Node EventEmitter и не запускается в браузере. CSP страницы не ослабляется, сторонние CDN не используются.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import {
|
||||
dicomLimitExceeded,
|
||||
logDicomSeries,
|
||||
logDicomVolumeEstimate,
|
||||
} from "../dicom-diagnostics";
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
it("reports source bytes separately from the 768-slice decoded estimate", () => {
|
||||
const info = vi.spyOn(console, "info").mockImplementation(() => {});
|
||||
const files = Array.from({ length: 768 }, () => ({
|
||||
name: "private.dcm",
|
||||
source: "/private?token=secret",
|
||||
size: 2 * 1024 * 1024,
|
||||
}));
|
||||
expect(logDicomSeries(files).sourceBytes).toBe(1.5 * 1024 ** 3);
|
||||
expect(logDicomVolumeEstimate(512, 512, 768)).toBe(0.75 * 1024 ** 3);
|
||||
expect(info.mock.calls[0][1]).toMatchObject({
|
||||
fileCount: 768,
|
||||
sourceBytes: 1610612736,
|
||||
});
|
||||
expect(info.mock.calls[1][1]).toMatchObject({
|
||||
dimensions: [512, 512, 768],
|
||||
decodedBytes: 805306368,
|
||||
});
|
||||
expect(JSON.stringify(info.mock.calls)).not.toMatch(/private|secret/);
|
||||
});
|
||||
it("logs the precise failing limit before preserving the existing error code", () => {
|
||||
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
expect(() =>
|
||||
dicomLimitExceeded(
|
||||
"total source bytes (directory listing)",
|
||||
1610612736,
|
||||
1073741824
|
||||
)
|
||||
).toThrow("DICOM_VOLUME_LIMIT");
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining("total source bytes"),
|
||||
expect.objectContaining({ actual: 1610612736, limit: 1073741824 })
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
MAX_SERIES_FILES,
|
||||
MAX_VOLUME_BYTES,
|
||||
type DicomSource,
|
||||
} from "./dicom-series";
|
||||
|
||||
const size = (bytes: number) =>
|
||||
`${(bytes / 1024 ** 3).toFixed(3)} GiB (${bytes.toLocaleString("en-US")} bytes)`;
|
||||
|
||||
export function logDicomSeries(sources: DicomSource[]) {
|
||||
const sourceBytes = sources.reduce((total, file) => total + file.size, 0);
|
||||
const largestFileBytes = sources.reduce(
|
||||
(largest, file) => Math.max(largest, file.size),
|
||||
0
|
||||
);
|
||||
// Only sizes and counts: never include paths, share tokens or patient tags.
|
||||
console.info("[DICOM 3D] Series size", {
|
||||
fileCount: sources.length,
|
||||
sourceBytes,
|
||||
sourceSize: size(sourceBytes),
|
||||
largestFileBytes,
|
||||
largestFileSize: size(largestFileBytes),
|
||||
sourceLimit: size(MAX_VOLUME_BYTES),
|
||||
decodedVolumeLimit: size(MAX_VOLUME_BYTES),
|
||||
perFileLimit: "64 MiB",
|
||||
fileCountLimit: MAX_SERIES_FILES,
|
||||
});
|
||||
return { sourceBytes, largestFileBytes };
|
||||
}
|
||||
|
||||
export function logDicomVolumeEstimate(
|
||||
rows: number,
|
||||
cols: number,
|
||||
count: number
|
||||
) {
|
||||
const decodedBytes = rows * cols * count * Float32Array.BYTES_PER_ELEMENT;
|
||||
console.info("[DICOM 3D] Decoded volume estimate", {
|
||||
dimensions: [cols, rows, count],
|
||||
bytesPerVoxel: Float32Array.BYTES_PER_ELEMENT,
|
||||
decodedBytes,
|
||||
decodedSize: size(decodedBytes),
|
||||
decodedVolumeLimit: size(MAX_VOLUME_BYTES),
|
||||
});
|
||||
return decodedBytes;
|
||||
}
|
||||
|
||||
export function dicomLimitExceeded(
|
||||
reason: string,
|
||||
actual: number,
|
||||
limit: number
|
||||
): never {
|
||||
console.warn(`[DICOM 3D] Limit exceeded: ${reason}`, {
|
||||
actual,
|
||||
limit,
|
||||
...(reason !== "file count" && {
|
||||
actualSize: size(actual),
|
||||
limitSize: size(limit),
|
||||
}),
|
||||
});
|
||||
throw new Error("DICOM_VOLUME_LIMIT");
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
import DicomWorker from "./dicom.worker?worker";
|
||||
import { readDicomFile } from "./dicom-file";
|
||||
import {
|
||||
logDicomSeries,
|
||||
logDicomVolumeEstimate,
|
||||
dicomLimitExceeded,
|
||||
} from "./dicom-diagnostics";
|
||||
import {
|
||||
assembleVolume,
|
||||
checkSlice,
|
||||
@@ -14,13 +19,21 @@ export async function loadDicomVolume(
|
||||
signal: AbortSignal,
|
||||
progress: (loaded: number) => void
|
||||
) {
|
||||
const { sourceBytes, largestFileBytes } = logDicomSeries(sources);
|
||||
if (sources.length < 2 || sources.length > MAX_SERIES_FILES)
|
||||
throw new Error("DICOM_VOLUME_LIMIT");
|
||||
if (
|
||||
sources.some((s) => s.size > 64 * 1024 * 1024) ||
|
||||
sources.reduce((n, s) => n + s.size, 0) > MAX_VOLUME_BYTES
|
||||
)
|
||||
throw new Error("DICOM_VOLUME_LIMIT");
|
||||
dicomLimitExceeded("file count", sources.length, MAX_SERIES_FILES);
|
||||
if (largestFileBytes > 64 * 1024 * 1024)
|
||||
dicomLimitExceeded(
|
||||
"single source file bytes",
|
||||
largestFileBytes,
|
||||
64 * 1024 * 1024
|
||||
);
|
||||
if (sourceBytes > MAX_VOLUME_BYTES)
|
||||
dicomLimitExceeded(
|
||||
"total source bytes (directory listing)",
|
||||
sourceBytes,
|
||||
MAX_VOLUME_BYTES
|
||||
);
|
||||
const worker = new DicomWorker();
|
||||
const slices: DicomSlice[] = [];
|
||||
let bytes = 0;
|
||||
@@ -30,7 +43,12 @@ export async function loadDicomVolume(
|
||||
const buffer = await readDicomFile(source.source, signal);
|
||||
if (signal.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
bytes += buffer.byteLength;
|
||||
if (bytes > MAX_VOLUME_BYTES) throw new Error("DICOM_VOLUME_LIMIT");
|
||||
if (bytes > MAX_VOLUME_BYTES)
|
||||
dicomLimitExceeded(
|
||||
"total source bytes (downloaded)",
|
||||
bytes,
|
||||
MAX_VOLUME_BYTES
|
||||
);
|
||||
const slice = await new Promise<DicomSlice>((resolve, reject) => {
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
@@ -61,13 +79,31 @@ export async function loadDicomVolume(
|
||||
]);
|
||||
});
|
||||
checkSlice(slice, slices[0] || slice);
|
||||
if (slices.length === 0)
|
||||
logDicomVolumeEstimate(slice.rows, slice.cols, sources.length);
|
||||
if (slice.pixels.byteLength * sources.length > MAX_VOLUME_BYTES)
|
||||
throw new Error("DICOM_VOLUME_LIMIT");
|
||||
dicomLimitExceeded(
|
||||
"decoded Float32 voxel bytes",
|
||||
slice.pixels.byteLength * sources.length,
|
||||
MAX_VOLUME_BYTES
|
||||
);
|
||||
slices.push(slice);
|
||||
progress(slices.length);
|
||||
}
|
||||
if (signal.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
console.info("[DICOM 3D] Series loaded", {
|
||||
fileCount: slices.length,
|
||||
downloadedBytes: bytes,
|
||||
});
|
||||
return assembleVolume(slices);
|
||||
} catch (error) {
|
||||
if (!signal.aborted)
|
||||
console.warn("[DICOM 3D] Loading stopped", {
|
||||
reason: error instanceof Error ? error.message : "Unknown error",
|
||||
decodedFiles: slices.length,
|
||||
downloadedBytes: bytes,
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
worker.terminate();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
param([string]$Version = '3.0.0-sso.27')
|
||||
param([string]$Version = '3.0.0-sso.28')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
Push-Location $repo
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
VERSION="${VERSION:-3.0.0-sso.27}"
|
||||
VERSION="${VERSION:-3.0.0-sso.28}"
|
||||
COMMIT=$(git rev-parse --short HEAD)
|
||||
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
|
||||
mkdir -p build/release/linux-amd64
|
||||
|
||||
Reference in new issue
Block a user