6 Commits

61 changed files with 1183 additions and 156 deletions

View File

@@ -1,75 +0,0 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace FictionArchive.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
/*private readonly FictionArchiveDbContext _dbContext;
private readonly ISourceAdapter _novelpiaAdapter;
private readonly ITranslationEngineAdapter _translationEngine;
public TestController(ISourceAdapter novelpiaAdapter, FictionArchiveDbContext dbContext, ITranslationEngineAdapter translationEngine)
{
_novelpiaAdapter = novelpiaAdapter;
_dbContext = dbContext;
_translationEngine = translationEngine;
}
[HttpGet("GetNovel")]
public async Task<Novel> GetNovel(string novelUrl)
{
var novel = await _novelpiaAdapter.GetMetadata(novelUrl);
novel.Source = new Source()
{
Name = "Novelpia",
Id = 1,
Url = "https://novelpia.com"
};
_dbContext.Novels.Add(novel);
await _dbContext.SaveChangesAsync();
return novel;
}
[HttpGet("GetChapter")]
public async Task<string> GetChapter(uint novelId, uint chapterNumber)
{
var novel = await _dbContext.Novels.Include(n => n.Chapters).ThenInclude(c => c.Translations).FirstOrDefaultAsync(n => n.Id == novelId);
var chapter = novel.Chapters.FirstOrDefault(c => c.Order == chapterNumber);
var rawChapter = await _novelpiaAdapter.GetRawChapter(chapter.Url);
chapter.Translations.Add(new ChapterTranslation()
{
Language = novel.RawLanguage,
Body = rawChapter
});
await _dbContext.SaveChangesAsync();
return rawChapter;
}
[HttpPost("TranslateChapter")]
public async Task<ChapterTranslation> TranslateChapter(uint novelId, uint chapterNumber, Language to)
{
var novel = await _dbContext.Novels.Include(n => n.Chapters)
.ThenInclude(c => c.Translations).FirstOrDefaultAsync(novel => novel.Id == novelId);
var chapter = novel.Chapters.FirstOrDefault(c => c.Order == chapterNumber);
var chapterRaw = chapter.Translations.FirstOrDefault(ct => ct.Language == novel.RawLanguage);
var newTranslation = new ChapterTranslation()
{
Language = to,
TranslationEngine = new TranslationEngine()
{
Name = "DeepL"
}
};
var translation = await _translationEngine.GetTranslation(chapterRaw.Body, novel.RawLanguage, to);
newTranslation.Body = translation;
chapter.Translations.Add(newTranslation);
await _dbContext.SaveChangesAsync();
return newTranslation;
}*/
}
}

View File

@@ -11,6 +11,7 @@
<PackageReference Include="HotChocolate.AspNetCore" Version="15.1.11" /> <PackageReference Include="HotChocolate.AspNetCore" Version="15.1.11" />
<PackageReference Include="HotChocolate.Data" Version="15.1.11" /> <PackageReference Include="HotChocolate.Data" Version="15.1.11" />
<PackageReference Include="HotChocolate.Data.EntityFramework" Version="15.1.11" /> <PackageReference Include="HotChocolate.Data.EntityFramework" Version="15.1.11" />
<PackageReference Include="HotChocolate.Fusion" Version="15.1.11" />
<PackageReference Include="HotChocolate.Types.Scalars" Version="15.1.11" /> <PackageReference Include="HotChocolate.Types.Scalars" Version="15.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
@@ -28,8 +29,11 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="Controllers\" />
<Folder Include="GraphQL\" /> <Folder Include="GraphQL\" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
</ItemGroup>
</Project> </Project>

View File

@@ -1,3 +1,5 @@
using FictionArchive.Service.Shared.Extensions;
namespace FictionArchive.API; namespace FictionArchive.API;
public class Program public class Program
@@ -6,38 +8,26 @@ public class Program
{ {
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// OpenAPI & REST
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMemoryCache();
builder.Services.AddHealthChecks(); builder.Services.AddHealthChecks();
#region Fusion Gateway
builder.Services.AddHttpClient("Fusion");
builder.Services
.AddFusionGatewayServer()
.ConfigureFromFile("gateway.fgp")
.CoreBuilder.ApplySaneDefaults();
#endregion
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapGraphQL();
app.MapHealthChecks("/healthz"); app.MapHealthChecks("/healthz");
app.MapControllers(); app.MapGraphQL();
app.Run(); app.Run();
} }

View File

