Skip to content

Commit

Permalink
Merge pull request #220 from EasilyNET/dev
Browse files Browse the repository at this point in the history
🐛 修复一些情况下会导致异常的问题
  • Loading branch information
joesdu authored Aug 23, 2023
2 parents 4dcbf0d + 0273d03 commit a4d4a1d
Show file tree
Hide file tree
Showing 8 changed files with 178 additions and 81 deletions.
54 changes: 52 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,67 @@ EasilyNET Packages

- AES,DES,RC4,TripleDES,RSA,SM2,SM3,SM4
- mongodb based distributed locks
- property injection
- simple qrcode
- eventbus with rabbitmq
- simplifying the use of mongodb drivers
- some common tool extensions
- automatic module injection
- automatic module injection, property injection
- mongodb adds (dynamic|object) serialization support (mongodb.driver 2.19.0+ onwards has removed it)
- mongodb storage support for identityserver 6
- mongodb gridfs usage simplification support
- integration of some common filters, middleware in webapi

#### Recently Updated

- EasilyNET.Mongo.ConsoleDebug 添加新的输出样式
```text
╭───────────────────────────────Command────────────────────────────────╮╭──────────────────Calendar──────────────────╮
│ { ││ 2023 August │
│ "insert" : "mongo.test", ││ ┌─────┬─────┬─────┬─────┬─────┬─────┬────┐ │
│ "ordered" : true, ││ │ Sun │ Mon │ Tue │ Wed │ Thu │ Fri │ S… │ │
│ "$db" : "test1", ││ ├─────┼─────┼─────┼─────┼─────┼─────┼────┤ │
│ "lsid" : { ││ │ │ │ 1 │ 2 │ 3 │ 4 │ 5 │ │
│ "id" : CSUUID("f12dd90d-2f58-4655-9bf2-cbce2d9bd2c4") ││ │ 6 │ 7 │ 8 │ 9 │ 10 │ 11 │ 12 │ │
│ }, ││ │ 13 │ 14 │ 15 │ 16 │ 17 │ 18 │ 19 │ │
│ "documents" : [{ ││ │ 20 │ 21 │ 22 │ 23* │ 24 │ 25 │ 26 │ │
│ "_id" : ObjectId("64e57f266a1a63e69c52b9cb"), ││ │ 27 │ 28 │ 29 │ 30 │ 31 │ │ │ │
│ "dateTime" : ISODate("2023-08-23T03:38:14.121Z"), ││ │ │ │ │ │ │ │ │ │
│ "timeSpan" : "00:00:50", ││ └─────┴─────┴─────┴─────┴─────┴─────┴────┘ │
│ "dateOnly" : "2023-08-23", │╰────────────────────────────────────────────╯
│ "timeOnly" : "11:38:14", │╭────────────────────Info────────────────────╮
│ "nullableDateOnly" : "2023-08-23", ││ { │
│ "nullableTimeOnly" : null ││ "RequestId": 86, │
│ }] ││ "Timestamp": "2023-08-23 03:38:14", │
│ } ││ "Method": "insert", │
│ ││ "DatabaseName": "test1", │
│ ││ "CollectionName": "mongo.test", │
│ ││ "ConnectionInfo": { │
│ ││ "ClusterId": 1, │
│ ││ "EndPoint": "127.0.0.1:27018" │
│ ││ } │
│ ││ } │
│ │╰────────────────────────────────────────────╯
│ │╭───────────────Request Status───────────────╮
│ ││ ┌───────────┬────────────────┬───────────┐ │
│ ││ │ RequestId │ Time │ Status │ │
│ ││ ├───────────┼────────────────┼───────────┤ │
│ ││ │ 86 │ 11:38:14.12640 │ Succeeded │ │
│ ││ └───────────┴────────────────┴───────────┘ │
│ │╰────────────────────────────────────────────╯
│ │╭───────────────────NiuNiu───────────────────╮
│ ││ -------------------------------------- │
│ ││ / Only two things are infinite, \ │
│ ││ \ the universe and human stupidity. / │
│ ││ -------------------------------------- │
│ ││ ^__^ O ^__^ │
│ ││ _______/(oo) o (oo)\_______ │
│ ││ /\/( /(__) (__)\ )\/\ │
│ ││ ||w----|| ||----w|| │
│ ││ || || || || │
│ ││ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ │
╰──────────────────────────────────────────────────────────────────────╯╰────────────────────────────────────────────╯
```

