| | | 1 | | using System.Diagnostics; |
| | | 2 | | using GistBackend.Exceptions; |
| | | 3 | | using GistBackend.Handlers.AIHandler; |
| | | 4 | | using GistBackend.Handlers.ChromaDbHandler; |
| | | 5 | | using GistBackend.Handlers.MariaDbHandler; |
| | | 6 | | using GistBackend.Handlers.RssFeedHandler; |
| | | 7 | | using GistBackend.Handlers.WebCrawlHandler; |
| | | 8 | | using GistBackend.Types; |
| | | 9 | | using GistBackend.Utils; |
| | | 10 | | using Microsoft.Extensions.Hosting; |
| | | 11 | | using Microsoft.Extensions.Logging; |
| | | 12 | | using Prometheus; |
| | | 13 | | using static GistBackend.Utils.LogEvents; |
| | | 14 | | using static GistBackend.Utils.ServiceUtils; |
| | | 15 | | using PrometheusSummary = Prometheus.Summary; |
| | | 16 | | using Summary = GistBackend.Types.Summary; |
| | | 17 | | |
| | | 18 | | namespace GistBackend.Services; |
| | | 19 | | |
| | 8 | 20 | | public class GistService( |
| | 8 | 21 | | IRssFeedHandler rssFeedHandler, |
| | 8 | 22 | | IWebCrawlHandler webCrawlHandler, |
| | 8 | 23 | | IMariaDbHandler mariaDbHandler, |
| | 8 | 24 | | IAIHandler aiHandler, |
| | 8 | 25 | | IChromaDbHandler chromaDbHandler, |
| | 8 | 26 | | ILogger<GistService>? logger = null |
| | 8 | 27 | | ) : BackgroundService |
| | | 28 | | { |
| | 1 | 29 | | private static readonly Gauge ProcessFeedsGauge = |
| | 1 | 30 | | Metrics.CreateGauge("process_feeds_seconds", "Time spent to process all feeds"); |
| | 1 | 31 | | private static readonly PrometheusSummary ProcessEntrySummary = |
| | 1 | 32 | | Metrics.CreateSummary("process_entry_seconds", "Time spent to process an entry", "feed_title"); |
| | 1 | 33 | | private static readonly PrometheusSummary SummarizeEntrySummary = |
| | 1 | 34 | | Metrics.CreateSummary("summarize_entry_seconds", "Time spent to summarize an entry"); |
| | | 35 | | |
| | 8 | 36 | | private readonly Dictionary<int, RssFeed> _feedsByFeedId = new(); |
| | | 37 | | |
| | | 38 | | protected override async Task ExecuteAsync(CancellationToken ct) |
| | | 39 | | { |
| | 8 | 40 | | while (!ct.IsCancellationRequested) |
| | | 41 | | { |
| | 8 | 42 | | var startTime = DateTime.UtcNow; |
| | 16 | 43 | | using (new SelfReportingStopwatch(elapsed => ProcessFeedsGauge.Set(elapsed))) |
| | | 44 | | { |
| | 8 | 45 | | await ProcessFeedsAsync(ct); |
| | 48 | 46 | | await Task.WhenAll(_feedsByFeedId.Values.Select(feed => ProcessEntriesAsync(feed.Entries!.OrderBy(e => e |
| | 8 | 47 | | } |
| | 8 | 48 | | await DelayUntilNextExecutionAsync(startTime, 5, logger, ct); |
| | | 49 | | } |
| | 0 | 50 | | } |
| | | 51 | | |
| | | 52 | | private async Task ProcessFeedsAsync(CancellationToken ct) |
| | | 53 | | { |
| | 55 | 54 | | foreach (var feed in rssFeedHandler.Definitions) await ProcessFeedAsync(feed, ct); |
| | 8 | 55 | | } |
| | | 56 | | |
| | | 57 | | private async Task ProcessFeedAsync(RssFeed feed, CancellationToken ct) |
| | | 58 | | { |
| | | 59 | | try |
| | | 60 | | { |
| | 13 | 61 | | await rssFeedHandler.ParseFeedAsync(feed, ct); |
| | 13 | 62 | | var feedId = await EnsureCurrentFeedInfoInDbAsync(feed, ct); |
| | 13 | 63 | | feed.ParseEntries(feedId); |
| | 13 | 64 | | _feedsByFeedId[feedId] = feed; |
| | 13 | 65 | | } |
| | 0 | 66 | | catch (ParsingFeedException e) |
| | | 67 | | { |
| | 0 | 68 | | logger?.LogWarning(ParsingFeedFailed, e, "Skipping feed, failed to parse RSS feed from {RssUrl}", |
| | 0 | 69 | | feed.RssUrl); |
| | 0 | 70 | | } |
| | 13 | 71 | | } |
| | | 72 | | |
| | | 73 | | private async Task<int> EnsureCurrentFeedInfoInDbAsync(RssFeed feed, CancellationToken ct) |
| | | 74 | | { |
| | 13 | 75 | | var existingFeedInfo = await mariaDbHandler.GetFeedInfoByRssUrlAsync(feed.RssUrl, ct); |
| | 13 | 76 | | var parsedFeedInfo = feed.ToRssFeedInfo(); |
| | | 77 | | |
| | 13 | 78 | | if (existingFeedInfo is null) |
| | | 79 | | { |
| | 12 | 80 | | var feedId = await mariaDbHandler.InsertFeedInfoAsync(parsedFeedInfo, ct); |
| | 12 | 81 | | return feedId; |
| | | 82 | | } |
| | 1 | 83 | | if (parsedFeedInfo with { Id = existingFeedInfo.Id } != existingFeedInfo) |
| | | 84 | | { |
| | 1 | 85 | | await mariaDbHandler.UpdateFeedInfoAsync(parsedFeedInfo, ct); |
| | | 86 | | } |
| | 1 | 87 | | return existingFeedInfo.Id!.Value; |
| | 13 | 88 | | } |
| | | 89 | | |
| | | 90 | | private async Task ProcessEntriesAsync(IEnumerable<RssEntry> entries, CancellationToken ct) |
| | | 91 | | { |
| | 112 | 92 | | foreach (var entry in entries) await ProcessEntryAsync(entry, ct); |
| | 8 | 93 | | } |
| | | 94 | | |
| | | 95 | | private async Task ProcessEntryAsync(RssEntry entry, CancellationToken ct) |
| | | 96 | | { |
| | 32 | 97 | | var stopwatch = Stopwatch.StartNew(); |
| | 32 | 98 | | using var loggingScope = logger?.BeginScope("Processing entry with reference {Reference}", entry.Reference); |
| | | 99 | | |
| | 32 | 100 | | var existingGist = await mariaDbHandler.GetGistByReferenceAsync(entry.Reference, ct); |
| | 32 | 101 | | var currentVersionAlreadyExists = existingGist is not null && existingGist.Updated == entry.Updated; |
| | 32 | 102 | | if (currentVersionAlreadyExists) return; |
| | | 103 | | |
| | 32 | 104 | | var feed = _feedsByFeedId[entry.FeedId]; |
| | | 105 | | |
| | | 106 | | try |
| | | 107 | | { |
| | 32 | 108 | | var fetchResponse = await webCrawlHandler.FetchAsync(entry.Url.AbsoluteUri, ct); |
| | 32 | 109 | | if (fetchResponse.Status != 200) |
| | | 110 | | { |
| | 0 | 111 | | logger?.LogWarning(FetchingPageContentFailed, |
| | 0 | 112 | | "Skipping entry, fetched page content returned status {Status} for {Url}", fetchResponse.Status, |
| | 0 | 113 | | entry.Url.AbsoluteUri); |
| | 0 | 114 | | return; |
| | | 115 | | } |
| | | 116 | | |
| | 32 | 117 | | if (feed.CheckForPaywall(fetchResponse.Content)) |
| | | 118 | | { |
| | 2 | 119 | | var disabledGist = new DisabledGist(entry); |
| | 3 | 120 | | if (existingGist is not null) await mariaDbHandler.UpdateDisabledGistAsync(disabledGist, ct); |
| | 1 | 121 | | else await mariaDbHandler.InsertDisabledGistAsync(disabledGist, ct); |
| | 2 | 122 | | logger?.LogInformation(PaywallDetected, |
| | 2 | 123 | | "Disabled gist for entry with reference {Reference} due to detected paywall", |
| | 2 | 124 | | entry.Reference); |
| | 2 | 125 | | return; |
| | | 126 | | } |
| | | 127 | | |
| | 30 | 128 | | var entryText = feed.ExtractText(fetchResponse.Content); |
| | 30 | 129 | | var summaryAIResponse = await GenerateSummaryAIResponse(feed.Language, entry.Title, entryText, ct); |
| | 30 | 130 | | var isSponsoredContent = feed.CheckForSponsoredContent(fetchResponse.Content); |
| | | 131 | | |
| | 30 | 132 | | var gist = new Gist(entry, summaryAIResponse, isSponsoredContent); |
| | | 133 | | |
| | 30 | 134 | | await chromaDbHandler.UpsertEntryAsync(entry, summaryAIResponse.SummaryEnglish, ct); |
| | | 135 | | |
| | 30 | 136 | | if (existingGist is null) |
| | | 137 | | { |
| | 25 | 138 | | await InsertDataIntoDatabaseAsync(entry, gist, summaryAIResponse, feed.Language, ct); |
| | | 139 | | } |
| | | 140 | | else |
| | | 141 | | { |
| | 5 | 142 | | await UpdateDataInDatabaseAsync(entry, existingGist.Id!.Value, gist, summaryAIResponse, feed.Language, |
| | 5 | 143 | | ct); |
| | | 144 | | } |
| | 30 | 145 | | } |
| | 0 | 146 | | catch (ExtractingEntryTextException e) |
| | | 147 | | { |
| | 0 | 148 | | logger?.LogWarning(ExtractingPageContentFailed, e, |
| | 0 | 149 | | "Skipping entry, failed to extract text from page content for {Url}", |
| | 0 | 150 | | entry.Url.AbsoluteUri); |
| | 0 | 151 | | } |
| | 0 | 152 | | catch (Exception e) when (e is ExternalServiceException or HttpRequestException) |
| | | 153 | | { |
| | 0 | 154 | | logger?.LogWarning(FetchingPageContentFailed, e, "Skipping entry, failed to fetch page content for {Url}", |
| | 0 | 155 | | entry.Url.AbsoluteUri); |
| | 0 | 156 | | } |
| | | 157 | | finally |
| | | 158 | | { |
| | 32 | 159 | | stopwatch.Stop(); |
| | 32 | 160 | | ProcessEntrySummary.WithLabels(feed.Title!).Observe(stopwatch.Elapsed.Seconds); |
| | | 161 | | } |
| | 32 | 162 | | } |
| | | 163 | | |
| | | 164 | | private async Task<SummaryAIResponse> GenerateSummaryAIResponse(Language feedLanguage, string entryTitle, |
| | | 165 | | string text, CancellationToken ct) |
| | | 166 | | { |
| | 60 | 167 | | using var stopwatch = new SelfReportingStopwatch(elapsed => SummarizeEntrySummary.Observe(elapsed)); |
| | 30 | 168 | | return await aiHandler.GenerateSummaryAIResponseAsync(feedLanguage, entryTitle, text, ct); |
| | 30 | 169 | | } |
| | | 170 | | |
| | | 171 | | private async Task InsertDataIntoDatabaseAsync(RssEntry entry, Gist gist, SummaryAIResponse summaryAIResponse, |
| | | 172 | | Language feedLanguage, CancellationToken ct) |
| | | 173 | | { |
| | 25 | 174 | | await using var handle = await mariaDbHandler.OpenTransactionAsync(ct); |
| | | 175 | | try |
| | | 176 | | { |
| | 25 | 177 | | var gistId = await mariaDbHandler.InsertGistAsync(gist, handle, ct); |
| | | 178 | | |
| | 25 | 179 | | var germanSummary = CreateSummary(gistId, entry, summaryAIResponse, feedLanguage, Language.De); |
| | 25 | 180 | | await mariaDbHandler.InsertSummaryAsync(germanSummary, handle, ct); |
| | | 181 | | |
| | 25 | 182 | | var englishSummary = CreateSummary(gistId, entry, summaryAIResponse, feedLanguage, Language.En); |
| | 25 | 183 | | await mariaDbHandler.InsertSummaryAsync(englishSummary, handle, ct); |
| | | 184 | | |
| | 25 | 185 | | await handle.Transaction.CommitAsync(ct); |
| | 25 | 186 | | logger?.LogInformation(GistInserted, "Gist inserted with ID {Id}", gistId); |
| | 25 | 187 | | } |
| | 0 | 188 | | catch (Exception e) |
| | | 189 | | { |
| | 0 | 190 | | logger?.LogError(InsertingGistFailed, e, "Failed to insert gist with Reference {Reference}", |
| | 0 | 191 | | gist.Reference); |
| | 0 | 192 | | await handle.Transaction.RollbackAsync(ct); |
| | 0 | 193 | | throw; |
| | | 194 | | } |
| | 25 | 195 | | } |
| | | 196 | | |
| | | 197 | | private async Task UpdateDataInDatabaseAsync(RssEntry entry, int gistId, Gist gist, |
| | | 198 | | SummaryAIResponse summaryAIResponse, Language feedLanguage, CancellationToken ct) |
| | | 199 | | { |
| | 5 | 200 | | await using var handle = await mariaDbHandler.OpenTransactionAsync(ct); |
| | | 201 | | try |
| | | 202 | | { |
| | 5 | 203 | | await mariaDbHandler.UpdateGistAsync(gist, handle, ct); |
| | | 204 | | |
| | 5 | 205 | | var germanSummary = CreateSummary(gistId, entry, summaryAIResponse, feedLanguage, Language.De); |
| | 5 | 206 | | await mariaDbHandler.UpdateSummaryAsync(germanSummary, handle, ct); |
| | | 207 | | |
| | 5 | 208 | | var englishSummary = CreateSummary(gistId, entry, summaryAIResponse, feedLanguage, Language.En); |
| | 5 | 209 | | await mariaDbHandler.UpdateSummaryAsync(englishSummary, handle, ct); |
| | | 210 | | |
| | 5 | 211 | | await handle.Transaction.CommitAsync(ct); |
| | 5 | 212 | | logger?.LogInformation(GistUpdated, "Gist updated at ID {Id}", gistId); |
| | 5 | 213 | | } |
| | 0 | 214 | | catch (Exception e) |
| | | 215 | | { |
| | 0 | 216 | | logger?.LogError(UpdatingGistFailed, e, "Failed to update gist with ID {Id}", gistId); |
| | 0 | 217 | | await handle.Transaction.RollbackAsync(ct); |
| | 0 | 218 | | throw; |
| | | 219 | | } |
| | 5 | 220 | | } |
| | | 221 | | |
| | | 222 | | private static Summary CreateSummary(int gistId, RssEntry entry, SummaryAIResponse summaryAIResponse, |
| | | 223 | | Language feedLanguage, Language summaryLanguage) => |
| | 60 | 224 | | new(gistId, summaryLanguage, feedLanguage != summaryLanguage, |
| | 60 | 225 | | feedLanguage == summaryLanguage ? entry.Title : summaryAIResponse.TitleTranslated, |
| | 60 | 226 | | summaryLanguage == Language.En ? summaryAIResponse.SummaryEnglish : summaryAIResponse.SummaryGerman); |
| | | 227 | | } |