@@ -23,7 +23,7 @@
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": true, "dotnetRunMessages": true,
"launchBrowser": true, "launchBrowser": true,
"launchUrl": "swagger", "launchUrl": "graphql",
"applicationUrl": "https://localhost:7063;http://localhost:5234", "applicationUrl": "https://localhost:7063;http://localhost:5234",
"environmentVariables": { "environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"

View File

@@ -0,0 +1,99 @@
@echo off
setlocal enabledelayedexpansion
set ROOT=%~dp0
for %%A in ("%ROOT%..") do set SERVICES_DIR=%%~fA\
REM ----------------------------------------
REM List of project names to skip
REM (space-separated, match folder names exactly)
REM ----------------------------------------
set SKIP_PROJECTS=FictionArchive.Service.Shared FictionArchive.Service.AuthenticationService
echo ----------------------------------------
echo Finding GraphQL services...
echo ----------------------------------------
set SERVICE_LIST=
for /d %%F in ("%SERVICES_DIR%FictionArchive.Service.*") do (
set "PROJECT_NAME=%%~nxF"
set "SKIP=0"
REM Check if this project name is in the skip list
for %%X in (%SKIP_PROJECTS%) do (
if /I "!PROJECT_NAME!"=="%%X" (
set "SKIP=1"
)
)
if !SKIP!==0 (
echo Found service: !PROJECT_NAME!
set SERVICE_LIST=!SERVICE_LIST! %%F
) else (
echo Skipping service: !PROJECT_NAME!
)
)
echo:
echo ----------------------------------------
echo Exporting schemas and packing subgraphs...
echo ----------------------------------------
for %%S in (%SERVICE_LIST%) do (
echo Processing service folder: %%S
pushd "%%S"
echo Running schema export...
dotnet run -- schema export --output schema.graphql
if errorlevel 1 (
echo ERROR during schema export in %%S
popd
exit /b 1
)
echo Running fusion subgraph pack...
fusion subgraph pack
if errorlevel 1 (
echo ERROR during subgraph pack in %%S
popd
exit /b 1
)
popd
echo Completed: %%S
echo.
)
echo ----------------------------------------
echo Running fusion compose...
echo ----------------------------------------
pushd "%ROOT%"
if exist gateway.fgp del gateway.fgp
for %%S in (%SERVICE_LIST%) do (
REM Extract the full folder name WITH dots preserved
set "SERVICE_NAME=%%~nxS"
echo Composing subgraph: !SERVICE_NAME!
fusion compose -p gateway.fgp -s "..\!SERVICE_NAME!"
if errorlevel 1 (
echo ERROR during fusion compose
popd
exit /b 1
)
)
popd
echo ----------------------------------------
echo Fusion build complete!
echo ----------------------------------------
endlocal
exit /b 0

View File

@@ -0,0 +1,104 @@
#!/usr/bin/env bash
set -euo pipefail
###############################################
# Resolve important directories
###############################################
# Directory where this script lives
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Services live one directory above the script's directory
SERVICES_DIR="$(cd "$ROOT/.." && pwd)"
###############################################
# Skip list (folder names, match exactly)
###############################################
SKIP_PROJECTS=(
"FictionArchive.Service.Shared"
"FictionArchive.Service.Legacy"
)
echo "----------------------------------------"
echo " Finding GraphQL services..."
echo "----------------------------------------"
SERVICE_LIST=()
# Convert skip projects into a single searchable string
SKIP_STRING=" ${SKIP_PROJECTS[*]} "
# Find service directories
shopt -s nullglob
for FOLDER in "$SERVICES_DIR"/FictionArchive.Service.*; do
[ -d "$FOLDER" ] || continue
PROJECT_NAME="$(basename "$FOLDER")"
# Skip entries that match the skip list
if [[ "$SKIP_STRING" == *" $PROJECT_NAME "* ]]; then
echo "Skipping service: $PROJECT_NAME"
continue
fi
echo "Found service: $PROJECT_NAME"
SERVICE_LIST+=("$FOLDER")
done
shopt -u nullglob
echo
echo "----------------------------------------"
echo " Exporting schemas and packing subgraphs..."
echo "----------------------------------------"
for SERVICE in "${SERVICE_LIST[@]}"; do
PROJECT_NAME="$(basename "$SERVICE")"
echo "Processing service: $PROJECT_NAME"
pushd "$SERVICE" >/dev/null
echo "Building service..."
dotnet build -c Release >/dev/null
# Automatically detect built DLL in bin/Release/<TFM>/
DLL_PATH="$(find "bin/Release" -maxdepth 3 -name '*.dll' | head -n 1)"
if [[ -z "$DLL_PATH" ]]; then
echo "ERROR: Could not locate DLL for $PROJECT_NAME"
popd >/dev/null
exit 1
fi
echo "Running schema export..."
dotnet exec "$DLL_PATH" schema export --output schema.graphql
echo "Running subgraph pack..."
fusion subgraph pack
popd >/dev/null
echo "Completed: $PROJECT_NAME"
echo
done
echo "----------------------------------------"
echo " Running fusion compose..."
echo "----------------------------------------"
pushd "$ROOT" >/dev/null
# Remove old composition file
rm -f gateway.fgp
for SERVICE in "${SERVICE_LIST[@]}"; do
SERVICE_NAME="$(basename "$SERVICE")"
echo "Composing subgraph: $SERVICE_NAME"
# Note: Fusion compose must reference parent dir (services live above ROOT)
fusion compose -p gateway.fgp -s "../$SERVICE_NAME"
done
popd >/dev/null
echo "----------------------------------------"
echo " Fusion build complete!"
echo "----------------------------------------"

Binary file not shown.

View File

@@ -0,0 +1,36 @@
using FictionArchive.Service.AuthenticationService.Models.Requests;
using FictionArchive.Service.AuthenticationService.Models.IntegrationEvents;
using FictionArchive.Service.Shared.Services.EventBus;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FictionArchive.Service.AuthenticationService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthenticationWebhookController : ControllerBase
{
private readonly IEventBus _eventBus;
public AuthenticationWebhookController(IEventBus eventBus)
{
_eventBus = eventBus;
}
[HttpPost(nameof(UserRegistered))]
public async Task<ActionResult> UserRegistered([FromBody] UserRegisteredWebhookPayload payload)
{
var authUserAddedEvent = new AuthUserAddedEvent
{
OAuthProviderId = payload.OAuthProviderId,
InviterOAuthProviderId = payload.InviterOAuthProviderId,
EventUserEmail = payload.EventUserEmail,
EventUserUsername = payload.EventUserUsername
};
await _eventBus.Publish(authUserAddedEvent);
return Ok();
}
}
}

