-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
298 lines (250 loc) · 9.6 KB
/
Program.cs
File metadata and controls
298 lines (250 loc) · 9.6 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
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
using Azure;
using Azure.Data.Tables;
using Azure.Storage.Queues;
using Microsoft.Extensions.Options;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
// Configure logging for Azure App Service
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
builder.Logging.AddApplicationInsights();
// Set minimum log level
builder.Logging.SetMinimumLevel(LogLevel.Information);
builder.Services.Configure<StorageOptions>(builder.Configuration.GetSection("Storage"));
builder.Services.Configure<QueueOptions>(builder.Configuration.GetSection("Queue"));
builder.Services.Configure<AppOptions>(builder.Configuration.GetSection("App"));
// App Insights
var aiConn = builder.Configuration["ApplicationInsights:ConnectionString"];
if (!string.IsNullOrWhiteSpace(aiConn))
{
builder.Services.AddApplicationInsightsTelemetry(o => o.ConnectionString = aiConn);
}
// Services
builder.Services.AddSingleton<IUrlRepository, TableUrlRepository>();
builder.Services.AddSingleton<ICodeGenerator>(_ => new CodeGenerator(7));
builder.Services.AddSingleton<IClickLogger, StreamClickLogger>();
var app = builder.Build();
// Add request logging middleware
app.Use(async (context, next) =>
{
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Request: {Method} {Path}", context.Request.Method, context.Request.Path);
await next();
});
app.MapGet("/health", (ILogger<Program> logger) =>
{
logger.LogInformation("Health check endpoint hit");
return Results.Ok(new { status = "ok", timestamp = DateTimeOffset.UtcNow });
});
app.MapGet("/{code}", async (string code, HttpContext http, IUrlRepository repo, IClickLogger clicker, ILogger<Program> logger) =>
{
logger.LogInformation("Redirect request for code: {Code}", code);
if (string.IsNullOrWhiteSpace(code))
{
logger.LogWarning("Empty code provided");
return Results.NotFound();
}
var entity = await repo.GetAsync(code);
if (entity is null)
{
logger.LogWarning("Code not found: {Code}", code);
return Results.NotFound();
}
logger.LogInformation("Redirecting {Code} to {Url}", code, entity.OriginalUrl);
// Much simpler click logging - no Task.Run needed!
var referer = http.Request.Headers.Referer.ToString();
var ua = http.Request.Headers.UserAgent.ToString();
var ip = http.Connection.RemoteIpAddress?.ToString() ?? "unknown";
var anonIp = SHA256.HashData(Encoding.UTF8.GetBytes(ip));
var anonIpHex = Convert.ToHexString(anonIp);
await clicker.LogAsync(new ClickLog
{
Code = code,
TimestampUtc = DateTimeOffset.UtcNow,
Referrer = referer,
UserAgent = ua,
IpHash = anonIpHex
});
return Results.Redirect(entity.OriginalUrl, permanent: true);
});
app.MapPost("/api/shorten", async (CreateRequest req, HttpContext http, IUrlRepository repo, ICodeGenerator gen, IOptions<AppOptions> appOpts, ILogger<Program> logger) =>
{
logger.LogInformation("Shorten API called with URL: {Url}", req?.Url);
if (req is null || string.IsNullOrWhiteSpace(req.Url))
{
logger.LogWarning("Bad request: URL required");
return Results.BadRequest("url required");
}
if (!Uri.TryCreate(req.Url, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
{
logger.LogWarning("Invalid URL provided: {Url}", req.Url);
return Results.BadRequest("invalid url");
}
string code = string.IsNullOrWhiteSpace(req.CustomCode) ? gen.Generate() : req.CustomCode.Trim();
logger.LogInformation("Generated/using code: {Code}", code);
// enforce allowed chars for custom code
if (!CodeGenerator.IsValid(code))
{
logger.LogWarning("Invalid code: {Code}", code);
return Results.BadRequest("invalid code");
}
try
{
// collision check and insert
var created = await repo.CreateAsync(code, uri.ToString());
if (!created)
{
logger.LogWarning("Code collision: {Code}", code);
return Results.Conflict("code already exists");
}
var baseUrl = appOpts.Value.BaseUrl?.TrimEnd('/') ?? "";
var shortUrl = $"{http.Request.Scheme}://{http.Request.Host}/{code}";
logger.LogInformation("Successfully created short URL: {ShortUrl} -> {OriginalUrl}", shortUrl, req.Url);
return Results.Ok(new { code, shortUrl });
}
catch (Exception ex)
{
logger.LogError(ex, "Error creating short URL for: {Url}", req.Url);
return Results.Problem("Internal server error");
}
});
// Global exception handler
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Unhandled exception occurred");
throw;
}
});
app.Run();
// Models & Options
record CreateRequest(string Url, string? CustomCode);
record UrlEntity(string Code, string OriginalUrl, DateTimeOffset CreatedUtc);
class StorageOptions { public string? ConnectionString { get; set; } public string TableName { get; set; } = "UrlMappings"; }
class AppOptions { public string? BaseUrl { get; set; } = ""; }
// Repo
interface IUrlRepository
{
Task<UrlEntity?> GetAsync(string code);
Task<bool> CreateAsync(string code, string url);
}
/// <summary>
/// TODO: Will add logic to ensure table is not more than 100 entries to keep costs low for this basic project
/// </summary>
class TableUrlRepository : IUrlRepository
{
private readonly TableClient _table;
private readonly ILogger<TableUrlRepository> _logger;
public TableUrlRepository(IOptions<StorageOptions> opts, ILogger<TableUrlRepository> logger)
{
_logger = logger;
var o = opts.Value;
_logger.LogInformation("Initializing table repository with connection string: {HasConnectionString}",
!string.IsNullOrEmpty(o.ConnectionString));
var service = new TableServiceClient(o.ConnectionString);
_table = service.GetTableClient(o.TableName);
_table.CreateIfNotExists();
_logger.LogInformation("Table client initialized for table: {TableName}", o.TableName);
}
public async Task<UrlEntity?> GetAsync(string code)
{
try
{
_logger.LogDebug("Getting entity for code: {Code}", code);
var resp = await _table.GetEntityAsync<TableEntity>("url", code);
var e = resp.Value;
var entity = new UrlEntity(code, e.GetString("OriginalUrl")!, e.GetDateTime("CreatedUtc")!.Value);
_logger.LogDebug("Found entity for code: {Code}", code);
return entity;
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
_logger.LogDebug("Entity not found for code: {Code}", code);
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting entity for code: {Code}", code);
throw;
}
}
public async Task<bool> CreateAsync(string code, string url)
{
var entity = new TableEntity("url", code)
{
{ "OriginalUrl", url },
{ "CreatedUtc", DateTimeOffset.UtcNow }
};
try
{
_logger.LogDebug("Creating entity for code: {Code}", code);
await _table.AddEntityAsync(entity);
_logger.LogInformation("Successfully created entity for code: {Code}", code);
return true;
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
_logger.LogWarning("Entity already exists for code: {Code}", code);
return false;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating entity for code: {Code}", code);
throw;
}
}
}
// Code generator
interface ICodeGenerator { string Generate(); }
class CodeGenerator : ICodeGenerator
{
private static readonly char[] Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
private readonly int _length;
private static readonly HashSet<char> Allowed = Alphabet.ToHashSet();
public CodeGenerator(int length) { _length = length; }
public string Generate()
{
var bytes = RandomNumberGenerator.GetBytes(_length);
var chars = new char[_length];
for (int i = 0; i < _length; i++)
{
chars[i] = Alphabet[bytes[i] % Alphabet.Length];
}
return new string(chars);
}
public static bool IsValid(string code) => !string.IsNullOrWhiteSpace(code) && code.All(c => Allowed.Contains(c)) && code.Length <= 32;
}
// Click log
record ClickLog
{
public string Code { get; init; } = default!;
public DateTimeOffset TimestampUtc { get; init; }
public string? Referrer { get; init; }
public string? UserAgent { get; init; }
public string? IpHash { get; init; }
}
interface IClickLogger { Task LogAsync(ClickLog log); }
class StreamClickLogger : IClickLogger
{
private readonly ILogger<StreamClickLogger> _logger;
public StreamClickLogger(ILogger<StreamClickLogger> logger)
{
_logger = logger;
}
public Task LogAsync(ClickLog log)
{
// Just log it as structured data - App Insights will capture it
_logger.LogInformation("Click tracked for {Code} from {IpHash} via {Referrer} using {UserAgent}",
log.Code, log.IpHash, log.Referrer ?? "direct", log.UserAgent ?? "unknown");
return Task.CompletedTask;
}
}