forked from 1b-agent/opencadstudio-upstream
Add ocs_doc_api: object-oriented CAD entity API (v2)
New crate crates/ocs_doc_api: object-centric facade (DocApi -> Document -> collections -> typed handles), transport-agnostic wire layer (DocApiEnvelope = single op | read-only query batch), per-op autocommit (no write transactions), bulk ops with upfront-validation all-or-nothing, structured ApiError, and build-time codegen (spec/entities.toml -> ops/query enums, api_reference.md, binding_schema.json). ocs_plugin_api: append-only PluginRequest::DocApiRequest / PluginResponse:: DocApiResponse (serde_bytes payload) + defaulted HostApi::doc_api_dispatch. Host: DocApiBackend impl for HostSession (src/app/doc_api.rs) mapping to scene primitives (solid_models lift-on-miss, register_prepared_solid_model, meshes metrics), entity conversions (doc_api_convert.rs), HostSession accessors + doc_api_dispatch override. Tests: 592 host lib (incl. 7 DocApi integration tests: create/boolean/query, unknown-id, transform-many all-or-nothing, query-batch cap, 2D/geometric/DWG roundtrips), 8 crate unit tests. Examples + README/ARCHITECTURE/IMPLEMENTATION docs.
This commit is contained in:
1 parent
9129c85f97
commit
e41086b058
44 files changed
+4837
-12
No files matched your search
@@ -0,0 +1,98 @@
|
||||
# ocs_doc_api — binding generator contract
|
||||
|
||||
How to build a REPL/scripting bridge to `ocs_doc_api` in **any** language
|
||||
(Python, Lua, JS, …) — no Rust FFI, one versioned schema. This is the binding
|
||||
handover defined in the plan (§10.2, decision #13).
|
||||
|
||||
## What you consume
|
||||
|
||||
**One artifact:** `gen/binding_schema.json` (also exposed as
|
||||
`ocs_doc_api::binding_schema_json()`). It is self-contained:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"schema": "ocs_doc_api/binding_schema",
|
||||
"envelope_version": 1,
|
||||
"object_model": { "root": "DocApi", "document": "Document",
|
||||
"collections": ["solids","curves","entities"],
|
||||
"handles": ["Entity","Solid","Line","Circle","Polyline","Point"] },
|
||||
"families": [ /* per family: handle, collection, methods[] */ ],
|
||||
"layouts": { /* traced wire layouts for ObjectId / Operation / Query */ }
|
||||
}
|
||||
```
|
||||
|
||||
Each `families[].methods[]` entry:
|
||||
```jsonc
|
||||
{ "name": "intersect", "kind": "op", // "op" (write) | "query" (read)
|
||||
"op": "SolidBoolean", "query": null, // the Operation/Query it maps to
|
||||
"args": [{ "name": "other", "ty": "Solid" }],
|
||||
"returns": "Solid",
|
||||
"bulk": false, "read_only": false,
|
||||
"fixed": { "op": "Intersection", "erase_sources": true } }
|
||||
```
|
||||
|
||||
## What you implement (3 things)
|
||||
|
||||
1. **Code generator** — read `binding_schema.json`, emit language classes:
|
||||
`DocApi` → `document(tab)` → `solids()/curves()/entities()` → handles
|
||||
(`Solid`, `Line`, …). Each generated method builds the `Operation`/`Query` its
|
||||
schema node names (applying `fixed` fields) and ships it (step 2). Handles are
|
||||
`{ ObjectId, kind }` — an `ObjectId` is a plain `u64`.
|
||||
|
||||
2. **`DocApiEnvelope` (de)serializer** — the wire unit (bincode over the host's
|
||||
plugin channel). Layout:
|
||||
```
|
||||
DocApiEnvelope { version: u16, body: EnvelopeBody }
|
||||
EnvelopeBody = Op(Operation) | Queries(Vec<Query>)
|
||||
```
|
||||
A **write** request carries exactly ONE `Operation`; a **read** request carries
|
||||
one-or-more `Query` (read-only batching is safe). Serialize with bincode
|
||||
semantics matching the `layouts` map (enum variants are appended at the END
|
||||
only, so discriminants are stable). The host replies with a bincode
|
||||
`Result<Receipt, ApiError>`; `Receipt` carries `outcome`, `query_results`,
|
||||
`new_revision`.
|
||||
|
||||
3. **Session glue** — send the envelope over the existing `ocs_plugin_api`
|
||||
channel. The host already exposes the DocApi executor via
|
||||
`PluginRequest::DocApiRequest { tab_id, bytes }` →
|
||||
`PluginResponse::DocApiResponse { bytes }`. A REPL bridge typically rides the
|
||||
V4 `ExecuteCode` loop (the mechanism the `ocs_python_repl` plugin uses) or a
|
||||
direct `PluginRequestSender`.
|
||||
|
||||
## Errors → language exceptions
|
||||
|
||||
Map the structured `ApiError` to your language's exceptions:
|
||||
|
||||
| `ApiError` variant | meaning |
|
||||
|---|---|
|
||||
| `Validation { op, reason }` | input rejected before any mutation (bulk op names the failing index) |
|
||||
| `Geometry { kind, msg }` | the kernel failed (boolean refused, invalid input, ACIS) |
|
||||
| `UnknownId(ObjectId)` | the handle is stale/deleted/never existed |
|
||||
| `Unsupported(msg)` | capability not implemented (e.g. a later-phase family) |
|
||||
| `Transport(msg)` | the channel failed (disconnected/oversized/timeout) |
|
||||
|
||||
## Version / compatibility rule
|
||||
|
||||
- Check `binding_schema.json.envelope_version` against `DocApiEnvelope.version`
|
||||
(currently `1`) before speaking; a mismatch is a hard bridge error.
|
||||
- `Operation`/`Query` variants are **append-only**: a bridge built against an
|
||||
older schema keeps working; unknown new variants are simply not generated until
|
||||
you regenerate.
|
||||
|
||||
## Reference implementation
|
||||
|
||||
See `bindings/python/generate.py` — it reads `binding_schema.json` and emits
|
||||
`ocs_doc.py` with `DocApi`/`Document`/`Solid`/`Line`/… classes whose methods build
|
||||
and ship `DocApiEnvelope` ops. Lua/JS follow the same contract; only the
|
||||
serializer + codegen differ.
|
||||
|
||||
## Semantics to honour
|
||||
|
||||
- **Per-op autocommit:** every write method is one atomic host call = one undo
|
||||
step. There are no multi-op write transactions. A failed op applies nothing and
|
||||
records no undo step; earlier ops stay committed (no rollback).
|
||||
- **`erase_sources` booleans** replace the first input (`a`) in place and erase
|
||||
the second (`b`); the result is returned at `a`'s id.
|
||||
- **Bulk ops** (`CreateMany`/`TransformMany`/`DeleteMany`) are single ops,
|
||||
all-or-nothing via upfront validation (no rollback), item-cap `100_000`.
|
||||
- **Query batching** is read-only and safe; it never bumps the geometry revision.
|
||||
@@ -0,0 +1,192 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reference binding generator for ocs_doc_api (plan §10.2).
|
||||
|
||||
Reads `gen/binding_schema.json` and emits a Python module `ocs_doc.py` with the
|
||||
object model (DocApi -> Document -> collections -> handles) whose methods build
|
||||
`DocApiEnvelope` ops/queries and ship them through a caller-supplied transport.
|
||||
|
||||
This is the *contract* in executable form (bindings/README.md): one versioned
|
||||
schema, no Rust FFI, thin serializer. Lua/JS generators follow the same shape.
|
||||
|
||||
Usage:
|
||||
python bindings/python/generate.py gen/binding_schema.json > ocs_doc.py
|
||||
|
||||
The emitted module expects a `transport` object with:
|
||||
def apply(self, envelope: DocApiEnvelope) -> Receipt
|
||||
which the bridge author implements (the session glue over the plugin channel).
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from typing import List, Dict, Any
|
||||
|
||||
HEADER = '''"""Auto-generated ocs_doc_api Python bindings. Do NOT edit by hand.
|
||||
Generated by bindings/python/generate.py from binding_schema.json (envelope_version {ver}).
|
||||
Check envelope_version before use; see bindings/README.md."""
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, List, Optional
|
||||
|
||||
# --- wire DTOs (thin, schema-driven) -----------------------------------------
|
||||
ObjectId = int # u64
|
||||
|
||||
@dataclass
|
||||
class Receipt:
|
||||
outcome: Any
|
||||
query_results: List[Any]
|
||||
new_revision: int
|
||||
|
||||
@dataclass
|
||||
class DocApiEnvelope:
|
||||
version: int
|
||||
body: Any # ("Op", operation_dict) | ("Queries", [query_dict])
|
||||
|
||||
ENVELOPE_VERSION = {ver}
|
||||
|
||||
|
||||
def _check_version(schema_version: int) -> None:
|
||||
if schema_version != ENVELOPE_VERSION:
|
||||
raise RuntimeError(
|
||||
f"binding_schema envelope_version {{schema_version}} != {{ENVELOPE_VERSION}}"
|
||||
)
|
||||
'''
|
||||
|
||||
HANDLE_TEMPLATE = '''
|
||||
@dataclass
|
||||
class {handle}:
|
||||
id: ObjectId
|
||||
_doc: "Document"
|
||||
|
||||
{methods}
|
||||
'''
|
||||
|
||||
# Rust type -> Python annotation (schema types are Rust-flavoured).
|
||||
PY_TYPES = {
|
||||
"Solid": "'Solid'", "Line": "'Line'", "Circle": "'Circle'",
|
||||
"Polyline": "'Polyline'", "Point": "'Point'", "Entity": "'Entity'",
|
||||
"f64": "float", "bool": "bool", "usize": "int",
|
||||
"[f64; 3]": "tuple", "ObjectId": "ObjectId", "()": "None", "None": "None",
|
||||
}
|
||||
|
||||
def py_type(rust_ty: str) -> str:
|
||||
return PY_TYPES.get(rust_ty, "Any")
|
||||
|
||||
|
||||
def py_lit(v: Any) -> str:
|
||||
"""A JSON value as a Python literal (handles booleans/None)."""
|
||||
if v is True:
|
||||
return "True"
|
||||
if v is False:
|
||||
return "False"
|
||||
if v is None:
|
||||
return "None"
|
||||
return json.dumps(v)
|
||||
|
||||
|
||||
METHOD_OP = ''' def {name}(self{sig}) -> {ret}:
|
||||
op = {{"{variant}": {body}}}
|
||||
return self._doc._apply_op(op)
|
||||
'''
|
||||
|
||||
METHOD_QUERY = ''' def {name}(self{sig}) -> {ret}:
|
||||
q = {{"{variant}": {body}}}
|
||||
return self._doc._apply_query(q)
|
||||
'''
|
||||
|
||||
|
||||
def render_method(m: Dict[str, Any]) -> str:
|
||||
"""Emit one facade method. `self.id` is the receiver's ObjectId (`a`/`id`);
|
||||
each handle-typed arg contributes its `.id`. Fixed fields are injected from
|
||||
the schema node."""
|
||||
name = m["name"]
|
||||
args = m.get("args", [])
|
||||
sig = "".join(f", {a['name']}" for a in args)
|
||||
ret = py_type(m.get("returns") or "None")
|
||||
|
||||
# Receiver is `a` for SolidBoolean, `id` otherwise. Handle args map to .id.
|
||||
field_for_arg = {}
|
||||
for a in args:
|
||||
# a handle arg becomes `<name>_id` in the payload when the variant needs ids
|
||||
field_for_arg[a["name"]] = a["name"]
|
||||
|
||||
body_items: List[str] = []
|
||||
variant = m["op"] if m["kind"] == "op" else m["query"]
|
||||
if variant == "SolidBoolean":
|
||||
body_items.append("'op': '%s'" % (m.get("fixed", {}).get("op", "")))
|
||||
body_items.append("'a': self.id")
|
||||
if args:
|
||||
body_items.append(f"'b': {args[0]['name']}.id")
|
||||
body_items.append(f"'erase_sources': {py_lit((m.get('fixed') or {}).get('erase_sources', True))}")
|
||||
elif variant in ("GetVolume", "GetCentroid", "GetBounds", "GetEntity"):
|
||||
body_items.append("'id': self.id")
|
||||
elif variant == "GetIntersects":
|
||||
body_items.append("'a': self.id")
|
||||
if args:
|
||||
body_items.append(f"'b': {args[0]['name']}.id")
|
||||
elif variant == "AddVertex":
|
||||
body_items.append("'id': self.id")
|
||||
for a in args:
|
||||
body_items.append(f"'{a['name']}': {a['name']}")
|
||||
else:
|
||||
for a in args:
|
||||
body_items.append(f"'{a['name']}': {a['name']}")
|
||||
body = "{" + ", ".join(body_items) + "}"
|
||||
|
||||
if m["kind"] == "op":
|
||||
return METHOD_OP.format(name=name, sig=sig, ret=ret, variant=variant, body=body)
|
||||
return METHOD_QUERY.format(name=name, sig=sig, ret=ret, variant=variant, body=body)
|
||||
|
||||
|
||||
def render(schema: Dict[str, Any]) -> str:
|
||||
out = [HEADER.format(ver=schema["envelope_version"])]
|
||||
handles = set(schema["object_model"]["handles"])
|
||||
for fam in schema["families"]:
|
||||
handle = fam.get("handle") or fam["name"]
|
||||
methods = "\n".join(render_method(m) for m in fam.get("methods", []))
|
||||
if not methods.strip():
|
||||
methods = " pass\n"
|
||||
out.append(HANDLE_TEMPLATE.format(handle=handle, methods=methods))
|
||||
out.append(
|
||||
'''
|
||||
@dataclass
|
||||
class Document:
|
||||
_transport: Any
|
||||
_tab: int
|
||||
|
||||
def _apply_op(self, op, want):
|
||||
env = DocApiEnvelope(ENVELOPE_VERSION, ("Op", op))
|
||||
return self._transport.apply(env)
|
||||
|
||||
def _apply_query(self, q, want):
|
||||
env = DocApiEnvelope(ENVELOPE_VERSION, ("Queries", [q]))
|
||||
return self._transport.apply(env)
|
||||
|
||||
def solids(self): return Solids(self)
|
||||
def curves(self): return Curves(self)
|
||||
def entities(self): return Entities(self)
|
||||
|
||||
class Solids:
|
||||
def __init__(self, doc): self._doc = doc
|
||||
class Curves:
|
||||
def __init__(self, doc): self._doc = doc
|
||||
class Entities:
|
||||
def __init__(self, doc): self._doc = doc
|
||||
|
||||
@dataclass
|
||||
class DocApi:
|
||||
_transport: Any
|
||||
|
||||
def document(self, tab: int) -> Document:
|
||||
return Document(self._transport, tab)
|
||||
'''
|
||||
)
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
path = sys.argv[1] if len(sys.argv) > 1 else "gen/binding_schema.json"
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
schema = json.load(f)
|
||||
sys.stdout.write(render(schema))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user