Metadata-Version: 2.4
Name: vcti-fileloader
Version: 7.0.0
Summary: Plugin-based file loader framework that attaches locked subtrees into a LockableTree
Author: Visual Collaboration Technologies Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Repository, https://github.com/vcollab/vcti-python-fileloader
Project-URL: Changelog, https://github.com/vcollab/vcti-python-fileloader/blob/main/CHANGELOG.md
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: vcti-plugin-catalog<4,>=3.0.0
Requires-Dist: vcti-tree<4,>=3.0.0
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy; extra == "typecheck"
Dynamic: license-file

# vcti-fileloader

Plugin-based file loader framework that attaches locked subtrees into a LockableTree

## Overview

Applications that work with simulation and CAE data load many file
formats, and each file's content is hierarchical — groups, datasets,
attributes. `vcti-fileloader` defines the protocol every loader plugin
implements: `populate(handle, tree, parent)` builds the file's content
as a new subtree under `parent` in a tree the application owns, and
locks it before returning, so several files combine into one browsable
tree with no merge step. Loaders pass the file's native attributes
through verbatim into a read-only side of each node payload
(`file_attributes`); a separate mutable side (`enricher_attributes`)
is left for the caller's post-load enrichment. The framework codes
against the `LockableTree` protocol from
[vcti-tree](https://github.com/vcollab/vcti-python-tree), so the
caller picks the backing.

Install as `vcti-fileloader`; import from `vcti.fileloader.core`.
`vcti.fileloader` is a namespace package: loader plugins ship as their
own distributions beside `core`. The package is fully typed
(`py.typed`) and passes `mypy --strict`.

```
┌─────────────────────────────────────────────────────┐
│                  Application Code                   │
│        (owns LockableTree, uses Loader protocol)    │
└──────────────┬──────────────────────┬───────────────┘
               │                      │
       ┌───────▼───────┐      ┌───────▼───────┐
       │  HDF5 Loader  │      │  JSON Loader  │  ...
       │  (plugin pkg) │      │  (plugin pkg) │
       └───────────────┘      └───────────────┘
                  attach subtrees into the tree
```

## Installation

```bash
pip install "vcti-fileloader>=7.0.0"
```

```toml
dependencies = [
    "vcti-fileloader>=7.0.0",
]
```

## Quick Start

Register a plugin's loader at startup, then load a file into a tree
you own. `hdf5_loader` stands for a loader object from a plugin
package.

```python
from pathlib import Path

from vcti.tree.core import DictTree, DictTreeHandle, descendants
from vcti.fileloader.core import (
    DataNode,
    LoaderDescriptor,
    LoaderRegistry,
    prepare_loader,
)

# At startup
registry = LoaderRegistry()
registry.register(LoaderDescriptor(
    id="hdf5-h5py-loader",
    name="HDF5 Loader (h5py)",
    loader=hdf5_loader,
    attributes={"supported_formats": ["hdf5-file"]},
))

# At runtime: validate and set up once; raises ValidationError / SetupError
loader = registry.get("hdf5-h5py-loader").loader
prepare_loader(loader)

# The application owns the tree
tree: DictTree[DataNode] = DictTree(DataNode())

handle = loader.load(Path("simulation.h5"))
try:
    subtree_root: DictTreeHandle = loader.populate(handle, tree, tree.root_handle)
    # The subtree is now structure-locked and payload-locked.
    for h in descendants(tree, subtree_root):
        node = tree.payload(h)
        print(node.name, dict(node.attributes))
finally:
    loader.unload(handle)
```

### With a `before_lock` hook

The hook runs after the file's content is attached and before the
locks fire. Use it to stamp attributes, compute derived values, or
refuse the file by raising — a raise rolls the whole subtree back.

```python
def stamp_source(tree, root):
    for h in descendants(tree, root, include_self=True):
        payload = tree.payload(h)
        if payload is not None:
            payload.enricher_attributes["file_path"] = "simulation.h5"

handle = loader.load(Path("simulation.h5"))
try:
    root = loader.populate(handle, tree, tree.root_handle, before_lock=stamp_source)
finally:
    loader.unload(handle)

print(tree.payload(root).attributes["file_path"])
```

The hook is any callable `(tree, root) -> None`. A rule-driven
enrichment library plugs in the same way; hand it the payloads
(`tree.payload(h)`), not the handles.

## Key API

| Name | Role |
|---|---|
| `Loader` | Protocol every plugin implements: `can_load`, `load`, `populate`, `unload`, plus optional `validator` / `setup`. Structural — no base class. |
| `SubtreeBuilder` | Transactional helper for implementing `populate`: scoped writes, `before_commit` hook, lock on success, rollback on failure. |
| `DataNode` | Payload: `data`, `name`, read-only `file_attributes`, mutable `enricher_attributes`, and the merged `attributes` view (enricher first). |
| `LazyDataNode` | `DataNode` whose data loads on demand; `shape` and `dtype` are known before loading. |
| `materialise_subtree` | Load every `LazyDataNode` in a subtree, so the file can be closed. |
| `LoaderDescriptor` / `LoaderRegistry` | Register loaders with filterable metadata; look them up by id or attributes. |
| `LoaderValidator` / `LoaderSetup` | Optional protocols for checking and configuring a loader's runtime dependencies: return `True`, or raise `ValidationError` / `SetupError` with a diagnostic. |
| `prepare_loader` | Run a loader's validator and setup. Any failure of either step — a raised exception or a bare `False` — surfaces as `ValidationError` / `SetupError` respectively. Existing domain exceptions propagate unchanged; unexpected exceptions are preserved on `__cause__`. |

### Lifecycle

1. **Prepare** — `prepare_loader(loader)` once, before the first
   `load()`.
2. **Check** — `can_load(path)` before `load()`.
3. **Load** — `load(path)` opens the file and returns an opaque handle.
4. **Populate** — `populate(handle, tree, parent, before_lock=...)`
   grafts the subtree under `parent`, runs the hook, locks, and returns
   the subtree root. On failure the partial subtree is removed. If that
   removal fails too — typically because `parent` was structure-locked
   while `populate` ran — the error carries a note naming the subtree
   and the state it was found in.
5. **Unload** — `unload(handle)` releases resources; idempotent. Lazy
   nodes may hold the handle: call `materialise_subtree(tree, root)`
   first if the tree must stay usable after unload.

## Error Handling

All exceptions inherit from `LoaderError`:

| Exception | Raised when |
|-----------|-------------|
| `LoadError` | A file cannot be opened or parsed |
| `LazyLoadError` | A `LazyDataNode` cannot produce its data (a `LoadError`, and a `RuntimeError`) |
| `UnsupportedFormatError` | A loader does not recognize the file format |
| `UnloadError` | Resource cleanup failed |
| `ValidationError` | A loader's validator found unmet requirements (raised by it, or by `prepare_loader` on `False`) |
| `SetupError` | A loader's setup could not configure the environment (raised by it, or by `prepare_loader` on `False`) |
| `TreeAttachmentError` | `populate()` cannot attach: `parent` is missing, deleted, or structure-locked |

`TreeAttachmentError` wraps the tree's own exception, which stays on
`__cause__`.

## Dependencies

- [numpy](https://numpy.org/) (>=1.24) — array-aware `DataNode` equality and display
- [vcti-plugin-catalog](https://pypi.org/project/vcti-plugin-catalog/) (>=3.0.0, <4) — descriptor and registry base classes; `LoaderRegistry.lookup` filters with [vcti-lookup](https://pypi.org/project/vcti-lookup/) 5 rules
- [vcti-tree](https://pypi.org/project/vcti-tree/) (>=3.0.0, <4) — `LockableTree` protocol, walks, and tree exceptions

## Versioning

This package follows [Semantic Versioning](https://semver.org/).
Breaking changes to the `Loader` protocol, `SubtreeBuilder` semantics or
the `DataNode` shape only occur in major versions. Loader plugins should
pin a compatible major version, e.g. `vcti-fileloader>=6.0,<7`.

## Documentation

| If you want to… | Read |
|---|---|
| Get started using the package | Quick Start above |
| Implement a loader, wire hooks, handle errors and lazy data | [docs/patterns.md](docs/patterns.md) |
| Understand the architecture, attribute model and locking model | [docs/design.md](docs/design.md) |
