feat(bim): integrate portable IFC viewer, project map and prepared layers

This commit is contained in:
DCCONSTRUCTIONS
2026-11-14 18:49:43 +03:00
parent a49fb00b8e
commit cd27a5e483
18 changed files with 365 additions and 1 deletions
+11
View File
@@ -10,6 +10,7 @@
"hasInstallScript": true,
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.1.1.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
@@ -882,6 +883,16 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@nodedc/bim-viewer": {
"version": "0.1.1",
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.1.1.tgz",
"integrity": "sha512-x01cSS6nH2xhbZzkcl6JSlZmXQnQlifalLVwMd2prNsVJotT3Arj+PkWrLOkEypMY9yZKFmmDccgE8dATXEx7Q==",
"peerDependencies": {
"@nodedc/ui-react": "0.7.0",
"react": ">=19 <20",
"react-dom": ">=19 <20"
}
},
"node_modules/@nodedc/map-cesium-react": {
"resolved": "../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"link": true
+1
View File
@@ -15,6 +15,7 @@
},
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.1.1.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
+2 -1
View File
@@ -59,6 +59,7 @@ import {
type ObservationWorkspaceLayoutProfile,
} from "./core/observation/workspaceLayout";
import {
capabilityStatusLabel,
rootById,
roots,
workspaceById,
@@ -852,7 +853,7 @@ export default function App() {
onChange={openNavigationView}
/>
) : (
<StatusBadge tone="warning">Интерфейс готов</StatusBadge>
<StatusBadge tone={activeDefinition.status === "active" ? "success" : "warning"}>{capabilityStatusLabel[activeDefinition.status ?? "contract"]}</StatusBadge>
)
}
utilityActions={contentActions}
+8
View File
@@ -23,6 +23,7 @@ export type WorkspaceKind =
| "workers"
| "vps"
| "network-monitor"
| "architectural-projects"
| "datasets"
| "artifact-health"
| "lab-archive"
@@ -52,6 +53,7 @@ export interface WorkspaceDefinition {
description: string;
icon: IconName;
kind: WorkspaceKind;
status?: CapabilityStatus;
internalOnly?: boolean;
groups: CapabilityGroup[];
}
@@ -148,6 +150,12 @@ export const roots: RootDefinition[] = [
];
export const workspaces: WorkspaceDefinition[] = [
{
id: "architectural-projects", root: "data", kind: "architectural-projects", status: "active",
label: "Архитектурные проекты", title: "Архитектурные проекты",
eyebrow: "ДАННЫЕ / ОБЪЕКТЫ", description: "Проекты, BIM-модели и пространственные слои.",
icon: "building", groups: [],
},
{
id: "lab-archive",
root: "polygon",
@@ -1,3 +1,4 @@
import {ArchitecturalProjectsWorkspace} from "./data/ArchitecturalProjectsWorkspace";
import {SpatialWorkspace} from "./spatial/SpatialWorkspace";
import { PlanningSpatialWorkspace } from "./missions/PlanningSpatialWorkspace";
import { MissionPlannerWorkspace } from "./missions/MissionPlannerWorkspace";
@@ -451,6 +452,8 @@ export function WorkspaceRenderer(props: WorkspaceRendererProps) {
return <ComputeModulesWorkspace />;
case "network-monitor":
return <NetworkWorkspace />;
case "architectural-projects":
return <ArchitecturalProjectsWorkspace />;
case "datasets":
return <DatasetGatewayWorkspace />;
case "artifact-health":
@@ -0,0 +1,29 @@
import {lazy, Suspense, useCallback, useMemo, useState, type ComponentProps} from 'react';
import {Description, ToastStack} from '@nodedc/ui-react';
import type {BimHost, Notice} from '@nodedc/bim-viewer';
import fragmentsWorker from '@nodedc/bim-viewer/fragments-worker?url';
import mapWorker from '@nodedc/bim-viewer/map-worker?url';
type NotificationMessage = ComponentProps<typeof ToastStack>['items'][number];
const Workspace = lazy(async () => {
const module = await import('@nodedc/bim-viewer');
await import('@nodedc/bim-viewer/style.css');
return {default: module.BimWorkspace};
});
/** Host composition only: the module owns its catalog, intake, maps and renderer. */
export function ArchitecturalProjectsWorkspace() {
const [toasts, setToasts] = useState<NotificationMessage[]>([]);
const notify = useCallback((notice: Notice) => {
setToasts(items => [...items, {...notice, id: 'bim:' + crypto.randomUUID()}].slice(-5));
}, []);
const host = useMemo<BimHost>(() => ({
apiBase: '/api/v1/bim', assets: {fragmentsWorker, mapWorker}, notify,
}), [notify]);
return <>
<Suspense fallback={<Description role="status">Открываем архитектурные проекты…</Description>}>
<Workspace host={host}/>
</Suspense>
<ToastStack items={toasts} onDismiss={id => setToasts(items => items.filter(item => item.id !== id))}/>
</>;
}
@@ -0,0 +1,3 @@
declare module '@nodedc/bim-viewer/fragments-worker?url' { const url: string; export default url; }
declare module '@nodedc/bim-viewer/map-worker?url' { const url: string; export default url; }
declare module '@nodedc/bim-viewer/style.css';
+37
View File
@@ -0,0 +1,37 @@
# Portable BIM module in Mission Core
Qualified on 2026-11-14: **Данные → Архитектурные проекты** at the canonical `http://127.0.0.1:8000/`. The operator can create a project, upload IFC, wait for Worker conversion, download the prepared product and view it in 3D or plan. MapLibre, project tree, model versions and visibility share the same catalog. Map markers, project eyes and version rows enter the same project viewer.
## Ownership and integration
The implementation belongs to [NODEDC_BIM_MOD](https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD), branch `feat/portable-bim-ifc`. Core consumes Python host services 0.1.0 and browser workspace 0.1.1 from `vendor/bim/`; release manifests hold source commits and SHA-256 identities. The Python package owns contracts, project documents, transfer lifecycle and the host API. The browser package owns catalog, intake, map and renderer. It uses the host's React and NODE.DC UI, while keeping its Three/Fragments graph private; render objects are not exchanged with existing Core renderers.
Core-specific files are `src/k1link/web/bim_module.py`, `apps/control-station/src/workspaces/data/ArchitecturalProjectsWorkspace.tsx` and asset declarations. The app mounts `/api/v1/bim`, closes the module on shutdown and runs its ready-copy retention with the existing reaper. Product registry/composition select the workspace. The generic shell reads capability status; no BIM pipeline is implemented in App.tsx. The adapter emits canonical toasts, observed by the current Core notification history. It does not depend on that history's source files.
The backend admits only the local operator boundary (loopback peer, loopback Host and same-origin browser requests). This is not a multi-tenant authorization model. It initializes lazily and reports storage/connection failures without blocking unrelated Core workspaces. Local copy admission uses Core's shared physical-disk reservation ledger and its 2 GiB reserve, rather than a separate hard directory quota.
## Data and execution
Under `data_dir/architectural-projects/`, `documents` contains durable catalog, version references, selection and placement; `ready-copies` contains selected immutable renderable products and copy metadata. `connection` contains private Worker binding and a separately protected service token. Do not commit it. The independent module documents `WorkerBinding` configuration and validates allowed HTTP/SSH transport. The qualified path uses the existing SSH alias to a fixed API pipe inside the Worker container; no public port or extra sidecar was introduced.
Worker 006 owns **one** `ndc-bim-worker`, its `ndc-bim-data` volume, installed IFC converter, SQLite queue, Sources and published products. The qualified image is `sha256:edee7bea327ea017cd5717df000e1666c5adf8c02d10d478ff2f9851b30d2ea2` (module source `60e1de66a631f3d34671480823ff48fe0c567d21`). It has an internal network, no published ports or Docker socket, read-only root, UID 10001 and 2 CPU / 4 GiB / 128 PID limits. Other Worker containers and the existing PlayCanvas simulation were not changed by this integration.
Raw IFC streams through Core to the Worker; it is not spooled into Core data. Worker paths are readable Latin project/material/version directories with content deduplication. Local removal retains catalog references and Worker ownership. Re-download restores the same immutable product without conversion. Pin and active viewer leases protect local copies; unpinned inactive copies follow retention. Downloads currently use one active transfer and bounded in-memory status records, without restart-resume. No local IFC conversion fallback exists.
## Verified behavior
The real UI uploaded a six-element IFC twice as separate versions and the public That Open `school_str.ifc` (8,593,426 bytes, SHA-256 `82c3406c11cdf83a7ad00e2155bdcfdef50877e491e780623824161d8955b340`). Worker produced **1,526** geometric elements for the school; its `model.frag` is 708,042 bytes, SHA-256 `18b362ea65aeba88f57dfd011a1f4ce8cb1b5e607aa8f2b9aec9790624b7d381`.
The building renders as real geometry in 3D and on MapLibre, with editable metadata, coordinates, height, yaw and representative BIM version. Example coordinates are explicitly arbitrary, not its surveyed position. Map entry and direct version entry after reload open the same saved project. Plan/3D, fit, fullscreen/Escape, visibility and a 700 px narrow composition were checked. Computed typography uses 13 px operational text, 12 px descriptions and 18 px window titles.
One local version was removed through the UI and downloaded again: references remained and its Worker generation stayed 1. Pins persisted. Worker archive inspection found all three source receipts, a shared inode for the duplicate IFC versions and no scratch files; Core's architectural-project runtime contained no IFC. The source file selected by the user remains their own input outside Core storage. Success notices reached the existing history. Typed failures are wired to the same adapter; live UI fault injection was not completed.
Validation passed: 63 module Python tests, one Node reader regression, four client contract tests, two Core adapter tests, architecture/typecheck/typography gates, 1,596 frontend unit tests and production build. A fast-publication race is covered: a published job with no product in the preceding catalog snapshot keeps polling until publication appears. Both the repeated version and school import completed without a manual refresh.
Full evidence and limitations: [module qualification](https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD/src/branch/feat/portable-bim-ifc/docs/ifc-ui-qualification.md). Canonical Ops reference: [MISSIONCOR-100](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-100).
## Remaining scope
This is the first IFC slice, not full BIM acceptance. LAS/LAZ and new Gaussian captures, full BIM properties/selection/measurements/sections/federation, placement gizmos and unsaved-draft flow, large-model qualification, persistent download resume, full live fault injection, a second host and physical volume migration remain open. Existing PlayCanvas simulation is a separate system. Map markers cover all placed projects; detailed BIM geometry currently belongs to the selected project's preview. Multiple simultaneous building previews remain an acceptance case.
The 256 MiB prepared-member budget does not guarantee arbitrary GPU/RAM capacity. WebGL was visually qualified. Optional Fragments WebGPU imports produce build warnings and WebGPU is not claimed; multiple Three instances are expected across the private module graph and existing host renderers. The four scoped PASS cases in the module matrix do not close the remaining 139 cases.
+2
View File
@@ -18,6 +18,7 @@ dependencies = [
"httpx>=0.28,<1",
"lz4>=4.4,<5",
"missioncore-plugin-sdk",
"nodedc-bim-module==0.1.0",
"paho-mqtt>=2.1,<3",
"pillow>=12,<13",
"pyyaml>=6.0,<7",
@@ -28,6 +29,7 @@ dependencies = [
]
[tool.uv.sources]
nodedc-bim-module = { path = "vendor/bim/nodedc_bim_module-0.1.0-py3-none-any.whl" }
missioncore-plugin-sdk = { path = "packages/plugin-sdk", editable = true }
[project.optional-dependencies]
+11
View File
@@ -770,6 +770,7 @@ async def _local_copy_reaper() -> None:
while True:
try:
await asyncio.to_thread(local_presentation_copies.prune)
await asyncio.to_thread(bim_module_surface.prune)
except (OSError, ValueError):
logging.getLogger(__name__).exception(
"Local presentation retention failed; files preserved"
@@ -828,6 +829,10 @@ async def app_lifespan(application: FastAPI) -> AsyncIterator[None]:
local_copy_reaper.cancel()
with suppress(asyncio.CancelledError):
await local_copy_reaper
try:
await asyncio.to_thread(bim_module_surface.close)
except Exception:
logging.getLogger(__name__).exception("BIM host close failed")
if blueprint_reaper is not None:
blueprint_reaper.cancel()
with suppress(asyncio.CancelledError):
@@ -1208,6 +1213,12 @@ app.include_router(
)
from k1link.web.bim_module import BimModuleSurface
bim_module_surface = BimModuleSurface(session_store.data_dir)
app.mount("/api/v1/bim", bim_module_surface, name="bim-module")
if frontend_dist.is_dir():
app.mount(
"/",
+152
View File
@@ -0,0 +1,152 @@
"""Thin Core binding for the independently released NODE.DC BIM host package."""
from __future__ import annotations
import ipaddress
import logging
import sqlite3
import threading
from contextlib import contextmanager
from pathlib import Path
from urllib.parse import urlsplit
from fastapi import Request
from nodedc_bim.binding import BoundWorker, WorkerBinding
from nodedc_bim.copies import LocalCopies
from nodedc_bim.errors import BimError, ErrorCode
from nodedc_bim.host_api import HostServices, create_host_app
from nodedc_bim.projects import ProjectStore
from starlette.responses import JSONResponse
from k1link.observatory.transfer_space import TransferCapacityError, TransferSpace
_LOG = logging.getLogger(__name__)
def authorize_operator(request: Request, _project_id=None, _action=None) -> None:
"""Core's local operator boundary, without a dependency on the fleet registry."""
try:
peer = ipaddress.ip_address(request.client.host)
host = urlsplit(f"http://{request.headers.get('host', '')}")
if not peer.is_loopback or host.hostname not in (
"127.0.0.1",
"localhost",
"::1",
):
raise ValueError
origin = request.headers.get("origin")
if origin and origin != f"http://{request.headers['host']}":
raise ValueError
if request.headers.get("sec-fetch-site") == "cross-site":
raise ValueError
except (ValueError, AttributeError, KeyError):
raise BimError(
ErrorCode.FORBIDDEN, "Откройте Mission Core на компьютере оператора."
) from None
class CoreCopyBudget:
def __init__(self, data_dir: Path, copies_root: Path):
self.space = TransferSpace(data_dir / "observatory-transfer-reservations")
self.copies_root = copies_root
@contextmanager
def reserve(self, byte_length: int):
try:
# Conservative full reservation until publication; same physical-disk ledger as LAB.
with self.space.reservation(self.copies_root, byte_length + 4 * 1024**2):
yield
except TransferCapacityError as exc:
raise BimError(
ErrorCode.INSUFFICIENT_SPACE, "Недостаточно места для готовой копии."
) from exc
class BimModuleSurface:
def __init__(self, data_dir: Path):
self.data_dir = data_dir
self.lock = threading.RLock()
self.services: HostServices | None = None
self.binding: WorkerBinding | None = None
self.application = None
def _application(self):
with self.lock:
if self.application is not None:
return self.application
root = self.data_dir / "architectural-projects"
copies_root = root / "ready-copies"
binding = WorkerBinding(root / "connection")
copies = LocalCopies(
copies_root, CoreCopyBudget(self.data_dir, copies_root)
)
services = None
try:
services = HostServices(
ProjectStore(root / "documents"), copies, BoundWorker(binding)
)
application = create_host_app(services, authorize_operator)
except BaseException:
if services is not None:
services.close()
else:
copies.close()
binding.close()
raise
self.binding, self.services, self.application = (
binding,
services,
application,
)
return application
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return
try:
# Reject foreign origins before parsing bodies or creating stores.
authorize_operator(Request(scope))
application = self._application()
except BimError as exc:
reply = JSONResponse(
{
"error": {
"code": exc.code.value,
"message": exc.message,
"retryable": exc.retryable,
}
},
status_code=403 if exc.code == ErrorCode.FORBIDDEN else 503,
)
await reply(scope, receive, send)
return
except (OSError, ValueError, sqlite3.Error):
_LOG.exception(
"BIM host storage could not initialize; existing files preserved"
)
reply = JSONResponse(
{
"error": {
"code": "service_unavailable",
"message": "Хранилище архитектурных проектов недоступно.",
"retryable": False,
}
},
status_code=503,
)
await reply(scope, receive, send)
return
await application(scope, receive, send)
def prune(self):
if self.services is not None:
self.services.copies.prune()
def close(self):
with self.lock:
try:
if self.services is not None:
self.services.close()
finally:
if self.binding is not None:
self.binding.close()
+50
View File
@@ -0,0 +1,50 @@
from pathlib import Path
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.bim_module import BimModuleSurface
def test_bim_host_is_offline_capable_and_does_not_depend_on_fleet(tmp_path: Path):
surface = BimModuleSurface(tmp_path)
app = FastAPI()
app.mount("/api/v1/bim", surface)
try:
with TestClient(
app, base_url="http://localhost", client=("127.0.0.1", 50000)
) as client:
prefix = "/api/v1/bim"
assert client.get(prefix + "/projects").json() == []
project = client.post(
prefix + "/projects", json={"name": "Объект", "contractor": "Тест"}
)
assert project.status_code == 201
path = prefix + "/projects/" + project.json()["id"]
assert client.get(path).json()["project"]["name"] == "Объект"
assert client.get(prefix + "/capabilities").status_code == 503
assert client.get(path).status_code == 200
assert not surface.binding.route
assert not list(tmp_path.rglob("*.ifc"))
assert not list(tmp_path.rglob("source.part"))
finally:
surface.close()
def test_bim_surface_rejects_cross_site_before_creating_state(tmp_path: Path):
surface = BimModuleSurface(tmp_path / "uncreated")
app = FastAPI()
app.mount("/api/v1/bim", surface)
with TestClient(
app, base_url="http://localhost", client=("127.0.0.1", 50000)
) as client:
for headers in (
{"Origin": "https://other.example"},
{"Sec-Fetch-Site": "cross-site"},
{"Host": "evil.example"},
):
assert (
client.get("/api/v1/bim/projects", headers=headers).status_code == 403
)
assert not surface.data_dir.exists()
assert surface.services is None
Generated
+24
View File
@@ -477,6 +477,28 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" },
]
[[package]]
name = "nodedc-bim-module"
version = "0.1.0"
source = { path = "vendor/bim/nodedc_bim_module-0.1.0-py3-none-any.whl" }
dependencies = [
{ name = "fastapi" },
{ name = "httpx" },
{ name = "pydantic" },
{ name = "uvicorn" },
]
wheels = [
{ filename = "nodedc_bim_module-0.1.0-py3-none-any.whl", hash = "sha256:7937ce65d51ad99ba3e3abadd8d49b5a23181bcb2195e86e7bfc00f213017e43" },
]
[package.metadata]
requires-dist = [
{ name = "fastapi", specifier = ">=0.116,<1" },
{ name = "httpx", specifier = ">=0.28,<1" },
{ name = "pydantic", specifier = ">=2.11,<3" },
{ name = "uvicorn", specifier = ">=0.35,<1" },
]
[[package]]
name = "nodedc-mission-core"
version = "0.1.0"
@@ -489,6 +511,7 @@ dependencies = [
{ name = "httpx" },
{ name = "lz4" },
{ name = "missioncore-plugin-sdk" },
{ name = "nodedc-bim-module" },
{ name = "paho-mqtt" },
{ name = "pillow" },
{ name = "pyyaml" },
@@ -533,6 +556,7 @@ requires-dist = [
{ name = "httpx", specifier = ">=0.28,<1" },
{ name = "lz4", specifier = ">=4.4,<5" },
{ name = "missioncore-plugin-sdk", editable = "packages/plugin-sdk" },
{ name = "nodedc-bim-module", path = "vendor/bim/nodedc_bim_module-0.1.0-py3-none-any.whl" },
{ name = "paho-mqtt", specifier = ">=2.1,<3" },
{ name = "pillow", specifier = ">=12,<13" },
{ name = "pyyaml", specifier = ">=6.0,<7" },
+10
View File
@@ -0,0 +1,10 @@
# BIM module releases
Immutable packages from the independent [NODEDC_BIM_MOD](https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD) repository:
- Python host services 0.1.0: `release.json`, wheel, `uv.lock` integrity.
- Browser workspace 0.1.1: `client-release.json`, npm tarball, Control Station lockfile integrity. Runtime workers and third-party notices are included in the tarball.
Core consumes these versioned artifacts without importing a sibling checkout or copying the domain implementation. Update through a new module release, identity review and host qualification. The Worker image and durable data volume remain on Worker 006. Private connection settings and service tokens are never part of these releases.
See [integration and qualification](../../docs/BIM_MODULE.md) for the accepted scope and remaining work.
+12
View File
@@ -0,0 +1,12 @@
{
"schema_version": "missioncore.bim-client-release/v1",
"repository": "https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD",
"source_commit": "b9c2f36eed55d4c5b4bb48d40bcc66bbb8aa4f47",
"package": "nodedc-bim-viewer-0.1.1.tgz",
"sha256": "bdf5de0e8f7227b62ed0b6d122f50236c212304defd6e70d96f77baae9cf9b10",
"types": "pass",
"contract_tests": 4,
"visual_acceptance": "pass: bounded IFC workflow, map/tree/layers on canonical Core",
"evidence": "docs/BIM_MODULE.md",
"qualification_date": "2026-11-14"
}
Binary file not shown.
Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
{
"schema_version": "missioncore.bim-release/v1",
"repository": "https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD",
"source_commit": "4eb454500ea395951308b0af025a00cf2a90d297",
"package": "nodedc_bim_module-0.1.0-py3-none-any.whl",
"sha256": "7937ce65d51ad99ba3e3abadd8d49b5a23181bcb2195e86e7bfc00f213017e43",
"python_tests": 63,
"node_reader_tests": 1,
"scope": "portable host API; bounded integrated IFC workflow qualified, see docs/BIM_MODULE.md"
}