#### Core

| NuGet Package | Version | Download | Description |
Expand Down
1 change: 0 additions & 1 deletion build/common.props
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
<GenerateAssemblyConfigurationAttribute>True</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>True</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>True</GenerateAssemblyProductAttribute>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
Expand Down
2 changes: 1 addition & 1 deletion build/version.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<PropertyGroup>
<VersionMajor>1</VersionMajor>
<VersionMinor>8</VersionMinor>
<VersionPatch>2</VersionPatch>
<VersionPatch>3</VersionPatch>
<VersionQuality></VersionQuality>
<VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix>
</PropertyGroup>
Expand Down
10 changes: 9 additions & 1 deletion sample/WebApi.Test.Unit/ServiceModules/MongoModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,20 @@ public override void ConfigureServices(ConfigureServicesContext context)
// cs.ClusterConfigurator = cb => cb.Subscribe(new ActivityEventSubscriber());
// };
//});
HashSet<string> CommandsWithCollectionName = new()
{
"mongo.test"
};
context.Services.AddMongoContext<DbContext>(new()
{
Servers = new List<MongoServerAddress> { new("127.0.0.1", 27018) },
Credential = MongoCredential.CreateCredential("admin", "guest", "guest"),
LinqProvider = LinqProvider.V3,
ClusterConfigurator = s => s.Subscribe(new ActivityEventSubscriber())
ClusterConfigurator = s => s.Subscribe(new ActivityEventSubscriber(new()
{
Enable = true,
ShouldStartCollection = coll => CommandsWithCollectionName.Contains(coll)
}))
}, c =>
{
c.DatabaseName = "test1";
Expand Down
73 changes: 51 additions & 22 deletions src/EasilyNET.Mongo.ConsoleDebug/ActivityEventSubscriber.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
using Spectre.Console;
using Spectre.Console.Json;
using Spectre.Console.Rendering;
using System.Collections.Concurrent;
using System.Reflection;

// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Local

Expand Down Expand Up @@ -34,6 +36,8 @@ public sealed class ActivityEventSubscriber : IEventSubscriber
"listIndexes"
};

private static readonly ConcurrentDictionary<int, string> RequestIdWithCollectionName = new();

private readonly InstrumentationOptions _options;
private readonly ReflectionEventSubscriber _subscriber;

Expand Down Expand Up @@ -82,8 +86,8 @@ private void WritStatus(int request_id, bool success)
Header = new("Command", Justify.Center)
}.Collapse().Border(new RoundedBoxBorder()).NoSafeBorder().Expand())
{
MinimumSize = 64,
Size = 96
MinimumSize = 48,
Size = 72
},
new Layout(new Rows(new Panel(new Calendar(DateTime.Now)
{
Expand All @@ -103,11 +107,11 @@ private void WritStatus(int request_id, bool success)
})
{
Height = 13,
Header = new("Mongo Info", Justify.Center)
Header = new("Info", Justify.Center)
}.Collapse().Border(new RoundedBoxBorder()).NoSafeBorder().Expand(), new Panel(table)
{
Height = 7,
Header = new("Mongo Request Status", Justify.Center)
Header = new("Request Status", Justify.Center)
}.Collapse().Border(new RoundedBoxBorder()).NoSafeBorder().Expand(), new Panel(new Text("""
--------------------------------------
/ Only two things are infinite, \
Expand Down Expand Up @@ -138,34 +142,59 @@ private void WritStatus(int request_id, bool success)
#pragma warning disable IDE0051
private void Handle(CommandStartedEvent @event)
{
if (_options.ShouldStartActivity is not null && !_options.ShouldStartActivity(@event)) return;
if (!CommandsWithCollectionNameAsValue.Contains(@event.CommandName)) return;
// 使用字符串的方式替代序列化
InfoJson = $$"""
{
"RequestId": {{@event.RequestId}},
"Timestamp": "{{@event.Timestamp:yyyy-MM-dd HH:mm:ss}}",
"Method": "{{@event.CommandName}}",
"DatabaseName": "{{@event.DatabaseNamespace.DatabaseName}}",
"CollectionName": "{{@event.Command.Elements.First(c => c.Name == @event.CommandName).Value}}",
"ConnectionInfo": {
"ClusterId": {{@event.ConnectionId.ServerId.ClusterId.Value}},
"EndPoint": "{{@event.ConnectionId.ServerId.EndPoint}}"
}
}
""";
CommandJson = @event.Command.ToJson(new() { Indent = true });
if (CommandJson.Length >= 1000) CommandJson = $"{CommandJson[..1000]}\n...\n Excessively long text truncation(文本过长截断)";
if (RequestIdWithCollectionName.Count > 50) RequestIdWithCollectionName.Clear();
if (@event.Command.Elements.All(c => c.Name != @event.CommandName)) return;
var coll_name = @event.Command.Elements.First(c => c.Name == @event.CommandName).Value.ToString() ?? "N/A";
RequestIdWithCollectionName.AddOrUpdate(@event.RequestId, coll_name, (_, v) => v);
switch (_options.Enable)
{
case true when !CommandsWithCollectionNameAsValue.Contains(@event.CommandName):
return;
case true when _options.ShouldStartCollection is not null && !_options.ShouldStartCollection(coll_name):
return;
case true:
{
// 使用字符串的方式替代序列化
InfoJson = $$"""
{
"RequestId": {{@event.RequestId}},
"Timestamp": "{{@event.Timestamp:yyyy-MM-dd HH:mm:ss}}",
"Method": "{{@event.CommandName}}",
"DatabaseName": "{{@event.DatabaseNamespace.DatabaseName}}",
"CollectionName": "{{coll_name}}",
"ConnectionInfo": {
"ClusterId": {{@event.ConnectionId.ServerId.ClusterId.Value}},
"EndPoint": "{{@event.ConnectionId.ServerId.EndPoint}}"
}
}
""";
CommandJson = @event.Command.ToJson(new() { Indent = true });
if (CommandJson.Length >= 1000) CommandJson = $"{CommandJson[..1000]}\n...\n Excessively long text truncation(命令过长截断)";
break;
}
}
}

private void Handle(CommandSucceededEvent @event)
{
if (!_options.Enable) return;
if (_options.ShouldStartCollection is not null)
{
var success = RequestIdWithCollectionName.TryGetValue(@event.RequestId, out var coll_name);
if (success && !_options.ShouldStartCollection(coll_name!)) return;
}
if (!CommandsWithCollectionNameAsValue.Contains(@event.CommandName)) return;
WritStatus(@event.RequestId, true);
}

private void Handle(CommandFailedEvent @event)
{
if (!_options.Enable) return;
if (_options.ShouldStartCollection is not null)
{
var success = RequestIdWithCollectionName.TryGetValue(@event.RequestId, out var coll_name);
if (success && !_options.ShouldStartCollection(coll_name!)) return;
}
if (!CommandsWithCollectionNameAsValue.Contains(@event.CommandName)) return;
WritStatus(@event.RequestId, false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

<ItemGroup>
<PackageReference Include="MongoDB.Driver.Core" Version="2.21.0" />
<!-- 默认引入 Serilog.Sinks.Spectre 方便使用 -->
<!-- 这里引入直接 Serilog.Sinks.Spectre 方便上层使用 -->
<PackageReference Include="Serilog.Sinks.Spectre" Version="0.4.1" />
<PackageReference Include="Spectre.Console.Json" Version="0.47.1-preview.0.11" />
</ItemGroup>
Expand Down
14 changes: 8 additions & 6 deletions src/EasilyNET.Mongo.ConsoleDebug/InstrumentationOptions.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
using MongoDB.Driver.Core.Events;

namespace EasilyNET.Mongo.ConsoleDebug;
namespace EasilyNET.Mongo.ConsoleDebug;

/// <summary>
/// 选项
/// </summary>
public sealed class InstrumentationOptions
{
/// <summary>
/// 是否开启Activity
/// 是否启用, 默认值: <see langword="true" />
/// </summary>
public bool Enable { get; set; } = true;

/// <summary>
/// 过滤哪些集合需要开启信息输出
/// </summary>
// ReSharper disable once UnusedAutoPropertyAccessor.Global
public Func<CommandStartedEvent, bool>? ShouldStartActivity { get; set; }
public Func<string, bool>? ShouldStartCollection { get; set; }
}
Loading

0 comments on commit a4d4a1d

Please sign in to comment.