View File

@@ -0,0 +1,23 @@
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["FictionArchive.Service.AuthenticationService/FictionArchive.Service.AuthenticationService.csproj", "FictionArchive.Service.AuthenticationService/"]
RUN dotnet restore "FictionArchive.Service.AuthenticationService/FictionArchive.Service.AuthenticationService.csproj"
COPY . .
WORKDIR "/src/FictionArchive.Service.AuthenticationService"
RUN dotnet build "./FictionArchive.Service.AuthenticationService.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./FictionArchive.Service.AuthenticationService.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "FictionArchive.Service.AuthenticationService.dll"]

View File

@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2"/>
</ItemGroup>
<ItemGroup>
<Content Include="..\.dockerignore">
<Link>.dockerignore</Link>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Controllers\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@FictionArchive.Service.AuthenticationService_HostAddress = http://localhost:5091
GET {{FictionArchive.Service.AuthenticationService_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@@ -0,0 +1,16 @@
using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.AuthenticationService.Models.IntegrationEvents;
public class AuthUserAddedEvent : IIntegrationEvent
{
public string OAuthProviderId { get; set; }
public string InviterOAuthProviderId { get; set; }
// The email of the user that created the event
public string EventUserEmail { get; set; }
// The username of the user that created the event
public string EventUserUsername { get; set; }
}

View File

@@ -0,0 +1,17 @@
namespace FictionArchive.Service.AuthenticationService.Models.Requests;
public class UserRegisteredWebhookPayload
{
// The body of the notification message
public string Body { get; set; }
public string OAuthProviderId { get; set; }
public string InviterOAuthProviderId { get; set; }
// The email of the user that created the event
public string EventUserEmail { get; set; }
// The username of the user that created the event
public string EventUserUsername { get; set; }
}

View File

@@ -0,0 +1,49 @@
using FictionArchive.Service.Shared;
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
namespace FictionArchive.Service.AuthenticationService;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
#region Event Bus
builder.Services.AddRabbitMQ(opt =>
{
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
});
#endregion
builder.Services.AddHealthChecks();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapHealthChecks("/healthz");
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}

View File

@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:23522",
"sslPort": 44397
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5091",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7223;http://localhost:5091",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"RabbitMQ": {
"ConnectionString": "amqp://localhost",
"ClientIdentifier": "AuthenticationService"
},
"AllowedHosts": "*"
}

View File

@@ -8,6 +8,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="HotChocolate.AspNetCore.CommandLine" Version="15.1.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

View File

@@ -2,7 +2,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents; namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
public class ChapterPullRequestedEvent : IntegrationEvent public class ChapterPullRequestedEvent : IIntegrationEvent
{ {
public uint NovelId { get; set; } public uint NovelId { get; set; }
public uint ChapterNumber { get; set; } public uint ChapterNumber { get; set; }

View File

@@ -2,7 +2,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents; namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
public class NovelUpdateRequestedEvent : IntegrationEvent public class NovelUpdateRequestedEvent : IIntegrationEvent
{ {
public string NovelUrl { get; set; } public string NovelUrl { get; set; }
} }

View File

@@ -3,7 +3,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents; namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
public class TranslationRequestCompletedEvent : IntegrationEvent public class TranslationRequestCompletedEvent : IIntegrationEvent
{ {
/// <summary> /// <summary>
/// Maps this event back to a triggering request. /// Maps this event back to a triggering request.

View File

@@ -3,7 +3,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.NovelService.Models.IntegrationEvents; namespace FictionArchive.Service.NovelService.Models.IntegrationEvents;
public class TranslationRequestCreatedEvent : IntegrationEvent public class TranslationRequestCreatedEvent : IIntegrationEvent
{ {
public Guid TranslationRequestId { get; set; } public Guid TranslationRequestId { get; set; }
public Language From { get; set; } public Language From { get; set; }

View File

@@ -77,6 +77,6 @@ public class Program
app.MapGraphQL(); app.MapGraphQL();
app.Run(); app.RunWithGraphQLCommands(args);
} }
} }

View File

@@ -0,0 +1,6 @@
{
"subgraph": "Novels",
"http": {
"baseAddress": "http://localhost:5101/graphql"
}
}

View File

@@ -69,6 +69,6 @@ public class Program
app.MapGraphQL(); app.MapGraphQL();
app.Run(); app.RunWithGraphQLCommands(args);
} }
} }

