Setup etcd helper and magic onion

This commit is contained in:
2025-07-07 22:32:03 +08:00
parent 8d2f4a4c47
commit 0d47716713
11 changed files with 163 additions and 29 deletions

View File

@@ -84,16 +84,16 @@ public class AccountEventService(
foreach (var userId in userIds)
{
var cacheKey = $"{StatusCacheKey}{userId}";
// var cachedStatus = await cache.GetAsync<Status>(cacheKey);
// if (cachedStatus != null)
// {
// cachedStatus.IsOnline = !cachedStatus.IsInvisible && ws.GetAccountIsConnected(userId);
// results[userId] = cachedStatus;
// }
// else
// {
var cachedStatus = await cache.GetAsync<Status>(cacheKey);
if (cachedStatus != null)
{
cachedStatus.IsOnline = !cachedStatus.IsInvisible /*&& ws.GetAccountIsConnected(userId)*/;
results[userId] = cachedStatus;
}
else
{
cacheMissUserIds.Add(userId);
// }
}
}
if (cacheMissUserIds.Any())
@@ -115,7 +115,7 @@ public class AccountEventService(
status.IsOnline = !status.IsInvisible && isOnline;
results[status.AccountId] = status;
var cacheKey = $"{StatusCacheKey}{status.AccountId}";
// await cache.SetAsync(cacheKey, status, TimeSpan.FromMinutes(5));
await cache.SetAsync(cacheKey, status, TimeSpan.FromMinutes(5));
foundUserIds.Add(status.AccountId);
}
@@ -170,12 +170,12 @@ public class AccountEventService(
public async Task<bool> CheckInDailyDoAskCaptcha(Shared.Models.Account user)
{
var cacheKey = $"{CaptchaCacheKey}{user.Id}";
// var needsCaptcha = await cache.GetAsync<bool?>(cacheKey);
// if (needsCaptcha is not null)
// return needsCaptcha!.Value;
var needsCaptcha = await cache.GetAsync<bool?>(cacheKey);
if (needsCaptcha is not null)
return needsCaptcha!.Value;
var result = Random.Next(100) < CaptchaProbabilityPercent;
// await cache.SetAsync(cacheKey, result, TimeSpan.FromHours(24));
await cache.SetAsync(cacheKey, result, TimeSpan.FromHours(24));
return result;
}

View File

@@ -184,6 +184,7 @@ public class AccountService(
public async Task RequestAccountDeletion(Shared.Models.Account account)
{
await Task.CompletedTask;
// var spell = await spells.CreateMagicSpell(
// account,
// MagicSpellType.AccountRemoval,
@@ -196,6 +197,7 @@ public class AccountService(
public async Task RequestPasswordReset(Shared.Models.Account account)
{
await Task.CompletedTask;
// var spell = await spells.CreateMagicSpell(
// account,
// MagicSpellType.AuthPasswordReset,
@@ -520,6 +522,7 @@ public class AccountService(
public async Task VerifyContactMethod(Shared.Models.Account account, AccountContact contact)
{
await Task.CompletedTask;
// var spell = await spells.CreateMagicSpell(
// account,
// MagicSpellType.ContactVerification,

View File

@@ -66,8 +66,8 @@ public class NotificationService(
AccountId = account.Id,
};
// db.NotificationPushSubscriptions.Add(subscription);
// await db.SaveChangesAsync();
db.NotificationPushSubscriptions.Add(subscription);
await db.SaveChangesAsync();
return subscription;
}
@@ -107,7 +107,7 @@ public class NotificationService(
}
if (!isSilent)
Console.WriteLine("Simulating notification delivery."); // _ = DeliveryNotification(notification);
_ = DeliveryNotification(notification);
return notification;
}
@@ -134,10 +134,10 @@ public class NotificationService(
var id = notifications.Where(n => n.ViewedAt == null).Select(n => n.Id).ToList();
if (id.Count == 0) return;
// await db.Notifications
// .Where(n => id.Contains(n.Id))
// .ExecuteUpdateAsync(s => s.SetProperty(n => n.ViewedAt, now)
// );
await db.Notifications
.Where(n => id.Contains(n.Id))
.ExecuteUpdateAsync(s => s.SetProperty(n => n.ViewedAt, now)
);
}
public async Task BroadcastNotification(Notification notification, bool save = false)
@@ -161,7 +161,7 @@ public class NotificationService(
};
return newNotification;
}).ToList();
// await db.BulkInsertAsync(notifications);
await db.BulkInsertAsync(notifications);
}
foreach (var account in accounts)

View File

@@ -189,8 +189,6 @@ public class DysonTokenAuthHandler(
{
return false;
}
break;
default:
return false;
}

View File

@@ -105,6 +105,7 @@ public class AuthService(
public async Task<bool> ValidateCaptcha(string token)
{
await Task.CompletedTask;
if (string.IsNullOrWhiteSpace(token)) return false;
// var provider = config.GetSection("Captcha")["Provider"]?.ToLower();

View File

@@ -21,8 +21,7 @@ public class OidcProviderController(
AppDatabase db,
OidcProviderService oidcService,
IConfiguration configuration,
IOptions<OidcProviderOptions> options,
ILogger<OidcProviderController> logger
IOptions<OidcProviderOptions> options
)
: ControllerBase
{

View File

@@ -27,6 +27,7 @@ public class OidcProviderService(
public async Task<CustomApp?> FindClientByIdAsync(Guid clientId)
{
await Task.CompletedTask;
return null;
// return await db.CustomApps
// .Include(c => c.Secrets)
@@ -35,6 +36,7 @@ public class OidcProviderService(
public async Task<CustomApp?> FindClientByAppIdAsync(Guid appId)
{
await Task.CompletedTask;
return null;
// return await db.CustomApps
// .Include(c => c.Secrets)

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
@@ -12,7 +12,7 @@
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Google.Protobuf" Version="3.27.2" />
<PackageReference Include="dotnet-etcd" Version="8.0.1" />
<PackageReference Include="MagicOnion.Client" Version="7.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
@@ -33,4 +33,6 @@
</Reference>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,70 @@
using dotnet_etcd;
using Etcdserverpb;
using Grpc.Core;
namespace DysonNetwork.Shared.Etcd;
public class EtcdService(string connectionString) : IEtcdService
{
private readonly EtcdClient _etcdClient = new(connectionString);
private long _leaseId;
private string? _serviceKey;
private readonly CancellationTokenSource _cts = new();
public async Task RegisterServiceAsync(string serviceName, string serviceAddress, int ttl = 15)
{
_serviceKey = $"/services/{serviceName}/{Guid.NewGuid()}";
var leaseGrantResponse = await _etcdClient.LeaseGrantAsync(new LeaseGrantRequest { TTL = ttl });
_leaseId = leaseGrantResponse.ID;
await _etcdClient.PutAsync(new PutRequest
{
Key = Google.Protobuf.ByteString.CopyFromUtf8(_serviceKey),
Value = Google.Protobuf.ByteString.CopyFromUtf8(serviceAddress),
Lease = _leaseId
});
_ = Task.Run(async () =>
{
while (!_cts.Token.IsCancellationRequested)
{
try
{
await _etcdClient.LeaseKeepAlive(new LeaseKeepAliveRequest { ID = _leaseId },
_ => { }, _cts.Token);
await Task.Delay(TimeSpan.FromSeconds(ttl / 3), _cts.Token);
}
catch (RpcException)
{
// Ignored
}
}
}, _cts.Token);
}
public async Task UnregisterServiceAsync()
{
if (!string.IsNullOrEmpty(_serviceKey))
{
await _etcdClient.DeleteRangeAsync(_serviceKey);
}
}
public async Task<List<string>> DiscoverServicesAsync(string serviceName)
{
var prefix = $"/services/{serviceName}/";
var rangeResponse = await _etcdClient.GetRangeAsync(prefix);
return rangeResponse.Kvs.Select(kv => kv.Value.ToStringUtf8()).ToList();
}
public void Dispose()
{
_cts.Cancel();
if (_leaseId != 0)
{
_etcdClient.LeaseRevoke(new LeaseRevokeRequest { ID = _leaseId });
}
_etcdClient.Dispose();
}
}

View File

@@ -0,0 +1,46 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Grpc.Net.Client;
using MagicOnion.Client;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace DysonNetwork.Shared.Etcd
{
public static class EtcdServiceExtensions
{
public static IServiceCollection AddEtcdService(this IServiceCollection services, IConfiguration configuration)
{
var etcdConnectionString = configuration.GetConnectionString("Etcd");
services.AddSingleton<IEtcdService>(new EtcdService(etcdConnectionString!));
return services;
}
public static IServiceCollection AddMagicOnionService<TService>(this IServiceCollection services)
where TService : class, MagicOnion.IService<TService>
{
services.AddSingleton(serviceProvider =>
{
var etcdService = serviceProvider.GetRequiredService<IEtcdService>();
var serviceName = typeof(TService).Name.TrimStart('I'); // Convention: IMyService -> MyService
// Synchronously wait for service discovery (or handle asynchronously if preferred)
var endpoints = etcdService.DiscoverServicesAsync(serviceName).GetAwaiter().GetResult();
if (!endpoints.Any())
{
throw new InvalidOperationException($"No endpoints found for MagicOnion service: {serviceName}");
}
// For simplicity, use the first discovered endpoint
var endpoint = endpoints.First();
var channel = GrpcChannel.ForAddress(endpoint);
return MagicOnionClient.Create<TService>(channel);
});
return services;
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DysonNetwork.Shared.Etcd
{
public interface IEtcdService : IDisposable
{
Task RegisterServiceAsync(string serviceName, string serviceAddress, int ttl = 15);
Task UnregisterServiceAsync();
Task<List<string>> DiscoverServicesAsync(string serviceName);
}
}