Skip to content

Commit

Permalink
Merge pull request #683 from qdraw/feature/202203_package_tel_to_bg_s…
Browse files Browse the repository at this point in the history
…ervice

Add package Telemetry to Background Service
  • Loading branch information
qdraw authored Mar 15, 2022
2 parents 05eaeb9 + efd1af4 commit 0b17381
Show file tree
Hide file tree
Showing 6 changed files with 161 additions and 4 deletions.
1 change: 1 addition & 0 deletions history.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ node starsky-tools/build-tools/app-version-update.js
# version 0.5.0-beta.4 _(Unreleased)_ - 2022-03-09
- [x] (Changed) _Back-end_ Upgrade to .NET 6 - SDK 6.0.201 (Runtime: 6.0.3) (PR #674)
- [x] (Added) _Back-end_ Added package telemetry (Disable using: EnablePackageTelemetry setting) (PR #657)
- [x] (Added) _Back-end_ Add Package Telemetry to Background Service (PR #683)

# version 0.5.0-beta.3 - 2022-03-09
- [x] (Breaking change) _Back-end_ Upgrade to .NET 6 - SDK 6.0.200 (PR #642)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ internal List<KeyValuePair<string, string>> GetSystemData()

var data = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("UTCTime", DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)),
new KeyValuePair<string, string>("AppVersion", _appSettings.AppVersion),
new KeyValuePair<string, string>("NetVersion", RuntimeInformation.FrameworkDescription),
new KeyValuePair<string, string>("OSArchitecture", RuntimeInformation.OSArchitecture.ToString()),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using starsky.foundation.http.Interfaces;
using starsky.foundation.injection;
using starsky.foundation.platform.Models;
using starsky.foundation.webtelemetry.Helpers;

namespace starsky.foundation.webtelemetry.Services
{

[Service(typeof(IHostedService), InjectionLifetime = InjectionLifetime.Singleton)]
public class PackageTelemetryBackgroundService : BackgroundService
{
private readonly IServiceScopeFactory _serviceScopeFactory;

public PackageTelemetryBackgroundService(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}

/// <summary>
/// Running scoped services
/// @see: https://thinkrethink.net/2018/07/12/injecting-a-scoped-service-into-ihostedservice/
/// </summary>
/// <param name="stoppingToken">Cancellation Token, but it ignored</param>
/// <returns>CompletedTask</returns>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var appSettings = scope.ServiceProvider.GetRequiredService<AppSettings>();
var httpClientHelper = scope.ServiceProvider.GetRequiredService<IHttpClientHelper>();
if ( appSettings.ApplicationType == AppSettings.StarskyAppType.WebController )
{
await new PackageTelemetry(httpClientHelper, appSettings).PackageTelemetrySend();
}
}
}
}
}
3 changes: 0 additions & 3 deletions starsky/starsky/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -296,9 +296,6 @@ void PrepareResponse(StaticFileResponseContext ctx)
var onStoppedSync = new FlushApplicationInsights(app);
applicationLifetime?.ApplicationStopping.Register(onStoppedSync.Flush);
}

new PackageTelemetry(app.ApplicationServices
.GetService<IHttpClientHelper>(), _appSettings).PackageTelemetrySend();
}


Expand Down
2 changes: 1 addition & 1 deletion starsky/starskytest/FakeMocks/FakeIHttpProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace starskytest.FakeMocks
{
public class FakeIHttpProvider : IHttpProvider
{
public readonly List<string> UrlCalled = new List<string>();
public List<string> UrlCalled = new List<string>();

private readonly Dictionary<string, HttpContent> _inputDictionary;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using starsky.foundation.http.Interfaces;
using starsky.foundation.http.Services;
using starsky.foundation.platform.Interfaces;
using starsky.foundation.platform.Models;
using starsky.foundation.storage.Interfaces;
using starsky.foundation.webtelemetry.Helpers;
using starsky.foundation.webtelemetry.Services;
using starskytest.FakeMocks;

namespace starskytest.starsky.foundation.platform.Services;

public static class ExtensionMethods
{
public static async Task InvokeAsync(this MethodInfo @this, object obj, params object[] parameters)
{
dynamic awaitable = @this.Invoke(obj, parameters);
await awaitable;
awaitable.GetAwaiter();
}
}

[TestClass]
public class PackageTelemetryBackgroundServiceTest
{
private readonly IServiceScopeFactory _serviceScopeFactory;

public PackageTelemetryBackgroundServiceTest()
{
var services = new ServiceCollection();
services.AddSingleton<AppSettings>();
services.AddSingleton<IHttpClientHelper, HttpClientHelper>();
services.AddSingleton<IHttpProvider, FakeIHttpProvider>();
services.AddSingleton<IWebLogger, FakeIWebLogger>();
services.AddSingleton<ISelectorStorage, FakeSelectorStorage>();

var serviceProvider = services.BuildServiceProvider();
_serviceScopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();

var appSettings = serviceProvider.GetRequiredService<AppSettings>();
appSettings.EnablePackageTelemetry = true;
}


[TestMethod]
[Timeout(3000)]
public async Task ExecuteAsyncTest_WebController()
{
var appSettings = _serviceScopeFactory.CreateScope().ServiceProvider
.GetService<AppSettings>();
appSettings!.ApplicationType = AppSettings.StarskyAppType.WebController;

var service = new PackageTelemetryBackgroundService(_serviceScopeFactory);

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
source.Cancel(); // <- cancel before start

MethodInfo dynMethod = service.GetType().GetMethod("ExecuteAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
if ( dynMethod == null )
throw new Exception("missing ExecuteAsync");
await dynMethod.InvokeAsync(service, new object[]
{
token
});

var httpProvider = _serviceScopeFactory.CreateScope().ServiceProvider
.GetService<IHttpProvider>();

var fakeHttpProvider = httpProvider as FakeIHttpProvider;
Assert.IsTrue(fakeHttpProvider?.UrlCalled.Any(p => p.Contains(PackageTelemetry.PackageTelemetryUrl)));
}

[TestMethod]
[Timeout(2000)]
public void ExecuteAsyncTest_NotWhenDisabled()
{
var appSettings = _serviceScopeFactory.CreateScope().ServiceProvider
.GetService<AppSettings>();
appSettings.ApplicationType = AppSettings.StarskyAppType.Admin;
var httpProvider1 = _serviceScopeFactory.CreateScope().ServiceProvider
.GetService<IHttpProvider>();

var fakeHttpProvider1 = httpProvider1 as FakeIHttpProvider;
fakeHttpProvider1.UrlCalled = new List<string>();

var service = new PackageTelemetryBackgroundService(_serviceScopeFactory);

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
source.Cancel(); // <- cancel before start

MethodInfo dynMethod = service.GetType().GetMethod("ExecuteAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
if ( dynMethod == null )
throw new Exception("missing ExecuteAsync");
dynMethod.Invoke(service, new object[]
{
token
});

var httpProvider = _serviceScopeFactory.CreateScope().ServiceProvider
.GetService<IHttpProvider>();

var fakeHttpProvider = httpProvider as FakeIHttpProvider;
Assert.IsFalse(fakeHttpProvider?.UrlCalled.Contains(PackageTelemetry.PackageTelemetryUrl));
}
}

0 comments on commit 0b17381

Please sign in to comment.