Architecture

WEISS is split into three main services: a React front-end for user interface and widget rendering, a FastAPI back-end for handling OPI contents, authentication and git interaction, and a dedicated EPICS WebSocket bridge. The block diagram below summarizes their interactions:

../_images/architecture-dark.svg ../_images/architecture-light.svg

The next sections have a more detailed breakdown of the internal structure of each service and their interactions.


NGINX

NGINX (“engine-x”) serves as a reverse proxy for all incoming traffic. It routes the browser requests to either the frontend, backend API or the EPICS WebSocket internal ports as needed. Behind NGINX all services run under plain HTTP, being the NGINX layer responsible for TLS termination, HTTPS support and routing.

Frontend

The frontend is a single-page React application that operates mainly in two modes: editing (available for developer role only, see User Roles), and runtime. In edit mode the user can create and modify widgets on the canvas, while in runtime mode the user can only interact with the widgets but not change their properties or layout.

Both modes share the same core components. When in runtime, however, the connection to the EPICS WebSocket is opened, and widgets are rendered through a separate component through which PV Data traffic is injected.

Core shared frontend components:

For both modes, the state of the editor is held in Zustand stores in src/stores/; there are no React context providers for app state.

Important

These are not all the shared elements of the frontend composition, but the more important ones. Starting by these will naturally guide you through the other related files.

State management layer

Stores live in src/stores/ (conventions in its README.md). Components subscribe with a selector for the slice they need, and call actions through useXStore.getState() in event handlers. Side effects are not React effects: each store reacts to the services and stores it depends on with subscriptions at the bottom of its own file.

  • editorStore - owns the canonical list of widgets on the canvas. It handles selection, undo/redo history, clipboard, grouping, macros, and serialisation/deserialisation of OPI files. Derived values (widget index, selection bounds, runtime macros, resolved PV list) are computed by its actions and stored.

  • uiStore - UI-only state: the current mode (edit vs. runtime), panning, canvas text editing, and the widget picker and editor sidebar state. Widgets read the mode with useUIStore((s) => s.inEditMode).

  • sessionStore - the authenticated user, role and git token status, login and logout. Follows AuthService status changes, restores the session on page load, checks it again when a page returns from the back/forward cache, and fetches the token status of a developer.

  • repoStore - repository trees and the selected file (or image preview). Fetches the trees on login or role change, clears them on logout, loads the selected file into editorStore (or as an image) when it changes, and reopens the last opened file once the trees load.

  • actions.ts - actions involving several stores and reactions related to them: operators switched to runtime, the WebSocket session management, the resolved PV list sent to the WebSocket session, the rule-driven macro sync in runtime, and the debounced auto-save of the edited file (flushed on file or mode switch). main.tsx imports it before App, which loads every store.

  • WebSocket session (src/services/WSClient/session.ts) - a module, not a context. It owns the WSClient instance and exports startNewSession, stopSession, setSubscribedPVs, writePVValue, takeSnapshot and restoreFromSnapshot, which components import directly. The connection state is in wsStore (src/stores/wsStore.ts). A subscription in src/stores/actions.ts passes editorStore.resolvedPVList to setSubscribedPVs; the session subscribes the difference, and the whole list again after each (re)connect. WSClient reconnects with backoff; the session clears PV data on disconnect and notifies the user when the connection stays lost for 3 s, and again when it is restored.

Live PV data is stored in a Zustand module-level store (usePVStore, src/stores/pvStore.ts). The WebSocket session collects incoming WebSocket messages in a buffer and flushes them into the store via requestAnimationFrame, capping updates at the user’s monitor update rate. Widget components subscribe with a PV-specific selector:

const pvData = usePVStore((state) => state.pvs["MY:PV"]);

This means each widget re-renders only when its own PV changes, with no re-render propagation through React context.

Image frames (NTNDArray updates, and plain array PVs a widget registered as images) never enter pvStore: the WebSocket session routes them to a separate imageStore, and pvStore only keeps a summary of the PV without its pixels. Large images therefore never pass through React props, rules or macros.

