Skip to content

Commit

Permalink
Cleanup namespaces
Browse files Browse the repository at this point in the history
  • Loading branch information
aritchie committed Jan 24, 2025
1 parent b85d86e commit d153ce2
Show file tree
Hide file tree
Showing 15 changed files with 122 additions and 86 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using Microsoft.Extensions.Caching.Memory;
using Shiny.Mediator.Caching;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator;

Expand Down
1 change: 0 additions & 1 deletion src/Shiny.Mediator.Maui/MauiExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ public static MauiAppBuilder AddShinyMediator(
public static ShinyConfigurator UseMaui(this ShinyConfigurator cfg, bool includeStandardMiddleware = true)
{
cfg.AddEventCollector<MauiEventCollector>();
cfg.Services.TryAddSingleton<ISerializerService, SerializerService>();
cfg.Services.TryAddSingleton<IStorageService, StorageService>();
cfg.Services.TryAddSingleton<IInternetService, InternetService>();
cfg.Services.TryAddSingleton<IAlertDialogService, AlertDialogService>();
Expand Down
1 change: 1 addition & 0 deletions src/Shiny.Mediator/Caching/CacheExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Shiny.Mediator.Caching;
using Shiny.Mediator.Caching.Infrastructure;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator.Caching.Infrastructure;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator.Caching.Infrastructure;


Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Shiny.Mediator.Caching;
namespace Shiny.Mediator.Infrastructure;

public record CacheItemConfig(
TimeSpan? AbsoluteExpiration = null,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Shiny.Mediator.Services;
namespace Shiny.Mediator.Infrastructure;


public interface ICommandScheduler
Expand Down
8 changes: 8 additions & 0 deletions src/Shiny.Mediator/Infrastructure/ISerializerService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Shiny.Mediator.Infrastructure;

public interface ISerializerService
{
string Serialize<T>(T obj);
T Deserialize<T>(string json);
}

Original file line number Diff line number Diff line change
@@ -1,35 +1,17 @@
using System.Timers;
using Microsoft.Extensions.Logging;
using Timer = System.Timers.Timer;

namespace Shiny.Mediator.Services.Impl;
namespace Shiny.Mediator.Infrastructure.Impl;


public class InMemoryCommandScheduler : ICommandScheduler
public class InMemoryCommandScheduler(
IMediator mediator,
ILogger<ICommandScheduler> logger,
TimeProvider timeProvider
) : ICommandScheduler
{
readonly List<CommandContext> commands = new();
readonly TimeProvider timeProvider;
readonly ILogger logger;
readonly IMediator mediator;
readonly Timer timer = new();


public InMemoryCommandScheduler(
IMediator mediator,
ILogger<ICommandScheduler> logger,
TimeProvider timeProvider
)
{
this.mediator = mediator;
this.logger = logger;
ITimer? timer;

// TODO: timeprovider
this.timeProvider = timeProvider;

// var tt = this.timeProvider.CreateTimer(null, null, TimeSpan.Zero, TimeSpan.FromSeconds(30));
this.timer.Interval = TimeSpan.FromSeconds(15).TotalMilliseconds;
this.timer.Elapsed += this.OnTimerElapsed;
}


public Task<bool> Schedule(CommandContext command, CancellationToken cancellationToken)
Expand All @@ -42,27 +24,26 @@ public Task<bool> Schedule(CommandContext command, CancellationToken cancellatio
{
lock (this.commands)
this.commands.Add(command);

if (!this.timer.Enabled)
this.timer.Start();


scheduled = true;
this.timer ??= timeProvider.CreateTimer(_ => this.OnTimerElapsed(), null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
}
return Task.FromResult(scheduled);
}



protected virtual async void OnTimerElapsed(object? sender, ElapsedEventArgs e)
protected virtual async void OnTimerElapsed()
{
this.timer.Stop();
this.timer!.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); // stop

List<CommandContext> items = null!;
lock (this.commands)
items = this.commands.ToList();

foreach (var item in items)
{
var command = (IScheduledCommand)item.Command;
if (command.DueAt < this.timeProvider.GetUtcNow())
if (command.DueAt < timeProvider.GetUtcNow())
{
var headers = item
.Values
Expand All @@ -71,21 +52,21 @@ protected virtual async void OnTimerElapsed(object? sender, ElapsedEventArgs e)

try
{
await this.mediator
await mediator
.Send(command, CancellationToken.None, headers)
.ConfigureAwait(false);
}
catch (Exception ex)
{
// might be picked up by other middleware
// TODO: retries?
this.logger.LogError(ex, "Error running scheduled command");
logger.LogError(ex, "Error running scheduled command");
}
lock (this.commands)
this.commands.Remove(item);
}
}

this.timer.Start();
this.timer!.Change(TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
}
}
28 changes: 28 additions & 0 deletions src/Shiny.Mediator/Infrastructure/Impl/SysTextJsonSerializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Shiny.Mediator.Infrastructure.Impl;


public class SysTextJsonSerializerService : ISerializerService
{
public JsonSerializerOptions JsonOptions { get; set; } = new JsonSerializerOptions
{
Converters =
{
new JsonStringEnumConverter()
}
};

public string Serialize<T>(T obj)
{
var json = JsonSerializer.Serialize(obj, this.JsonOptions);
return json;
}

public T Deserialize<T>(string json)
{
var obj = JsonSerializer.Deserialize<T>(json, this.JsonOptions)!;
return obj;
}
}
39 changes: 0 additions & 39 deletions src/Shiny.Mediator/Infrastructure/SerializerService.cs

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using Microsoft.Extensions.Logging;
using Shiny.Mediator.Services;
using Shiny.Mediator.Infrastructure;

namespace Shiny.Mediator.Middleware;

Expand Down
6 changes: 2 additions & 4 deletions src/Shiny.Mediator/RegistrationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
using Shiny.Mediator.Http;
using Shiny.Mediator.Infrastructure;
using Shiny.Mediator.Middleware;
using Shiny.Mediator.Services;
using Shiny.Mediator.Services.Impl;

namespace Shiny.Mediator;

Expand Down Expand Up @@ -35,7 +33,7 @@ public static IServiceCollection AddShinyMediator(
cfg.AddPerformanceLoggingMiddleware();
cfg.AddTimerRefreshStreamMiddleware();
}
services.TryAddSingleton<ISerializerService, SerializerService>();
services.TryAddSingleton<ISerializerService, Infrastructure.Impl.SysTextJsonSerializerService>();
services.TryAddSingleton<IMediator, Infrastructure.Impl.Mediator>();
return services;
}
Expand Down Expand Up @@ -81,7 +79,7 @@ public static ShinyConfigurator AddCommandScheduling<TScheduler>(this ShinyConfi
/// <param name="configurator"></param>
/// <returns></returns>
public static ShinyConfigurator AddInMemoryCommandScheduling(this ShinyConfigurator configurator)
=> configurator.AddCommandScheduling<InMemoryCommandScheduler>();
=> configurator.AddCommandScheduling<Infrastructure.Impl.InMemoryCommandScheduler>();


/// <summary>
Expand Down
58 changes: 57 additions & 1 deletion tests/Shiny.Mediator.Tests/AttributeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,61 @@ namespace Shiny.Mediator.Tests;

public class AttributeTests
{
[Fact]
public void FoundAttributeOnContract()
{
new MyAttributeRequestHandler()
.GetHandlerHandleMethodAttribute<MyAttributeRequest, MyAttributeAttribute>()
.ShouldNotBeNull();
}

}


[Fact]
public void FoundAttributeOnlyOnOneHandleMethod()
{
var handler = new MyAttributeCommandHandler();
handler
.GetHandlerHandleMethodAttribute<MyAttribute1Command, MyAttributeAttribute>()
.ShouldNotBeNull();

handler
.GetHandlerHandleMethodAttribute<MyAttribute2Command, MyAttributeAttribute>()
.ShouldBeNull();
}
}


public record MyAttributeRequest : IRequest<string>;
public class MyAttributeRequestHandler : IRequestHandler<MyAttributeRequest, string>
{
[MyAttribute]
public Task<string> Handle(MyAttributeRequest request, RequestContext<MyAttributeRequest> context, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}



public record MyAttribute1Command : ICommand;
public record MyAttribute2Command : ICommand;

public class MyAttributeCommandHandler : ICommandHandler<MyAttribute1Command>, ICommandHandler<MyAttribute2Command>
{
[MyAttribute]
public Task Handle(MyAttribute1Command command, CommandContext<MyAttribute1Command> context, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}


public Task Handle(MyAttribute2Command command, CommandContext<MyAttribute2Command> context, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAttributeAttribute : Attribute;
3 changes: 2 additions & 1 deletion tests/Shiny.Mediator.Tests/Http/HttpRequestTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Shiny.Mediator.Http;
using Shiny.Mediator.Infrastructure;
using Shiny.Mediator.Infrastructure.Impl;
using Xunit.Abstractions;

namespace Shiny.Mediator.Tests;
Expand All @@ -18,7 +19,7 @@ public void Test(string path, string? query, string expectedUri)
TheValue = path,
QueryValue = query
};
var serializer = new SerializerService();
var serializer = new SysTextJsonSerializerService();
var logger = Logging.CreateLogger<HttpRequestHandler<MyHttpResultRequest, HttpResult>>(output);
var handler = new TestHttpRequestHandler<MyHttpResultRequest, HttpResult>(logger, null, serializer, null!);
var message = handler.GetMessage(request, "https://test.com");
Expand Down

0 comments on commit d153ce2

Please sign in to comment.