using AS1024.GeoFeed.Core.CacheService; using AS1024.GeoFeed.Core.GeoFeedProviders; using AS1024.GeoFeed.Core.Interfaces; using AS1024.GeoFeed.Core.Tools; using AS1024.GeoFeed.Models; using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using System; using System.Text.Json.Serialization; namespace AS1024.GeoFeed.MinimalAPI { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateSlimBuilder(args); builder.Services.AddTransient(); builder.Services.AddHostedService(); builder.Services.AddTransient(); builder.Services.AddMemoryCache(); builder.Services.AddLogging(); builder.Services.AddHttpClient(); builder.Services.ConfigureHttpJsonOptions(options => { options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default); }); var app = builder.Build(); var geoFeed = app.Map("/geofeed.csv", async (IGeoFeedProvider provider, ILogger logger, IGeoFeedPersistentCacheProvider cacheProvider, IMemoryCache memoryCache, IWebHostEnvironment environment) => { try { if (!memoryCache.TryGetValue("Geofeed", out List? feed)) { feed = await provider.GetGeoFeedData(); if (environment.IsProduction()) { MemoryCacheEntryOptions cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(15)); memoryCache.Set("Geofeed", feed, cacheEntryOptions); } } return feed.ToGeoFeedCsv(); } catch (HttpRequestException ex) { logger.LogWarning($"Temporary failure of retrieving GeoData from upstream. {ex}"); string geoFeedData = cacheProvider.GetGeoFeed(); return geoFeedData; } catch (Exception ex) { logger.LogError($"Error: {ex}"); } return ""; }); app.Run(); } } [JsonSerializable(typeof(NetboxData))] [JsonSerializable(typeof(Result))] [JsonSerializable(typeof(CustomFields))] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower)] internal partial class AppJsonSerializerContext : JsonSerializerContext { } }