Note

The state management layer is the brains of the application. All global UI states and behaviors pass through one of the above.

Rendering layer

  • GridZoneComp - the main editor canvas. It handles drag-and-drop of new widgets, panning, zooming, and keyboard shortcuts. It is itself registered as a widget so that its editable properties (background, grid size, macros, …) are managed through the same widget pipeline as every other widget.

  • WidgetRenderer - renders each top-level widget as a memoized WidgetItem inside a resizable and draggable container (react-rnd); a multi-selection is moved and resized by SelectionGroup, an empty overlay over the selection bounds, while the selected widgets stay in place in the render order (and keep their layer). A WidgetItem selects its own widget (by id, from editorStore.widgetIdMap) and selection state, so a selection change re-renders only the widgets whose selection state changed. A widget either renders the static component directly (edit mode), or delegates it to LiveWidget in runtime.

  • LiveWidget - operates in runtime mode only. Subscribes to usePVStore with a PV-specific selector (using useShallow for reference equality), then calls applyWidgetPVData() (widgetRenderUtils.ts) to merge PV data, evaluate configured rules, and resolve macros before rendering the widget component.

    Image widgets (AreaDetector) render off the main thread: each runtime widget owns a web worker that draws on an OffscreenCanvas, while zoom, pixel readout and the colorbar stay on the main thread.

    Runtime rule semantics are property-oriented: each rule targets one property and contains ordered condition rulesets. If multiple rulesets match in the same rule, the last match wins; if multiple rules target the same property, later rules in the list win. Legacy action-map rule payloads from older .opi.json files (WEISS < 2.0.0) are still accepted on import and converted during load.

Services

  • APIClient - auto-generated TypeScript client produced by @hey-api/openapi-ts from the FastAPI OpenAPI schema. Provides type-safe wrappers for all backend REST endpoints (auth, repo CRUD, file read/write, Git operations).

    Warning

    Do not edit this folder manually. Regenerate it with pnpm exec openapi-ts after any backend endpoint changes (API must be running on :8000).

  • AuthService - singleton (authService) that drives the full OAuth login lifecycle. Handles provider redirect (replacing the login page in the history), code exchange, session restoration on page load (restoreSession()) and on back/forward cache restores (revalidateSession()), and logout (local state is kept when the request fails). Broadcasts auth state changes via a callback observer consumed by sessionStore and repoStore.

  • Dialog - imperative confirmation dialog. Call confirmDialog(options) from anywhere in the app to open a modal; it returns a Promise<boolean> resolved when the user confirms or cancels.

    Note

    <DialogService /> must be mounted once in the component tree (currently in App.tsx) to register the underlying handler. The same applies to <NotificationService /> below.

  • Notifications - fire-and-forget toast notifications. Call notifyUser(message, severity?) to display a 4-second auto-dismiss snackbar. Accepted severity values: "success", "info", "warning", "error".

  • WSClient - stateful WebSocket class used by the WebSocket session (session.ts). Manages subscribe/unsubscribe/write messaging to the EPICS bridge, auto-reconnects with exponential backoff on unexpected disconnection, and decodes binary array updates into typed arrays before data reaches pvStore.

  • pvStore - Zustand store for live EPICS PV data. See the State management layer section above for a full description.

  • imageStore - Zustand store holding the latest frame of each image PV (NTNDArray, or a plain array PV a widget registered as an image), read by image widgets. Cleared when the WebSocket closes.


Backend

API

