Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/development/code-generation.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,10 @@ python scripts/codegen/sdk_rust_gen.py --fixtures --check

`--out` writes a separate model artifact. `--ops` requires `--out` and selects registry operations for
a preview; production generation covers the full registry. The generator owns
`wire_models.rs`, `operations.rs`, `blocking_operations.rs` and `registry_contracts.rs`.
`wire_models.rs`, the serde default helpers in `wire_defaults.rs`, `operations.rs`,
`blocking_operations.rs` and `registry_contracts.rs`. The helpers are a separate module so
`wire_models.rs` stays inside the per-file source limit a static analyser reads; `--out`
keeps them in the one artifact it writes.
The models include identity, idempotence and
read-only policies for the full registry, used by the public generic client call.
Caller and authorship inputs receive bound identity; reader filters remain explicit.
Expand Down
2 changes: 1 addition & 1 deletion scripts/codegen/rust_schema_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def build_fixture() -> str:
+ SUPPORT
+ "\n".join(em.declarations.values())
+ "\n"
+ "\n".join(em.defaults)
+ "\n".join(em.defaults.values())
+ TESTS
)
return rustfmt(text)
Expand Down
78 changes: 64 additions & 14 deletions scripts/codegen/sdk_rust_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

COMMAND = "python scripts/codegen/sdk_rust_gen.py"
TARGET = ROOT / "sdk/rust/src/wire_models.rs"
DEFAULTS_TARGET = ROOT / "sdk/rust/src/wire_defaults.rs"
MEMORY_OPS = ("memory.set", "memory.get", "memory.search", "memory.delete")
CONVENIENCE_OPS = (
*MEMORY_OPS,
Expand Down Expand Up @@ -96,6 +97,13 @@
)


def snake(name: str) -> str:
"""`ContextPackOutput` -> `context_pack_output`, `r#type` -> `type`."""
value = name.removeprefix("r#")
value = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", value)
return re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_")


def rust_ident(name: str) -> str:
value = re.sub(r"[^a-zA-Z0-9_]", "_", name)
if not value or value[0].isdigit():
Expand Down Expand Up @@ -267,7 +275,7 @@ class Emitter:
def __init__(self) -> None:
self.declarations: dict[str, str] = {}
self.shapes: dict[str, str] = {}
self.defaults: list[str] = []
self.defaults: dict[str, str] = {}
self.defs: dict[str, Any] = {}
self.request = False
self.active: set[str] = set()
Expand Down Expand Up @@ -426,7 +434,7 @@ def field(
f'deserialize_with = "{"present_nullable" if nullable else "present_value"}"',
]
elif not required:
attrs += [self.default_attr(prop, ty)]
attrs += [self.default_attr(model, field.removeprefix("r#"), prop, ty)]
if required and nullable:
attrs += ['deserialize_with = "required_nullable"']
return WireField(field, raw, ty, nullable, required, attrs)
Expand All @@ -445,15 +453,24 @@ def debug_impl(name: str, fields: list[str], secrets: set[str]) -> str:
"} }"
)

def default_attr(self, prop: dict[str, Any], ty: str) -> str:
def default_attr(self, model: str, field: str, prop: dict[str, Any], ty: str) -> str:
if "default" not in prop:
return "default"
fn = "default_" + str(len(self.defaults))
literal = json.dumps(prop["default"], separators=(",", ":"), ensure_ascii=False)
self.defaults.append(
f"fn {fn}() -> {ty} {{ serde_json::from_str("
f'{rust_string(literal)}).expect("schema default") }}'
)

def body(name: str) -> str:
return (
f"fn {name}() -> {ty} {{ serde_json::from_str("
f'{rust_string(literal)}).expect("schema default") }}'
)

base = f"default_{snake(model)}_{snake(field)}"
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
fn = base
suffix = 2
while fn in self.defaults and self.defaults[fn] != body(fn):
fn = f"{base}_{suffix}"
suffix += 1
self.defaults[fn] = body(fn)
return f'default = "{fn}"'

