|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using Microsoft.Extensions.Configuration; |
| 5 | +using Microsoft.Graph.DeveloperProxy.Abstractions; |
| 6 | +using Titanium.Web.Proxy.Http; |
| 7 | + |
| 8 | +namespace Microsoft.Graph.DeveloperProxy.Plugins.Guidance; |
| 9 | + |
| 10 | +public class CachingGuidancePluginConfiguration |
| 11 | +{ |
| 12 | + public int CacheThresholdSeconds { get; set; } = 5; |
| 13 | +} |
| 14 | + |
| 15 | +public class CachingGuidancePlugin : BaseProxyPlugin |
| 16 | +{ |
| 17 | + public override string Name => nameof(CachingGuidancePlugin); |
| 18 | + private readonly CachingGuidancePluginConfiguration _configuration = new(); |
| 19 | + private IDictionary<string, DateTime> _interceptedRequests = new Dictionary<string, DateTime>(); |
| 20 | + |
| 21 | + public override void Register(IPluginEvents pluginEvents, |
| 22 | + IProxyContext context, |
| 23 | + ISet<UrlToWatch> urlsToWatch, |
| 24 | + IConfigurationSection? configSection = null) |
| 25 | + { |
| 26 | + base.Register(pluginEvents, context, urlsToWatch, configSection); |
| 27 | + configSection?.Bind(_configuration); |
| 28 | + |
| 29 | + pluginEvents.BeforeRequest += BeforeRequest; |
| 30 | + } |
| 31 | + |
| 32 | + private async Task BeforeRequest(object? sender, ProxyRequestArgs e) |
| 33 | + { |
| 34 | + if (_urlsToWatch is null || !e.HasRequestUrlMatch(_urlsToWatch)) |
| 35 | + { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + Request request = e.Session.HttpClient.Request; |
| 40 | + var url = request.RequestUri.AbsoluteUri; |
| 41 | + var now = DateTime.Now; |
| 42 | + |
| 43 | + if (!_interceptedRequests.ContainsKey(url)) |
| 44 | + { |
| 45 | + _interceptedRequests.Add(url, now); |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + var lastIntercepted = _interceptedRequests[url]; |
| 50 | + var secondsSinceLastIntercepted = (now - lastIntercepted).TotalSeconds; |
| 51 | + if (secondsSinceLastIntercepted <= _configuration.CacheThresholdSeconds) |
| 52 | + { |
| 53 | + _logger?.LogRequest(BuildCacheWarningMessage(request, _configuration.CacheThresholdSeconds, lastIntercepted), MessageType.Warning, new LoggingContext(e.Session)); |
| 54 | + } |
| 55 | + |
| 56 | + _interceptedRequests[url] = now; |
| 57 | + } |
| 58 | + |
| 59 | + private static string[] BuildCacheWarningMessage(Request r, int _warningSeconds, DateTime lastIntercepted) => new[] { |
| 60 | + $"Another request to {r.RequestUri.PathAndQuery} intercepted within {_warningSeconds} seconds.", |
| 61 | + $"Last intercepted at {lastIntercepted}.", |
| 62 | + "Consider using cache to avoid calling the API too often." |
| 63 | + }; |
| 64 | +} |
0 commit comments