View File

@@ -0,0 +1,6 @@
{
"subgraph": "Scheduler",
"http": {
"baseAddress": "http://localhost:5213/graphql"
}
}

View File

@@ -12,7 +12,13 @@ public static class GraphQLExtensions
return services.AddGraphQLServer() return services.AddGraphQLServer()
.AddQueryType<TQuery>() .AddQueryType<TQuery>()
.AddMutationType<TMutation>() .AddMutationType<TMutation>()
.AddDiagnosticEventListener<ErrorEventListener>() .ApplySaneDefaults();
}
public static IRequestExecutorBuilder ApplySaneDefaults(this IRequestExecutorBuilder builder)
{
return builder.AddDiagnosticEventListener<ErrorEventListener>()
.AddErrorFilter<LoggingErrorFilter>() .AddErrorFilter<LoggingErrorFilter>()
.AddType<UnsignedIntType>() .AddType<UnsignedIntType>()
.AddType<InstantType>() .AddType<InstantType>()

View File

@@ -9,6 +9,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="GraphQL.Server.Ui.GraphiQL" Version="8.3.3" /> <PackageReference Include="GraphQL.Server.Ui.GraphiQL" Version="8.3.3" />
<PackageReference Include="HotChocolate.AspNetCore" Version="15.1.11" /> <PackageReference Include="HotChocolate.AspNetCore" Version="15.1.11" />
<PackageReference Include="HotChocolate.AspNetCore.CommandLine" Version="15.1.11" />
<PackageReference Include="HotChocolate.Data.EntityFramework" Version="15.1.11" /> <PackageReference Include="HotChocolate.Data.EntityFramework" Version="15.1.11" />
<PackageReference Include="HotChocolate.Types.Scalars" Version="15.1.11" /> <PackageReference Include="HotChocolate.Types.Scalars" Version="15.1.11" />
<PackageReference Include="HotChocolate.Types.NodaTime" Version="15.1.11" /> <PackageReference Include="HotChocolate.Types.NodaTime" Version="15.1.11" />

View File

@@ -16,7 +16,7 @@ public class EventBusBuilder<TEventBus> where TEventBus : class, IEventBus
_services.AddSingleton<SubscriptionManager>(_subscriptionManager); _services.AddSingleton<SubscriptionManager>(_subscriptionManager);
} }
public EventBusBuilder<TEventBus> Subscribe<TEvent, TEventHandler>() where TEvent : IntegrationEvent where TEventHandler : class, IIntegrationEventHandler<TEvent> public EventBusBuilder<TEventBus> Subscribe<TEvent, TEventHandler>() where TEvent : IIntegrationEvent where TEventHandler : class, IIntegrationEventHandler<TEvent>
{ {
_services.AddKeyedTransient<IIntegrationEventHandler, TEventHandler>(typeof(TEvent).Name); _services.AddKeyedTransient<IIntegrationEventHandler, TEventHandler>(typeof(TEvent).Name);
_subscriptionManager.RegisterSubscription<TEvent>(); _subscriptionManager.RegisterSubscription<TEvent>();

View File

@@ -2,6 +2,6 @@ namespace FictionArchive.Service.Shared.Services.EventBus;
public interface IEventBus public interface IEventBus
{ {
Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IntegrationEvent; Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IIntegrationEvent;
Task Publish(object integrationEvent, string eventType); Task Publish(object integrationEvent, string eventType);
} }

View File

@@ -0,0 +1,7 @@
using NodaTime;
namespace FictionArchive.Service.Shared.Services.EventBus;
public interface IIntegrationEvent
{
}

View File

@@ -1,12 +1,12 @@
namespace FictionArchive.Service.Shared.Services.EventBus; namespace FictionArchive.Service.Shared.Services.EventBus;
public interface IIntegrationEventHandler<in TEvent> : IIntegrationEventHandler where TEvent : IntegrationEvent public interface IIntegrationEventHandler<in TEvent> : IIntegrationEventHandler where TEvent : IIntegrationEvent
{ {
Task Handle(TEvent @event); Task Handle(TEvent @event);
Task IIntegrationEventHandler.Handle(IntegrationEvent @event) => Handle((TEvent)@event); Task IIntegrationEventHandler.Handle(IIntegrationEvent @event) => Handle((TEvent)@event);
} }
public interface IIntegrationEventHandler public interface IIntegrationEventHandler
{ {
Task Handle(IntegrationEvent @event); Task Handle(IIntegrationEvent @event);
} }

View File

@@ -22,6 +22,8 @@ public class RabbitMQEventBus : IEventBus, IHostedService
private readonly JsonSerializerSettings _jsonSerializerSettings; private readonly JsonSerializerSettings _jsonSerializerSettings;
private const string ExchangeName = "fiction-archive-event-bus"; private const string ExchangeName = "fiction-archive-event-bus";
private const string CreatedAtHeader = "X-Created-At";
private const string EventIdHeader = "X-Event-Id";
public RabbitMQEventBus(IServiceScopeFactory serviceScopeFactory, RabbitMQConnectionProvider connectionProvider, IOptions<RabbitMQOptions> options, SubscriptionManager subscriptionManager, ILogger<RabbitMQEventBus> logger) public RabbitMQEventBus(IServiceScopeFactory serviceScopeFactory, RabbitMQConnectionProvider connectionProvider, IOptions<RabbitMQOptions> options, SubscriptionManager subscriptionManager, ILogger<RabbitMQEventBus> logger)
{ {
@@ -33,14 +35,10 @@ public class RabbitMQEventBus : IEventBus, IHostedService
_jsonSerializerSettings = new JsonSerializerSettings().ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); _jsonSerializerSettings = new JsonSerializerSettings().ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
} }
public async Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IntegrationEvent public async Task Publish<TEvent>(TEvent integrationEvent) where TEvent : IIntegrationEvent
{ {
var routingKey = typeof(TEvent).Name; var routingKey = typeof(TEvent).Name;
// Set integration event values
integrationEvent.CreatedAt = Instant.FromDateTimeUtc(DateTime.UtcNow);
integrationEvent.EventId = Guid.NewGuid();
await Publish(integrationEvent, routingKey); await Publish(integrationEvent, routingKey);
} }
@@ -48,7 +46,16 @@ public class RabbitMQEventBus : IEventBus, IHostedService
{ {
var channel = await _connectionProvider.GetDefaultChannelAsync(); var channel = await _connectionProvider.GetDefaultChannelAsync();
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(integrationEvent)); var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(integrationEvent));
await channel.BasicPublishAsync(ExchangeName, eventType, true, body);
// headers
var props = new BasicProperties();
props.Headers = new Dictionary<string, object?>()
{
{ CreatedAtHeader, Instant.FromDateTimeUtc(DateTime.UtcNow).ToString() },
{ EventIdHeader, Guid.NewGuid().ToString() }
};
await channel.BasicPublishAsync(ExchangeName, eventType, true, props, body);
_logger.LogInformation("Published event {EventName}", eventType); _logger.LogInformation("Published event {EventName}", eventType);
} }
@@ -70,6 +77,8 @@ public class RabbitMQEventBus : IEventBus, IHostedService
return OnReceivedEvent(sender, @event, channel); return OnReceivedEvent(sender, @event, channel);
}; };
await channel.BasicConsumeAsync(_options.ClientIdentifier, false, consumer, cancellationToken: cancellationToken);
foreach (var subscription in _subscriptionManager.Subscriptions) foreach (var subscription in _subscriptionManager.Subscriptions)
{ {
await channel.QueueBindAsync(_options.ClientIdentifier, ExchangeName, subscription.Key, await channel.QueueBindAsync(_options.ClientIdentifier, ExchangeName, subscription.Key,
@@ -77,8 +86,6 @@ public class RabbitMQEventBus : IEventBus, IHostedService
_logger.LogInformation("Subscribed to {SubscriptionKey}", subscription.Key); _logger.LogInformation("Subscribed to {SubscriptionKey}", subscription.Key);
} }
await channel.BasicConsumeAsync(_options.ClientIdentifier, false, consumer, cancellationToken: cancellationToken);
_logger.LogInformation("RabbitMQ EventBus started."); _logger.LogInformation("RabbitMQ EventBus started.");
} }
catch (Exception e) catch (Exception e)
@@ -106,7 +113,7 @@ public class RabbitMQEventBus : IEventBus, IHostedService
} }
var eventBody = Encoding.UTF8.GetString(@event.Body.Span); var eventBody = Encoding.UTF8.GetString(@event.Body.Span);
var eventObject = JsonConvert.DeserializeObject(eventBody, _subscriptionManager.Subscriptions[eventName], _jsonSerializerSettings) as IntegrationEvent; var eventObject = JsonConvert.DeserializeObject(eventBody, _subscriptionManager.Subscriptions[eventName], _jsonSerializerSettings) as IIntegrationEvent;
using var scope = _serviceScopeFactory.CreateScope(); using var scope = _serviceScopeFactory.CreateScope();

