From bc2525f99a05ee02ac3607f02c4efb05dfebb74c Mon Sep 17 00:00:00 2001 From: Clemens Vasters Date: Wed, 18 Nov 2026 15:59:44 +0100 Subject: [PATCH] Support raw AMQP XML in C# Service Bus templates Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 9 +- test/codegen/test_codegen.py | 84 +++++++++++++++++ .../cs/net100/dependencies.csproj | 2 +- xrcg/generator/template_renderer.py | 91 +++++++++++++++++-- xrcg/templates/cs/_common/amqp.jinja.include | 57 ++++++++++++ .../cs/_common/cloudevents.jinja.include | 2 +- .../cs/_common/servicebus.jinja.include | 4 +- xrcg/templates/cs/_common/util.jinja.include | 5 +- .../cs/sbazfn/src/DispatchInterfaces.cs.jinja | 20 +++- .../templates/cs/sbazfn/src/Function.cs.jinja | 48 +++++++++- .../cs/sbazfn/test/FunctionTest.cs.jinja | 50 ++++++++-- .../cs/sbazfn/{rootdir}README.md.jinja | 5 + .../cs/sbproducer/src/EventFactory.cs.jinja | 23 +++-- .../cs/sbproducer/test/ProducerTest.cs.jinja | 6 +- .../cs/sbproducer/{rootdir}README.md.jinja | 6 ++ 15 files changed, 375 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 31bcca8a..52ea141f 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/test/codegen/test_codegen.py b/test/codegen/test_codegen.py index 559b5dc4..16366c8a 100644 --- a/test/codegen/test_codegen.py +++ b/test/codegen/test_codegen.py @@ -1,3 +1,4 @@ +import json import platform import re import xrcg @@ -29,6 +30,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 = """ + + + + """ + 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. diff --git a/xrcg/dependencies/cs/net100/dependencies.csproj b/xrcg/dependencies/cs/net100/dependencies.csproj index a78addc6..01356141 100644 --- a/xrcg/dependencies/cs/net100/dependencies.csproj +++ b/xrcg/dependencies/cs/net100/dependencies.csproj @@ -32,7 +32,7 @@ - + diff --git a/xrcg/generator/template_renderer.py b/xrcg/generator/template_renderer.py index f4241a82..f5757cd7 100644 --- a/xrcg/generator/template_renderer.py +++ b/xrcg/generator/template_renderer.py @@ -4,6 +4,7 @@ from ast import main import glob +import hashlib import json import os import re @@ -194,9 +195,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) @@ -206,6 +210,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): @@ -225,7 +234,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): # Separate JSON Structure schemas from Avro/other schemas jstruct_schemas = [s for s in avrotize_queue if s.get("format_short") == "jstruct"] avro_schemas = [s for s in avrotize_queue if s.get("format_short") != "jstruct"] @@ -259,7 +268,7 @@ def get_schema_key(schema_content: JsonNode) -> str: self._process_jstruct_schemas(jstruct_merged, project_data_dir, json_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: @@ -271,6 +280,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] @@ -282,7 +295,8 @@ def get_schema_key(schema_content: JsonNode) -> str: elif self.language == "cs": 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 + pascal_properties=True, system_text_json_annotation=json_enabled, avro_annotation=avro_enabled, + system_xml_annotation=bool(xsd_models) ) self._update_csproj_target_framework(project_data_dir) elif self.language == "java": @@ -321,6 +335,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) -> None: """Process JSON Structure schemas using dedicated Avrotize converters. @@ -956,8 +1022,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 @@ -1007,8 +1072,10 @@ 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", "schema", "schemaurl", "dataschemaurl", "dataschemauri"] and isinstance(value, str): - schema_refs.add(value) + if key in ["dataschemaxid", "dataschema", "schema", "schemaurl", "dataschemaurl", "dataschemauri"] and isinstance(value, str): + if key == "schema" and self.is_xsd_doc(value): + continue + schema_refs.add(self._local_schema_reference(value)) # Look for inline schemas elif key == "schema" and isinstance(value, (dict, str)): @@ -1024,6 +1091,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) @@ -1230,6 +1301,8 @@ def _get_format_short(self, schema_format: str) -> str: return "jstruct" elif format_lower.startswith("avro"): return "avro" + elif format_lower.startswith("xsd"): + return "xsd" return "unknown" def _extract_proto_class_name(self, proto_content: str, class_hint: str) -> str: @@ -1241,7 +1314,7 @@ def _extract_proto_class_name(self, proto_content: str, class_hint: str) -> str: def should_use_avrotize(self, schema_info: Dict[str, Any]) -> bool: """Check if schema should be processed with avrotize.""" - return self.language in ["py", "cs", "java", "js", "ts", "go"] + return schema_info["format_short"] != "xsd" and self.language in ["py", "cs", "java", "js", "ts", "go"] def convert_json_to_avro_if_needed(self, schema_info: Dict[str, Any]) -> None: """Convert JSON schema to Avro if needed.""" diff --git a/xrcg/templates/cs/_common/amqp.jinja.include b/xrcg/templates/cs/_common/amqp.jinja.include index 6d5a5f0b..dccea8ab 100644 --- a/xrcg/templates/cs/_common/amqp.jinja.include +++ b/xrcg/templates/cs/_common/amqp.jinja.include @@ -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 diff --git a/xrcg/templates/cs/_common/cloudevents.jinja.include b/xrcg/templates/cs/_common/cloudevents.jinja.include index 14ad9b29..886d8015 100644 --- a/xrcg/templates/cs/_common/cloudevents.jinja.include +++ b/xrcg/templates/cs/_common/cloudevents.jinja.include @@ -203,7 +203,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 %} case "{{ messageid }}": if ( this.{{ messagegroupid | strip_namespace | camel }}Dispatcher != null ) diff --git a/xrcg/templates/cs/_common/servicebus.jinja.include b/xrcg/templates/cs/_common/servicebus.jinja.include index e62b6e47..9d232a52 100644 --- a/xrcg/templates/cs/_common/servicebus.jinja.include +++ b/xrcg/templates/cs/_common/servicebus.jinja.include @@ -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 -%} \ No newline at end of file diff --git a/xrcg/templates/cs/_common/util.jinja.include b/xrcg/templates/cs/_common/util.jinja.include index 2456559b..633184f2 100644 --- a/xrcg/templates/cs/_common/util.jinja.include +++ b/xrcg/templates/cs/_common/util.jinja.include @@ -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 %} diff --git a/xrcg/templates/cs/sbazfn/src/DispatchInterfaces.cs.jinja b/xrcg/templates/cs/sbazfn/src/DispatchInterfaces.cs.jinja index fbd8401b..66d8f9a2 100644 --- a/xrcg/templates/cs/sbazfn/src/DispatchInterfaces.cs.jinja +++ b/xrcg/templates/cs/sbazfn/src/DispatchInterfaces.cs.jinja @@ -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) }} \ No newline at end of file +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 %} \ No newline at end of file diff --git a/xrcg/templates/cs/sbazfn/src/Function.cs.jinja b/xrcg/templates/cs/sbazfn/src/Function.cs.jinja index 2a77f2ed..536673ad 100644 --- a/xrcg/templates/cs/sbazfn/src/Function.cs.jinja +++ b/xrcg/templates/cs/sbazfn/src/Function.cs.jinja @@ -2,7 +2,10 @@ {%- set function_name = project_name | pascal | strip_dots -%} {%- import "cloudevents.jinja.include" as cloudEvents -%} {%- import "servicebus.jinja.include" as servicebus -%} +{%- import "amqp.jinja.include" as amqp -%} {%- import "util.jinja.include" as util -%} +{%- set raw_servicebus_groups = {} -%} +{{- amqp.CollectRawServiceBusGroups(messagegroups, raw_servicebus_groups) -}} {{ util.CommonFileHeader() }} using System; @@ -20,16 +23,57 @@ namespace {{ project_name | pascal }} {%- set class_name = (project_name | pascal | strip_namespace)+"Function" %} public class {{ class_name }} { - ILogger<{{class_name}}> _logger; + {%- set ce_args = cloudEvents.DeclareDispatchObjectsArgs(project_name, messagegroups, true) %} {{ cloudEvents.DeclareDispatchObjectsFields( project_name, messagegroups ) | indent(8) }} - {{ cloudEvents.DeclareDispatchObjectsConstructor( project_name, class_name, messagegroups, "ILoggerFactory? loggerFactory", "_logger = loggerFactory?.CreateLogger<"+ class_name +">()??new LoggerFactory().CreateLogger<"+ class_name +">();") | indent(8) }} + {%- for group_id in raw_servicebus_groups %} + private readonly global::{{ group_id | concat_namespace(project_name) | pascal }}.I{{ group_id | pascal | strip_namespace }}ServiceBusDispatcher _raw{{ group_id | pascal | strip_dots }}; + {%- endfor %} + + public {{ class_name }}(ILoggerFactory? loggerFactory{% if ce_args %}, {{ ce_args }}{% endif %} + {%- for group_id in raw_servicebus_groups %}, + global::{{ group_id | concat_namespace(project_name) | pascal }}.I{{ group_id | pascal | strip_namespace }}ServiceBusDispatcher raw{{ group_id | pascal | strip_dots }} + {%- endfor %}) + { + {%- for group_id, group in messagegroups.items() if group | exists("envelope","CloudEvents/1.0") %} + this.{{ group_id | strip_namespace | camel }}Dispatcher = {{ group_id | strip_namespace | camel }}Dispatcher; + {%- endfor %} + {%- for group_id in raw_servicebus_groups %} + _raw{{ group_id | pascal | strip_dots }} = raw{{ group_id | pascal | strip_dots }}; + {%- endfor %} + } {{ servicebus.CloudEventsMethods() | indent(8) }} public async virtual Task Run(ServiceBusReceivedMessage message, ILogger log) { + {%- if raw_servicebus_groups %} + if (!IsCloudEvent(message)) + { + switch (message.Subject) + { + {%- for group_id, messages in raw_servicebus_groups.items() %} + {%- for message_id, definition in messages.items() %} + {%- set body_type = util.body_type(data_project_name, root, definition) %} + case {{ amqp.ServiceBusSubject(message_id, definition) | tojson }}: + await _raw{{ group_id | pascal | strip_dots }}.On{{ amqp.ServiceBusFactoryMessageName(message_id, true) }}Async(message, + {%- if body_type == "byte[]" %} message.Body.ToArray() + {%- else %} {{ body_type }}.FromData(message.Body.ToArray(), message.ContentType ?? {{ amqp.ServiceBusContentType(definition) | tojson }}) + ?? throw new System.IO.InvalidDataException("Missing Service Bus message body") + {%- endif %}); + return; + {%- endfor %} + {%- endfor %} + default: + throw new System.IO.InvalidDataException($"Unsupported Service Bus subject '{message.Subject}'"); + } + } + {%- endif %} + {%- if messagegroups | exists("envelope","CloudEvents/1.0") %} var cloudEvent = CloudEventFromServiceBusMessage(message); {{ cloudEvents.DispatchToDispatchObjects( project_name, data_project_name, root, "cloudEvent", messagegroups, "log" ) | indent(12) }} + {%- else %} + throw new System.IO.InvalidDataException("This receiver does not accept CloudEvents"); + {%- endif %} } } } \ No newline at end of file diff --git a/xrcg/templates/cs/sbazfn/test/FunctionTest.cs.jinja b/xrcg/templates/cs/sbazfn/test/FunctionTest.cs.jinja index f574053c..2751cbe5 100644 --- a/xrcg/templates/cs/sbazfn/test/FunctionTest.cs.jinja +++ b/xrcg/templates/cs/sbazfn/test/FunctionTest.cs.jinja @@ -3,7 +3,10 @@ {%- set function_class_name = (project_name | pascal)+"."+(project_name | pascal | strip_namespace) + "Function" -%} {%- import "cloudevents.jinja.include" as cloudEvents -%} {%- import "servicebus.jinja.include" as servicebus -%} +{%- import "amqp.jinja.include" as amqp -%} {%- import "util.jinja.include" as util -%} +{%- set raw_servicebus_groups = {} -%} +{{- amqp.CollectRawServiceBusGroups(messagegroups, raw_servicebus_groups) -}} {{ util.CommonFileHeader() }} #pragma warning disable CS8602 // Dereference of a possibly null reference. @@ -29,6 +32,9 @@ namespace {{ project_name | pascal }}.Tests private Mock loggerFactoryMock; private Mock> loggerMock; {{ cloudEvents.DeclareDispatchObjectMocks( project_name, messagegroups ) | indent(8) }} + {%- for group_id in raw_servicebus_groups %} + private Mock _raw{{ group_id | pascal | strip_dots }}; + {%- endfor %} [SetUp] public void Setup() @@ -37,15 +43,21 @@ namespace {{ project_name | pascal }}.Tests loggerMock = new Mock>(); loggerFactoryMock.Setup(x => x.CreateLogger(typeof({{ function_class_ref }}).FullName!)).Returns(loggerMock.Object); {{ cloudEvents.SetupDispatchObjectMocks( project_name, messagegroups ) | indent(12) }} + {%- for group_id in raw_servicebus_groups %} + _raw{{ group_id | pascal | strip_dots }} = new(); + {%- endfor %} {{ function_class_field }} = new {{ function_class_ref }}( - loggerFactoryMock.Object, + loggerFactoryMock.Object {%- for messagegroupid, messagegroup in messagegroups.items() if (messagegroup | exists("envelope","CloudEvents/1.0")) -%} - _{{ messagegroupid | strip_namespace | camel }}DispatcherMock.Object{% if not loop.last %}, - {% endif -%} + , _{{ messagegroupid | strip_namespace | camel }}DispatcherMock.Object + {%- endfor -%} + {%- for group_id in raw_servicebus_groups -%} + , _raw{{ group_id | pascal | strip_dots }}.Object {%- endfor -%}); } + {%- if messagegroups | exists("envelope","CloudEvents/1.0") %} [Test] public async Task Run_WithNoMessages_ShouldNotInvokeAnyDispatcherMethods() { @@ -64,7 +76,7 @@ namespace {{ project_name | pascal }}.Tests // Assert {%- for messagegroupid, messagegroup in messagegroups.items() if (messagegroup | exists("envelope","CloudEvents/1.0")) -%} {%- for messageid, message in messagegroup.messages.items() -%} - {%- if message.envelope.startswith("CloudEvents") -%} + {%- if (message.envelope or "").startswith("CloudEvents") -%} {%- set messagename = messageid | pascal %} {%- set message_body_type = util.body_type(data_project_name, root, message) %} _{{ messagegroupid | strip_namespace | camel }}DispatcherMock.Verify( @@ -79,10 +91,34 @@ namespace {{ project_name | pascal }}.Tests {%- endfor -%} {%- endfor -%} } + {%- endif %} + + {%- for group_id, messages in raw_servicebus_groups.items() %} + {%- for message_id, definition in messages.items() %} + {%- set body_type = util.body_type(data_project_name, root, definition) %} + {%- set method = "On" ~ amqp.ServiceBusFactoryMessageName(message_id, true) ~ "Async" %} + [Test] + public async Task Run_{{ group_id | pascal | strip_dots }}_{{ method }}() + { + const string contentType = {{ amqp.ServiceBusContentType(definition) | tojson }}; + {%- if body_type == "byte[]" %} + var bytes = new byte[] { 1, 2, 3 }; + {%- else %} + var bytes = new {{ body_type }}().ToByteArray(contentType); + {%- endif %} + var message = ServiceBusModelFactory.ServiceBusReceivedMessage( + body: new BinaryData(bytes), subject: {{ amqp.ServiceBusSubject(message_id, definition) | tojson }}, + contentType: contentType); + await {{ function_class_field }}.Run(message, loggerMock.Object); + _raw{{ group_id | pascal | strip_dots }}.Verify( + x => x.{{ method }}(message, It.IsAny<{{ body_type }}>()), Times.Once); + } + {%- endfor %} + {%- endfor %} {%- for messagegroupid, messagegroup in messagegroups.items() if (messagegroup | exists("envelope","CloudEvents/1.0")) -%} {%- for messageid, message in messagegroup.messages.items() -%} - {%- if message.envelope.startswith("CloudEvents") -%} + {%- if (message.envelope or "").startswith("CloudEvents") -%} {%- set messagename = messageid | pascal %} [Test] public async Task Run_With{{ messageid | strip_namespace | pascal }}_ShouldInvoke{{ messagegroupid | strip_namespace | pascal }}DispatcherOn{{ messageid | strip_namespace | pascal }}Async() @@ -106,14 +142,14 @@ namespace {{ project_name | pascal }}.Tests contentType: "application/json", properties: new Dictionary { - {"cloudEvents:specversion", "1.0"}, + {"cloudEvents_specversion", "1.0"}, {"cloudEvents_type", "{{ messageid }}"} } ); {%- endif %} await {{ function_class_field }}.Run(message, loggerMock.Object); _{{ messagegroupid | strip_namespace | camel }}DispatcherMock.Verify( - x => x.On{{ messageid | strip_namespace | pascal }}Async(It.IsAny(), It.IsAny<{{ message_body_type if message_body_type != "byte[]" else "BinaryData" }}>()), + x => x.On{{ messageid | strip_namespace | pascal }}Async(It.IsAny(), It.IsAny<{{ message_body_type if message_body_type != "byte[]" else "object" }}>()), Times.Once ); } diff --git a/xrcg/templates/cs/sbazfn/{rootdir}README.md.jinja b/xrcg/templates/cs/sbazfn/{rootdir}README.md.jinja index 2749f7a9..13063f7e 100644 --- a/xrcg/templates/cs/sbazfn/{rootdir}README.md.jinja +++ b/xrcg/templates/cs/sbazfn/{rootdir}README.md.jinja @@ -10,6 +10,11 @@ Auto-generated Azure Function for processing Azure Service Bus messages. ## Overview +Raw AMQP messages are routed by their declared subject (the catalogue message ID +when no subject is declared). Implement the generated `ServiceBusDispatcher` +interface to receive the original broker message and the deserialized body. +CloudEvents still use their separate type-based dispatcher. + This Azure Function automatically triggers when messages arrive in your Service Bus queue or topic subscription. It deserializes messages and calls your custom handlers - perfect for building event-driven microservices! ## Quick Start diff --git a/xrcg/templates/cs/sbproducer/src/EventFactory.cs.jinja b/xrcg/templates/cs/sbproducer/src/EventFactory.cs.jinja index 6a5c0ecc..e7964d2d 100644 --- a/xrcg/templates/cs/sbproducer/src/EventFactory.cs.jinja +++ b/xrcg/templates/cs/sbproducer/src/EventFactory.cs.jinja @@ -8,6 +8,8 @@ {%- set uses_amqp_endpoint = amqp.uses_amqp_endpoint(root) %} using CloudNative.CloudEvents; using CloudNative.CloudEvents.SystemTextJson; +using Azure; +using Azure.Core; using Azure.Messaging.ServiceBus; {% for messagegroupid, messagegroup in messagegroups.items() -%} @@ -25,8 +27,7 @@ namespace {{ groupname | concat_namespace(project_name) | pascal }} {%- if root.endpoints -%} {%- for endpointid, endpoint in root.endpoints.items() -%} {%- if endpoint.usage and "producer" in endpoint.usage -%} - {%- set protocol = endpoint.protocol | lower -%} - {%- if protocol == "amqp" -%} + {%- if amqp.is_amqp(endpoint) -%} {%- set options = endpoint.protocoloptions -%} {%- set endpoints = endpoint.endpoints %} {%- macro createforbody(class_name, endpoints, options) -%} @@ -110,24 +111,26 @@ namespace {{ groupname | concat_namespace(project_name) | pascal }} } {% for messageid, message in messagegroup.messages.items() -%} - {%- set messagename = messageid | pascal %} {%- set isCloudEvent = cloudEvents.isCloudEvent(message) %} - {%- set is_amqp = amqp.is_amqp(message) %} + {%- set is_amqp = amqp.is_amqp(message) or amqp.IsRawServiceBusMessage(messagegroup, message) %} + {%- set messagename = amqp.ServiceBusFactoryMessageName(messageid, is_amqp and not isCloudEvent) %} {%- set type_name = util.body_type(data_project_name, root, message) %} {%- if message.description %} /// /// {{ message.description }} /// {%- endif %} - public static ServiceBusMessage Create{{ messagename | strip_namespace }}Event( + public static ServiceBusMessage Create{{ messagename }}Event( {{ type_name }} data {%- if isCloudEvent -%} {{- cloudEvents.DeclareUriTemplateArguments(message) -}} {%- elif is_amqp -%} - {{- amqp.DeclareUriTemplateArguments(message) -}} + {%- if message.protocoloptions -%}{{- amqp.DeclareUriTemplateArguments(message) -}}{%- endif -%} {%- endif -%} {%- if isCloudEvent and "datacontenttype" in message.envelopemetadata and "value" in message.envelopemetadata["datacontenttype"] -%} , string contentType = "{{ message.envelopemetadata["datacontenttype"]["value"] }}" + {%- elif is_amqp and not isCloudEvent -%} + , string contentType = {{ amqp.ServiceBusContentType(message) | tojson }} {%- else -%} , string contentType = System.Net.Mime.MediaTypeNames.Application.Json {%- endif %} @@ -145,16 +148,20 @@ namespace {{ groupname | concat_namespace(project_name) | pascal }} {{ cloudEvents.DeclareCloudNativeCloudEvent("cloudEvent", message) | indent(12) }} return CreateMessage(cloudEvent, data, contentType, bodySerializer, formatter); {%- elif is_amqp %} - return CreateMessage(null, data, contentType, bodySerializer, null); + var message = CreateMessage(null, data, contentType, bodySerializer, null); {%- endif %} {% else %} {%- if isCloudEvent %} {{ cloudEvents.DeclareCloudNativeCloudEvent("cloudEvent", message) | indent(12) }} return CreateMessage(cloudEvent, data, contentType, null, formatter); {%- elif is_amqp %} - return CreateMessage(null, data, contentType, null, null); + var message = CreateMessage(null, data, contentType, null, null); {%- endif %} {% endif %} + {%- if is_amqp and not isCloudEvent %} + message.Subject = {{ amqp.ServiceBusSubject(messageid, message) | tojson }}; + return message; + {%- endif %} } {% endfor %} } diff --git a/xrcg/templates/cs/sbproducer/test/ProducerTest.cs.jinja b/xrcg/templates/cs/sbproducer/test/ProducerTest.cs.jinja index 3aea8b48..06da5a33 100644 --- a/xrcg/templates/cs/sbproducer/test/ProducerTest.cs.jinja +++ b/xrcg/templates/cs/sbproducer/test/ProducerTest.cs.jinja @@ -206,10 +206,10 @@ namespace {{ project_name | pascal }}.Test #pragma warning disable CS8604 // init takes care of nullables {%- for messageid, message in messagegroup.messages.items() %} - {%- set messagename = messageid | strip_namespace | pascal %} - {%- set is_amqp = amqp.is_amqp(message) %} + {%- set is_amqp = amqp.is_amqp(message) or amqp.IsRawServiceBusMessage(messagegroup, message) %} {%- set isCloudEvent = cloudEvents.isCloudEvent(message) %} - {%- set uriargs = cloudEvents.DeclareUriTemplateArguments(message) %} + {%- set messagename = amqp.ServiceBusFactoryMessageName(messageid, is_amqp and not isCloudEvent) %} + {%- set uriargs = cloudEvents.DeclareUriTemplateArguments(message) if isCloudEvent else (amqp.DeclareUriTemplateArguments(message) if message.protocoloptions else "") %} [Fact] public async Task Test{{ messagename }}Message() { diff --git a/xrcg/templates/cs/sbproducer/{rootdir}README.md.jinja b/xrcg/templates/cs/sbproducer/{rootdir}README.md.jinja index 6dae8886..af1a4f8e 100644 --- a/xrcg/templates/cs/sbproducer/{rootdir}README.md.jinja +++ b/xrcg/templates/cs/sbproducer/{rootdir}README.md.jinja @@ -73,6 +73,12 @@ var producer = new {{ class_name }}( ## Available Methods +For raw AMQP messages, `CreateEvent` factory names use the full catalogue message +ID: `example.001.02` becomes `CreateExample00102Event`. Dotted segments are not +stripped as namespaces. CloudEvents factory naming is unchanged. +Raw messages use the declared AMQP subject and content type. XSD-backed bodies +are serialized as XML, without a CloudEvents envelope. + {% for messageid, message in messagegroup.messages.items() -%} {%- set messagename = messageid | pascal | strip_namespace %} {%- set message_body_type = util.body_type(data_project_name, root, message) %}