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
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,14 @@ Unlike snippet generators, this tool produces **complete SDK-like projects**:
| Feature | What's Generated |
|---------|------------------|
| **Type-safe clients** | Producer/consumer classes with strongly-typed methods per message |
| **Data classes** | Schema-derived classes via [Avrotize](https://github.com/clemensv/avrotize) (JSON Schema, Avro, Protobuf) |
| **Data classes** | Schema-derived classes via [Avrotize](https://github.com/clemensv/avrotize) (JSON Schema, Avro, Protobuf, and XSD for C#) |

C# XSD model generation uses local registry schema references such as `dataschemaxid`.
It supports a single document element with an inline or same-named complex type
and requires Avrotize with the XML generation fixes in
[clemensv/avrotize#584](https://github.com/clemensv/avrotize/pull/584).
The template's wire protocol is independent of model generation. Validate XML
against the original XSD when schema conformance is required.
| **Build files** | `pom.xml`, `.csproj`, `package.json`, `pyproject.toml` with correct dependencies |
| **Integration tests** | Docker-based tests using Testcontainers for Kafka, MQTT, AMQP brokers |
| **Project structure** | Language-idiomatic layout ready for IDE import |
Expand Down
84 changes: 84 additions & 0 deletions test/codegen/test_codegen.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import platform
import re
import json
Expand Down Expand Up @@ -35,6 +36,89 @@ def pascal(string: str) -> str:
words = re.findall(r'[a-z0-9]+\.?|[A-Z][a-z0-9_]*\.?', string)
return ''.join(word.capitalize() for word in words)

def test_sbproducer_preserves_dotted_amqp_message_ids(tmp_path, monkeypatch):
"""Raw AMQP message IDs sharing a version must generate distinct factories."""
messages = {
f"example.{kind}.02": {"protocol": "AMQP/1.0", "protocoloptions": {}}
for kind in ("001", "002")
}
messages["example.status.updated"] = {
"protocol": "AMQP/1.0",
"envelope": "CloudEvents/1.0",
"envelopemetadata": {},
}
definitions = tmp_path / "catalogue.json"
definitions.write_text(json.dumps({
"messagegroups": {"example": {"messages": messages}},
}), encoding="utf-8")
output = tmp_path / "generated"
monkeypatch.setattr(sys, "argv", [
"xrcg", "generate", "--language", "cs", "--style", "sbproducer",
"--projectname", "NamingProbe", "--definitions", str(definitions),
"--output", str(output), "--noschema",
])
assert xrcg.cli() == 0

factory = next(output.rglob("EventFactory.cs")).read_text(encoding="utf-8")
tests = next(output.rglob("ProducerTest.cs")).read_text(encoding="utf-8")
expected = {"CreateExample00102Event", "CreateExample00202Event", "CreateUpdatedEvent"}
assert set(re.findall(r"public static ServiceBusMessage (Create\w+Event)\(", factory)) == expected
assert set(re.findall(r"EventFactory\.(Create\w+Event)\(", tests)) == expected


def test_xsd_model_generation_is_shared_across_csharp_templates(tmp_path, monkeypatch):
"""The same registry XSD binds to the same generated type across transports."""
definitions = tmp_path / "catalogue.json"
xsd = """<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:example:payments" elementFormDefault="qualified">
<xs:element name="Document"><xs:complexType><xs:sequence>
<xs:element name="Id" type="xs:string"/>
</xs:sequence></xs:complexType></xs:element>
</xs:schema>"""
definitions.write_text(json.dumps({
"messagegroups": {"example": {"messages": {
"payment.001.02": {
"protocol": "AMQP/1.0", "dataschemaformat": "XSD/1.0",
"dataschemaxid": "/schemagroups/example/schemas/payment.001.02",
"protocoloptions": {"properties": {
"subject": {"type": "string", "value": "Payment"},
"content-type": {"type": "string", "value": "application/xml"},
}},
},
}}},
"schemagroups": {"example": {"schemas": {"payment.001.02": {
"defaultversionid": "1", "versions": {"1": {"format": "XSD/1.0", "schema": xsd}},
}}}},
}), encoding="utf-8")
model_names = set()
for style, source in (
("sbproducer", "EventFactory.cs"),
("sbazfn", "DispatchInterfaces.cs"),
("amqpproducer", "EventProducer.cs"),
):
output = tmp_path / style
monkeypatch.setattr(sys, "argv", [
"xrcg", "generate", "--language", "cs", "--style", style,
"--projectname", "XmlProbe", "--definitions", str(definitions), "--output", str(output),
])
assert xrcg.cli() == 0
model, = output.rglob("Document.cs")
generated = model.read_text(encoding="utf-8")
assert '[XmlRoot("Document", Namespace="urn:example:payments")]' in generated
namespace = re.search(r"^namespace (\S+)", generated, re.MULTILINE).group(1)
code = next(output.rglob(source)).read_text(encoding="utf-8")
assert f"global::{namespace}.Document" in code
model_names.add(namespace)
if style == "sbproducer":
assert 'message.Subject = "Payment"' in code
assert 'string contentType = "application/xml"' in code
elif style == "sbazfn":
dispatch = next(output.rglob("Function.cs")).read_text(encoding="utf-8")
assert 'case "Payment":' in dispatch
assert f"global::{namespace}.Document.FromData(" in dispatch
assert len(model_names) == 1


def test_codegen_cs():
"""
This does a basic test of the code generation for all the styles in the cs template.
Expand Down
84 changes: 76 additions & 8 deletions xrcg/generator/template_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from ast import main
import glob
import hashlib
import json
import os
import re
Expand Down Expand Up @@ -196,9 +197,12 @@ def generate(self) -> None:

# Process unhandled schemas using the composed document
avrotize_queue = []
xsd_models = {}
unhandled_schemas = self.get_unhandled_schema_references(xregistry_document)

for schema_reference in unhandled_schemas:
for schema_reference in sorted(unhandled_schemas):
if "#/" + schema_reference.lstrip("#/") in xsd_models:
continue
schema_data = self.resolve_schema_reference_in_document(schema_reference, xregistry_document)
if not schema_data:
logger.warning("Could not resolve schema reference: %s", schema_reference)
Expand All @@ -208,6 +212,11 @@ def generate(self) -> None:
if not schema_info:
logger.warning("Could not extract schema info for: %s", schema_reference)
continue
if schema_info["format_short"] == "xsd":
if self.language == "cs":
if not self.suppress_schema_output:
xsd_models[schema_reference] = self._convert_xsd_model(schema_reference, schema_info["content"])
continue

# Check if this schema should be processed with avrotize
if self.should_use_avrotize(schema_info):
Expand All @@ -230,7 +239,7 @@ def generate(self) -> None:
schema_template_dirs, schema_env, self.template_args, self.suppress_schema_output
)
# Process avrotize queue using the refactored approach
if len(avrotize_queue) > 0:
if not self.suppress_schema_output and (avrotize_queue or xsd_models):
os.makedirs(project_data_dir, exist_ok=True)
# Separate JSON Structure schemas from Avro/other schemas
jstruct_schemas = [s for s in avrotize_queue if s.get("format_short") == "jstruct"]
Expand Down Expand Up @@ -266,7 +275,7 @@ def get_schema_key(schema_content: JsonNode) -> str:
self._process_jstruct_schemas(jstruct_merged, project_data_dir, json_enabled, avro_enabled, xml_enabled)

# Process Avro/converted schemas
if avro_schemas:
if avro_schemas or xsd_models:
merged_schema = []
seen_keys: set[str] = set()
for schema_info in avro_schemas:
Expand All @@ -281,6 +290,10 @@ def get_schema_key(schema_content: JsonNode) -> str:
seen_keys.add(key)
merged_schema.append(c)

if xsd_models and avro_enabled:
raise RuntimeError("C# XSD models cannot share a project with Avro encoding enabled")
if xsd_models:
merged_schema.extend(xsd_models.values())
if len(merged_schema) == 1:
merged_schema = merged_schema[0]

Expand All @@ -294,7 +307,7 @@ def get_schema_key(schema_content: JsonNode) -> str:
avrotize.convert_avro_schema_to_csharp(
merged_schema, project_data_dir, base_namespace=JinjaFilters.pascal(self.data_project_name),
pascal_properties=True, system_text_json_annotation=json_enabled, avro_annotation=avro_enabled,
system_xml_annotation=xml_enabled,
system_xml_annotation=xml_enabled or bool(xsd_models),
target_framework=self._get_target_framework()
)
elif self.language == "java":
Expand Down Expand Up @@ -344,6 +357,58 @@ def get_schema_key(schema_content: JsonNode) -> str:
self.template_args, self.suppress_schema_output
)

def _xsd_namespace(self, pointer: str) -> str:
schema_id = self._extract_class_name_from_ref(pointer)
name = re.sub(r"[^a-zA-Z0-9]", "_", schema_id)
return f"Xsd_{name}_{hashlib.sha256(pointer.encode()).hexdigest()[:12]}"

@staticmethod
def _xsd_root_name(pointer: str, content: str) -> str:
schema = ET.fromstring(content)
roots = schema.findall("{http://www.w3.org/2001/XMLSchema}element")
if len(roots) != 1 or not roots[0].get("name"):
raise RuntimeError(f"{pointer}: expected a single named XSD document element")
return roots[0].attrib["name"]

def _convert_xsd_model(self, pointer: str, content: str) -> dict:
from avrotize.xsdtoavro import XSDToAvro
from pathlib import Path

name = self._xsd_root_name(pointer, content)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "schema.xsd"
path.write_text(content, encoding="utf-8")
model = XSDToAvro().xsd_to_avro(str(path), code_namespace=self._xsd_namespace(pointer))
candidate = model
if model.get("name") != name:
candidate = next((f["type"] for f in model.get("fields", []) if f["name"] == name), None)
if not isinstance(candidate, dict) or candidate.get("xmlname") != name:
raise RuntimeError(
f"{pointer}: requires an inline or same-named complex XML root and Avrotize with XSD XML support "
"(clemensv/avrotize#584)"
)
return model

@staticmethod
def _local_schema_reference(reference: str) -> str:
if reference.startswith(("/", "#")):
return "#/" + reference.lstrip("#/")
return reference

def _schema_type(self, reference: JsonNode, project: str, root: JsonNode, schema_format: str) -> str:
if isinstance(reference, str) and reference.startswith(("/", "#")):
pointer = self._local_schema_reference(reference)
if self.language == "cs" and isinstance(root, dict):
resolved = self.resolve_schema_reference_in_document(pointer, root)
info = self.extract_schema_info_from_resolved_data(pointer, resolved)
if info and info["format_short"] == "xsd":
from avrotize.common import pascal

name = self._xsd_root_name(pointer, info["content"])
return f"{project}.{pascal(self._xsd_namespace(pointer))}.{pascal(name)}"
reference = pointer
return SchemaUtils.schema_type(self.ctx, reference, project, root, schema_format)

def _process_jstruct_schemas(self, jstruct_schema: JsonNode, project_data_dir: str, json_enabled: bool, avro_enabled: bool = False, xml_enabled: bool = False) -> None:
"""Process JSON Structure schemas using dedicated Avrotize converters.

Expand Down Expand Up @@ -983,8 +1048,7 @@ def setup_jinja_env(self, template_dirs: List[str]) -> jinja2.Environment:
env.filters['concat_namespace'] = JinjaFilters.concat_namespace
env.filters['strip_dots'] = JinjaFilters.strip_dots
env.filters['lstrip'] = JinjaFilters.lstrip
env.filters['schema_type'] = lambda schema_ref, project_name, root, schema_format: SchemaUtils.schema_type(
self.ctx, schema_ref, project_name, root, schema_format)
env.filters['schema_type'] = self._schema_type
env.filters['strip_invalid_identifier_characters'] = JinjaFilters.strip_invalid_identifier_characters
env.filters['pad'] = JinjaFilters.pad
env.filters['toyaml'] = JinjaFilters.to_yaml
Expand Down Expand Up @@ -1049,8 +1113,8 @@ def scan_for_schemas(obj: JsonNode, path: str = "") -> None:
current_path = f"{path}/{key}" if path else key

# Look for schema reference properties
if key in ["dataschema", "schemaurl", "dataschemaurl", "dataschemauri"] and isinstance(value, str):
schema_refs.add(value)
if key in ["dataschemaxid", "dataschema", "schemaurl", "dataschemaurl", "dataschemauri"] and isinstance(value, str):
schema_refs.add(self._local_schema_reference(value))

# Look for inline schemas
elif key == "schema" and isinstance(value, (dict, str)):
Expand All @@ -1068,6 +1132,10 @@ def scan_for_schemas(obj: JsonNode, path: str = "") -> None:
scan_for_schemas(document)
return schema_refs

@staticmethod
def is_xsd_doc(value: str) -> bool:
return "http://www.w3.org/2001/XMLSchema" in value and value.lstrip().startswith("<")

def get_unhandled_schema_references(self, document: JsonNode) -> set[str]:
"""Get schema references that haven't been marked as handled."""
all_schemas = self.collect_schema_references_from_document(document)
Expand Down
57 changes: 57 additions & 0 deletions xrcg/templates/cs/_common/amqp.jinja.include
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,63 @@

{%- import "util.jinja.include" as util -%}

{%- macro IsRawServiceBusMessage(group, message) -%}
{%- set protocol = message.protocol or group.protocol or "" -%}
{%- if protocol.lower().startswith("amqp") and not (message.envelope or "").lower().startswith("cloudevents") -%}
true
{%- endif -%}
{%- endmacro -%}

{%- macro CollectRawServiceBusGroups(messagegroups, groups) -%}
{%- set subjects = {} -%}
{%- for group_id, group in messagegroups.items() -%}
{%- for message_id, message in group.messages.items() if IsRawServiceBusMessage(group, message) -%}
{%- set subject = ServiceBusSubject(message_id, message) -%}
{%- if subject in subjects -%}
{%- error "Duplicate Service Bus subject: " ~ subject -%}
{%- endif -%}
{%- set _ = subjects.update({subject: true}) -%}
{%- set _ = groups.setdefault(group_id, {}).update({message_id: message}) -%}
{%- endfor -%}
{%- endfor -%}
{%- endmacro -%}

{%- macro ServiceBusFactoryMessageName(messageid, raw_amqp) -%}
{%- if raw_amqp -%}
{{- messageid | replace('.', '_') | pascal -}}
{%- else -%}
{{- messageid | pascal | strip_namespace -}}
{%- endif -%}
{%- endmacro -%}

{%- macro ServiceBusSubject(messageid, message) -%}
{%- if message.protocoloptions and message.protocoloptions.properties and "subject" in message.protocoloptions.properties -%}
{%- set subject = message.protocoloptions.properties.subject -%}
{%- if subject.value is not string or subject.type == "uritemplate" -%}
{%- error "Service Bus subject must be a literal string" -%}
{%- endif -%}
{{- subject.value -}}
{%- else -%}
{{- messageid -}}
{%- endif -%}
{%- endmacro -%}

{%- macro ServiceBusContentType(message) -%}
{%- if message.protocoloptions and message.protocoloptions.properties and "content-type" in message.protocoloptions.properties -%}
{%- set content_type = message.protocoloptions.properties["content-type"] -%}
{%- if content_type.value is not string or content_type.type == "uritemplate" -%}
{%- error "Service Bus content type must be a literal string" -%}
{%- endif -%}
{{- content_type.value -}}
{%- elif message.datacontenttype -%}
{{- message.datacontenttype -}}
{%- elif message.dataschemaformat and message.dataschemaformat.lower().startswith("xsd/") -%}
application/xml
{%- else -%}
application/json
{%- endif -%}
{%- endmacro -%}

{%- macro is_amqp(message) -%}
{%- if message.protocol and message.protocol.lower().startswith("amqp") -%}
true
Expand Down
2 changes: 1 addition & 1 deletion xrcg/templates/cs/_common/cloudevents.jinja.include
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ var cloudEventType = {{ cloudEvent }}.Type;
switch (cloudEventType)
{
{% for messagegroupid, messagegroup in messagegroups.items() if (messagegroup | exists("envelope","CloudEvents/1.0")) -%}
{% for messageid, message in messagegroup.messages.items() -%}
{% for messageid, message in messagegroup.messages.items() if (message | exists("envelope","CloudEvents/1.0")) -%}
{% set messagename = messageid | pascal %}
{%- set ce_type_value = message.envelopemetadata["type"]["value"] if ("type" in message.envelopemetadata and "value" in message.envelopemetadata["type"]) else messageid %}
case "{{ ce_type_value }}":
Expand Down
4 changes: 2 additions & 2 deletions xrcg/templates/cs/_common/servicebus.jinja.include
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,6 @@ protected CloudEvent CloudEventFromServiceBusMessage(ServiceBusReceivedMessage s

public static bool IsCloudEvent(ServiceBusReceivedMessage serviceBusMessage) =>
MimeUtilities.IsCloudEventsContentType(serviceBusMessage.ContentType) ||
serviceBusMessage.ApplicationProperties.ContainsKey(amqpCloudEventPrefix1) ||
serviceBusMessage.ApplicationProperties.ContainsKey(amqpCloudEventPrefix2);
serviceBusMessage.ApplicationProperties.ContainsKey(amqpCloudEventPrefix1 + "specversion") ||
serviceBusMessage.ApplicationProperties.ContainsKey(amqpCloudEventPrefix2 + "specversion");
{%- endmacro -%}
5 changes: 3 additions & 2 deletions xrcg/templates/cs/_common/util.jinja.include
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@


{%- macro body_type(data_project_name, root, message) -%}
{%- if message.dataschemauri or message.dataschema -%}
global::{{ (message.dataschemauri if message.dataschemauri else message.dataschema) | schema_type( data_project_name, root, message.dataschemaformat) | pascal }}
{%- set reference = message.dataschemaxid or message.dataschemauri or message.dataschema -%}
{%- if reference -%}
global::{{ reference | schema_type(data_project_name, root, message.dataschemaformat) | pascal }}
{%- else -%}
byte[]
{%- endif %}
Expand Down
20 changes: 19 additions & 1 deletion xrcg/templates/cs/sbazfn/src/DispatchInterfaces.cs.jinja
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
{%- import "cloudevents.jinja.include" as cloudEvents -%}
{%- import "amqp.jinja.include" as amqp -%}
{%- import "util.jinja.include" as util -%}
{%- set raw_servicebus_groups = {} -%}
{{- amqp.CollectRawServiceBusGroups(root.messagegroups, raw_servicebus_groups) -}}
{{ util.CommonFileHeader() }}

{{ cloudEvents.DeclareDispatchInterfaces(project_name, data_project_name, root) }}
using System.Threading.Tasks;

{{ cloudEvents.DeclareDispatchInterfaces(project_name, data_project_name, root) }}

{% for group_id, messages in raw_servicebus_groups.items() -%}
namespace {{ group_id | concat_namespace(project_name) | pascal }}
{
public interface I{{ group_id | pascal | strip_namespace }}ServiceBusDispatcher
{
{%- for message_id, message in messages.items() %}
Task On{{ amqp.ServiceBusFactoryMessageName(message_id, true) }}Async(
global::Azure.Messaging.ServiceBus.ServiceBusReceivedMessage message, {{ util.body_type(data_project_name, root, message) }} data);
{%- endfor %}
}
}
{% endfor %}
Loading
Loading