Besides authentication (see below), the FastAPI back-end exposes three route groups:

  • Developer routes (/api/v1/repos/staging): developer-only endpoints (enforced by require_developer) that manage per-user editable copies of OPI repositories. Each registered repository is cloned as a bare Git repository; every developer who opens it gets an isolated git worktree created automatically for their user ID. This means concurrent edits from different users never interfere with each other. Commits, tags, file CRUD, and deployments are all driven through these worktrees via their respective endpoints. For interaction with remote, the Technical Account Token is used. See Git Interaction for more details.

  • Operator routes (/api/v1/repos/runtime): read-only endpoints used by the frontend to serve the currently deployed OPI snapshot to “operator” users.

  • Snapshot routes (/api/v1/snapshots): provides storage interaction with PV snapshots (saving to disk, fetching values, etc.). These endpoints DO NOT communicate to PVs in any form, i.e., you need to provide the data to be saved, and for restoring, you need to restore it yourself (WEISS frontend does that). This will change as the snapshot feature becomes a standalone service.

Authentication

Authentication is based on OAuth 2.0 / OpenID Connect and is available through the /api/v1/auth route group. The backend loads the configured non-demo provider from api.auth.providers using AUTH_IDENTITY_PROVIDER (default oauth) and also supports a dedicated demo provider when DEMO_MODE=true. See Organization credentials for more details.


EPICS WebSocket bridge (epicsWS)

epicsWS is a standalone Python WebSocket service that sits between the frontend and the EPICS IOCs. The frontend connects to it through WSClient and subscribes to PV names based on the widgets present on the canvas.

  • The PVA library used is p4p, see backend/epicsWS/PVAClient.py.

  • The CA library used is PyEpics, see backend/epicsWS/CAClient.py.

The web socket application and connection manager can be seen in backend/epicsWS/epicsWS.py. The concept was based on ORNL PV Web Socket (PVWS).

How it works

Based on the default protocol (see Environment Variables) or the channel prefix of the PV names (e.g pva:// or ca://), the WS chooses the correct provider.

The incoming messages from all origins are parsed through a common interface defined on pvParser source file. This results in a standard structure in the format of the PVData class, regardless of the origin of the message.

This class was based on the EPICS Normative Types (with minor modifications for convenience). This way, a known format is always used, and the front-end client only needs to know one data structure for all protocols. Extra fields provide enumeration strings for enum/enum-like records.

Binary array updates

Scalar and disconnect updates, client requests, and snapshot/restore messages use standard JSON text frames. For efficiency of transport of bigger amounts of data, Nonempty numeric array updates use a single binary WebSocket frame, without size thresholds or capability negotiation. Empty and nonnumeric arrays stay in JSON.

Binary frames contain [uint32 LE header length][UTF-8 JSON header][ASCII-space padding][raw array bytes]. The length includes padding, which aligns the payload offset to the element size. Array bytes are little-endian; dtype in the header is the PV’s native element type, one of int8, uint8, int16, uint16, int32, uint32, int64, uint64, float32, or float64. The header carries the usual update fields except value; first updates also include metadata. The client exposes the array as a zero-copy typed array view over the received buffer (NumericArray in src/types/epicsWS.ts); consumers must use isNumericArray() from src/utils/numericArray.ts instead of Array.isArray(). NTNDArray updates add an ndarray header field (dimensions, frame uniqueId, codec and color mode); other arrays carry no shape. Compressed NTNDArray frames are forwarded as-is and not decoded by the client.

Each client has its own send queue. A client that cannot keep up receives fewer array frames rather than a backlog: a waiting array frame is replaced by the next one of the same PV. Scalar updates are always delivered in order.

Snapshots keep their base64 JSON format for arrays, but never capture image PVs: NTNDArray PVs and the plain image waveforms the client lists in the request are reported in excluded instead.

Note

JavaScript has no safe 64-bit integer view, so int64/uint64 arrays are converted to Float64Array on the client and integers beyond Number.MAX_SAFE_INTEGER (2^53 - 1) lose precision. This only applies to actual 64-bit integer PV arrays, which are not expected to be common. If you need exact 64-bit integer values, consider opening an issue or feature request to discuss BigInt64Array support in the client.

This service is intentionally isolated from the API: it has no dependency on authentication or repository management.

Further tests on performance and scalability are planned for the near future.