def request_field(
Expand Down Expand Up @@ -753,7 +770,7 @@ def operation_type(op: Any, *, request: bool) -> str:
return type_name(model.__name__)


def build(selected: tuple[str, ...] | None = None) -> str:
def _emit(selected: tuple[str, ...] | None = None) -> Emitter:
em = Emitter()
operations = selected_operations(selected)
roots = {operation_type(op, request=request) for op in operations for request in (False, True)}
Expand Down Expand Up @@ -787,10 +804,17 @@ def build(selected: tuple[str, ...] | None = None) -> str:
request=request,
operation=(key, operation_type(op, request=False)) if request else None,
)
# Helpers are shared even when a selection happens not to need one of them.
return em


def _models_text(em: Emitter, *, helpers_inline: bool) -> str:
# Helpers live in `wire_defaults` when checked in, so neither generated
# file is larger than a static analyser's per-file source limit.
use_helpers = "" if helpers_inline else "use crate::wire_defaults::*;\n"
text = (
f"// Generated by {COMMAND}; do not edit.\n"
"use serde::{Deserialize, Serialize};\nuse serde_json::Value;\n"
+ use_helpers
+ SUPPORT
+ "\npub(crate) type OperationPolicy = "
"(&'static str, bool, bool, &'static [&'static str], &'static [&'static str]);\n"
Expand All @@ -802,12 +826,34 @@ def build(selected: tuple[str, ...] | None = None) -> str:
+ "\n];\n"
+ "\n\n".join(em.declarations.values())
+ "\n"
+ "\n".join(em.defaults)
)
if helpers_inline:
# A lone `--out` artifact has no sibling module to reach into.
text += "\n".join(em.defaults.values()) + "\n"
return rustfmt(text)


def _defaults_text(em: Emitter) -> str:
# Helpers are shared even when a selection happens not to need one of them.
text = (
f"// Generated by {COMMAND}; do not edit.\n"
"#![allow(dead_code)]\n"
"use crate::wire_models::*;\n"
"use serde_json::Value;\n\n"
+ "\n".join("pub(crate) " + body for body in em.defaults.values())
+ "\n"
)
return rustfmt(text)


def build(selected: tuple[str, ...] | None = None, *, helpers_inline: bool = True) -> str:
return _models_text(_emit(selected), helpers_inline=helpers_inline)


def build_defaults(selected: tuple[str, ...] | None = None) -> str:
return _defaults_text(_emit(selected))


def build_client(*, blocking: bool = False, selected: tuple[str, ...] | None = None) -> str:
prefix = "" if blocking else "async "
wait = "" if blocking else ".await"
Expand Down Expand Up @@ -915,9 +961,13 @@ def main(argv: list[str] | None = None) -> int:
build_fixture(), check=args.check
)
selected = tuple(args.ops) if args.ops is not None else None
artifacts = [(args.out or TARGET, build(selected))]
if args.out is None:
artifacts += [
if args.out is not None:
artifacts = [(args.out, build(selected))]
else:
em = _emit(selected)
artifacts = [
(TARGET, _models_text(em, helpers_inline=False)),
(DEFAULTS_TARGET, _defaults_text(em)),
(ROOT / "sdk/rust/src/operations.rs", build_client(selected=selected)),
(
ROOT / "sdk/rust/src/blocking_operations.rs",
Expand Down
1 change: 1 addition & 0 deletions scripts/release/rust_sdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
REQUIRED = {
"src/lib.rs",
"src/wire_models.rs",
"src/wire_defaults.rs",
"src/operations.rs",
"src/blocking.rs",
"src/blocking_operations.rs",
Expand Down
1 change: 1 addition & 0 deletions sdk/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ mod operations;
mod retry;
mod routes;
mod token;
mod wire_defaults;
mod wire_models;

#[cfg(feature = "blocking")]
Expand Down
Loading