forked from mtusi2026/mtusi2026lab5
90 lines
6.0 KiB
C#
90 lines
6.0 KiB
C#
using System.Security.Cryptography;
|
|
using Amazon.S3.Model;
|
|
using Messenger.Api.Contracts;
|
|
using Messenger.Api.Data;
|
|
using Messenger.Api.Infrastructure;
|
|
using Npgsql;
|
|
using SkiaSharp;
|
|
namespace Messenger.Api.Services;
|
|
public sealed class AttachmentService(S3Storage storage, NpgsqlDataSource db, IConfiguration config)
|
|
{
|
|
public const long MaxBytes=10*1024*1024;
|
|
private readonly SemaphoreSlim slots=new(1,1);
|
|
public async Task<AttachmentDto> UploadAsync(HttpRequest request, Guid chat, Guid actor, string name)
|
|
{
|
|
using var timeout=CancellationTokenSource.CreateLinkedTokenSource(request.HttpContext.RequestAborted);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(90));
|
|
var ct=timeout.Token;
|
|
if (request.ContentLength>MaxBytes) throw new AttachmentException(413,"payload_too_large","Файл больше 10 MiB");
|
|
await slots.WaitAsync(ct);
|
|
var path=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N"));
|
|
try
|
|
{
|
|
await using var file=new FileStream(path,FileMode.CreateNew,FileAccess.ReadWrite,FileShare.None,
|
|
65536,FileOptions.Asynchronous|FileOptions.DeleteOnClose);
|
|
var buffer=new byte[65536]; long size=0;
|
|
using var digest=IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
|
while(true)
|
|
{
|
|
var count=await request.Body.ReadAsync(buffer,ct); if(count==0) break;
|
|
size+=count;
|
|
if(size>MaxBytes) throw new AttachmentException(413,"payload_too_large","Файл больше 10 MiB");
|
|
digest.AppendData(buffer,0,count); await file.WriteAsync(buffer.AsMemory(0,count),ct);
|
|
}
|
|
if(size==0) throw new AttachmentException(415,"unsupported_media_type","Пустое изображение");
|
|
string mime;
|
|
file.Position=0;
|
|
using (var stream=new SKManagedStream(file,false))
|
|
using (var codec=SKCodec.Create(stream))
|
|
{
|
|
if(codec is null) throw new AttachmentException(415,"unsupported_media_type","Повреждённое изображение");
|
|
var info=codec.Info;
|
|
if((long)info.Width*info.Height>40_000_000)
|
|
throw new AttachmentException(413,"payload_too_large","Слишком много пикселей");
|
|
mime=codec.EncodedFormat switch {SKEncodedImageFormat.Png=>"image/png",SKEncodedImageFormat.Jpeg=>"image/jpeg",_=>""};
|
|
if(mime=="" || request.ContentType?.Split(';')[0].Trim()!=mime)
|
|
throw new AttachmentException(415,"unsupported_media_type","Требуется PNG или JPEG с верным MIME");
|
|
using var bitmap=new SKBitmap(new SKImageInfo(info.Width,info.Height,SKColorType.Rgba8888,SKAlphaType.Premul));
|
|
if(codec.GetPixels(bitmap.Info,bitmap.GetPixels())!=SKCodecResult.Success)
|
|
throw new AttachmentException(415,"unsupported_media_type","Повреждённое изображение");
|
|
}
|
|
var id=Guid.NewGuid(); var job=Guid.NewGuid(); var staging=$"staging/{id:N}"; var key=$"originals/{id:N}/v1"; var now=UtcClock.Now();
|
|
var sha=Convert.ToHexString(digest.GetHashAndReset()).ToLowerInvariant();
|
|
await using var connection=await db.OpenConnectionAsync(ct);
|
|
await using var transaction=await connection.BeginTransactionAsync(ct);
|
|
await using(var gate=new NpgsqlCommand($"SELECT pg_advisory_xact_lock_shared({AppDatabase.AttachmentGate})",connection,transaction))
|
|
await gate.ExecuteNonQueryAsync(ct);
|
|
await using(var gate=new NpgsqlCommand("SELECT pg_advisory_xact_lock(48260105)",connection,transaction))
|
|
await gate.ExecuteNonQueryAsync(ct);
|
|
var capacity=Math.Clamp(config.GetValue("PIPELINE_CAPACITY",128),1,10000);
|
|
await using(var count=new NpgsqlCommand("SELECT count(*) FROM attachment_jobs WHERE state IN ('queued','processing')",connection,transaction))
|
|
if((long)(await count.ExecuteScalarAsync(ct))!>=capacity)
|
|
{
|
|
request.HttpContext.Response.Headers.RetryAfter="3";
|
|
throw new AttachmentException(429,"rate_limited","Очередь заполнена. Попробуйте через несколько секунд");
|
|
}
|
|
file.Position=0;
|
|
await storage.Client.PutObjectAsync(new PutObjectRequest {BucketName=storage.Bucket,Key=staging,
|
|
InputStream=file,ContentType=mime,AutoCloseStream=false,UseChunkEncoding=false},ct);
|
|
await using(var insert=new NpgsqlCommand("""
|
|
INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,status,created_at,updated_at)
|
|
VALUES (@id,@chat,@actor,@name,@mime,@size,@sha,@key,'queued',@now,@now);
|
|
INSERT INTO attachment_jobs(id,attachment_id,staging_key,state) VALUES (@job,@id,@staging,'queued');
|
|
INSERT INTO attachment_outbox(job_id) VALUES (@job);
|
|
INSERT INTO attachment_job_events(job_id,event,attempt) VALUES (@job,'accepted',0)
|
|
""",connection,transaction))
|
|
{
|
|
insert.Parameters.AddWithValue("job",job);insert.Parameters.AddWithValue("staging",staging);
|
|
insert.Parameters.AddWithValue("id",id);insert.Parameters.AddWithValue("chat",chat);
|
|
insert.Parameters.AddWithValue("actor",actor);insert.Parameters.AddWithValue("name",name);
|
|
insert.Parameters.AddWithValue("mime",mime);insert.Parameters.AddWithValue("size",size);
|
|
insert.Parameters.AddWithValue("sha",sha);insert.Parameters.AddWithValue("key",key);insert.Parameters.AddWithValue("now",now);
|
|
await insert.ExecuteNonQueryAsync(ct);
|
|
}
|
|
await transaction.CommitAsync(ct);
|
|
return new(id,chat,actor,name,mime,size,sha,"queued",[],null,now.ToString("O"),now.ToString("O"));
|
|
}
|
|
finally { slots.Release(); File.Delete(path); }
|
|
}
|
|
}
|