| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Collections.Generic; |
| | 6 | | using System.Globalization; |
| | 7 | | using System.IO; |
| | 8 | | using System.Linq; |
| | 9 | | using System.Security.Cryptography; |
| | 10 | | using System.Text; |
| | 11 | | using System.Text.Json; |
| | 12 | | using System.Threading; |
| | 13 | | using System.Threading.Tasks; |
| | 14 | | using System.Web; |
| | 15 | | using Azure.Core; |
| | 16 | | using Azure.Core.Pipeline; |
| | 17 | | using Azure.Core.Serialization; |
| | 18 | | using Azure.Messaging.EventGrid.Models; |
| | 19 | |
|
| | 20 | | namespace Azure.Messaging.EventGrid |
| | 21 | | { |
| | 22 | | /// <summary> |
| | 23 | | /// Client used to interact with the Event Grid service. |
| | 24 | | /// </summary> |
| | 25 | | public class EventGridPublisherClient |
| | 26 | | { |
| | 27 | | private readonly ServiceRestClient _serviceRestClient; |
| | 28 | | private readonly ClientDiagnostics _clientDiagnostics; |
| 44 | 29 | | private string _hostName => _endpoint.Host; |
| | 30 | | private readonly Uri _endpoint; |
| | 31 | | private readonly AzureKeyCredential _key; |
| | 32 | | private readonly string _apiVersion; |
| | 33 | | private readonly ObjectSerializer _dataSerializer; |
| | 34 | |
|
| | 35 | | /// <summary>Initalizes an instance of EventGridClient.</summary> |
| 44 | 36 | | protected EventGridPublisherClient() |
| | 37 | | { |
| 44 | 38 | | } |
| | 39 | |
|
| | 40 | | /// <summary>Initalizes an instance of EventGridClient.</summary> |
| | 41 | | /// <param name="endpoint">Topic endpoint. For example, "https://TOPIC-NAME.REGION-NAME-1.eventgrid.azure.net/ap |
| | 42 | | /// <param name="credential">Credential used to connect to Azure.</param> |
| | 43 | | public EventGridPublisherClient(Uri endpoint, AzureKeyCredential credential) |
| 0 | 44 | | : this(endpoint, credential, new EventGridPublisherClientOptions()) |
| | 45 | | { |
| 0 | 46 | | } |
| | 47 | |
|
| | 48 | | /// <summary>Initalizes an instance of EventGridClient.</summary> |
| | 49 | | /// <param name="endpoint">Topic endpoint. For example, "https://TOPIC-NAME.REGION-NAME-1.eventgrid.azure.net/ap |
| | 50 | | /// <param name="credential">Credential used to connect to Azure.</param> |
| | 51 | | public EventGridPublisherClient(Uri endpoint, EventGridSharedAccessSignatureCredential credential) |
| 0 | 52 | | : this(endpoint, credential, new EventGridPublisherClientOptions()) |
| | 53 | | { |
| 0 | 54 | | } |
| | 55 | |
|
| | 56 | | /// <summary>Initalizes an instance of the<see cref="EventGridPublisherClient"/> class.</summary> |
| | 57 | | /// <param name="endpoint">Topic endpoint. For example, "https://TOPIC-NAME.REGION-NAME-1.eventgrid.azure.net/ap |
| | 58 | | /// <param name="credential">Credential used to connect to Azure.</param> |
| | 59 | | /// <param name="options">Configuring options.</param> |
| 40 | 60 | | public EventGridPublisherClient(Uri endpoint, AzureKeyCredential credential, EventGridPublisherClientOptions opt |
| | 61 | | { |
| 40 | 62 | | Argument.AssertNotNull(credential, nameof(credential)); |
| 40 | 63 | | options ??= new EventGridPublisherClientOptions(); |
| 40 | 64 | | _dataSerializer = options.DataSerializer ?? new JsonObjectSerializer(); |
| 40 | 65 | | _apiVersion = options.Version.GetVersionString(); |
| 40 | 66 | | _endpoint = endpoint; |
| 40 | 67 | | _key = credential; |
| 40 | 68 | | HttpPipeline pipeline = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(credential, Constant |
| 40 | 69 | | _serviceRestClient = new ServiceRestClient(new ClientDiagnostics(options), pipeline, options.Version.GetVers |
| 40 | 70 | | _clientDiagnostics = new ClientDiagnostics(options); |
| 40 | 71 | | } |
| | 72 | |
|
| | 73 | | /// <summary> |
| | 74 | | /// Initializes a new instance of the <see cref="EventGridPublisherClient"/> class. |
| | 75 | | /// </summary> |
| | 76 | | /// <param name="endpoint">Topic endpoint. For example, "https://TOPIC-NAME.REGION-NAME-1.eventgrid.azure.net/ap |
| | 77 | | /// <param name="credential">Credential used to connect to Azure.</param> |
| | 78 | | /// <param name="options">Configuring options.</param> |
| 4 | 79 | | public EventGridPublisherClient(Uri endpoint, EventGridSharedAccessSignatureCredential credential, EventGridPubl |
| | 80 | | { |
| 4 | 81 | | Argument.AssertNotNull(credential, nameof(credential)); |
| 4 | 82 | | options ??= new EventGridPublisherClientOptions(); |
| 4 | 83 | | _dataSerializer = options.DataSerializer ?? new JsonObjectSerializer(); |
| 4 | 84 | | _endpoint = endpoint; |
| 4 | 85 | | HttpPipeline pipeline = HttpPipelineBuilder.Build(options, new EventGridSharedAccessSignatureCredentialPolic |
| 4 | 86 | | _serviceRestClient = new ServiceRestClient(new ClientDiagnostics(options), pipeline, options.Version.GetVers |
| 4 | 87 | | _clientDiagnostics = new ClientDiagnostics(options); |
| 4 | 88 | | } |
| | 89 | |
|
| | 90 | | /// <summary> Publishes a batch of EventGridEvents to an Azure Event Grid topic. </summary> |
| | 91 | | /// <param name="events"> An array of events to be published to Event Grid. </param> |
| | 92 | | /// <param name="cancellationToken"> The cancellation token to use. </param> |
| | 93 | | public virtual async Task<Response> SendEventsAsync(IEnumerable<EventGridEvent> events, CancellationToken cancel |
| 8 | 94 | | => await PublishEventsInternal(events, true /*async*/, cancellationToken).ConfigureAwait(false); |
| | 95 | |
|
| | 96 | | /// <summary> Publishes a batch of EventGridEvents to an Azure Event Grid topic. </summary> |
| | 97 | | /// <param name="events"> An array of events to be published to Event Grid. </param> |
| | 98 | | /// <param name="cancellationToken"> The cancellation token to use. </param> |
| | 99 | | public virtual Response SendEvents(IEnumerable<EventGridEvent> events, CancellationToken cancellationToken = def |
| 8 | 100 | | => PublishEventsInternal(events, false /*async*/, cancellationToken).EnsureCompleted(); |
| | 101 | |
|
| | 102 | | /// <summary> Publishes a batch of EventGridEvents to an Azure Event Grid topic. </summary> |
| | 103 | | /// <param name="events"> An array of events to be published to Event Grid. </param> |
| | 104 | | /// <param name="async">Whether to invoke the operation asynchronously.</param> |
| | 105 | | /// <param name="cancellationToken"> The cancellation token to use. </param> |
| | 106 | | private async Task<Response> PublishEventsInternal(IEnumerable<EventGridEvent> events, bool async, CancellationT |
| | 107 | | { |
| 16 | 108 | | using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(EventGridPublisherClient)}.{nameof(Se |
| 16 | 109 | | scope.Start(); |
| | 110 | |
|
| | 111 | | try |
| | 112 | | { |
| | 113 | | // List of events cannot be null |
| 16 | 114 | | Argument.AssertNotNull(events, nameof(events)); |
| | 115 | |
|
| 16 | 116 | | List<EventGridEventInternal> eventsWithSerializedPayloads = new List<EventGridEventInternal>(); |
| 352 | 117 | | foreach (EventGridEvent egEvent in events) |
| | 118 | | { |
| | 119 | | // Individual events cannot be null |
| 160 | 120 | | Argument.AssertNotNull(egEvent, nameof(egEvent)); |
| | 121 | |
|
| 160 | 122 | | MemoryStream stream = new MemoryStream(); |
| 160 | 123 | | _dataSerializer.Serialize(stream, egEvent.Data, egEvent.Data.GetType(), cancellationToken); |
| 160 | 124 | | stream.Position = 0; |
| 160 | 125 | | JsonDocument data = JsonDocument.Parse(stream); |
| | 126 | |
|
| 160 | 127 | | EventGridEventInternal newEGEvent = new EventGridEventInternal( |
| 160 | 128 | | egEvent.Id, |
| 160 | 129 | | egEvent.Subject, |
| 160 | 130 | | data.RootElement, |
| 160 | 131 | | egEvent.EventType, |
| 160 | 132 | | egEvent.EventTime, |
| 160 | 133 | | egEvent.DataVersion) |
| 160 | 134 | | { |
| 160 | 135 | | Topic = egEvent.Topic |
| 160 | 136 | | }; |
| | 137 | |
|
| 160 | 138 | | eventsWithSerializedPayloads.Add(newEGEvent); |
| | 139 | | } |
| 16 | 140 | | if (async) |
| | 141 | | { |
| | 142 | | // Publish asynchronously if called via an async path |
| 8 | 143 | | return await _serviceRestClient.PublishEventsAsync( |
| 8 | 144 | | _hostName, |
| 8 | 145 | | eventsWithSerializedPayloads, |
| 8 | 146 | | cancellationToken).ConfigureAwait(false); |
| | 147 | | } |
| | 148 | | else |
| | 149 | | { |
| 8 | 150 | | return _serviceRestClient.PublishEvents( |
| 8 | 151 | | _hostName, |
| 8 | 152 | | eventsWithSerializedPayloads, |
| 8 | 153 | | cancellationToken); |
| | 154 | | } |
| | 155 | | } |
| 0 | 156 | | catch (Exception e) |
| | 157 | | { |
| 0 | 158 | | scope.Failed(e); |
| 0 | 159 | | throw; |
| | 160 | | } |
| 16 | 161 | | } |
| | 162 | |
|
| | 163 | | /// <summary> Publishes a batch of CloudEvents to an Azure Event Grid topic. </summary> |
| | 164 | | /// <param name="events"> An array of events to be published to Event Grid. </param> |
| | 165 | | /// <param name="cancellationToken"> The cancellation token to use. </param> |
| | 166 | | public virtual async Task<Response> SendEventsAsync(IEnumerable<CloudEvent> events, CancellationToken cancellati |
| 10 | 167 | | => await PublishCloudEventsInternal(events, true /*async*/, cancellationToken).ConfigureAwait(false); |
| | 168 | |
|
| | 169 | | /// <summary> Publishes a batch of CloudEvents to an Azure Event Grid topic. </summary> |
| | 170 | | /// <param name="events"> An array of events to be published to Event Grid. </param> |
| | 171 | | /// <param name="cancellationToken"> The cancellation token to use. </param> |
| | 172 | | public virtual Response SendEvents(IEnumerable<CloudEvent> events, CancellationToken cancellationToken = default |
| 10 | 173 | | => PublishCloudEventsInternal(events, false /*async*/, cancellationToken).EnsureCompleted(); |
| | 174 | |
|
| | 175 | | /// <summary> Publishes a batch of CloudEvents to an Azure Event Grid topic. </summary> |
| | 176 | | /// <param name="events"> An array of events to be published to Event Grid. </param> |
| | 177 | | /// <param name="async">Whether to invoke the operation asynchronously.</param> |
| | 178 | | /// <param name="cancellationToken"> The cancellation token to use. </param> |
| | 179 | | private async Task<Response> PublishCloudEventsInternal(IEnumerable<CloudEvent> events, bool async, Cancellation |
| | 180 | | { |
| 20 | 181 | | using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(EventGridPublisherClient)}.{nameof(Se |
| 20 | 182 | | scope.Start(); |
| | 183 | |
|
| | 184 | | try |
| | 185 | | { |
| | 186 | | // List of events cannot be null |
| 20 | 187 | | Argument.AssertNotNull(events, nameof(events)); |
| | 188 | |
|
| 20 | 189 | | List<CloudEventInternal> eventsWithSerializedPayloads = new List<CloudEventInternal>(); |
| 480 | 190 | | foreach (CloudEvent cloudEvent in events) |
| | 191 | | { |
| | 192 | | // Individual events cannot be null |
| 220 | 193 | | Argument.AssertNotNull(cloudEvent, nameof(cloudEvent)); |
| | 194 | |
|
| 220 | 195 | | CloudEventInternal newCloudEvent = new CloudEventInternal( |
| 220 | 196 | | cloudEvent.Id, |
| 220 | 197 | | cloudEvent.Source, |
| 220 | 198 | | cloudEvent.Type, |
| 220 | 199 | | "1.0") |
| 220 | 200 | | { |
| 220 | 201 | | Time = cloudEvent.Time, |
| 220 | 202 | | Datacontenttype = cloudEvent.DataContentType, |
| 220 | 203 | | Dataschema = cloudEvent.DataSchema, |
| 220 | 204 | | Subject = cloudEvent.Subject |
| 220 | 205 | | }; |
| | 206 | |
|
| 600 | 207 | | foreach (KeyValuePair<string, object> kvp in cloudEvent.ExtensionAttributes) |
| | 208 | | { |
| 80 | 209 | | newCloudEvent.Add(kvp.Key, new CustomModelSerializer(kvp.Value, _dataSerializer, cancellationTok |
| | 210 | | } |
| | 211 | |
|
| | 212 | | // The 'Data' property is optional for CloudEvents |
| 220 | 213 | | if (cloudEvent.Data != null) |
| | 214 | | { |
| 180 | 215 | | if (cloudEvent.Data is IEnumerable<byte> enumerable) |
| | 216 | | { |
| 40 | 217 | | newCloudEvent.DataBase64 = Convert.ToBase64String(enumerable.ToArray()); |
| | 218 | | } |
| 140 | 219 | | else if (cloudEvent.Data is ReadOnlyMemory<byte> memory) |
| | 220 | | { |
| 20 | 221 | | newCloudEvent.DataBase64 = Convert.ToBase64String(memory.ToArray()); |
| | 222 | | } |
| | 223 | | else |
| | 224 | | { |
| 120 | 225 | | MemoryStream stream = new MemoryStream(); |
| 120 | 226 | | _dataSerializer.Serialize(stream, cloudEvent.Data, cloudEvent.Data.GetType(), cancellationTo |
| 120 | 227 | | stream.Position = 0; |
| 120 | 228 | | JsonDocument data = JsonDocument.Parse(stream); |
| 120 | 229 | | newCloudEvent.Data = data.RootElement; |
| | 230 | | } |
| | 231 | | } |
| 220 | 232 | | eventsWithSerializedPayloads.Add(newCloudEvent); |
| | 233 | | } |
| 20 | 234 | | if (async) |
| | 235 | | { |
| | 236 | | // Publish asynchronously if called via an async path |
| 10 | 237 | | return await _serviceRestClient.PublishCloudEventEventsAsync( |
| 10 | 238 | | _hostName, |
| 10 | 239 | | eventsWithSerializedPayloads, |
| 10 | 240 | | cancellationToken).ConfigureAwait(false); |
| | 241 | | } |
| | 242 | | else |
| | 243 | | { |
| 10 | 244 | | return _serviceRestClient.PublishCloudEventEvents( |
| 10 | 245 | | _hostName, |
| 10 | 246 | | eventsWithSerializedPayloads, |
| 10 | 247 | | cancellationToken); |
| | 248 | | } |
| | 249 | | } |
| 0 | 250 | | catch (Exception e) |
| | 251 | | { |
| 0 | 252 | | scope.Failed(e); |
| 0 | 253 | | throw; |
| | 254 | | } |
| 20 | 255 | | } |
| | 256 | |
|
| | 257 | | /// <summary> Publishes a batch of custom events to an Azure Event Grid topic. </summary> |
| | 258 | | /// <param name="events"> An array of events to be published to Event Grid. </param> |
| | 259 | | /// <param name="cancellationToken"> The cancellation token to use. </param> |
| | 260 | | public virtual async Task<Response> SendEventsAsync(IEnumerable<object> events, CancellationToken cancellationTo |
| 4 | 261 | | => await PublishCustomEventsInternal(events, true /*async*/, cancellationToken).ConfigureAwait(false); |
| | 262 | |
|
| | 263 | | /// <summary> Publishes a batch of custom events to an Azure Event Grid topic. </summary> |
| | 264 | | /// <param name="events"> An array of events to be published to Event Grid. </param> |
| | 265 | | /// <param name="cancellationToken"> The cancellation token to use. </param> |
| | 266 | | public virtual Response SendEvents(IEnumerable<object> events, CancellationToken cancellationToken = default) |
| 4 | 267 | | => PublishCustomEventsInternal(events, false /*async*/, cancellationToken).EnsureCompleted(); |
| | 268 | |
|
| | 269 | | private async Task<Response> PublishCustomEventsInternal(IEnumerable<object> events, bool async, CancellationTok |
| | 270 | | { |
| 8 | 271 | | using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(EventGridPublisherClient)}.{nameof(Se |
| 8 | 272 | | scope.Start(); |
| | 273 | |
|
| | 274 | | try |
| | 275 | | { |
| 8 | 276 | | List<CustomModelSerializer> serializedEvents = new List<CustomModelSerializer>(); |
| 176 | 277 | | foreach (object customEvent in events) |
| | 278 | | { |
| 80 | 279 | | serializedEvents.Add( |
| 80 | 280 | | new CustomModelSerializer( |
| 80 | 281 | | customEvent, |
| 80 | 282 | | _dataSerializer, |
| 80 | 283 | | cancellationToken)); |
| | 284 | | } |
| 8 | 285 | | if (async) |
| | 286 | | { |
| 4 | 287 | | return await _serviceRestClient.PublishCustomEventEventsAsync( |
| 4 | 288 | | _hostName, |
| 4 | 289 | | serializedEvents, |
| 4 | 290 | | cancellationToken).ConfigureAwait(false); |
| | 291 | | } |
| | 292 | | else |
| | 293 | | { |
| 4 | 294 | | return _serviceRestClient.PublishCustomEventEvents( |
| 4 | 295 | | _hostName, |
| 4 | 296 | | serializedEvents, |
| 4 | 297 | | cancellationToken); |
| | 298 | | } |
| | 299 | | } |
| 0 | 300 | | catch (Exception e) |
| | 301 | | { |
| 0 | 302 | | scope.Failed(e); |
| 0 | 303 | | throw; |
| | 304 | | } |
| 8 | 305 | | } |
| | 306 | |
|
| | 307 | | /// <summary> |
| | 308 | | /// Creates a SAS token for use with Event Grid service. |
| | 309 | | /// </summary> |
| | 310 | | /// <param name="endpoint">The path for the event grid topic to which you're sending events. For example, "https |
| | 311 | | /// <param name="expirationUtc">Time at which the SAS token becomes invalid for authentication.</param> |
| | 312 | | /// <param name="key">Key credential used to generate the token.</param> |
| | 313 | | /// <param name="apiVersion">Service version to use when handling requests made with the SAS token.</param> |
| | 314 | | /// <returns>Returns the generated SAS token string.</returns> |
| | 315 | | public static string BuildSharedAccessSignature(Uri endpoint, DateTimeOffset expirationUtc, AzureKeyCredential k |
| | 316 | | { |
| | 317 | | const char Resource = 'r'; |
| | 318 | | const char Expiration = 'e'; |
| | 319 | | const char Signature = 's'; |
| | 320 | |
|
| 4 | 321 | | var uriBuilder = new RequestUriBuilder(); |
| 4 | 322 | | uriBuilder.Reset(endpoint); |
| 4 | 323 | | uriBuilder.AppendQuery("api-version", apiVersion.GetVersionString(), true); |
| 4 | 324 | | string encodedResource = HttpUtility.UrlEncode(uriBuilder.ToString()); |
| 4 | 325 | | var culture = CultureInfo.CreateSpecificCulture("en-US"); |
| 4 | 326 | | var encodedExpirationUtc = HttpUtility.UrlEncode(expirationUtc.ToString(culture)); |
| | 327 | |
|
| 4 | 328 | | string unsignedSas = $"{Resource}={encodedResource}&{Expiration}={encodedExpirationUtc}"; |
| 4 | 329 | | using (var hmac = new HMACSHA256(Convert.FromBase64String(key.Key))) |
| | 330 | | { |
| 4 | 331 | | string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(unsignedSas))); |
| 4 | 332 | | string encodedSignature = HttpUtility.UrlEncode(signature); |
| 4 | 333 | | string signedSas = $"{unsignedSas}&{Signature}={encodedSignature}"; |
| | 334 | |
|
| 4 | 335 | | return signedSas; |
| | 336 | | } |
| 4 | 337 | | } |
| | 338 | | } |
| | 339 | | } |