-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
MessageOutboxService.cs
50 lines (48 loc) · 1.88 KB
/
MessageOutboxService.cs
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
namespace SIL.Machine.AspNetCore.Services;
public class MessageOutboxService(
IRepository<Sequence> messageIndexes,
IRepository<OutboxMessage> messages,
ISharedFileService sharedFileService
) : IMessageOutboxService
{
private readonly IRepository<Sequence> _messageIndex = messageIndexes;
private readonly IRepository<OutboxMessage> _messages = messages;
private readonly ISharedFileService _sharedFileService = sharedFileService;
protected int MaxDocumentSize { get; set; } = 1_000_000;
public async Task<string> EnqueueMessageAsync(
OutboxMessageMethod method,
string groupId,
string requestContent,
CancellationToken cancellationToken
)
{
// get next index
Sequence outboxIndex = (
await _messageIndex.UpdateAsync(
i => i.Context == "MessageOutbox",
i => i.Inc(b => b.CurrentIndex, 1),
upsert: true,
cancellationToken: cancellationToken
)
)!;
string id = Sequence.IndexToObjectIdString(outboxIndex.CurrentIndex);
OutboxMessage outboxMessage = new OutboxMessage
{
Id = id,
Method = method,
GroupId = groupId,
RequestContent = requestContent
};
if (requestContent.Length > MaxDocumentSize)
{
// The file is too large - save it to disk and send a reference.
// MongoDB has a 16MB document size limit - let's keep below that.
await using StreamWriter sourceTrainWriter =
new(await _sharedFileService.OpenWriteAsync($"outbox/{id}.json", cancellationToken));
sourceTrainWriter.Write(requestContent);
outboxMessage.RequestContent = null;
}
await _messages.InsertAsync(outboxMessage, cancellationToken: cancellationToken);
return id;
}
}