View File

@@ -1,9 +0,0 @@
using NodaTime;
namespace FictionArchive.Service.Shared.Services.EventBus;
public abstract class IntegrationEvent
{
public Guid EventId { get; set; }
public Instant CreatedAt { get; set; }
}

View File

@@ -1,4 +1,5 @@
// <auto-generated /> // <auto-generated />
using System;
using FictionArchive.Service.TranslationService.Services.Database; using FictionArchive.Service.TranslationService.Services.Database;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
@@ -12,7 +13,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace FictionArchive.Service.TranslationService.Migrations namespace FictionArchive.Service.TranslationService.Migrations
{ {
[DbContext(typeof(TranslationServiceDbContext))] [DbContext(typeof(TranslationServiceDbContext))]
[Migration("20251118052322_Initial")] [Migration("20251122225458_Initial")]
partial class Initial partial class Initial
{ {
/// <inheritdoc /> /// <inheritdoc />
@@ -27,11 +28,9 @@ namespace FictionArchive.Service.TranslationService.Migrations
modelBuilder.Entity("FictionArchive.Service.TranslationService.Models.Database.TranslationRequest", b => modelBuilder.Entity("FictionArchive.Service.TranslationService.Models.Database.TranslationRequest", b =>
{ {
b.Property<long>("Id") b.Property<Guid>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("bigint"); .HasColumnType("uuid");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<long>("BilledCharacterCount") b.Property<long>("BilledCharacterCount")
.HasColumnType("bigint"); .HasColumnType("bigint");

View File

@@ -1,6 +1,6 @@
using Microsoft.EntityFrameworkCore.Migrations; using System;
using Microsoft.EntityFrameworkCore.Migrations;
using NodaTime; using NodaTime;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable #nullable disable
@@ -16,8 +16,7 @@ namespace FictionArchive.Service.TranslationService.Migrations
name: "TranslationRequests", name: "TranslationRequests",
columns: table => new columns: table => new
{ {
Id = table.Column<long>(type: "bigint", nullable: false) Id = table.Column<Guid>(type: "uuid", nullable: false),
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
OriginalText = table.Column<string>(type: "text", nullable: false), OriginalText = table.Column<string>(type: "text", nullable: false),
TranslatedText = table.Column<string>(type: "text", nullable: true), TranslatedText = table.Column<string>(type: "text", nullable: true),
From = table.Column<int>(type: "integer", nullable: false), From = table.Column<int>(type: "integer", nullable: false),

View File

@@ -1,4 +1,5 @@
// <auto-generated /> // <auto-generated />
using System;
using FictionArchive.Service.TranslationService.Services.Database; using FictionArchive.Service.TranslationService.Services.Database;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
@@ -24,11 +25,9 @@ namespace FictionArchive.Service.TranslationService.Migrations
modelBuilder.Entity("FictionArchive.Service.TranslationService.Models.Database.TranslationRequest", b => modelBuilder.Entity("FictionArchive.Service.TranslationService.Models.Database.TranslationRequest", b =>
{ {
b.Property<long>("Id") b.Property<Guid>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("bigint"); .HasColumnType("uuid");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<long>("BilledCharacterCount") b.Property<long>("BilledCharacterCount")
.HasColumnType("bigint"); .HasColumnType("bigint");

View File

@@ -4,7 +4,7 @@ using FictionArchive.Service.TranslationService.Models.Enums;
namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents; namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents;
public class TranslationRequestCompletedEvent : IntegrationEvent public class TranslationRequestCompletedEvent : IIntegrationEvent
{ {
/// <summary> /// <summary>
/// Maps this event back to a triggering request. /// Maps this event back to a triggering request.

View File

@@ -3,7 +3,7 @@ using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents; namespace FictionArchive.Service.TranslationService.Models.IntegrationEvents;
public class TranslationRequestCreatedEvent : IntegrationEvent public class TranslationRequestCreatedEvent : IIntegrationEvent
{ {
public Guid TranslationRequestId { get; set; } public Guid TranslationRequestId { get; set; }
public Language From { get; set; } public Language From { get; set; }

View File

@@ -73,6 +73,6 @@ public class Program
app.MapGraphQL(); app.MapGraphQL();
app.Run(); app.RunWithGraphQLCommands(args);
} }
} }

View File

@@ -0,0 +1,6 @@
{
"subgraph": "Translation",
"http": {
"baseAddress": "http://localhost:5234/graphql"
}
}

View File

@@ -0,0 +1,23 @@
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["FictionArchive.Service.UserService/FictionArchive.Service.UserService.csproj", "FictionArchive.Service.UserService/"]
RUN dotnet restore "FictionArchive.Service.UserService/FictionArchive.Service.UserService.csproj"
COPY . .
WORKDIR "/src/FictionArchive.Service.UserService"
RUN dotnet build "./FictionArchive.Service.UserService.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./FictionArchive.Service.UserService.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "FictionArchive.Service.UserService.dll"]

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<Content Include="..\.dockerignore">
<Link>.dockerignore</Link>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,13 @@
using FictionArchive.Service.UserService.Models.Database;
using FictionArchive.Service.UserService.Services;
namespace FictionArchive.Service.UserService.GraphQL;
public class Mutation
{
public async Task<User> RegisterUser(string username, string email, string oAuthProviderId,
string? inviterOAuthProviderId, UserManagementService userManagementService)
{
return await userManagementService.RegisterUser(username, email, oAuthProviderId, inviterOAuthProviderId);
}
}

View File

@@ -0,0 +1,12 @@
using FictionArchive.Service.UserService.Models.Database;
using FictionArchive.Service.UserService.Services;
namespace FictionArchive.Service.UserService.GraphQL;
public class Query
{
public async Task<IQueryable<User>> GetUsers(UserManagementService userManagementService)
{
return userManagementService.GetUsers();
}
}

View File

@@ -0,0 +1,77 @@
// <auto-generated />
using System;
using FictionArchive.Service.UserService.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NodaTime;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
[DbContext(typeof(UserServiceDbContext))]
[Migration("20251122034145_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Instant>("CreatedTime")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Disabled")
.HasColumnType("boolean");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("InviterId")
.HasColumnType("uuid");
b.Property<Instant>("LastUpdatedTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("OAuthProviderId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("InviterId");
b.ToTable("Users");
});
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.HasOne("FictionArchive.Service.UserService.Models.Database.User", "Inviter")
.WithMany()
.HasForeignKey("InviterId");
b.Navigation("Inviter");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,51 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using NodaTime;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Username = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
OAuthProviderId = table.Column<string>(type: "text", nullable: false),
Disabled = table.Column<bool>(type: "boolean", nullable: false),
InviterId = table.Column<Guid>(type: "uuid", nullable: true),
CreatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
LastUpdatedTime = table.Column<Instant>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
table.ForeignKey(
name: "FK_Users_Users_InviterId",
column: x => x.InviterId,
principalTable: "Users",
principalColumn: "Id");
});
migrationBuilder.CreateIndex(
name: "IX_Users_InviterId",
table: "Users",
column: "InviterId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@@ -0,0 +1,80 @@
// <auto-generated />
using System;
using FictionArchive.Service.UserService.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NodaTime;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
[DbContext(typeof(UserServiceDbContext))]
[Migration("20251122040724_UniqueOAuthProviderId")]
partial class UniqueOAuthProviderId
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Instant>("CreatedTime")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Disabled")
.HasColumnType("boolean");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("InviterId")
.HasColumnType("uuid");
b.Property<Instant>("LastUpdatedTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("OAuthProviderId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("InviterId");
b.HasIndex("OAuthProviderId")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.HasOne("FictionArchive.Service.UserService.Models.Database.User", "Inviter")
.WithMany()
.HasForeignKey("InviterId");
b.Navigation("Inviter");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
/// <inheritdoc />
public partial class UniqueOAuthProviderId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_Users_OAuthProviderId",
table: "Users",
column: "OAuthProviderId",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_OAuthProviderId",
table: "Users");
}
}
}

View File

@@ -0,0 +1,77 @@
// <auto-generated />
using System;
using FictionArchive.Service.UserService.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NodaTime;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FictionArchive.Service.UserService.Migrations
{
[DbContext(typeof(UserServiceDbContext))]
partial class UserServiceDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Instant>("CreatedTime")
.HasColumnType("timestamp with time zone");
b.Property<bool>("Disabled")
.HasColumnType("boolean");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("InviterId")
.HasColumnType("uuid");
b.Property<Instant>("LastUpdatedTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("OAuthProviderId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("InviterId");
b.HasIndex("OAuthProviderId")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("FictionArchive.Service.UserService.Models.Database.User", b =>
{
b.HasOne("FictionArchive.Service.UserService.Models.Database.User", "Inviter")
.WithMany()
.HasForeignKey("InviterId");
b.Navigation("Inviter");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,20 @@
using FictionArchive.Service.Shared.Models;
using Microsoft.EntityFrameworkCore;
namespace FictionArchive.Service.UserService.Models.Database;
[Index(nameof(OAuthProviderId), IsUnique = true)]
public class User : BaseEntity<Guid>
{
public string Username { get; set; }
public string Email { get; set; }
public string OAuthProviderId { get; set; }
public bool Disabled { get; set; }
/// <summary>
/// The user that generated an invite used by this user.
/// </summary>
public User? Inviter { get; set; }
}

View File

@@ -0,0 +1,16 @@
using FictionArchive.Service.Shared.Services.EventBus;
namespace FictionArchive.Service.UserService.Models.IntegrationEvents;
public class AuthUserAddedEvent : IIntegrationEvent
{
public string OAuthProviderId { get; set; }
public string InviterOAuthProviderId { get; set; }
// The email of the user that created the event
public string EventUserEmail { get; set; }
// The username of the user that created the event
public string EventUserUsername { get; set; }
}

View File

@@ -0,0 +1,52 @@
using FictionArchive.Service.Shared.Extensions;
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
using FictionArchive.Service.UserService.GraphQL;
using FictionArchive.Service.UserService.Models.IntegrationEvents;
using FictionArchive.Service.UserService.Services;
using FictionArchive.Service.UserService.Services.EventHandlers;
namespace FictionArchive.Service.UserService;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
#region Event Bus
builder.Services.AddRabbitMQ(opt =>
{
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
})
.Subscribe<AuthUserAddedEvent, AuthUserAddedEventHandler>();
#endregion
#region GraphQL
builder.Services.AddDefaultGraphQl<Query, Mutation>();
#endregion
builder.Services.RegisterDbContext<UserServiceDbContext>(builder.Configuration.GetConnectionString("DefaultConnection"));
builder.Services.AddTransient<UserManagementService>();
builder.Services.AddHealthChecks();
var app = builder.Build();
// Update database
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<UserServiceDbContext>();
dbContext.UpdateDatabase();
}
app.MapGraphQL();
app.MapHealthChecks("/healthz");
app.RunWithGraphQLCommands(args);
}
}

View File

@@ -0,0 +1,39 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:20480",
"sslPort": 44309
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5145",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "graphql",
"applicationUrl": "https://localhost:7157;http://localhost:5145",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,23 @@
using FictionArchive.Service.Shared.Services.EventBus;
using FictionArchive.Service.UserService.Models.IntegrationEvents;
using FictionArchive.Service.UserService.Models.Database;
using Microsoft.EntityFrameworkCore; // Add this line to include the UserModel
namespace FictionArchive.Service.UserService.Services.EventHandlers;
public class AuthUserAddedEventHandler : IIntegrationEventHandler<AuthUserAddedEvent>
{
private readonly UserManagementService _userManagementService;
private readonly ILogger<AuthUserAddedEventHandler> _logger;
public AuthUserAddedEventHandler(UserServiceDbContext dbContext, ILogger<AuthUserAddedEventHandler> logger, UserManagementService userManagementService)
{
_logger = logger;
_userManagementService = userManagementService;
}
public async Task Handle(AuthUserAddedEvent @event)
{
await _userManagementService.RegisterUser(@event.EventUserUsername, @event.EventUserEmail, @event.OAuthProviderId, @event.InviterOAuthProviderId);
}
}

View File

@@ -0,0 +1,45 @@
using FictionArchive.Service.UserService.Models.Database;
using Microsoft.EntityFrameworkCore;
namespace FictionArchive.Service.UserService.Services;
public class UserManagementService
{
private readonly ILogger<UserManagementService> _logger;
private readonly UserServiceDbContext _dbContext;
public UserManagementService(UserServiceDbContext dbContext, ILogger<UserManagementService> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task<User> RegisterUser(string username, string email, string oAuthProviderId,
string? inviterOAuthProviderId)
{
var newUser = new User();
User? inviter =
await _dbContext.Users.FirstOrDefaultAsync(user => user.OAuthProviderId == inviterOAuthProviderId);
if (inviter == null && inviterOAuthProviderId != null)
{
_logger.LogCritical(
"A user with OAuthProviderId {OAuthProviderId} was marked as having inviter with OAuthProviderId {inviterOAuthProviderId}, but no user was found with that value.",
inviterOAuthProviderId, inviterOAuthProviderId);
newUser.Disabled = true;
}
newUser.Username = username;
newUser.Email = email;
newUser.OAuthProviderId = oAuthProviderId;
_dbContext.Users.Add(newUser); // Add the new user to the DbContext
await _dbContext.SaveChangesAsync(); // Save changes to the database
return newUser;
}
public IQueryable<User> GetUsers()
{
return _dbContext.Users.AsQueryable();
}
}

View File

@@ -0,0 +1,14 @@
using FictionArchive.Service.Shared.Services.Database;
using FictionArchive.Service.UserService.Models.Database;
using Microsoft.EntityFrameworkCore;
namespace FictionArchive.Service.UserService.Services;
public class UserServiceDbContext : FictionArchiveDbContext
{
public DbSet<User> Users { get; set; }
public UserServiceDbContext(DbContextOptions options, ILogger<UserServiceDbContext> logger) : base(options, logger)
{
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,16 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=FictionArchive_UserService;Username=postgres;password=postgres"
},
"RabbitMQ": {
"ConnectionString": "amqp://localhost",
"ClientIdentifier": "UserService"
},
"AllowedHosts": "*"
}

View File

@@ -0,0 +1,6 @@
{
"subgraph": "User",
"http": {
"baseAddress": "http://localhost:5145/graphql"
}
}

View File

@@ -12,6 +12,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.Shar
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.SchedulerService", "FictionArchive.Service.SchedulerService\FictionArchive.Service.SchedulerService.csproj", "{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.SchedulerService", "FictionArchive.Service.SchedulerService\FictionArchive.Service.SchedulerService.csproj", "{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.UserService", "FictionArchive.Service.UserService\FictionArchive.Service.UserService.csproj", "{EE4D4795-2F79-4614-886D-AF8DA77120AC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.AuthenticationService", "FictionArchive.Service.AuthenticationService\FictionArchive.Service.AuthenticationService.csproj", "{70C4AE82-B01E-421D-B590-C0F47E63CD0C}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -42,5 +46,13 @@ Global
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Debug|Any CPU.Build.0 = Debug|Any CPU {6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Release|Any CPU.ActiveCfg = Release|Any CPU {6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Release|Any CPU.Build.0 = Release|Any CPU {6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Release|Any CPU.Build.0 = Release|Any CPU
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EE4D4795-2F79-4614-886D-AF8DA77120AC}.Release|Any CPU.Build.0 = Release|Any CPU
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{70C4AE82-B01E-421D-B590-C0F47E63CD0C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal