Skip to content

Commit

Permalink
setup storing metrics in memory and serve by url
Browse files Browse the repository at this point in the history
  • Loading branch information
CAPCHIK committed May 5, 2024
1 parent a850970 commit c349a55
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 19 deletions.
14 changes: 0 additions & 14 deletions Excursion360.Desktop/ImageMetricsMiddleware.cs

This file was deleted.

17 changes: 13 additions & 4 deletions Excursion360.Desktop/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
Console.ForegroundColor = ConsoleColor.White;

var builder = WebApplication.CreateBuilder(args);

builder.Logging.SetMinimumLevel(LogLevel.Information);
builder.Services.AddSingleton<IStateImagesMetricsStore, InMemoryIStateImagesMetricsStore>();

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Expand All @@ -24,9 +24,15 @@
}

var app = builder.Build();
app.UseMiddleware<ImageMetricsMiddleware>();
var targetDirectory = GetExcursionDirectory(builder.Configuration.ExcursionDirectoryPath());

app.MapGet("/eapi/preload.json", (IStateImagesMetricsStore stateImagesMetrics) => {
return new
{
images = stateImagesMetrics.MostPopularUrls(),
};
});

var fso = new FileServerOptions
{
FileProvider = new CompositeFileProvider(
Expand All @@ -36,8 +42,11 @@
fso.DefaultFilesOptions.DefaultFileNames.Add("Resources/NotFound.html");
fso.StaticFileOptions.OnPrepareResponse = (context) =>
{
context.Context.Response.Headers.CacheControl = "no-cache, no-store";
context.Context.Response.Headers.Expires = "-1";
if (context.File.Name.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && context.File.PhysicalPath is not null)
{
var stateImagesMetricsStore = context.Context.RequestServices.GetRequiredService<IStateImagesMetricsStore>();
stateImagesMetricsStore.IncrementImageHit(context.Context.Request.Path);
}
};
app.UseFileServer(fso);

Expand Down
47 changes: 47 additions & 0 deletions Excursion360.Desktop/Services/IStateImagesMetricsStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.RegularExpressions;

namespace Excursion360.Desktop.Services;

public interface IStateImagesMetricsStore
{
void IncrementImageHit(string path);
string[] MostPopularUrls();
}

public partial class InMemoryIStateImagesMetricsStore : IStateImagesMetricsStore
{
/// <summary>
/// Количества получений картинок по адресу. ключ = адрес картинки. Значение - количество получений.
/// </summary>
private readonly ConcurrentDictionary<string, int>
hitCounts = new();
private Regex stateAndImageRegex = GetStateAndImageRegex();
public void IncrementImageHit(string path)
{
var match = stateAndImageRegex.Match(path);
if (!match.Success)
{
return;
}
hitCounts.AddOrUpdate(path, 1, (_, old) => old + 1);
Console.WriteLine(JsonSerializer.Serialize(hitCounts, new JsonSerializerOptions
{
WriteIndented = true,
}));
}
public string[] MostPopularUrls()
{
return hitCounts
.OrderByDescending(kvp => kvp.Value)
.ThenBy(kvp => kvp.Key)
.Select(kvp => kvp.Key)
.Take(10)
.ToArray();
}

[GeneratedRegex(@"state_.+[/\\].+\.jpg$")]
private static partial Regex GetStateAndImageRegex();

}
7 changes: 6 additions & 1 deletion ReleaseNotes.md
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
# Возможность выбирать используемый браузер из установленных на ПК
- `v4.0`
- Обновлен .NET/Nuke до 8, убраны все предупреждения
- Обновлена структура проекта до последней версии ASP.NET Core
- Базовая папка для выбора экскурсий может выбираться через `--excursionsPath путь_к_папке`
- Добавлена обработка `/eapi/preload.json`, по которому будут отдаваться адреса изображений, которые чаще всего просматриваются
- `v3.0` Возможность выбирать используемый браузер из установленных на ПК

0 comments on commit c349a55

Please sign in to comment.