9 Commits

76 changed files with 3082 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

@@ -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.SchedulerService/FictionArchive.Service.SchedulerService.csproj", "FictionArchive.Service.SchedulerService/"]
RUN dotnet restore "FictionArchive.Service.SchedulerService/FictionArchive.Service.SchedulerService.csproj"
COPY . .
WORKDIR "/src/FictionArchive.Service.SchedulerService"
RUN dotnet build "./FictionArchive.Service.SchedulerService.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./FictionArchive.Service.SchedulerService.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.SchedulerService.dll"]

View File

@@ -0,0 +1,32 @@
<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="AppAny.Quartz.EntityFrameworkCore.Migrations.PostgreSQL" Version="0.5.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Quartz" Version="3.15.1" />
<PackageReference Include="Quartz.AspNetCore" Version="3.15.1" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.15.1" />
<PackageReference Include="Quartz.Serialization.Json" Version="3.15.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,35 @@
using System.Data;
using FictionArchive.Service.SchedulerService.Models;
using FictionArchive.Service.SchedulerService.Services;
using HotChocolate.Types;
using Quartz;
namespace FictionArchive.Service.SchedulerService.GraphQL;
public class Mutation
{
[Error<DuplicateNameException>]
[Error<FormatException>]
public async Task<SchedulerJob> ScheduleEventJob(string key, string description, string eventType, string eventData, string cronSchedule, JobManagerService jobManager)
{
return await jobManager.ScheduleEventJob(key, description, eventType, eventData, cronSchedule);
}
[Error<JobPersistenceException>]
public async Task<bool> RunJob(string jobKey, JobManagerService jobManager)
{
return await jobManager.TriggerJob(jobKey);
}
[Error<KeyNotFoundException>]
public async Task<bool> DeleteJob(string jobKey, JobManagerService jobManager)
{
bool deleted = await jobManager.DeleteJob(jobKey);
if (!deleted)
{
throw new KeyNotFoundException($"Job with key '{jobKey}' was not found");
}
return true;
}
}

View File

@@ -0,0 +1,15 @@
using FictionArchive.Service.SchedulerService.Models;
using FictionArchive.Service.SchedulerService.Services;
using HotChocolate;
using Quartz;
using Quartz.Impl.Matchers;
namespace FictionArchive.Service.SchedulerService.GraphQL;
public class Query
{
public async Task<IEnumerable<SchedulerJob>> GetJobs(JobManagerService jobManager)
{
return await jobManager.GetScheduledJobs();
}
}

View File

