|
| 1 | +using System.Text; |
| 2 | +using System.Text.Json.Nodes; |
| 3 | +using SourceFlow.Messaging; |
| 4 | +using SourceFlow.Runtime; |
| 5 | + |
| 6 | +namespace SourceFlow.Catalog; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Exports a service's messaging contract as an AsyncAPI 3.0 document (doc 14 §2.2): the service endpoint receives the |
| 10 | +/// commands it owns, each published topic carries its contracts, and every message has its JSON Schema payload and the |
| 11 | +/// CloudEvents headers. Tools that read AsyncAPI (for example EventCatalog) can publish it as a browsable catalog. |
| 12 | +/// </summary> |
| 13 | +public static class AsyncApiExporter |
| 14 | +{ |
| 15 | + /// <summary>The AsyncAPI version written.</summary> |
| 16 | + public const string AsyncApiVersion = "3.0.0"; |
| 17 | + |
| 18 | + /// <summary>Writes the AsyncAPI document of a service.</summary> |
| 19 | + /// <param name="model">The runtime model.</param> |
| 20 | + /// <param name="routing">The routing table (endpoint and publications).</param> |
| 21 | + /// <param name="catalog">The schema catalog (payloads).</param> |
| 22 | + /// <param name="serviceName">The service name (document title).</param> |
| 23 | + /// <param name="version">The document version (for example the service's release).</param> |
| 24 | + public static string Export(RuntimeModel model, RoutingTable routing, SchemaCatalog catalog, string serviceName, string version = "1.0.0") |
| 25 | + { |
| 26 | + ArgumentNullException.ThrowIfNull(model); |
| 27 | + ArgumentNullException.ThrowIfNull(routing); |
| 28 | + ArgumentNullException.ThrowIfNull(catalog); |
| 29 | + ArgumentException.ThrowIfNullOrWhiteSpace(serviceName); |
| 30 | + |
| 31 | + var messages = new JsonObject(); |
| 32 | + var channels = new JsonObject(); |
| 33 | + var operations = new JsonObject(); |
| 34 | + |
| 35 | + // The service endpoint: the commands this service owns (and its timeouts and replies). |
| 36 | + var endpointMessages = new JsonObject(); |
| 37 | + foreach (MessageTypeInfo type in model.Registry.All.Where(t => t.Kind is MessageKind.Command && model.CommandOwners.ContainsKey(t.ClrType))) |
| 38 | + { |
| 39 | + endpointMessages[MessageId(type.Name, type.Version)] = Reference("#/components/messages/" + MessageId(type.Name, type.Version)); |
| 40 | + AddMessage(messages, catalog, type.Name, type.Version); |
| 41 | + } |
| 42 | + |
| 43 | + string endpointId = ChannelId(routing.Endpoint); |
| 44 | + channels[endpointId] = new JsonObject |
| 45 | + { |
| 46 | + ["address"] = routing.Endpoint, |
| 47 | + ["description"] = $"The {serviceName} service endpoint: commands it owns.", |
| 48 | + ["messages"] = endpointMessages, |
| 49 | + }; |
| 50 | + operations["receive-" + endpointId] = new JsonObject |
| 51 | + { |
| 52 | + ["action"] = "receive", |
| 53 | + ["channel"] = Reference("#/channels/" + endpointId), |
| 54 | + ["messages"] = new JsonArray([.. endpointMessages.Select(m => (JsonNode)Reference($"#/channels/{endpointId}/messages/{m.Key}"))]), |
| 55 | + }; |
| 56 | + |
| 57 | + // Published topics: the contracts mapped from domain events (integration events, or events published as is). |
| 58 | + foreach (IGrouping<string, PublicationRoute> topic in routing.Publications.Values.SelectMany(r => r).GroupBy(r => r.Destination, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal)) |
| 59 | + { |
| 60 | + var topicMessages = new JsonObject(); |
| 61 | + foreach (Type contract in topic.Select(r => r.ContractType).Distinct()) |
| 62 | + { |
| 63 | + if (model.Registry.TryGet(contract, out MessageTypeInfo? type)) |
| 64 | + { |
| 65 | + topicMessages[MessageId(type.Name, type.Version)] = Reference("#/components/messages/" + MessageId(type.Name, type.Version)); |
| 66 | + AddMessage(messages, catalog, type.Name, type.Version); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + string id = ChannelId(topic.Key); |
| 71 | + channels[id] = new JsonObject { ["address"] = topic.Key, ["messages"] = topicMessages }; |
| 72 | + operations["publish-" + id] = new JsonObject |
| 73 | + { |
| 74 | + ["action"] = "send", |
| 75 | + ["channel"] = Reference("#/channels/" + id), |
| 76 | + ["messages"] = new JsonArray([.. topicMessages.Select(m => (JsonNode)Reference($"#/channels/{id}/messages/{m.Key}"))]), |
| 77 | + }; |
| 78 | + } |
| 79 | + |
| 80 | + var document = new JsonObject |
| 81 | + { |
| 82 | + ["asyncapi"] = AsyncApiVersion, |
| 83 | + ["info"] = new JsonObject { ["title"] = serviceName, ["version"] = version }, |
| 84 | + ["defaultContentType"] = MessageEnvelope.JsonContentType, |
| 85 | + ["channels"] = channels, |
| 86 | + ["operations"] = operations, |
| 87 | + ["components"] = new JsonObject { ["messages"] = messages, ["schemas"] = new JsonObject { ["CloudEventsHeaders"] = CloudEventsHeaders() } }, |
| 88 | + }; |
| 89 | + return document.ToJsonString(new System.Text.Json.JsonSerializerOptions { WriteIndented = true, TypeInfoResolver = System.Text.Json.Serialization.Metadata.JsonTypeInfoResolver.Combine() }); |
| 90 | + } |
| 91 | + |
| 92 | + private static void AddMessage(JsonObject messages, SchemaCatalog catalog, string type, int version) |
| 93 | + { |
| 94 | + string id = MessageId(type, version); |
| 95 | + if (messages.ContainsKey(id) || !catalog.TryGet(type, version, out SchemaEntry? entry)) |
| 96 | + { |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + messages[id] = new JsonObject |
| 101 | + { |
| 102 | + ["name"] = type, |
| 103 | + ["title"] = $"{type} v{version}", |
| 104 | + ["contentType"] = MessageEnvelope.JsonContentType, |
| 105 | + ["headers"] = Reference("#/components/schemas/CloudEventsHeaders"), |
| 106 | + ["payload"] = entry.Schema.DeepClone(), |
| 107 | + ["x-sourceflow"] = new JsonObject { ["type"] = type, ["version"] = version, ["kind"] = SchemaEntry.KindName(entry.Kind) }, |
| 108 | + }; |
| 109 | + } |
| 110 | + |
| 111 | + // CloudEvents attributes in binary mode (doc 04 §1). |
| 112 | + private static JsonObject CloudEventsHeaders() |
| 113 | + { |
| 114 | + static JsonObject Text(string description) => new() { ["type"] = "string", ["description"] = description }; |
| 115 | + return new JsonObject |
| 116 | + { |
| 117 | + ["type"] = "object", |
| 118 | + ["properties"] = new JsonObject |
| 119 | + { |
| 120 | + ["ce_specversion"] = Text("CloudEvents version (1.0)."), |
| 121 | + ["ce_id"] = Text("Message id (UUIDv7)."), |
| 122 | + ["ce_type"] = Text("Logical message type, for example bank.account.opened."), |
| 123 | + ["ce_source"] = Text("Producing service."), |
| 124 | + ["ce_time"] = Text("Creation time (RFC 3339)."), |
| 125 | + ["ce_subject"] = Text("Stream id, when the message concerns one aggregate."), |
| 126 | + ["ce_sftypeversion"] = Text("Message type version."), |
| 127 | + ["ce_sfcorrelationid"] = Text("Correlation id."), |
| 128 | + ["ce_sfcausationid"] = Text("Causation id."), |
| 129 | + ["ce_sftenant"] = Text("Tenant id."), |
| 130 | + ["traceparent"] = Text("W3C trace context."), |
| 131 | + }, |
| 132 | + ["required"] = new JsonArray("ce_specversion", "ce_id", "ce_type", "ce_source"), |
| 133 | + }; |
| 134 | + } |
| 135 | + |
| 136 | + private static JsonObject Reference(string pointer) |
| 137 | + { |
| 138 | + return new JsonObject { ["$ref"] = pointer }; |
| 139 | + } |
| 140 | + |
| 141 | + private static string MessageId(string type, int version) |
| 142 | + { |
| 143 | + return ChannelId(type) + "_v" + version.ToString(System.Globalization.CultureInfo.InvariantCulture); |
| 144 | + } |
| 145 | + |
| 146 | + // AsyncAPI component keys: ^[a-zA-Z0-9\.\-_]+$. |
| 147 | + private static string ChannelId(string name) |
| 148 | + { |
| 149 | + var id = new StringBuilder(name.Length); |
| 150 | + foreach (char c in name) |
| 151 | + { |
| 152 | + id.Append(char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or '_' ? c : '_'); |
| 153 | + } |
| 154 | + |
| 155 | + return id.ToString(); |
| 156 | + } |
| 157 | +} |
0 commit comments