Metadata-Version: 2.5
Name: msb_arch
Version: 2.0.1
Summary: Mega-Super-Base (MSB) architecture for flexible and extensible Python applications
Project-URL: Homepage, https://github.com/Torward1024/MSB
Project-URL: Documentation, https://github.com/Torward1024/MSB/docs
Project-URL: Repository, https://github.com/Torward1024/MSB
Project-URL: Issues, https://github.com/Torward1024/MSB/issues
Author-email: Alexey Rudnitskiy <almax1024@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2025 Alexey Rudnitskiy
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
License-File: NOTICE
Keywords: architecture,extensible,msb
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# MSB Architecture

[![Python Version](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-Apache%202.0-green.svg)](LICENSE)
[![Version](https://img.shields.io/badge/version-2.0.1-brightgreen.svg)](https://github.com/Torward1024/MSB)

Mega-Super-Base (MSB) is for the application that outgrew a script: one whose data has a shape
worth validating, whose operations keep multiplying, and which now needs a window, a command line
and a server over the same model without three copies of the logic.

You describe the data as typed entities, you describe what may be done to it as operations, and
everything reaches both through one orchestrator. A request is data, not a call:

```text
{"operation": "configure", "obj": part, "attributes": {"set": {"params": {"price": 4.5}}}}
```

Which is a small thing that buys several large ones:

- The same code serves a dialog, a script and a remote caller, because none of them is calling a
  method — they are all sending the same dictionary.
- A session can be **recorded and replayed**: the journal keeps each request as data, with the
  object's address in the model rather than a reference to it, so a recorded session runs again
  against a model built from scratch and lands on the objects it meant.
- Menus, dependency graphs, handler stubs and execution order are **derived from the code** rather
  than listed, so none of them can go stale.
- Metrics, auditing, authorisation and rate limiting hang on one hook that sees every request, and
  the operations know nothing about them.

Written for a working instrument — [pAstroCORE](https://github.com/Torward1024/pAstroCORE), which
plans radio astronomy observations — and everything here exists because that application needed
it.

## Features

- **Typed entities.** Attributes validated against their annotations, nested to any depth,
  including `List`, `Dict`, `Tuple`, `Set`, `Union`, `Literal`, `Callable` and `Type[X]`. A value
  written after the annotation is what the field starts as, and a declared list or dict belongs
  to the object rather than to the class.
- **Constraints on values, not just types.** `price: Annotated[float, Positive()]` is enforced on
  construction, on assignment and on restore, with no `__init__` of your own.
- **Rules about the whole object.** `@invariant("end must be after start")` guards what no
  per-field rule can — the relation between several. Checked at the same three points, and a
  refused change is undone rather than half-applied.
- **Containers for collections.** Named, queryable, serializable, with bulk operations.
- **One entry point.** A `Manipulator` registers operations and processes requests; a facade per
  operation means you rarely write a request dictionary by hand.
- **Reading and writing come free.** `inspect`, `configure`, `save`, `load` and `catalogue` are
  registered for you, so an application that only reads and writes its model needs no operation
  layer at all.
- **Operations that write themselves.** A handler is usually one call to `_apply_methods`, which
  applies everything a request names and reports each outcome.
- **Pipelines.** Several requests that feed each other, given as data in one call. The order,
  what may run at once, and what to skip when a step fails all follow from the edges.
- **Serialization that round-trips.** `json.loads(json.dumps(obj.to_dict()))` restores an equal
  object, through lists, dicts, sets and tuples, nested to any depth. Cycles are detected rather
  than followed, and data carries the schema version of the class that wrote it.
- **Derived answers instead of hand-written ones.** What operations exist, what handlers they
  have, which handler needs which, which type holds which, and what a change reaches — all read
  back from the code, so a menu or a diagram cannot go stale.
- **One place to hang metrics, auditing, rate limiting and authorisation.** An interceptor sees a
  request before it runs and its response after, and may refuse or rewrite it. Request metrics
  and a replayable journal ship using nothing more than that hook.
- **A session that replays somewhere else.** The journal records each request as plain data, with
  the object's address in the model rather than a reference to it, so `json.dumps(journal.entries)`
  on one side and `manipulator.replay(json.loads(...))` on the other run the same session against
  another project, in another process -- landing on the objects it meant. `address` and `locate`
  are the same addressing on its own, for a request that has to cross a wire.
- **Asynchronous when you need it.** `await manipulator.ainspect(...)` moves the work off the
  event loop, and every synchronous signature is untouched.
- **Exceptions you can catch precisely.** Everything derives from `MSBError`, and also from the
  built-in it replaces, so `except TypeError` keeps working while `except DuplicateNameError`
  becomes possible.
- **No external dependencies.** Python >= 3.12 and nothing else.

## Installation

```bash
pip install msb_arch
```

## Quick start

Describe the data, describe the operations, drive both through the orchestrator.

```python
from msb_arch import BaseContainer, BaseEntity, Manipulator

# 1. the data
class Part(BaseEntity):
    price: float

    def get_price(self) -> float:
        return self.price

    def set_price(self, value: float) -> bool:
        self.price = value
        return True

class Parts(BaseContainer[Part]):
    pass

# 2. the entry point
class Workshop(Manipulator):
    pass

manipulator = Workshop(base_classes=[Part, Parts])

box = Parts(name="box")
box.add(Part(name="bolt", price=4.5))
bolt = box.get("bolt")

assert manipulator.inspect(bolt, get_price=None) == 4.5
manipulator.configure(bolt, set_price=5.0)
assert manipulator.inspect(bolt, get_price=None) == 5.0

assert box.to_dict()["items"]["bolt"]["price"] == 5.0
```

There is no operation layer to write: `inspect` and `configure` follow from the request model
itself. You write a `Super` when an operation carries logic of your own:

```python
from msb_arch import Super

class Pricing(Super):
    OPERATION = "price"

    def _price_parts(self, obj, attributes):
        return sum(part.price for part in obj.get_items())

manipulator.register_operation(Pricing(manipulator))
assert manipulator.price(box) == 5.0
```

A handler is short because `_apply_methods` owns the loop, and the orchestrator dispatches by
operation and by the type of the object, so adding an entity adds no code at all.

Ask for several things at once and every outcome comes back:

```python
answer = manipulator.inspect(bolt, get_price=None, get=["name", "isactive"])
assert answer["get_price"]["result"] == 5.0
assert answer["get"]["result"] == {"name": "bolt", "isactive": True}
```

Run several requests as one batch:

```python
manipulator.batch([
    {"operation": "configure", "obj": bolt, "attributes": {"set_price": 6.0}},
    {"operation": "inspect", "obj": bolt, "attributes": {"get_price": None}},
])
assert bolt.price == 6.0
```

Or as a pipeline, when the steps feed each other:

```python
outcome = manipulator.pipeline({
    "written": {"operation": "save", "obj": box, "path": "box.json"},
    "read":    {"operation": "load", "obj": box, "path": "box.json", "after": ["written"]},
    "total":   {"operation": "price", "obj": "@read"},
})
assert outcome.output == 6.0
```

## Architecture

Three layers, plus what they share.

| Layer | Module | What lives there |
| --- | --- | --- |
| **Base** — the data | [`serializable.py`](src/msb_arch/base/serializable.py), [`baseentity.py`](src/msb_arch/base/baseentity.py), [`basecontainer.py`](src/msb_arch/base/basecontainer.py) | Validation, serialization, caching, ownership |
| **Super** — the operations | [`super.py`](src/msb_arch/super/super.py), [`builtins.py`](src/msb_arch/super/builtins.py), [`project.py`](src/msb_arch/super/project.py) | Handlers, method resolution, the built-in operations |
| **Mega** — the entry point | [`manipulator.py`](src/msb_arch/mega/manipulator.py) | Operation registry, request processing, facades, batches, pipelines |
| Derivation | [`catalogue.py`](src/msb_arch/catalogue.py), [`model.py`](src/msb_arch/model.py), [`scaffold.py`](src/msb_arch/scaffold.py) | What is registered, what holds what, generated stubs |
| Shared | [`interceptors.py`](src/msb_arch/interceptors.py), [`results.py`](src/msb_arch/results.py), [`utils/`](src/msb_arch/utils) | Metrics and journal, result types, logging, validation |

Main classes:

- **`Serializable`** — what an entity and a container have in common: annotated fields and their
  validation, `name` and `isactive`, `to_dict`, the cache, `revision` and `fingerprint`.
- **`BaseEntity`** — an object addressed by its attributes.
- **`BaseContainer[T]`** — a named collection addressed by its items. A sibling of `BaseEntity`,
  not a subclass: the two mean different things by `get`, `set` and `clear`.
- **`Super`** — an operation. Subclass it, name the operation, and write handlers as
  `_<operation>_<type>`, or `_<operation>` for the fallback.
- **`Project`** — a named collection of entities with a factory for creating them: the thing an
  application saves as a whole. A `Serializable` like the other two, addressed by its items.
- **`Manipulator`** — the entry point. Registers operations, processes requests and pipelines,
  and answers what it knows about itself and the model.
- **`MethodResults`** — what an operation reports: every method it ran, mapped to its outcome.

## Documentation

- [**Guide**](docs/guide.md) — **start here**: a working application, built from nothing
- [API reference](docs/api.md) — every public class and method
- [Compatibility](docs/COMPATIBILITY.md) — what will not break, and how anything changes
- [Architecture](docs/architecture.md) and [diagrams](docs/diagrams.md)
- [Base module](docs/modules/base.md) — the data model, type hints, serialization, caching
- [Super module](docs/modules/super.md) — writing your own operation
- [Mega module](docs/modules/mega.md) — requests, pipelines, interceptors, the async surface
- [Examples](docs/examples.md)
- [Roadmap](docs/ROADMAP.md) — what is open, and what was decided against
- [Changelog](CHANGELOG.md) — release history and upgrade notes

## Testing

Unit, integration, performance and concurrency suites, run with pytest.

The tests import `msb_arch` rather than the source tree, so they exercise whatever is installed.
Install the package first:

```bash
pip install -e .
```

Then run them:

```bash
pytest tests/
```

CI builds the wheel, installs it, checks that `msb_arch` resolves inside `site-packages`, and
runs the same suites against it, so the distribution that ships is the one that was tested.

## Projects using MSB

- [pAstroCORE](https://github.com/Torward1024/pAstroCORE) — radio astronomy observation planning.

## License

[Apache License 2.0](LICENSE). Use it for anything, including commercially, in open or closed
source: keep the licence and the [NOTICE](NOTICE) with the code, state what you changed, and the
patent grant protects you as long as you do not sue over it.

Releases up to and including 1.10.0 went out under the earlier MSB Software License and stay under
it; 2.0.0 and later are Apache-2.0.

Available for collaboration, contract work and support — [almax1024@gmail.com](mailto:almax1024@gmail.com).

## Contacts

- **Author**: Alexey Rudnitskiy
- **Email**: [almax1024@gmail.com](mailto:almax1024@gmail.com)
- **Repository**: [https://github.com/Torward1024/MSB](https://github.com/Torward1024/MSB)
- **Version**: 2.0.1
