├── .dockerignore ├── .gitignore ├── LICENSE ├── README.md ├── Thisisnabi.TextStorage.sln ├── src └── TextStorage │ ├── AppSettings.cs │ ├── Balancer.cs │ ├── Dockerfile │ ├── Features │ ├── PasteText │ │ └── PasteText.cs │ └── Reading │ │ └── ReadingEndpoint.cs │ ├── Models │ └── Paste.cs │ ├── Persistence │ ├── Migrations │ │ ├── 20240829115412_InitDbContext.Designer.cs │ │ ├── 20240829115412_InitDbContext.cs │ │ ├── 20240829121109_AddPasswordToPaste.Designer.cs │ │ ├── 20240829121109_AddPasswordToPaste.cs │ │ └── TextStorageDbContextModelSnapshot.cs │ ├── TextStorageDbContext.cs │ └── TextStorageDbContextReadOnly.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── TenantPrincipal.cs │ ├── TextStorage.csproj │ ├── TextStorage.http │ ├── Workers │ └── CleanUpPastesBackgroundService.cs │ ├── appsettings.Development.json │ └── appsettings.json └── tests ├── TextStorage.UnitTests ├── BalancerTests.cs └── TextStorage.UnitTests.csproj └── loadtests └── paste.js /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md 26 | !**/.gitignore 27 | !.git/HEAD 28 | !.git/config 29 | !.git/packed-refs 30 | !.git/refs/heads/** -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Nabi Karampour 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TextStorage 2 | Text storage as a service in ASP.NET Core 3 | 4 | 5 | ![image](https://github.com/user-attachments/assets/7023870d-d20e-4cfc-9c57-4023fcda0f4a) 6 | -------------------------------------------------------------------------------- /Thisisnabi.TextStorage.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextStorage", "src\TextStorage\TextStorage.csproj", "{7AFAEDDF-52B2-4F38-AE27-3424535A9EC9}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{07B4EB72-DE23-437D-BF02-8AB63D23A29F}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{8A392F6B-855F-48E0-B313-F651074A86E9}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "loadtests", "loadtests", "{BC880F49-1CBD-4A3C-882E-ADF229F8DC19}" 13 | ProjectSection(SolutionItems) = preProject 14 | tests\loadtests\paste.js = tests\loadtests\paste.js 15 | EndProjectSection 16 | EndProject 17 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TextStorage.UnitTests", "tests\TextStorage.UnitTests\TextStorage.UnitTests.csproj", "{A973E45F-2FE5-4E71-B54D-DC28DCD08062}" 18 | EndProject 19 | Global 20 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 21 | Debug|Any CPU = Debug|Any CPU 22 | Release|Any CPU = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 25 | {7AFAEDDF-52B2-4F38-AE27-3424535A9EC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {7AFAEDDF-52B2-4F38-AE27-3424535A9EC9}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {7AFAEDDF-52B2-4F38-AE27-3424535A9EC9}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {7AFAEDDF-52B2-4F38-AE27-3424535A9EC9}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {A973E45F-2FE5-4E71-B54D-DC28DCD08062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {A973E45F-2FE5-4E71-B54D-DC28DCD08062}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {A973E45F-2FE5-4E71-B54D-DC28DCD08062}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {A973E45F-2FE5-4E71-B54D-DC28DCD08062}.Release|Any CPU.Build.0 = Release|Any CPU 33 | EndGlobalSection 34 | GlobalSection(SolutionProperties) = preSolution 35 | HideSolutionNode = FALSE 36 | EndGlobalSection 37 | GlobalSection(NestedProjects) = preSolution 38 | {7AFAEDDF-52B2-4F38-AE27-3424535A9EC9} = {07B4EB72-DE23-437D-BF02-8AB63D23A29F} 39 | {BC880F49-1CBD-4A3C-882E-ADF229F8DC19} = {8A392F6B-855F-48E0-B313-F651074A86E9} 40 | {A973E45F-2FE5-4E71-B54D-DC28DCD08062} = {8A392F6B-855F-48E0-B313-F651074A86E9} 41 | EndGlobalSection 42 | GlobalSection(ExtensibilityGlobals) = postSolution 43 | SolutionGuid = {1EB8803D-4D89-4C4B-B5AC-9581344A08E9} 44 | EndGlobalSection 45 | EndGlobal 46 | -------------------------------------------------------------------------------- /src/TextStorage/AppSettings.cs: -------------------------------------------------------------------------------- 1 | namespace TextStorage; 2 | 3 | public class AppSettings 4 | { 5 | public required ConnectionStrings ConnectionStrings { get; set; } 6 | } 7 | 8 | 9 | public class ConnectionStrings 10 | { 11 | public required string Master1 { get; set; } 12 | public required string Master2 { get; set; } 13 | public required string Master3 { get; set; } 14 | } -------------------------------------------------------------------------------- /src/TextStorage/Balancer.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace TextStorage; 3 | 4 | public class LoadBalancer 5 | { 6 | private readonly string[] _connections; 7 | private int currentIndex = -1; 8 | private const int charOffset = 97; 9 | 10 | public LoadBalancer(string[] connections) 11 | { 12 | _connections = connections; 13 | } 14 | 15 | public int TenantId => currentIndex; 16 | public string TenantConnectionString => _connections[currentIndex]; 17 | 18 | public Tenant MoveNext() 19 | { 20 | currentIndex++; 21 | if (currentIndex > 2) 22 | currentIndex = 0; 23 | 24 | var currentChar = (char)(charOffset + currentIndex); 25 | return new Tenant(currentIndex, _connections[currentIndex], currentChar); 26 | } 27 | 28 | internal string GetConnectionStringByPredicateId(char v) 29 | { 30 | var wordIndex = (int)v; 31 | var index = wordIndex - charOffset; 32 | return _connections[index]; 33 | } 34 | 35 | public IEnumerable GetConnections() => _connections; 36 | } 37 | 38 | public record Tenant(int Id,string ConnectionString, char Predicate); -------------------------------------------------------------------------------- /src/TextStorage/Dockerfile: -------------------------------------------------------------------------------- 1 | # See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | # This stage is used when running from VS in fast mode (Default for Debug configuration) 4 | FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base 5 | USER app 6 | WORKDIR /app 7 | EXPOSE 8080 8 | EXPOSE 8081 9 | 10 | 11 | # This stage is used to build the service project 12 | FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build 13 | ARG BUILD_CONFIGURATION=Release 14 | WORKDIR /src 15 | COPY ["src/TextStorage/TextStorage.csproj", "src/TextStorage/"] 16 | RUN dotnet restore "./src/TextStorage/TextStorage.csproj" 17 | COPY . . 18 | WORKDIR "/src/src/TextStorage" 19 | RUN dotnet build "./TextStorage.csproj" -c $BUILD_CONFIGURATION -o /app/build 20 | 21 | # This stage is used to publish the service project to be copied to the final stage 22 | FROM build AS publish 23 | ARG BUILD_CONFIGURATION=Release 24 | RUN dotnet publish "./TextStorage.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false 25 | 26 | # This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration) 27 | FROM base AS final 28 | WORKDIR /app 29 | COPY --from=publish /app/publish . 30 | ENTRYPOINT ["dotnet", "TextStorage.dll"] -------------------------------------------------------------------------------- /src/TextStorage/Features/PasteText/PasteText.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http.HttpResults; 2 | using System.ComponentModel.DataAnnotations; 3 | using TextStorage.Models; 4 | using TextStorage.Persistence; 5 | 6 | namespace TextStorage.Features.PasteText; 7 | 8 | public static class PasteTextEndpoint 9 | { 10 | 11 | public static void MapPasteTextEndpoint(this IEndpointRouteBuilder endpoint) 12 | { 13 | endpoint.MapPost("/texts", async (CreatePasteRequest request, 14 | TenantPrincipal tenantPrincipal, 15 | TextStorageDbContext dbContext) => 16 | { 17 | var randomCode = tenantPrincipal.Predicate +( Random.Shared.Next(77777, int.MaxValue)).ToString(); 18 | 19 | var paste = Paste.Create(request.Content, randomCode, request.Password, request.ExpireOn); 20 | 21 | dbContext.Pastes.Add(paste); 22 | await dbContext.SaveChangesAsync(); 23 | 24 | return Results.Ok($"http://localhost:5063/{randomCode}"); 25 | }); 26 | } 27 | } 28 | 29 | 30 | public record CreatePasteRequest 31 | { 32 | [Required] 33 | public required string Content { get; set; } 34 | 35 | public string? Password { get; set; } 36 | 37 | public DateTime? ExpireOn { get; set; } 38 | } -------------------------------------------------------------------------------- /src/TextStorage/Features/Reading/ReadingEndpoint.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http.HttpResults; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.Extensions.Caching.Distributed; 5 | using Microsoft.Extensions.Caching.Memory; 6 | using Microsoft.IdentityModel.Tokens; 7 | using System.ComponentModel.DataAnnotations; 8 | using TextStorage.Models; 9 | using TextStorage.Persistence; 10 | 11 | namespace TextStorage.Features.Reading; 12 | 13 | public static class ReadingEndpoint 14 | { 15 | 16 | public static void MapReadingEndpoint(this IEndpointRouteBuilder endpoint) 17 | { 18 | endpoint.MapGet("/{code}", async ( 19 | [FromRoute(Name = "code")] string code, 20 | IDistributedCache _cache, 21 | IServiceProvider serviceProvider) => 22 | { 23 | var content = await _cache.GetStringAsync(code); 24 | 25 | if (!string.IsNullOrEmpty(content)) 26 | return Results.Ok(content); 27 | 28 | var dbContext = serviceProvider.GetRequiredService(); 29 | var item = (await dbContext.Pastes.FirstOrDefaultAsync(d => d.ShortenCode == code)); 30 | if(item is null) 31 | return Results.NotFound(); 32 | 33 | _cache.SetStringAsync(code, item.Content); 34 | 35 | return Results.Ok(item.Content); 36 | }).CacheOutput(); 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /src/TextStorage/Models/Paste.cs: -------------------------------------------------------------------------------- 1 | namespace TextStorage.Models; 2 | 3 | public class Paste 4 | { 5 | public long Id { get; set; } 6 | 7 | public required string Content { get; set; } 8 | 9 | public DateTime ExpireOn { get; set; } 10 | 11 | public required string ShortenCode { get; set; } 12 | 13 | public string? Password { get; set; } 14 | 15 | public static Paste Create(string content, string code, string password, DateTime? expireOn = default) 16 | { 17 | expireOn ??= DateTime.Now.AddDays(7); 18 | return new Paste 19 | { 20 | Content = content, 21 | ShortenCode = code, 22 | ExpireOn = expireOn.Value, 23 | Password = password 24 | }; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/TextStorage/Persistence/Migrations/20240829115412_InitDbContext.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using TextStorage.Persistence; 9 | 10 | #nullable disable 11 | 12 | namespace TextStorage.Persistence.Migrations 13 | { 14 | [DbContext(typeof(TextStorageDbContext))] 15 | [Migration("20240829115412_InitDbContext")] 16 | partial class InitDbContext 17 | { 18 | /// 19 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 20 | { 21 | #pragma warning disable 612, 618 22 | modelBuilder 23 | .HasAnnotation("ProductVersion", "8.0.8") 24 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 25 | 26 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 27 | 28 | modelBuilder.Entity("TextStorage.Models.Paste", b => 29 | { 30 | b.Property("Id") 31 | .ValueGeneratedOnAdd() 32 | .HasColumnType("bigint"); 33 | 34 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 35 | 36 | b.Property("Content") 37 | .IsRequired() 38 | .HasMaxLength(4000) 39 | .IsUnicode(true) 40 | .HasColumnType("nvarchar(4000)"); 41 | 42 | b.Property("ExpireOn") 43 | .HasColumnType("datetime2"); 44 | 45 | b.Property("ShortenCode") 46 | .IsRequired() 47 | .HasColumnType("nvarchar(450)"); 48 | 49 | b.HasKey("Id"); 50 | 51 | b.HasIndex("ShortenCode") 52 | .IsUnique(); 53 | 54 | b.ToTable("Pastes"); 55 | }); 56 | #pragma warning restore 612, 618 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/TextStorage/Persistence/Migrations/20240829115412_InitDbContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace TextStorage.Persistence.Migrations 7 | { 8 | /// 9 | public partial class InitDbContext : Migration 10 | { 11 | /// 12 | protected override void Up(MigrationBuilder migrationBuilder) 13 | { 14 | migrationBuilder.CreateTable( 15 | name: "Pastes", 16 | columns: table => new 17 | { 18 | Id = table.Column(type: "bigint", nullable: false) 19 | .Annotation("SqlServer:Identity", "1, 1"), 20 | Content = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: false), 21 | ExpireOn = table.Column(type: "datetime2", nullable: false), 22 | ShortenCode = table.Column(type: "nvarchar(450)", nullable: false) 23 | }, 24 | constraints: table => 25 | { 26 | table.PrimaryKey("PK_Pastes", x => x.Id); 27 | }); 28 | 29 | migrationBuilder.CreateIndex( 30 | name: "IX_Pastes_ShortenCode", 31 | table: "Pastes", 32 | column: "ShortenCode", 33 | unique: true); 34 | } 35 | 36 | /// 37 | protected override void Down(MigrationBuilder migrationBuilder) 38 | { 39 | migrationBuilder.DropTable( 40 | name: "Pastes"); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/TextStorage/Persistence/Migrations/20240829121109_AddPasswordToPaste.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using TextStorage.Persistence; 9 | 10 | #nullable disable 11 | 12 | namespace TextStorage.Persistence.Migrations 13 | { 14 | [DbContext(typeof(TextStorageDbContext))] 15 | [Migration("20240829121109_AddPasswordToPaste")] 16 | partial class AddPasswordToPaste 17 | { 18 | /// 19 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 20 | { 21 | #pragma warning disable 612, 618 22 | modelBuilder 23 | .HasAnnotation("ProductVersion", "8.0.8") 24 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 25 | 26 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 27 | 28 | modelBuilder.Entity("TextStorage.Models.Paste", b => 29 | { 30 | b.Property("Id") 31 | .ValueGeneratedOnAdd() 32 | .HasColumnType("bigint"); 33 | 34 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 35 | 36 | b.Property("Content") 37 | .IsRequired() 38 | .HasMaxLength(4000) 39 | .IsUnicode(true) 40 | .HasColumnType("nvarchar(4000)"); 41 | 42 | b.Property("ExpireOn") 43 | .HasColumnType("datetime2"); 44 | 45 | b.Property("Password") 46 | .HasColumnType("nvarchar(max)"); 47 | 48 | b.Property("ShortenCode") 49 | .IsRequired() 50 | .HasColumnType("nvarchar(450)"); 51 | 52 | b.HasKey("Id"); 53 | 54 | b.HasIndex("ShortenCode") 55 | .IsUnique(); 56 | 57 | b.ToTable("Pastes"); 58 | }); 59 | #pragma warning restore 612, 618 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/TextStorage/Persistence/Migrations/20240829121109_AddPasswordToPaste.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace TextStorage.Persistence.Migrations 6 | { 7 | /// 8 | public partial class AddPasswordToPaste : Migration 9 | { 10 | /// 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.AddColumn( 14 | name: "Password", 15 | table: "Pastes", 16 | type: "nvarchar(max)", 17 | nullable: true); 18 | } 19 | 20 | /// 21 | protected override void Down(MigrationBuilder migrationBuilder) 22 | { 23 | migrationBuilder.DropColumn( 24 | name: "Password", 25 | table: "Pastes"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/TextStorage/Persistence/Migrations/TextStorageDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using TextStorage.Persistence; 8 | 9 | #nullable disable 10 | 11 | namespace TextStorage.Persistence.Migrations 12 | { 13 | [DbContext(typeof(TextStorageDbContext))] 14 | partial class TextStorageDbContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "8.0.8") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 22 | 23 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 24 | 25 | modelBuilder.Entity("TextStorage.Models.Paste", b => 26 | { 27 | b.Property("Id") 28 | .ValueGeneratedOnAdd() 29 | .HasColumnType("bigint"); 30 | 31 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 32 | 33 | b.Property("Content") 34 | .IsRequired() 35 | .HasMaxLength(4000) 36 | .IsUnicode(true) 37 | .HasColumnType("nvarchar(4000)"); 38 | 39 | b.Property("ExpireOn") 40 | .HasColumnType("datetime2"); 41 | 42 | b.Property("Password") 43 | .HasColumnType("nvarchar(max)"); 44 | 45 | b.Property("ShortenCode") 46 | .IsRequired() 47 | .HasColumnType("nvarchar(450)"); 48 | 49 | b.HasKey("Id"); 50 | 51 | b.HasIndex("ShortenCode") 52 | .IsUnique(); 53 | 54 | b.ToTable("Pastes"); 55 | }); 56 | #pragma warning restore 612, 618 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/TextStorage/Persistence/TextStorageDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System.Reflection.PortableExecutable; 3 | using TextStorage.Models; 4 | 5 | namespace TextStorage.Persistence 6 | { 7 | public class TextStorageDbContext(DbContextOptions dbContextOptions) 8 | : DbContext(dbContextOptions) 9 | { 10 | 11 | 12 | public DbSet Pastes { get; set; } 13 | 14 | protected override void OnModelCreating(ModelBuilder modelBuilder) 15 | { 16 | base.OnModelCreating(modelBuilder); 17 | 18 | modelBuilder.Entity().HasKey(x => x.Id); 19 | modelBuilder.Entity().HasIndex(x => x.ShortenCode) 20 | .IsUnique(); 21 | 22 | modelBuilder.Entity().Property(x => x.Content) 23 | .IsRequired() 24 | .IsUnicode(true) 25 | .HasMaxLength(4000); 26 | 27 | modelBuilder.Entity().Property(x => x.ExpireOn) 28 | .IsRequired(); 29 | } 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/TextStorage/Persistence/TextStorageDbContextReadOnly.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System.Reflection.PortableExecutable; 3 | using TextStorage.Models; 4 | 5 | namespace TextStorage.Persistence 6 | { 7 | public class TextStorageDbContextReadOnly(DbContextOptions dbContextOptions) 8 | : DbContext(dbContextOptions) 9 | { 10 | 11 | 12 | public DbSet Pastes { get; set; } 13 | 14 | protected override void OnModelCreating(ModelBuilder modelBuilder) 15 | { 16 | base.OnModelCreating(modelBuilder); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/TextStorage/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.Extensions.Options; 3 | using TextStorage; 4 | using TextStorage.Features.PasteText; 5 | using TextStorage.Features.Reading; 6 | using TextStorage.Persistence; 7 | using TextStorage.Workers; 8 | 9 | var builder = WebApplication.CreateBuilder(args); 10 | 11 | builder.Services.AddHttpContextAccessor(); 12 | 13 | builder.Services.AddSingleton(sp => { 14 | 15 | var connections = sp.GetRequiredService>().Value.ConnectionStrings; 16 | return new LoadBalancer([connections.Master1, connections.Master2, connections.Master3]); 17 | }); 18 | 19 | builder.Services.AddScoped((sp) => 20 | { 21 | var balancer = sp.GetRequiredService(); 22 | var tenant = balancer.MoveNext(); 23 | return new TenantPrincipal 24 | { 25 | ConnectionString = tenant.ConnectionString, 26 | Id = tenant.Id, 27 | Predicate = tenant.Predicate 28 | }; 29 | }); 30 | 31 | builder.Services.AddDbContext((sp, configure) => 32 | { 33 | var tenant = sp.GetRequiredService(); 34 | configure.UseSqlServer(tenant.ConnectionString); 35 | }); 36 | 37 | 38 | builder.Services.AddStackExchangeRedisCache((configure) => 39 | { 40 | configure.Configuration = "localhost:6379"; 41 | }); 42 | 43 | builder.Services.AddHostedService(); 44 | 45 | builder.Services.AddDbContext((sp, configure) => 46 | { 47 | var httpContext = sp.GetRequiredService(); 48 | var routeCode = httpContext.HttpContext.Request.RouteValues["code"].ToString(); 49 | var balancer = sp.GetRequiredService(); 50 | 51 | var connectionString = balancer.GetConnectionStringByPredicateId(routeCode.First()); 52 | 53 | configure.UseSqlServer(connectionString) 54 | .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); 55 | }); 56 | 57 | builder.Services.AddEndpointsApiExplorer(); 58 | builder.Services.AddSwaggerGen(); 59 | 60 | builder.Services.Configure(builder.Configuration); 61 | 62 | var app = builder.Build(); 63 | 64 | app.UseSwagger(); 65 | app.UseSwaggerUI(); 66 | 67 | app.MapPasteTextEndpoint(); 68 | app.MapReadingEndpoint(); 69 | 70 | app.Run(); -------------------------------------------------------------------------------- /src/TextStorage/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "http": { 4 | "commandName": "Project", 5 | "launchBrowser": true, 6 | "launchUrl": "swagger", 7 | "environmentVariables": { 8 | "ASPNETCORE_ENVIRONMENT": "Development" 9 | }, 10 | "dotnetRunMessages": true, 11 | "applicationUrl": "http://localhost:5063" 12 | }, 13 | "https": { 14 | "commandName": "Project", 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | }, 20 | "dotnetRunMessages": true, 21 | "applicationUrl": "https://localhost:7106;http://localhost:5063" 22 | }, 23 | "IIS Express": { 24 | "commandName": "IISExpress", 25 | "launchBrowser": true, 26 | "launchUrl": "swagger", 27 | "environmentVariables": { 28 | "ASPNETCORE_ENVIRONMENT": "Development" 29 | } 30 | }, 31 | "Container (Dockerfile)": { 32 | "commandName": "Docker", 33 | "launchBrowser": true, 34 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", 35 | "environmentVariables": { 36 | "ASPNETCORE_HTTPS_PORTS": "8081", 37 | "ASPNETCORE_HTTP_PORTS": "8080" 38 | }, 39 | "publishAllPorts": true, 40 | "useSSL": true 41 | } 42 | }, 43 | "$schema": "http://json.schemastore.org/launchsettings.json", 44 | "iisSettings": { 45 | "windowsAuthentication": false, 46 | "anonymousAuthentication": true, 47 | "iisExpress": { 48 | "applicationUrl": "http://localhost:18929", 49 | "sslPort": 44312 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /src/TextStorage/TenantPrincipal.cs: -------------------------------------------------------------------------------- 1 | namespace TextStorage; 2 | 3 | public class TenantPrincipal 4 | { 5 | public int Id { get; set; } 6 | public required string ConnectionString { get; set; } 7 | 8 | public char Predicate { get; set; } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/TextStorage/TextStorage.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | f9d6a52b-b6b4-44a8-8456-ade3c5e84cfb 8 | Linux 9 | ..\.. 10 | 11 | 12 | 13 | 14 | 15 | 16 | all 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/TextStorage/TextStorage.http: -------------------------------------------------------------------------------- 1 | @TextStorage_HostAddress = http://localhost:5063 2 | 3 | GET {{TextStorage_HostAddress}}/weatherforecast/ 4 | Accept: application/json 5 | 6 | ### 7 | -------------------------------------------------------------------------------- /src/TextStorage/Workers/CleanUpPastesBackgroundService.cs: -------------------------------------------------------------------------------- 1 |  2 | using Microsoft.EntityFrameworkCore; 3 | using TextStorage.Persistence; 4 | 5 | namespace TextStorage.Workers 6 | { 7 | public class CleanUpPastesBackgroundService(IServiceScopeFactory serviceScopeFactory) : BackgroundService 8 | { 9 | 10 | private readonly IServiceScopeFactory _serviceScopeFactory =serviceScopeFactory; 11 | 12 | protected override async Task ExecuteAsync(CancellationToken stoppingToken) 13 | { 14 | var serviceProvider = _serviceScopeFactory.CreateScope().ServiceProvider; 15 | var loadBalancer = serviceProvider.GetRequiredService(); 16 | 17 | while (!stoppingToken.IsCancellationRequested) 18 | { 19 | foreach (var conStr in loadBalancer.GetConnections()) 20 | { 21 | var options = new DbContextOptionsBuilder() 22 | .UseSqlServer(conStr) 23 | .Options; 24 | 25 | var dbContext = new TextStorageDbContext(options); 26 | 27 | 28 | await dbContext.Pastes 29 | .Where(x => x.ExpireOn < DateTime.Now) 30 | .ExecuteDeleteAsync(); 31 | 32 | await Task.Delay(5000); 33 | 34 | 35 | } 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/TextStorage/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/TextStorage/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "Master1": "data source=thisisnabi\\mssql;initial catalog=thisisnabi.paste;TrustServerCertificate=True;Trusted_Connection=True;", 4 | "Master2": "data source=thisisnabi\\np1;initial catalog=thisisnabi.paste;TrustServerCertificate=True;Trusted_Connection=True;", 5 | "Master3": "data source=thisisnabi\\np2;initial catalog=thisisnabi.paste;TrustServerCertificate=True;Trusted_Connection=True;" 6 | }, 7 | 8 | "Logging": { 9 | "LogLevel": { 10 | "Default": "Information", 11 | "Microsoft.AspNetCore": "Warning" 12 | } 13 | }, 14 | "AllowedHosts": "*" 15 | } 16 | -------------------------------------------------------------------------------- /tests/TextStorage.UnitTests/BalancerTests.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.EntityFrameworkCore.ChangeTracking; 3 | 4 | namespace TextStorage.UnitTests 5 | { 6 | public class BalancerTests 7 | { 8 | private readonly LoadBalancer _sut; 9 | 10 | public BalancerTests() 11 | { 12 | _sut = new LoadBalancer(["master1", "master2", "master3"]); 13 | } 14 | 15 | [Fact] 16 | public void Balancer() 17 | { 18 | _sut.TenantId.Should().Be(-1); 19 | _sut.MoveNext(); 20 | _sut.TenantId.Should().Be(0); 21 | _sut.MoveNext(); 22 | _sut.TenantId.Should().Be(1); 23 | _sut.MoveNext(); 24 | _sut.TenantId.Should().Be(2); 25 | _sut.MoveNext(); 26 | _sut.TenantId.Should().Be(0); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /tests/TextStorage.UnitTests/TextStorage.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | false 9 | true 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /tests/loadtests/paste.js: -------------------------------------------------------------------------------- 1 | import http from 'k6/http' 2 | import { check, sleep } from 'k6' 3 | import { Counter } from 'k6/metrics' 4 | 5 | const success_requests = new Counter('success_requests'); 6 | 7 | export const options = { 8 | VUs: 10000, 9 | duration: '1s', 10 | } 11 | 12 | export default function () { 13 | let result = http.get("http://localhost:5063/a1727558387"); 14 | 15 | var is_success = check(result, { 'Request is success': (r) => r.status === 200 }); 16 | if (is_success) success_requests.add(1); 17 | 18 | sleep(0.1); 19 | } --------------------------------------------------------------------------------