-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEventBridgeEventPublisher.cs
More file actions
194 lines (167 loc) · 7.22 KB
/
Copy pathEventBridgeEventPublisher.cs
File metadata and controls
194 lines (167 loc) · 7.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2025-Present Datadog, Inc.
*/
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2025 Datadog, Inc.
using System.Diagnostics;
using System.Text.Json.Nodes;
using Amazon.EventBridge;
using Amazon.EventBridge.Model;
using CloudNative.CloudEvents;
using CloudNative.CloudEvents.SystemTextJson;
using Datadog.Trace;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Saunter.Attributes;
using Stickerlandia.PrintService.Core;
using Stickerlandia.PrintService.Core.DeletePrinter;
using Stickerlandia.PrintService.Core.Observability;
using Stickerlandia.PrintService.Core.PrintJobs;
using Stickerlandia.PrintService.Core.RegisterPrinter;
using Log = Stickerlandia.PrintService.Core.Observability.Log;
namespace Stickerlandia.PrintService.AWS;
[AsyncApi]
public class EventBridgeEventPublisher(
ILogger<EventBridgeEventPublisher> logger,
IAmazonEventBridge client,
IOptions<AwsConfiguration> awsConfiguration) : IPrintServiceEventPublisher
{
[Channel("printJobs.queued.v1")]
[PublishOperation(typeof(PrintJobQueuedEvent))]
public async Task PublishPrintJobQueuedEvent(PrintJobQueuedEvent printJobQueuedEvent)
{
ArgumentNullException.ThrowIfNull(printJobQueuedEvent, nameof(printJobQueuedEvent));
var cloudEvent = new CloudEvent(CloudEventsSpecVersion.V1_0)
{
Id = Guid.NewGuid().ToString(),
Source = new Uri("https://stickerlandia.com"),
Type = printJobQueuedEvent.EventName,
Time = DateTime.UtcNow,
Data = printJobQueuedEvent
};
await PublishCloudEventAsync(cloudEvent);
}
[Channel("printJobs.failed.v1")]
[PublishOperation(typeof(PrintJobFailedEvent))]
public async Task PublishPrintJobFailedEvent(PrintJobFailedEvent printJobFailedEvent)
{
ArgumentNullException.ThrowIfNull(printJobFailedEvent, nameof(printJobFailedEvent));
var cloudEvent = new CloudEvent(CloudEventsSpecVersion.V1_0)
{
Id = Guid.NewGuid().ToString(),
Source = new Uri("https://stickerlandia.com"),
Type = printJobFailedEvent.EventName,
Time = DateTime.UtcNow,
Data = printJobFailedEvent
};
await PublishCloudEventAsync(cloudEvent);
}
[Channel("printers.registered.v1")]
[PublishOperation(typeof(PrinterRegisteredEvent))]
public async Task PublishPrinterRegisteredEvent(PrinterRegisteredEvent printerRegisteredEvent)
{
ArgumentNullException.ThrowIfNull(printerRegisteredEvent, nameof(printerRegisteredEvent));
var cloudEvent = new CloudEvent(CloudEventsSpecVersion.V1_0)
{
Id = Guid.NewGuid().ToString(),
Source = new Uri("https://stickerlandia.com"),
Type = printerRegisteredEvent.EventName,
Time = DateTime.UtcNow,
Data = printerRegisteredEvent
};
await PublishCloudEventAsync(cloudEvent);
}
[Channel("printJobs.completed.v1")]
[PublishOperation(typeof(PrintJobCompletedEvent))]
public async Task PublishPrintJobCompletedEvent(PrintJobCompletedEvent printJobCompletedEvent)
{
ArgumentNullException.ThrowIfNull(printJobCompletedEvent, nameof(printJobCompletedEvent));
var cloudEvent = new CloudEvent(CloudEventsSpecVersion.V1_0)
{
Id = Guid.NewGuid().ToString(),
Source = new Uri("https://stickerlandia.com"),
Type = printJobCompletedEvent.EventName,
Time = DateTime.UtcNow,
Data = printJobCompletedEvent
};
await PublishCloudEventAsync(cloudEvent);
}
[Channel("printers.deleted.v1")]
[PublishOperation(typeof(PrinterDeletedEvent))]
public async Task PublishPrinterDeletedEvent(PrinterDeletedEvent printerDeletedEvent)
{
ArgumentNullException.ThrowIfNull(printerDeletedEvent, nameof(printerDeletedEvent));
var cloudEvent = new CloudEvent(CloudEventsSpecVersion.V1_0)
{
Id = Guid.NewGuid().ToString(),
Source = new Uri("https://stickerlandia.com"),
Type = printerDeletedEvent.EventName,
Time = DateTime.UtcNow,
Data = printerDeletedEvent
};
await PublishCloudEventAsync(cloudEvent);
}
internal async Task PublishCloudEventAsync(CloudEvent cloudEvent)
{
using var activity = PrintJobInstrumentation.ActivitySource.StartActivity(
$"publish {cloudEvent.Type}", ActivityKind.Producer);
try
{
var currentActivity = Activity.Current;
if (currentActivity != null)
{
cloudEvent.SetAttributeFromString("traceparent",
$"00-{currentActivity.TraceId}-{currentActivity.SpanId}-01");
}
var formatter = new JsonEventFormatter();
var data = formatter.EncodeStructuredModeMessage(cloudEvent, out _);
var jsonString = System.Text.Encoding.UTF8.GetString(data.Span);
if (Tracer.Instance.ActiveScope is not null)
{
new SpanContextInjector().InjectIncludingDsm(jsonString, SetHeader, Tracer.Instance.ActiveScope.Span.Context, "eventbridge", cloudEvent.Type!);
}
else
{
Log.GenericWarning(logger, "Failure publishing event", null);
activity?.SetTag("dsm.injection_skipped", "no active scope");
}
var response = await client.PutEventsAsync(new PutEventsRequest()
{
Entries = new List<PutEventsRequestEntry>(1)
{
new()
{
EventBusName = awsConfiguration.Value.EventBusName,
Source = $"{Environment.GetEnvironmentVariable("ENV") ?? "dev"}.print",
DetailType = cloudEvent.Type,
Detail = jsonString,
}
}
});
if (response.FailedEntryCount is > 0)
{
var failedEntries = response.Entries
.Where(e => !string.IsNullOrEmpty(e.ErrorCode))
.ToList();
throw new EventBridgePartialFailureException(response.FailedEntryCount.Value, failedEntries);
}
activity?.SetStatus(ActivityStatusCode.Ok);
}
catch (Exception ex)
{
Log.MessagePublishingError(logger, "Failure publishing event", ex);
activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
activity?.SetTag("error.type", ex.GetType().Name);
throw;
}
}
private static void SetHeader(string eventJson, string key, string value)
{
var jsonNode = JsonNode.Parse(eventJson);
if (jsonNode?["_datadog"] == null) jsonNode!["_datadog"] = new JsonObject();
jsonNode!["_datadog"]![key] = value;
}
}