From 86dc0e8d958b3484037882ec46ddc7a9fa992f79 Mon Sep 17 00:00:00 2001 From: SantaSpeen Date: Thu, 22 Oct 2026 22:12:56 +0300 Subject: [PATCH] Log DICOM series sizes and exact volume limit failures --- docs/dicom-viewer-options.md | 2 + .../utils/__tests__/dicom-diagnostics.test.ts | 40 ++++++++++++ frontend/src/utils/dicom-diagnostics.ts | 61 +++++++++++++++++++ frontend/src/utils/dicom-volume.ts | 52 +++++++++++++--- scripts/build-release.ps1 | 2 +- scripts/build-release.sh | 2 +- 6 files changed, 149 insertions(+), 10 deletions(-) create mode 100644 frontend/src/utils/__tests__/dicom-diagnostics.test.ts create mode 100644 frontend/src/utils/dicom-diagnostics.ts diff --git a/docs/dicom-viewer-options.md b/docs/dicom-viewer-options.md index 0186f006..b3635b0d 100644 --- a/docs/dicom-viewer-options.md +++ b/docs/dicom-viewer-options.md @@ -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 не используются. diff --git a/frontend/src/utils/__tests__/dicom-diagnostics.test.ts b/frontend/src/utils/__tests__/dicom-diagnostics.test.ts new file mode 100644 index 00000000..5c97a3c2 --- /dev/null +++ b/frontend/src/utils/__tests__/dicom-diagnostics.test.ts @@ -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 }) + ); +}); diff --git a/frontend/src/utils/dicom-diagnostics.ts b/frontend/src/utils/dicom-diagnostics.ts new file mode 100644 index 00000000..f2083000 --- /dev/null +++ b/frontend/src/utils/dicom-diagnostics.ts @@ -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"); +} diff --git a/frontend/src/utils/dicom-volume.ts b/frontend/src/utils/dicom-volume.ts index 30d25c82..ece4194d 100644 --- a/frontend/src/utils/dicom-volume.ts +++ b/frontend/src/utils/dicom-volume.ts @@ -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((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(); } diff --git a/scripts/build-release.ps1 b/scripts/build-release.ps1 index f6cb56c1..1d1b15ff 100644 --- a/scripts/build-release.ps1 +++ b/scripts/build-release.ps1 @@ -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 diff --git a/scripts/build-release.sh b/scripts/build-release.sh index ae6e502c..b37417f2 100644 --- a/scripts/build-release.sh +++ b/scripts/build-release.sh @@ -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