feat: enhance PasteService with caching and cache invalidation methods

This commit is contained in:
2026-01-28 09:13:32 -05:00
parent 81f85defb0
commit 5375e1caa6
+129 -29
View File
@@ -1,20 +1,37 @@
using Microsoft.EntityFrameworkCore; using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
using System.Text;
namespace SharpbinV3.Server.Services namespace SharpbinV3.Server.Services
{ {
public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions<PasteSettings> options) public sealed class PasteService(
AppDbContext db,
ICompressionService cs,
IMemoryCache cache,
IOptions<PasteSettings> options
)
{ {
private readonly AppDbContext _db = db; private readonly AppDbContext _db = db;
private readonly ICompressionService _cs = cs; private readonly ICompressionService _cs = cs;
private readonly IMemoryCache _cache = cache;
private readonly PasteSettings _pasteSettings = options.Value; private readonly PasteSettings _pasteSettings = options.Value;
private readonly Lock _invalidationLock = new();
private readonly HashSet<string> _pasteListCacheKeys = [];
public async Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt, bool shouldCompress) public async Task<Paste> Create(
User? author,
string content,
string title,
string syntax,
int visibility,
long expiresAt,
bool shouldCompress
)
{ {
var data = Encoding.UTF8.GetBytes(content); var data = Encoding.UTF8.GetBytes(content);
if (shouldCompress) if (shouldCompress)
@@ -42,6 +59,9 @@ namespace SharpbinV3.Server.Services
_db.Users.Update(author); _db.Users.Update(author);
} }
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
InvalidatePasteListCache();
return paste; return paste;
} }
@@ -49,22 +69,32 @@ namespace SharpbinV3.Server.Services
{ {
_db.Pastes.Remove(paste); _db.Pastes.Remove(paste);
var result = await _db.SaveChangesAsync(); var result = await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return result > 0; return result > 0;
} }
public async Task<Paste> Edit(Paste paste) public async Task<Paste> Edit(Paste paste)
{ {
_db.Pastes.Update(paste); _db.Pastes.Update(paste);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return paste; return paste;
} }
public async Task<bool> Exists(string id) public async Task<bool> Exists(string id)
{ {
return await _db.Pastes.AnyAsync(p => p.ID == id); return await _db.Pastes.AnyAsync(p => p.ID == id);
} }
public async Task<bool> Exists(Guid uuid) public async Task<bool> Exists(Guid uuid)
{ {
return await _db.Pastes.AnyAsync(p => p.UUID == uuid); return await _db.Pastes.AnyAsync(p => p.UUID == uuid);
} }
public async Task<bool> EditText(Paste paste, string text) public async Task<bool> EditText(Paste paste, string text)
{ {
var data = Encoding.UTF8.GetBytes(text); var data = Encoding.UTF8.GetBytes(text);
@@ -78,13 +108,23 @@ namespace SharpbinV3.Server.Services
paste.IsCompressed = data.Length < Encoding.UTF8.GetByteCount(text); paste.IsCompressed = data.Length < Encoding.UTF8.GetByteCount(text);
_db.Pastes.Update(paste); _db.Pastes.Update(paste);
var result = await _db.SaveChangesAsync(); var result = await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return result > 0; return result > 0;
} }
public async Task<(Paste? paste, bool alreadyExists)> RecordView(Paste paste, HttpContext context)
public async Task<(Paste? paste, bool alreadyExists)> RecordView(
Paste paste,
HttpContext context
)
{ {
if (paste == null) return (null, false); if (paste == null)
if (context == null) return (null, false); return (null, false);
if (_pasteSettings.View_HMAC_Secret == null) return (null, false); if (context == null)
return (null, false);
if (_pasteSettings.View_HMAC_Secret == null)
return (null, false);
var viewerIp = context.GetRequestIP(); var viewerIp = context.GetRequestIP();
var viewerUserAgent = context.Request.Headers.UserAgent.ToString(); var viewerUserAgent = context.Request.Headers.UserAgent.ToString();
@@ -92,42 +132,85 @@ namespace SharpbinV3.Server.Services
string viewerHash; string viewerHash;
if (viewerUser != null) if (viewerUser != null)
viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerUser.UUID.ToString()); viewerHash = Utilities.ComputeHmacSha256(
_pasteSettings.View_HMAC_Secret,
viewerUser.UUID.ToString()
);
else else
viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerIp + viewerUserAgent); viewerHash = Utilities.ComputeHmacSha256(
_pasteSettings.View_HMAC_Secret,
viewerIp + viewerUserAgent
);
if (await _db.PasteViews.AnyAsync(pv => pv.PastePID == paste.PID && pv.ViewerHash == viewerHash)) if (
await _db.PasteViews.AnyAsync(pv =>
pv.PastePID == paste.PID && pv.ViewerHash == viewerHash
)
)
return (null, true); return (null, true);
_db.PasteViews.Add(new PasteView _db.PasteViews.Add(
{ new PasteView
PastePID = paste.PID, {
ViewerHash = viewerHash, PastePID = paste.PID,
ViewedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ViewerHash = viewerHash,
}); ViewedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
}
);
paste.Views += 1; paste.Views += 1;
_db.Pastes.Update(paste); _db.Pastes.Update(paste);
var result = await _db.SaveChangesAsync(); var result = await _db.SaveChangesAsync();
if (result > 0)
InvalidatePasteCache(paste.ID);
return (result > 0 ? paste : null, result > 0); return (result > 0 ? paste : null, result > 0);
} }
public async Task<Paste?> Get(string id) public async Task<Paste?> Get(string id)
{ {
var paste = await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id); string key = $"v1:paste:{id}";
var paste = await _cache.GetOrCreateAsync(
key,
async entry =>
{
entry.SetSlidingExpiration(TimeSpan.FromMinutes(10));
return await _db
.Pastes.Include(p => p.User)
.FirstOrDefaultAsync(p => p.ID == id);
}
);
return paste ?? null; return paste ?? null;
} }
public async Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false) public async Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false)
{ {
var query = _db.Pastes.AsQueryable(); string key = $"v1:list:pastes:public={publicOnly}:offset={offset}:count={count}";
if (publicOnly)
query = query.Where(p => p.Visibility == 0);
return await query var pastes = await _cache.GetOrCreateAsync(
.OrderByDescending(p => p.PID) key,
.Skip(offset) async entry =>
.Take(count) {
.Include(p => p.User) entry.SetSlidingExpiration(TimeSpan.FromMinutes(5));
.ToListAsync();
lock (_invalidationLock)
_pasteListCacheKeys.Add(key);
var query = _db.Pastes.AsQueryable();
if (publicOnly)
query = query.Where(p => p.Visibility == 0);
return await query
.OrderByDescending(p => p.PID)
.Skip(offset)
.Take(count)
.Include(p => p.User)
.ToListAsync();
}
);
return pastes ?? [];
} }
public bool ValidateSyntax(string syntax) public bool ValidateSyntax(string syntax)
@@ -147,10 +230,27 @@ namespace SharpbinV3.Server.Services
public bool ValidateExpiresAt(long expiresAt) public bool ValidateExpiresAt(long expiresAt)
{ {
if (expiresAt == 0) return true; if (expiresAt == 0)
return true;
var currentTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var currentTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
return expiresAt > currentTime - 1000; return expiresAt > currentTime - 1000;
} }
private void InvalidatePasteCache(string pasteId)
{
string key = $"v1:paste:{pasteId}";
_cache.Remove(key);
}
private void InvalidatePasteListCache()
{
lock (_invalidationLock)
{
foreach (var listKey in _pasteListCacheKeys)
_cache.Remove(listKey);
_pasteListCacheKeys.Clear();
}
}
} }
} }