Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Endorsement Count for Plugins #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions XLWebServices/Controllers/PluginController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Text.Json;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Prometheus;
using XLWebServices.Data;
Expand All @@ -26,6 +27,7 @@ public class PluginController : ControllerBase
private static bool UseFileProxy = true;

private static readonly Counter DownloadsOverTime = Metrics.CreateCounter("xl_plugindl", "XIVLauncher Plugin Downloads", "Name", "Testing");
private static readonly Counter EndorsementsOverTime = Metrics.CreateCounter("xl_pluginendorse", "XIVLauncher Plugin Endorsements", "Name");

private const string RedisCumulativeKey = "XLPluginDlCumulative";

Expand Down Expand Up @@ -81,6 +83,24 @@ public async Task<IActionResult> Download(string internalName, [FromQuery(Name =
return new RedirectResult($"{this.configuration["HostedUrl"]}/File/Get/{cachedFile.Id}");
}
}

[HttpPost("{internalName}")]
[EnableRateLimiting("limitip")]
public async Task<IActionResult> Endorse(string internalName) {
if (this.redis.HasFailed && this.pluginData.Get()?.PluginMaster == null)
return StatusCode(500, "Precondition failed");

var masterList = this.pluginData.Get()!.PluginMaster;

var manifest = masterList!.FirstOrDefault(x => x.InternalName == internalName);
if (manifest == null)
return BadRequest("Invalid plugin");

EndorsementsOverTime.WithLabels(internalName.ToLower()).Inc();
var endCount = await this.redis.Get()!.IncrementEndCount(internalName);

return Content(endCount.ToString());
}

[HttpGet]
public async Task<IActionResult> DownloadCounts()
Expand Down
12 changes: 12 additions & 0 deletions XLWebServices/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Net;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using Prometheus;
Expand Down Expand Up @@ -51,6 +53,13 @@
});
});

builder.Services.AddRateLimiter(o => {
o.AddPolicy("limitip", httpContext =>
RateLimitPartition.GetFixedWindowLimiter(httpContext.Connection.RemoteIpAddress ?? IPAddress.None,
_ => new FixedWindowRateLimiterOptions { Window = TimeSpan.FromMinutes(1), PermitLimit = 10 }));
o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});

builder.WebHost.UseSentry(sentryBuilder =>
{
sentryBuilder.SendDefaultPii = false;
Expand Down Expand Up @@ -91,6 +100,9 @@
endpoints.MapMetrics();
});

// UseRateLimiter must be used after the routes are registered
app.UseRateLimiter();

// Initialize services
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Starting XLWebServices {Version}", Util.GetGitHash());
Expand Down
21 changes: 12 additions & 9 deletions XLWebServices/Services/PluginData/PluginDataService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,11 @@ public async Task ClearCache()

if (!_redis.HasFailed)
{
var dlCount = await _redis.RunFallibleAsync(s => s.GetCount(manifest.InternalName));
if (dlCount.HasValue)
var result = await _redis.RunFallibleAsync(async s => (await s.GetCount(manifest.InternalName), await s.GetEndCount(manifest.InternalName)));
if (result is var (dlCount, endCount))
{
manifest.DownloadCount = dlCount.Value;
manifest.DownloadCount = dlCount;
manifest.EndorsementCount = endCount;
}
}

Expand Down Expand Up @@ -143,10 +144,11 @@ public async Task ClearCache()

if (!_redis.HasFailed)
{
var dlCount = await _redis.RunFallibleAsync(s => s.GetCount(manifest.InternalName));
if (dlCount.HasValue)
var result = await _redis.RunFallibleAsync(async s => (await s.GetCount(manifest.InternalName), await s.GetEndCount(manifest.InternalName)));
if (result is var (dlCount, endCount))
{
manifest.DownloadCount = dlCount.Value;
manifest.DownloadCount = dlCount;
manifest.EndorsementCount = endCount;
}
}

Expand Down Expand Up @@ -229,10 +231,11 @@ async Task ProcessPluginsInChannel(Dip17State.Channel channel, string channelNam

if (!_redis.HasFailed)
{
var dlCount = await _redis.RunFallibleAsync(s => s.GetCount(manifest.InternalName));
if (dlCount.HasValue)
var result = await _redis.RunFallibleAsync(async s => (await s.GetCount(manifest.InternalName), await s.GetEndCount(manifest.InternalName)));
if (result is var (dlCount, endCount))
{
manifest.DownloadCount = dlCount.Value;
manifest.DownloadCount = dlCount;
manifest.EndorsementCount = endCount;
}
}

Expand Down
7 changes: 7 additions & 0 deletions XLWebServices/Services/PluginData/PluginManifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public PluginManifest(PluginManifest toCopy)
this.ApplicableVersion = toCopy.ApplicableVersion;
this.DalamudApiLevel = toCopy.DalamudApiLevel;
this.DownloadCount = toCopy.DownloadCount;
this.EndorsementCount = toCopy.EndorsementCount;
this.LastUpdate = toCopy.LastUpdate;
this.DownloadLinkInstall = toCopy.DownloadLinkInstall;
this.DownloadLinkUpdate = toCopy.DownloadLinkUpdate;
Expand Down Expand Up @@ -148,6 +149,12 @@ public PluginManifest(PluginManifest toCopy)
[JsonPropertyName("DownloadCount")]
public long DownloadCount { get; set; }

/// <summary>
/// Gets the number of endorsements this plugin has.
/// </summary>
[JsonPropertyName("EndorsementCount")]
public long EndorsementCount { get; set; }

/// <summary>
/// Gets the last time this plugin was updated.
/// </summary>
Expand Down
19 changes: 19 additions & 0 deletions XLWebServices/Services/RedisService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public class RedisService
public IDatabase Database;

private const string RedisCountPrefix = "PC1-";
private const string RedisEndCountPrefix = "PEC1-";
private const string RedisPrPrefix = "PPR1-";

public RedisService(ILogger<RedisService> logger, IConfiguration configuration)
Expand Down Expand Up @@ -53,4 +54,22 @@ public async Task<long> GetCount(string internalName)
value.TryParse(out long result);
return result;
}

public async Task<long> IncrementEndCount(string internalName)
{
return await this.Database.StringIncrementAsync(RedisEndCountPrefix + internalName);
}

public async Task<long> GetEndCount(string internalName)
{
var value = await this.Database.StringGetAsync(RedisEndCountPrefix + internalName);

if (value.IsNullOrEmpty)
{
return 0;
}

value.TryParse(out long result);
return result;
}
}
Loading