@@ -0,0 +1,543 @@
// <auto-generated />
using FictionArchive.Service.SchedulerService.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FictionArchive.Service.SchedulerService.Migrations
{
[DbContext(typeof(SchedulerServiceDbContext))]
[Migration("20251120151130_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("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzBlobTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<byte[]>("BlobData")
.HasColumnType("bytea")
.HasColumnName("blob_data");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.ToTable("qrtz_blob_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzCalendar", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("CalendarName")
.HasColumnType("text")
.HasColumnName("calendar_name");
b.Property<byte[]>("Calendar")
.IsRequired()
.HasColumnType("bytea")
.HasColumnName("calendar");
b.HasKey("SchedulerName", "CalendarName");
b.ToTable("qrtz_calendars", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzCronTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<string>("CronExpression")
.IsRequired()
.HasColumnType("text")
.HasColumnName("cron_expression");
b.Property<string>("TimeZoneId")
.HasColumnType("text")
.HasColumnName("time_zone_id");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.ToTable("qrtz_cron_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzFiredTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("EntryId")
.HasColumnType("text")
.HasColumnName("entry_id");
b.Property<long>("FiredTime")
.HasColumnType("bigint")
.HasColumnName("fired_time");
b.Property<string>("InstanceName")
.IsRequired()
.HasColumnType("text")
.HasColumnName("instance_name");
b.Property<bool>("IsNonConcurrent")
.HasColumnType("bool")
.HasColumnName("is_nonconcurrent");
b.Property<string>("JobGroup")
.HasColumnType("text")
.HasColumnName("job_group");
b.Property<string>("JobName")
.HasColumnType("text")
.HasColumnName("job_name");
b.Property<int>("Priority")
.HasColumnType("integer")
.HasColumnName("priority");
b.Property<bool?>("RequestsRecovery")
.HasColumnType("bool")
.HasColumnName("requests_recovery");
b.Property<long>("ScheduledTime")
.HasColumnType("bigint")
.HasColumnName("sched_time");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text")
.HasColumnName("state");
b.Property<string>("TriggerGroup")
.IsRequired()
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<string>("TriggerName")
.IsRequired()
.HasColumnType("text")
.HasColumnName("trigger_name");
b.HasKey("SchedulerName", "EntryId");
b.HasIndex("InstanceName")
.HasDatabaseName("idx_qrtz_ft_trig_inst_name");
b.HasIndex("JobGroup")
.HasDatabaseName("idx_qrtz_ft_job_group");
b.HasIndex("JobName")
.HasDatabaseName("idx_qrtz_ft_job_name");
b.HasIndex("RequestsRecovery")
.HasDatabaseName("idx_qrtz_ft_job_req_recovery");
b.HasIndex("TriggerGroup")
.HasDatabaseName("idx_qrtz_ft_trig_group");
b.HasIndex("TriggerName")
.HasDatabaseName("idx_qrtz_ft_trig_name");
b.HasIndex("SchedulerName", "TriggerName", "TriggerGroup")
.HasDatabaseName("idx_qrtz_ft_trig_nm_gp");
b.ToTable("qrtz_fired_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzJobDetail", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("JobName")
.HasColumnType("text")
.HasColumnName("job_name");
b.Property<string>("JobGroup")
.HasColumnType("text")
.HasColumnName("job_group");
b.Property<string>("Description")
.HasColumnType("text")
.HasColumnName("description");
b.Property<bool>("IsDurable")
.HasColumnType("bool")
.HasColumnName("is_durable");
b.Property<bool>("IsNonConcurrent")
.HasColumnType("bool")
.HasColumnName("is_nonconcurrent");
b.Property<bool>("IsUpdateData")
.HasColumnType("bool")
.HasColumnName("is_update_data");
b.Property<string>("JobClassName")
.IsRequired()
.HasColumnType("text")
.HasColumnName("job_class_name");
b.Property<byte[]>("JobData")
.HasColumnType("bytea")
.HasColumnName("job_data");
b.Property<bool>("RequestsRecovery")
.HasColumnType("bool")
.HasColumnName("requests_recovery");
b.HasKey("SchedulerName", "JobName", "JobGroup");
b.HasIndex("RequestsRecovery")
.HasDatabaseName("idx_qrtz_j_req_recovery");
b.ToTable("qrtz_job_details", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzLock", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("LockName")
.HasColumnType("text")
.HasColumnName("lock_name");
b.HasKey("SchedulerName", "LockName");
b.ToTable("qrtz_locks", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzPausedTriggerGroup", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.HasKey("SchedulerName", "TriggerGroup");
b.ToTable("qrtz_paused_trigger_grps", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSchedulerState", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("InstanceName")
.HasColumnType("text")
.HasColumnName("instance_name");
b.Property<long>("CheckInInterval")
.HasColumnType("bigint")
.HasColumnName("checkin_interval");
b.Property<long>("LastCheckInTime")
.HasColumnType("bigint")
.HasColumnName("last_checkin_time");
b.HasKey("SchedulerName", "InstanceName");
b.ToTable("qrtz_scheduler_state", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSimplePropertyTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<bool?>("BooleanProperty1")
.HasColumnType("bool")
.HasColumnName("bool_prop_1");
b.Property<bool?>("BooleanProperty2")
.HasColumnType("bool")
.HasColumnName("bool_prop_2");
b.Property<decimal?>("DecimalProperty1")
.HasColumnType("numeric")
.HasColumnName("dec_prop_1");
b.Property<decimal?>("DecimalProperty2")
.HasColumnType("numeric")
.HasColumnName("dec_prop_2");
b.Property<int?>("IntegerProperty1")
.HasColumnType("integer")
.HasColumnName("int_prop_1");
b.Property<int?>("IntegerProperty2")
.HasColumnType("integer")
.HasColumnName("int_prop_2");
b.Property<long?>("LongProperty1")
.HasColumnType("bigint")
.HasColumnName("long_prop_1");
b.Property<long?>("LongProperty2")
.HasColumnType("bigint")
.HasColumnName("long_prop_2");
b.Property<string>("StringProperty1")
.HasColumnType("text")
.HasColumnName("str_prop_1");
b.Property<string>("StringProperty2")
.HasColumnType("text")
.HasColumnName("str_prop_2");
b.Property<string>("StringProperty3")
.HasColumnType("text")
.HasColumnName("str_prop_3");
b.Property<string>("TimeZoneId")
.HasColumnType("text")
.HasColumnName("time_zone_id");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.ToTable("qrtz_simprop_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSimpleTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<long>("RepeatCount")
.HasColumnType("bigint")
.HasColumnName("repeat_count");
b.Property<long>("RepeatInterval")
.HasColumnType("bigint")
.HasColumnName("repeat_interval");
b.Property<long>("TimesTriggered")
.HasColumnType("bigint")
.HasColumnName("times_triggered");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.ToTable("qrtz_simple_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<string>("CalendarName")
.HasColumnType("text")
.HasColumnName("calendar_name");
b.Property<string>("Description")
.HasColumnType("text")
.HasColumnName("description");
b.Property<long?>("EndTime")
.HasColumnType("bigint")
.HasColumnName("end_time");
b.Property<byte[]>("JobData")
.HasColumnType("bytea")
.HasColumnName("job_data");
b.Property<string>("JobGroup")
.IsRequired()
.HasColumnType("text")
.HasColumnName("job_group");
b.Property<string>("JobName")
.IsRequired()
.HasColumnType("text")
.HasColumnName("job_name");
b.Property<short?>("MisfireInstruction")
.HasColumnType("smallint")
.HasColumnName("misfire_instr");
b.Property<long?>("NextFireTime")
.HasColumnType("bigint")
.HasColumnName("next_fire_time");
b.Property<long?>("PreviousFireTime")
.HasColumnType("bigint")
.HasColumnName("prev_fire_time");
b.Property<int?>("Priority")
.HasColumnType("integer")
.HasColumnName("priority");
b.Property<long>("StartTime")
.HasColumnType("bigint")
.HasColumnName("start_time");
b.Property<string>("TriggerState")
.IsRequired()
.HasColumnType("text")
.HasColumnName("trigger_state");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("text")
.HasColumnName("trigger_type");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.HasIndex("NextFireTime")
.HasDatabaseName("idx_qrtz_t_next_fire_time");
b.HasIndex("TriggerState")
.HasDatabaseName("idx_qrtz_t_state");
b.HasIndex("NextFireTime", "TriggerState")
.HasDatabaseName("idx_qrtz_t_nft_st");
b.HasIndex("SchedulerName", "JobName", "JobGroup");
b.ToTable("qrtz_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzBlobTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", "Trigger")
.WithMany("BlobTriggers")
.HasForeignKey("SchedulerName", "TriggerName", "TriggerGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Trigger");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzCronTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", "Trigger")
.WithMany("CronTriggers")
.HasForeignKey("SchedulerName", "TriggerName", "TriggerGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Trigger");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSimplePropertyTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", "Trigger")
.WithMany("SimplePropertyTriggers")
.HasForeignKey("SchedulerName", "TriggerName", "TriggerGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Trigger");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSimpleTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", "Trigger")
.WithMany("SimpleTriggers")
.HasForeignKey("SchedulerName", "TriggerName", "TriggerGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Trigger");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzJobDetail", "JobDetail")
.WithMany("Triggers")
.HasForeignKey("SchedulerName", "JobName", "JobGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("JobDetail");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzJobDetail", b =>
{
b.Navigation("Triggers");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", b =>
{
b.Navigation("BlobTriggers");
b.Navigation("CronTriggers");
b.Navigation("SimplePropertyTriggers");
b.Navigation("SimpleTriggers");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,373 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FictionArchive.Service.SchedulerService.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.EnsureSchema(
name: "quartz");
migrationBuilder.CreateTable(
name: "qrtz_calendars",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
calendar_name = table.Column<string>(type: "text", nullable: false),
calendar = table.Column<byte[]>(type: "bytea", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_calendars", x => new { x.sched_name, x.calendar_name });
});
migrationBuilder.CreateTable(
name: "qrtz_fired_triggers",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
entry_id = table.Column<string>(type: "text", nullable: false),
trigger_name = table.Column<string>(type: "text", nullable: false),
trigger_group = table.Column<string>(type: "text", nullable: false),
instance_name = table.Column<string>(type: "text", nullable: false),
fired_time = table.Column<long>(type: "bigint", nullable: false),
sched_time = table.Column<long>(type: "bigint", nullable: false),
priority = table.Column<int>(type: "integer", nullable: false),
state = table.Column<string>(type: "text", nullable: false),
job_name = table.Column<string>(type: "text", nullable: true),
job_group = table.Column<string>(type: "text", nullable: true),
is_nonconcurrent = table.Column<bool>(type: "bool", nullable: false),
requests_recovery = table.Column<bool>(type: "bool", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_fired_triggers", x => new { x.sched_name, x.entry_id });
});
migrationBuilder.CreateTable(
name: "qrtz_job_details",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
job_name = table.Column<string>(type: "text", nullable: false),
job_group = table.Column<string>(type: "text", nullable: false),
description = table.Column<string>(type: "text", nullable: true),
job_class_name = table.Column<string>(type: "text", nullable: false),
is_durable = table.Column<bool>(type: "bool", nullable: false),
is_nonconcurrent = table.Column<bool>(type: "bool", nullable: false),
is_update_data = table.Column<bool>(type: "bool", nullable: false),
requests_recovery = table.Column<bool>(type: "bool", nullable: false),
job_data = table.Column<byte[]>(type: "bytea", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_job_details", x => new { x.sched_name, x.job_name, x.job_group });
});
migrationBuilder.CreateTable(
name: "qrtz_locks",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
lock_name = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_locks", x => new { x.sched_name, x.lock_name });
});
migrationBuilder.CreateTable(
name: "qrtz_paused_trigger_grps",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
trigger_group = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_paused_trigger_grps", x => new { x.sched_name, x.trigger_group });
});
migrationBuilder.CreateTable(
name: "qrtz_scheduler_state",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
instance_name = table.Column<string>(type: "text", nullable: false),
last_checkin_time = table.Column<long>(type: "bigint", nullable: false),
checkin_interval = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_scheduler_state", x => new { x.sched_name, x.instance_name });
});
migrationBuilder.CreateTable(
name: "qrtz_triggers",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
trigger_name = table.Column<string>(type: "text", nullable: false),
trigger_group = table.Column<string>(type: "text", nullable: false),
job_name = table.Column<string>(type: "text", nullable: false),
job_group = table.Column<string>(type: "text", nullable: false),
description = table.Column<string>(type: "text", nullable: true),
next_fire_time = table.Column<long>(type: "bigint", nullable: true),
prev_fire_time = table.Column<long>(type: "bigint", nullable: true),
priority = table.Column<int>(type: "integer", nullable: true),
trigger_state = table.Column<string>(type: "text", nullable: false),
trigger_type = table.Column<string>(type: "text", nullable: false),
start_time = table.Column<long>(type: "bigint", nullable: false),
end_time = table.Column<long>(type: "bigint", nullable: true),
calendar_name = table.Column<string>(type: "text", nullable: true),
misfire_instr = table.Column<short>(type: "smallint", nullable: true),
job_data = table.Column<byte[]>(type: "bytea", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_triggers", x => new { x.sched_name, x.trigger_name, x.trigger_group });
table.ForeignKey(
name: "FK_qrtz_triggers_qrtz_job_details_sched_name_job_name_job_group",
columns: x => new { x.sched_name, x.job_name, x.job_group },
principalSchema: "quartz",
principalTable: "qrtz_job_details",
principalColumns: new[] { "sched_name", "job_name", "job_group" },
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "qrtz_blob_triggers",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
trigger_name = table.Column<string>(type: "text", nullable: false),
trigger_group = table.Column<string>(type: "text", nullable: false),
blob_data = table.Column<byte[]>(type: "bytea", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_blob_triggers", x => new { x.sched_name, x.trigger_name, x.trigger_group });
table.ForeignKey(
name: "FK_qrtz_blob_triggers_qrtz_triggers_sched_name_trigger_name_tr~",
columns: x => new { x.sched_name, x.trigger_name, x.trigger_group },
principalSchema: "quartz",
principalTable: "qrtz_triggers",
principalColumns: new[] { "sched_name", "trigger_name", "trigger_group" },
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "qrtz_cron_triggers",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
trigger_name = table.Column<string>(type: "text", nullable: false),
trigger_group = table.Column<string>(type: "text", nullable: false),
cron_expression = table.Column<string>(type: "text", nullable: false),
time_zone_id = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_cron_triggers", x => new { x.sched_name, x.trigger_name, x.trigger_group });
table.ForeignKey(
name: "FK_qrtz_cron_triggers_qrtz_triggers_sched_name_trigger_name_tr~",
columns: x => new { x.sched_name, x.trigger_name, x.trigger_group },
principalSchema: "quartz",
principalTable: "qrtz_triggers",
principalColumns: new[] { "sched_name", "trigger_name", "trigger_group" },
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "qrtz_simple_triggers",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
trigger_name = table.Column<string>(type: "text", nullable: false),
trigger_group = table.Column<string>(type: "text", nullable: false),
repeat_count = table.Column<long>(type: "bigint", nullable: false),
repeat_interval = table.Column<long>(type: "bigint", nullable: false),
times_triggered = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_simple_triggers", x => new { x.sched_name, x.trigger_name, x.trigger_group });
table.ForeignKey(
name: "FK_qrtz_simple_triggers_qrtz_triggers_sched_name_trigger_name_~",
columns: x => new { x.sched_name, x.trigger_name, x.trigger_group },
principalSchema: "quartz",
principalTable: "qrtz_triggers",
principalColumns: new[] { "sched_name", "trigger_name", "trigger_group" },
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "qrtz_simprop_triggers",
schema: "quartz",
columns: table => new
{
sched_name = table.Column<string>(type: "text", nullable: false),
trigger_name = table.Column<string>(type: "text", nullable: false),
trigger_group = table.Column<string>(type: "text", nullable: false),
str_prop_1 = table.Column<string>(type: "text", nullable: true),
str_prop_2 = table.Column<string>(type: "text", nullable: true),
str_prop_3 = table.Column<string>(type: "text", nullable: true),
int_prop_1 = table.Column<int>(type: "integer", nullable: true),
int_prop_2 = table.Column<int>(type: "integer", nullable: true),
long_prop_1 = table.Column<long>(type: "bigint", nullable: true),
long_prop_2 = table.Column<long>(type: "bigint", nullable: true),
dec_prop_1 = table.Column<decimal>(type: "numeric", nullable: true),
dec_prop_2 = table.Column<decimal>(type: "numeric", nullable: true),
bool_prop_1 = table.Column<bool>(type: "bool", nullable: true),
bool_prop_2 = table.Column<bool>(type: "bool", nullable: true),
time_zone_id = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_qrtz_simprop_triggers", x => new { x.sched_name, x.trigger_name, x.trigger_group });
table.ForeignKey(
name: "FK_qrtz_simprop_triggers_qrtz_triggers_sched_name_trigger_name~",
columns: x => new { x.sched_name, x.trigger_name, x.trigger_group },
principalSchema: "quartz",
principalTable: "qrtz_triggers",
principalColumns: new[] { "sched_name", "trigger_name", "trigger_group" },
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "idx_qrtz_ft_job_group",
schema: "quartz",
table: "qrtz_fired_triggers",
column: "job_group");
migrationBuilder.CreateIndex(
name: "idx_qrtz_ft_job_name",
schema: "quartz",
table: "qrtz_fired_triggers",
column: "job_name");
migrationBuilder.CreateIndex(
name: "idx_qrtz_ft_job_req_recovery",
schema: "quartz",
table: "qrtz_fired_triggers",
column: "requests_recovery");
migrationBuilder.CreateIndex(
name: "idx_qrtz_ft_trig_group",
schema: "quartz",
table: "qrtz_fired_triggers",
column: "trigger_group");
migrationBuilder.CreateIndex(
name: "idx_qrtz_ft_trig_inst_name",
schema: "quartz",
table: "qrtz_fired_triggers",
column: "instance_name");
migrationBuilder.CreateIndex(
name: "idx_qrtz_ft_trig_name",
schema: "quartz",
table: "qrtz_fired_triggers",
column: "trigger_name");
migrationBuilder.CreateIndex(
name: "idx_qrtz_ft_trig_nm_gp",
schema: "quartz",
table: "qrtz_fired_triggers",
columns: new[] { "sched_name", "trigger_name", "trigger_group" });
migrationBuilder.CreateIndex(
name: "idx_qrtz_j_req_recovery",
schema: "quartz",
table: "qrtz_job_details",
column: "requests_recovery");
migrationBuilder.CreateIndex(
name: "idx_qrtz_t_next_fire_time",
schema: "quartz",
table: "qrtz_triggers",
column: "next_fire_time");
migrationBuilder.CreateIndex(
name: "idx_qrtz_t_nft_st",
schema: "quartz",
table: "qrtz_triggers",
columns: new[] { "next_fire_time", "trigger_state" });
migrationBuilder.CreateIndex(
name: "idx_qrtz_t_state",
schema: "quartz",
table: "qrtz_triggers",
column: "trigger_state");
migrationBuilder.CreateIndex(
name: "IX_qrtz_triggers_sched_name_job_name_job_group",
schema: "quartz",
table: "qrtz_triggers",
columns: new[] { "sched_name", "job_name", "job_group" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "qrtz_blob_triggers",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_calendars",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_cron_triggers",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_fired_triggers",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_locks",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_paused_trigger_grps",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_scheduler_state",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_simple_triggers",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_simprop_triggers",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_triggers",
schema: "quartz");
migrationBuilder.DropTable(
name: "qrtz_job_details",
schema: "quartz");
}
}
}

View File

@@ -0,0 +1,540 @@
// <auto-generated />
using FictionArchive.Service.SchedulerService.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FictionArchive.Service.SchedulerService.Migrations
{
[DbContext(typeof(SchedulerServiceDbContext))]
partial class SchedulerServiceDbContextModelSnapshot : 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("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzBlobTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<byte[]>("BlobData")
.HasColumnType("bytea")
.HasColumnName("blob_data");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.ToTable("qrtz_blob_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzCalendar", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("CalendarName")
.HasColumnType("text")
.HasColumnName("calendar_name");
b.Property<byte[]>("Calendar")
.IsRequired()
.HasColumnType("bytea")
.HasColumnName("calendar");
b.HasKey("SchedulerName", "CalendarName");
b.ToTable("qrtz_calendars", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzCronTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<string>("CronExpression")
.IsRequired()
.HasColumnType("text")
.HasColumnName("cron_expression");
b.Property<string>("TimeZoneId")
.HasColumnType("text")
.HasColumnName("time_zone_id");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.ToTable("qrtz_cron_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzFiredTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("EntryId")
.HasColumnType("text")
.HasColumnName("entry_id");
b.Property<long>("FiredTime")
.HasColumnType("bigint")
.HasColumnName("fired_time");
b.Property<string>("InstanceName")
.IsRequired()
.HasColumnType("text")
.HasColumnName("instance_name");
b.Property<bool>("IsNonConcurrent")
.HasColumnType("bool")
.HasColumnName("is_nonconcurrent");
b.Property<string>("JobGroup")
.HasColumnType("text")
.HasColumnName("job_group");
b.Property<string>("JobName")
.HasColumnType("text")
.HasColumnName("job_name");
b.Property<int>("Priority")
.HasColumnType("integer")
.HasColumnName("priority");
b.Property<bool?>("RequestsRecovery")
.HasColumnType("bool")
.HasColumnName("requests_recovery");
b.Property<long>("ScheduledTime")
.HasColumnType("bigint")
.HasColumnName("sched_time");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text")
.HasColumnName("state");
b.Property<string>("TriggerGroup")
.IsRequired()
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<string>("TriggerName")
.IsRequired()
.HasColumnType("text")
.HasColumnName("trigger_name");
b.HasKey("SchedulerName", "EntryId");
b.HasIndex("InstanceName")
.HasDatabaseName("idx_qrtz_ft_trig_inst_name");
b.HasIndex("JobGroup")
.HasDatabaseName("idx_qrtz_ft_job_group");
b.HasIndex("JobName")
.HasDatabaseName("idx_qrtz_ft_job_name");
b.HasIndex("RequestsRecovery")
.HasDatabaseName("idx_qrtz_ft_job_req_recovery");
b.HasIndex("TriggerGroup")
.HasDatabaseName("idx_qrtz_ft_trig_group");
b.HasIndex("TriggerName")
.HasDatabaseName("idx_qrtz_ft_trig_name");
b.HasIndex("SchedulerName", "TriggerName", "TriggerGroup")
.HasDatabaseName("idx_qrtz_ft_trig_nm_gp");
b.ToTable("qrtz_fired_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzJobDetail", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("JobName")
.HasColumnType("text")
.HasColumnName("job_name");
b.Property<string>("JobGroup")
.HasColumnType("text")
.HasColumnName("job_group");
b.Property<string>("Description")
.HasColumnType("text")
.HasColumnName("description");
b.Property<bool>("IsDurable")
.HasColumnType("bool")
.HasColumnName("is_durable");
b.Property<bool>("IsNonConcurrent")
.HasColumnType("bool")
.HasColumnName("is_nonconcurrent");
b.Property<bool>("IsUpdateData")
.HasColumnType("bool")
.HasColumnName("is_update_data");
b.Property<string>("JobClassName")
.IsRequired()
.HasColumnType("text")
.HasColumnName("job_class_name");
b.Property<byte[]>("JobData")
.HasColumnType("bytea")
.HasColumnName("job_data");
b.Property<bool>("RequestsRecovery")
.HasColumnType("bool")
.HasColumnName("requests_recovery");
b.HasKey("SchedulerName", "JobName", "JobGroup");
b.HasIndex("RequestsRecovery")
.HasDatabaseName("idx_qrtz_j_req_recovery");
b.ToTable("qrtz_job_details", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzLock", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("LockName")
.HasColumnType("text")
.HasColumnName("lock_name");
b.HasKey("SchedulerName", "LockName");
b.ToTable("qrtz_locks", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzPausedTriggerGroup", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.HasKey("SchedulerName", "TriggerGroup");
b.ToTable("qrtz_paused_trigger_grps", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSchedulerState", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("InstanceName")
.HasColumnType("text")
.HasColumnName("instance_name");
b.Property<long>("CheckInInterval")
.HasColumnType("bigint")
.HasColumnName("checkin_interval");
b.Property<long>("LastCheckInTime")
.HasColumnType("bigint")
.HasColumnName("last_checkin_time");
b.HasKey("SchedulerName", "InstanceName");
b.ToTable("qrtz_scheduler_state", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSimplePropertyTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<bool?>("BooleanProperty1")
.HasColumnType("bool")
.HasColumnName("bool_prop_1");
b.Property<bool?>("BooleanProperty2")
.HasColumnType("bool")
.HasColumnName("bool_prop_2");
b.Property<decimal?>("DecimalProperty1")
.HasColumnType("numeric")
.HasColumnName("dec_prop_1");
b.Property<decimal?>("DecimalProperty2")
.HasColumnType("numeric")
.HasColumnName("dec_prop_2");
b.Property<int?>("IntegerProperty1")
.HasColumnType("integer")
.HasColumnName("int_prop_1");
b.Property<int?>("IntegerProperty2")
.HasColumnType("integer")
.HasColumnName("int_prop_2");
b.Property<long?>("LongProperty1")
.HasColumnType("bigint")
.HasColumnName("long_prop_1");
b.Property<long?>("LongProperty2")
.HasColumnType("bigint")
.HasColumnName("long_prop_2");
b.Property<string>("StringProperty1")
.HasColumnType("text")
.HasColumnName("str_prop_1");
b.Property<string>("StringProperty2")
.HasColumnType("text")
.HasColumnName("str_prop_2");
b.Property<string>("StringProperty3")
.HasColumnType("text")
.HasColumnName("str_prop_3");
b.Property<string>("TimeZoneId")
.HasColumnType("text")
.HasColumnName("time_zone_id");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.ToTable("qrtz_simprop_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSimpleTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<long>("RepeatCount")
.HasColumnType("bigint")
.HasColumnName("repeat_count");
b.Property<long>("RepeatInterval")
.HasColumnType("bigint")
.HasColumnName("repeat_interval");
b.Property<long>("TimesTriggered")
.HasColumnType("bigint")
.HasColumnName("times_triggered");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.ToTable("qrtz_simple_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", b =>
{
b.Property<string>("SchedulerName")
.HasColumnType("text")
.HasColumnName("sched_name");
b.Property<string>("TriggerName")
.HasColumnType("text")
.HasColumnName("trigger_name");
b.Property<string>("TriggerGroup")
.HasColumnType("text")
.HasColumnName("trigger_group");
b.Property<string>("CalendarName")
.HasColumnType("text")
.HasColumnName("calendar_name");
b.Property<string>("Description")
.HasColumnType("text")
.HasColumnName("description");
b.Property<long?>("EndTime")
.HasColumnType("bigint")
.HasColumnName("end_time");
b.Property<byte[]>("JobData")
.HasColumnType("bytea")
.HasColumnName("job_data");
b.Property<string>("JobGroup")
.IsRequired()
.HasColumnType("text")
.HasColumnName("job_group");
b.Property<string>("JobName")
.IsRequired()
.HasColumnType("text")
.HasColumnName("job_name");
b.Property<short?>("MisfireInstruction")
.HasColumnType("smallint")
.HasColumnName("misfire_instr");
b.Property<long?>("NextFireTime")
.HasColumnType("bigint")
.HasColumnName("next_fire_time");
b.Property<long?>("PreviousFireTime")
.HasColumnType("bigint")
.HasColumnName("prev_fire_time");
b.Property<int?>("Priority")
.HasColumnType("integer")
.HasColumnName("priority");
b.Property<long>("StartTime")
.HasColumnType("bigint")
.HasColumnName("start_time");
b.Property<string>("TriggerState")
.IsRequired()
.HasColumnType("text")
.HasColumnName("trigger_state");
b.Property<string>("TriggerType")
.IsRequired()
.HasColumnType("text")
.HasColumnName("trigger_type");
b.HasKey("SchedulerName", "TriggerName", "TriggerGroup");
b.HasIndex("NextFireTime")
.HasDatabaseName("idx_qrtz_t_next_fire_time");
b.HasIndex("TriggerState")
.HasDatabaseName("idx_qrtz_t_state");
b.HasIndex("NextFireTime", "TriggerState")
.HasDatabaseName("idx_qrtz_t_nft_st");
b.HasIndex("SchedulerName", "JobName", "JobGroup");
b.ToTable("qrtz_triggers", "quartz");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzBlobTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", "Trigger")
.WithMany("BlobTriggers")
.HasForeignKey("SchedulerName", "TriggerName", "TriggerGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Trigger");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzCronTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", "Trigger")
.WithMany("CronTriggers")
.HasForeignKey("SchedulerName", "TriggerName", "TriggerGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Trigger");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSimplePropertyTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", "Trigger")
.WithMany("SimplePropertyTriggers")
.HasForeignKey("SchedulerName", "TriggerName", "TriggerGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Trigger");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzSimpleTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", "Trigger")
.WithMany("SimpleTriggers")
.HasForeignKey("SchedulerName", "TriggerName", "TriggerGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Trigger");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", b =>
{
b.HasOne("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzJobDetail", "JobDetail")
.WithMany("Triggers")
.HasForeignKey("SchedulerName", "JobName", "JobGroup")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("JobDetail");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzJobDetail", b =>
{
b.Navigation("Triggers");
});
modelBuilder.Entity("AppAny.Quartz.EntityFrameworkCore.Migrations.QuartzTrigger", b =>
{
b.Navigation("BlobTriggers");
b.Navigation("CronTriggers");
b.Navigation("SimplePropertyTriggers");
b.Navigation("SimpleTriggers");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,35 @@
using FictionArchive.Service.Shared.Services.EventBus;
using Newtonsoft.Json;
using Quartz;
namespace FictionArchive.Service.SchedulerService.Models.JobTemplates;
public class EventJobTemplate : IJob
{
private readonly IEventBus _eventBus;
private readonly ILogger<EventJobTemplate> _logger;
public const string EventTypeParameter = "RoutingKey";
public const string EventDataParameter = "MessageData";
public EventJobTemplate(IEventBus eventBus, ILogger<EventJobTemplate> logger)
{
_eventBus = eventBus;
_logger = logger;
}
public async Task Execute(IJobExecutionContext context)
{
try
{
var eventData = context.MergedJobDataMap.GetString(EventDataParameter);
var eventType = context.MergedJobDataMap.GetString(EventTypeParameter);
var eventObject = JsonConvert.DeserializeObject(eventData);
await _eventBus.Publish(eventObject, eventType);
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while running an event job.");
}
}
}

View File

@@ -0,0 +1,12 @@
using Quartz;
namespace FictionArchive.Service.SchedulerService.Models;
public class SchedulerJob
{
public JobKey JobKey { get; set; }
public string Description { get; set; }
public string JobTypeName { get; set; }
public List<string> CronSchedule { get; set; }
public Dictionary<string, string> JobData { get; set; }
}

View File

@@ -0,0 +1,74 @@
using FictionArchive.Service.SchedulerService.GraphQL;
using FictionArchive.Service.SchedulerService.Services;
using FictionArchive.Service.Shared.Extensions;
using FictionArchive.Service.Shared.Services.EventBus.Implementations;
using Quartz;
using Quartz.Impl.AdoJobStore;
namespace FictionArchive.Service.SchedulerService;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Services
builder.Services.AddDefaultGraphQl<Query, Mutation>();
builder.Services.AddHealthChecks();
builder.Services.AddTransient<JobManagerService>();
#region Database
builder.Services.RegisterDbContext<SchedulerServiceDbContext>(builder.Configuration.GetConnectionString("DefaultConnection"));
#endregion
#region Event Bus
builder.Services.AddRabbitMQ(opt =>
{
builder.Configuration.GetSection("RabbitMQ").Bind(opt);
});
#endregion
#region Quartz
builder.Services.AddQuartz(opt =>
{
opt.UsePersistentStore(pso =>
{
pso.UsePostgres(pgsql =>
{
pgsql.ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
pgsql.UseDriverDelegate<PostgreSQLDelegate>();
pgsql.TablePrefix = "quartz.qrtz_"; // Needed for Postgres due to the differing schema used
});
pso.UseNewtonsoftJsonSerializer();
});
});
builder.Services.AddQuartzHostedService(opt =>
{
opt.WaitForJobsToComplete = true;
});
#endregion
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<SchedulerServiceDbContext>();
dbContext.UpdateDatabase();
}
app.UseHttpsRedirection();
app.MapHealthChecks("/healthz");
app.MapGraphQL();
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:61312",
"sslPort": 44365
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5213",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "graphql",
"applicationUrl": "https://localhost:7145;http://localhost:5213",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,99 @@
using System.Data;
using FictionArchive.Service.SchedulerService.Models;
using FictionArchive.Service.SchedulerService.Models.JobTemplates;
using FictionArchive.Service.Shared.Services.EventBus;
using Quartz;
using Quartz.Impl.Matchers;
namespace FictionArchive.Service.SchedulerService.Services;
public class JobManagerService
{
private readonly ILogger<JobManagerService> _logger;
private readonly ISchedulerFactory _schedulerFactory;
public JobManagerService(ILogger<JobManagerService> logger, ISchedulerFactory schedulerFactory)
{
_logger = logger;
_schedulerFactory = schedulerFactory;
}
public async Task<List<SchedulerJob>> GetScheduledJobs()
{
var scheduler = await _schedulerFactory.GetScheduler();
var groups = await scheduler.GetJobGroupNames();
var result = new List<(IJobDetail Job, IReadOnlyCollection<ITrigger> Triggers)>();
foreach (var group in groups)
{
var jobKeys = await scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(group));
foreach (var jobKey in jobKeys)
{
var jobDetail = await scheduler.GetJobDetail(jobKey);
var triggers = await scheduler.GetTriggersOfJob(jobKey);
result.Add((jobDetail, triggers));
}
}
return result.Select(tuple => new SchedulerJob()
{
JobKey = tuple.Job.Key,
Description = tuple.Job.Description,
JobTypeName = tuple.Job.JobType.FullName,
JobData = tuple.Job.JobDataMap.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()),
CronSchedule = tuple.Triggers.Where(trigger => trigger is ICronTrigger).Select(trigger => (trigger as ICronTrigger).CronExpressionString).ToList()
}).ToList();
}
public async Task<SchedulerJob> ScheduleEventJob(string? jobKey, string? description, string eventType, string eventData, string cronSchedule)
{
var scheduler = await _schedulerFactory.GetScheduler();
if (await scheduler.GetJobDetail(new JobKey(jobKey)) != null)
{
throw new DuplicateNameException("A job with the same key already exists.");
}
jobKey ??= Guid.NewGuid().ToString();
var jobData = new JobDataMap
{
{ EventJobTemplate.EventTypeParameter, eventType },
{ EventJobTemplate.EventDataParameter, eventData }
};
var job = JobBuilder.Create<EventJobTemplate>()
.WithIdentity(jobKey)
.WithDescription(description ?? $"Fires off an event on a set schedule")
.SetJobData(jobData)
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity(jobKey)
.WithCronSchedule(cronSchedule)
.StartNow()
.Build();
await scheduler.ScheduleJob(job, trigger);
return new SchedulerJob()
{
CronSchedule = new List<string> { cronSchedule },
Description = description,
JobKey = new JobKey(jobKey),
JobTypeName = typeof(EventJobTemplate).FullName,
JobData = jobData.ToDictionary(kv => kv.Key, kv => kv.Value.ToString())
};
}
public async Task<bool> TriggerJob(string jobKey)
{
var scheduler = await _schedulerFactory.GetScheduler();
await scheduler.TriggerJob(new JobKey(jobKey));
return true;
}
public async Task<bool> DeleteJob(string jobKey)
{
var scheduler = await _schedulerFactory.GetScheduler();
return await scheduler.DeleteJob(new JobKey(jobKey));
}
}

View File

@@ -0,0 +1,19 @@
using AppAny.Quartz.EntityFrameworkCore.Migrations;
using AppAny.Quartz.EntityFrameworkCore.Migrations.PostgreSQL;
using FictionArchive.Service.Shared.Services.Database;
using Microsoft.EntityFrameworkCore;
namespace FictionArchive.Service.SchedulerService.Services;
public class SchedulerServiceDbContext : FictionArchiveDbContext
{
public SchedulerServiceDbContext(DbContextOptions options, ILogger<SchedulerServiceDbContext> logger) : base(options, logger)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddQuartz(builder => builder.UsePostgreSql());
base.OnModelCreating(modelBuilder);
}
}

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"
}
},
"RabbitMQ": {
"ConnectionString": "amqp://localhost",
"ClientIdentifier": "SchedulerService"
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=FictionArchive_SchedulerService;Username=postgres;password=postgres"
},
"AllowedHosts": "*"
}

View File

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

View File

@@ -10,14 +10,21 @@ public static class GraphQLExtensions
public static IRequestExecutorBuilder AddDefaultGraphQl<TQuery, TMutation>(this IServiceCollection services) where TQuery : class where TMutation : class public static IRequestExecutorBuilder AddDefaultGraphQl<TQuery, TMutation>(this IServiceCollection services) where TQuery : class where TMutation : class
{ {
return services.AddGraphQLServer() return services.AddGraphQLServer()
.AddQueryType<TQuery>() .AddQueryType<TQuery>()
.AddMutationType<TMutation>() .AddMutationType<TMutation>()
.AddDiagnosticEventListener<ErrorEventListener>() .ApplySaneDefaults();
.AddType<UnsignedIntType>()
.AddType<InstantType>() }
.AddMutationConventions(applyToAllMutations: true)
.AddFiltering(opt => opt.AddDefaults().BindRuntimeType<uint, UnsignedIntOperationFilterInputType>()) public static IRequestExecutorBuilder ApplySaneDefaults(this IRequestExecutorBuilder builder)
.AddSorting() {
.AddProjections(); return builder.AddDiagnosticEventListener<ErrorEventListener>()
.AddErrorFilter<LoggingErrorFilter>()
.AddType<UnsignedIntType>()
.AddType<InstantType>()
.AddMutationConventions(applyToAllMutations: true)
.AddFiltering(opt => opt.AddDefaults().BindRuntimeType<uint, UnsignedIntOperationFilterInputType>())
.AddSorting()
.AddProjections();
} }
} }

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,5 +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);
} }

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,18 +35,28 @@ 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;
await Publish(integrationEvent, routingKey);
}
public async Task Publish(object integrationEvent, string eventType)
{
var channel = await _connectionProvider.GetDefaultChannelAsync(); var channel = await _connectionProvider.GetDefaultChannelAsync();
// Set integration event values
integrationEvent.CreatedAt = Instant.FromDateTimeUtc(DateTime.UtcNow);
integrationEvent.EventId = Guid.NewGuid();
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(integrationEvent)); var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(integrationEvent));
await channel.BasicPublishAsync(ExchangeName, routingKey, true, body);
_logger.LogInformation("Published event {EventName}", routingKey); // 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);
} }
public async Task StartAsync(CancellationToken cancellationToken) public async Task StartAsync(CancellationToken cancellationToken)
@@ -65,14 +77,14 @@ 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,
cancellationToken: cancellationToken); cancellationToken: cancellationToken);
_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.");
} }
@@ -101,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

@@ -0,0 +1,23 @@
using Microsoft.Extensions.Logging;
namespace FictionArchive.Service.Shared.Services.GraphQL;
public class LoggingErrorFilter : IErrorFilter
{
private readonly ILogger<LoggingErrorFilter> _logger;
public LoggingErrorFilter(ILogger<LoggingErrorFilter> logger)
{
_logger = logger;
}
public IError OnError(IError error)
{
if (error.Exception != null)
{
_logger.LogError(error.Exception, "Unexpected GraphQL error occurred");
}
return error;
}
}

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

@@ -10,6 +10,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.Tran
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.Shared", "FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj", "{82638874-304C-43E6-8EFA-8AD4C41C4435}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.Shared", "FictionArchive.Service.Shared\FictionArchive.Service.Shared.csproj", "{82638874-304C-43E6-8EFA-8AD4C41C4435}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FictionArchive.Service.SchedulerService", "FictionArchive.Service.SchedulerService\FictionArchive.Service.SchedulerService.csproj", "{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}"
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
@@ -36,5 +42,17 @@ Global
{82638874-304C-43E6-8EFA-8AD4C41C4435}.Debug|Any CPU.Build.0 = Debug|Any CPU {82638874-304C-43E6-8EFA-8AD4C41C4435}.Debug|Any CPU.Build.0 = Debug|Any CPU
{82638874-304C-43E6-8EFA-8AD4C41C4435}.Release|Any CPU.ActiveCfg = Release|Any CPU {82638874-304C-43E6-8EFA-8AD4C41C4435}.Release|Any CPU.ActiveCfg = Release|Any CPU
{82638874-304C-43E6-8EFA-8AD4C41C4435}.Release|Any CPU.Build.0 = Release|Any CPU {82638874-304C-43E6-8EFA-8AD4C41C4435}.Release|Any CPU.Build.0 = Release|Any CPU
{6813A8AD-A071-4F86-B227-BC4A5BCD7F3C}.Debug|Any CPU.ActiveCfg = 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.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