aboutsummaryrefslogtreecommitdiff
path: root/lib/Emails.Transactional.Plugin/src/Mta/ResendMta.cs
blob: 3f20abad0dc74f7977c025f67bd1c66ab521ed7e (plain)
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: Emails.Transactional
* File: ResendMta.cs 
*
* ResendMta.cs is part of Emails.Transactional which is part of the larger 
* VNLib collection of libraries and utilities.
*
* Emails.Transactional is free software: you can redistribute it and/or modify 
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 2 of the License,
* or (at your option) any later version.
*
* Emails.Transactional is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License 
* along with Emails.Transactional. If not, see http://www.gnu.org/licenses/.
*/

using System;
using System.Net;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Text.Json.Serialization;

using RestSharp;

using VNLib.Net.Http;
using VNLib.Utils.Logging;
using VNLib.Utils.Extensions;
using VNLib.Net.Rest.Client.Construction;
using VNLib.Net.Rest.Client;
using VNLib.Plugins;
using VNLib.Plugins.Extensions.Loading;
using VNLib.Plugins.Extensions.Loading.Events;

using ContentType = VNLib.Net.Http.ContentType;

namespace Emails.Transactional.Mta
{
    [ConfigurationName("resend")]
    internal sealed class ResendMta : IMailTransferAgent
    {
        const int ResendMaxPerSecond = 10;

        /*
         * Resend has a rate limit of 10 request per second,
         * this timer resets the request counter every second
         */
        private int _remainingRequests;
       
        Task ResetRateLimitAsync(ILogProvider log, CancellationToken pluginExitToken)
        {
            //Reset the request counter
            _remainingRequests = ResendMaxPerSecond;
            return Task.CompletedTask;
        }

        private readonly ResendSiteAdapter _resendAdapter;
        private readonly TimeSpan _rateLimitDelay;
        private readonly int _rateLimitRetry;

        public ResendMta(PluginBase plugin, IConfigScope config)
        {
            int timeoutMs = config.GetRequiredProperty("timeout_ms", e => e.GetInt32());
            int maxClients = config.GetRequiredProperty("max_clients", e => e.GetInt32());
            string? userAgent = config.GetProperty("user_agent", e => e.GetString());
            _rateLimitDelay = config["rate_limit_delay_ms"].GetTimeSpan(TimeParseType.Milliseconds);
            _rateLimitRetry = config["rate_limit_retry"].GetInt32();

            //Create the resend adapter
            _resendAdapter = new ResendSiteAdapter(timeoutMs, maxClients, userAgent);

            //Retrieve the access token
            IAsyncLazy<string> authToken = plugin.GetSecretAsync("resend_token").ToLazy(p => p.Result.ToString());

            //Define the send endpoint
            //https://resend.com/docs/api-reference/emails/send-email
            _resendAdapter.DefineSingleEndpoint()
                .WithEndpoint<ResendEmail>()
                .WithMethod(Method.Post)
                .WithUrl("/emails")
                .WithHeader("Accept", "application/json")
                .WithHeader("Content-Type", HttpHelpers.GetContentTypeString(ContentType.Json))
                //Add authorization header on requests
                .WithHeader("Authorization", e => $"Bearer {authToken.Value}")
                //Add message body
                .WithModifier(static (re, r) => r.AddJsonBody(re));

            //Schedule timer to reset the rate limit
            plugin.ScheduleInterval(ResetRateLimitAsync, TimeSpan.FromSeconds(1));
        }

        ///<inheritdoc/>
        public async Task<MtaResult> SendEmailAsync(EmailTransaction transaction, IEmailMessageData message, CancellationToken cancellation = default)
        {
            int retryCount = 0;

            while (retryCount < _rateLimitRetry)
            {
                //Increment the request counter
                int newCount = Interlocked.Increment(ref _remainingRequests);

                //if rate limit hasn't been reached, break
                if (newCount >= 0)
                {
                    break;
                }
                
                retryCount++;

                //Wait for the rate limit delay
                await Task.Delay(_rateLimitDelay, cancellation);
            }

            //Create the resend email object
            ResendEmail email = new(transaction)
            {
                Html = message.GetHtml(),
            };

            //Execute the request
            RestResponse<ResendResponse> response = await _resendAdapter.ExecuteAsync<ResendEmail, ResendResponse>(email, cancellation);

            if(response.IsSuccessful)
            {
                //Store the raw response content data
                transaction.Result = response.Content;
                return new MtaResult(true, response.Data?.Id);
            }
            else
            {
                switch (response.StatusCode)
                {
                    case HttpStatusCode.UnprocessableEntity:
                        return new MtaResult(false, response.Data?.StatusText);
                    default:
                        return new MtaResult(false, response.Content);
                }
            }
        }

        private sealed record class ResendEmail(EmailTransaction Transaction)
        {
            [JsonPropertyName("from")]
            public string From => $"{Transaction.FromName} <{Transaction.From}>";

            [JsonPropertyName("subject")]
            public string? Subject => Transaction.Subject;

            [JsonPropertyName("to")]
            public string[]? To => Transaction.ToAddresses?.Select(static t => $"{t.Value} <{t.Key}>").ToArray();

            [JsonPropertyName("bcc")]
            public string[]? Bcc => Transaction.BccAddresses?.Select(static t => $"{t.Value} <{t.Key}>").ToArray();

            [JsonPropertyName("cc")]
            public string[]? Cc => Transaction.CcAddresses?.Select(static t => $"{t.Value} <{t.Key}>").ToArray();

            [JsonPropertyName("reply_to")]
            public string? ReplyTo => Transaction.ReplyTo == null ? null : $"{Transaction.ReplyToName} <{Transaction.ReplyTo}>";

            [JsonPropertyName("html")]
            public string Html { get; init; } = "";
        }

        private sealed class ResendResponse
        {
            [JsonPropertyName("id")]
            public string Id { get; set; } = null!;

            [JsonPropertyName("name")]
            public string? Name { get; set; }

            [JsonPropertyName("statusCode")]
            public int StatusCpde { get; set; }

            [JsonPropertyName("message")]
            public string? StatusText { get; set; }
        }

        private sealed class ResendSiteAdapter : RestSiteAdapterBase
        {
            //Fixed resend api url
            private const string BaseUrl = "https://api.resend.com";

            ///<inheritdoc/>
            protected override RestClientPool Pool { get; }

            public ResendSiteAdapter(int maxTimeoutMs, int maxClients, string? userAgent)
            {
                RestClientOptions options = new(BaseUrl)
                {
                    AutomaticDecompression = DecompressionMethods.All,
                    Encoding = Encoding.UTF8,
                    FollowRedirects = false,
                    MaxTimeout = maxTimeoutMs,
                    UserAgent = userAgent,
                };

                //Create client pool
                Pool = new RestClientPool(maxClients, options);
            }

            ///<inheritdoc/>
            public override void OnResponse(RestResponse response)
            { }

            ///<inheritdoc/>
            public override Task WaitAsync(CancellationToken cancellation = default)
            {
                //TODO implement rate limit wait
                return Task.CompletedTask;
            }
        }
    }
}