Skip to content
This repository has been archived by the owner on Nov 1, 2023. It is now read-only.

Commit

Permalink
Make the EntityConverter a singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
chkeita committed Aug 18, 2022
1 parent e74671b commit 9e4d3ea
Show file tree
Hide file tree
Showing 7 changed files with 21 additions and 17 deletions.
6 changes: 2 additions & 4 deletions src/ApiService/ApiService/Functions/AgentEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ public AgentEvents(ILogTracer log, IEndpointAuthorization auth, IOnefuzzContext
_context = context;
}

private static readonly EntityConverter _entityConverter = new();

[Function("AgentEvents")]
public Async.Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route="agents/events")]
Expand All @@ -31,7 +29,7 @@ private async Async.Task<HttpResponseData> Post(HttpRequestData req) {
}

var envelope = request.OkV;
_log.Info($"node event: machine_id: {envelope.MachineId} event: {_entityConverter.ToJsonString(envelope)}");
_log.Info($"node event: machine_id: {envelope.MachineId} event: {_context.EntityConverter.ToJsonString(envelope)}");

var error = envelope.Event switch {
NodeStateUpdate updateEvent => await OnStateUpdate(envelope.MachineId, updateEvent),
Expand Down Expand Up @@ -145,7 +143,7 @@ private async Async.Task<HttpResponseData> Post(HttpRequestData req) {
Error? error = null;
if (ev.Data is NodeDoneEventData doneData) {
if (doneData.Error is not null) {
var errorText = _entityConverter.ToJsonString(doneData);
var errorText = _context.EntityConverter.ToJsonString(doneData);
error = new Error(ErrorCode.TASK_FAILED, Errors: new string[] { errorText });
_log.Error($"node 'done' with error: machine_id:{machineId}, data:{errorText}");
}
Expand Down
1 change: 1 addition & 0 deletions src/ApiService/ApiService/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ public async static Async.Task Main() {
.AddScoped<IAutoScaleOperations, AutoScaleOperations>()

.AddSingleton<ICreds, Creds>()
.AddSingleton<EntityConverter>()
.AddSingleton<IServiceConfig, ServiceConfiguration>()
.AddSingleton<IStorage, Storage>()
.AddSingleton<ILogSinks, LogSinks>()
Expand Down
6 changes: 5 additions & 1 deletion src/ApiService/ApiService/onefuzzlib/OnefuzzContext.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace Microsoft.OneFuzz.Service;
using Microsoft.OneFuzz.Service.OneFuzzLib.Orm;

namespace Microsoft.OneFuzz.Service;

using Microsoft.Extensions.DependencyInjection;

Expand Down Expand Up @@ -40,6 +42,7 @@ public interface IOnefuzzContext {
INsgOperations NsgOperations { get; }
ISubnet Subnet { get; }
IImageOperations ImageOperations { get; }
EntityConverter EntityConverter { get; }
}

public class OnefuzzContext : IOnefuzzContext {
Expand Down Expand Up @@ -85,4 +88,5 @@ public OnefuzzContext(IServiceProvider serviceProvider) {
public INsgOperations NsgOperations => _serviceProvider.GetRequiredService<INsgOperations>();
public ISubnet Subnet => _serviceProvider.GetRequiredService<ISubnet>();
public IImageOperations ImageOperations => _serviceProvider.GetRequiredService<IImageOperations>();
public EntityConverter EntityConverter => _serviceProvider.GetRequiredService<EntityConverter>();
}
1 change: 0 additions & 1 deletion src/ApiService/ApiService/onefuzzlib/WebhookOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ public async Task<EventPing> Ping(Webhook webhook) {

// Not converting to bytes, as it's not neccessary in C#. Just keeping as string.
public async Async.Task<Tuple<string, string?>> BuildMessage(Guid webhookId, Guid eventId, EventType eventType, BaseEvent webhookEvent, String? secretToken, WebhookMessageFormat? messageFormat) {
var entityConverter = new EntityConverter();
string data = "";
if (messageFormat != null && messageFormat == WebhookMessageFormat.EventGrid) {
var eventGridMessage = new[] { new WebhookMessageEventGrid(Id: eventId, Data: webhookEvent, DataVersion: "1.0.0", Subject: _context.Creds.GetInstanceName(), EventType: eventType, EventTime: DateTimeOffset.UtcNow) };
Expand Down
18 changes: 10 additions & 8 deletions src/ApiService/ApiService/onefuzzlib/orm/EntityConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,22 +88,24 @@ public override string ConvertName(string name) {
}
}
public class EntityConverter {
private readonly JsonSerializerOptions _options;

private readonly ConcurrentDictionary<Type, EntityInfo> _cache;
private static readonly JsonSerializerOptions _options;

static EntityConverter() {
_options = new JsonSerializerOptions() {
PropertyNamingPolicy = new OnefuzzNamingPolicy(),
};
_options.Converters.Add(new CustomEnumConverterFactory());
_options.Converters.Add(new PolymorphicConverterFactory());
}

public EntityConverter() {
_options = GetJsonSerializerOptions();
_cache = new ConcurrentDictionary<Type, EntityInfo>();
}

public static JsonSerializerOptions GetJsonSerializerOptions() {
var options = new JsonSerializerOptions() {
PropertyNamingPolicy = new OnefuzzNamingPolicy(),
};
options.Converters.Add(new CustomEnumConverterFactory());
options.Converters.Add(new PolymorphicConverterFactory());
return options;
return _options;
}

internal static Func<object?[], object> BuildConstructerFrom(ConstructorInfo constructorInfo) {
Expand Down
2 changes: 1 addition & 1 deletion src/ApiService/ApiService/onefuzzlib/orm/Orm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class Orm<T> : IOrm<T> where T : EntityBase {
public Orm(ILogTracer logTracer, IOnefuzzContext context) {
_context = context;
_logTracer = logTracer;
_entityConverter = new EntityConverter();
_entityConverter = _context.EntityConverter;
}

public async IAsyncEnumerable<T> QueryAsync(string? filter = null) {
Expand Down
4 changes: 2 additions & 2 deletions src/ApiService/Tests/RequestsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
namespace Tests;

// This class contains tests for serialization and
// deserialization of examples generated by the
// deserialization of examples generated by the
// onefuzz-agent’s `debug` sub-command. We test each
// example for roundtripping which ensures that no
// data is lost upon deserialization.
Expand All @@ -25,7 +25,7 @@ public class RequestsTests {
private static JsonSerializerOptions serializationOptions() {
// base on the serialization options used at runtime, but
// also indent to match inputs:
var result = EntityConverter.GetJsonSerializerOptions();
var result = new JsonSerializerOptions(EntityConverter.GetJsonSerializerOptions());
result.WriteIndented = true;
return result;
}
Expand Down

0 comments on commit 9e4d3ea

Please sign in to comment.