82 lines
2.9 KiB
C#
82 lines
2.9 KiB
C#
using Butter.Types;
|
|
using Lactose.Context;
|
|
using Lactose.Models;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Lactose.Repositories;
|
|
|
|
/// <inheritdoc />
|
|
public class JobRecordRepository(LactoseDbContext context) : IJobRecordRepository {
|
|
/// <inheritdoc />
|
|
public void Insert(JobRecord job) {
|
|
job.ModifiedAt = DateTime.UtcNow;
|
|
context.JobRecords.Add(job);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public void Update(JobRecord job) {
|
|
job.ModifiedAt = DateTime.UtcNow;
|
|
context.JobRecords.Update(job);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task<List<JobRecord>> GetAllAsync(CancellationToken cancellationToken) =>
|
|
context.JobRecords
|
|
.OrderByDescending(j => j.Finished ?? j.Created)
|
|
.ToListAsync(cancellationToken);
|
|
|
|
static readonly EJobStatus[] PastStatuses = [EJobStatus.Completed, EJobStatus.CompletedWithErrors, EJobStatus.Failed, EJobStatus.Canceled];
|
|
|
|
/// <inheritdoc />
|
|
public async Task<(List<JobRecord> Jobs, int Total)> GetPastRootJobsAsync(int page, int pageSize, CancellationToken cancellationToken) {
|
|
var query = context.JobRecords
|
|
.Where(j => j.ParentJobId == null && PastStatuses.Contains(j.Status));
|
|
|
|
var total = await query.CountAsync(cancellationToken);
|
|
|
|
var jobs = await query
|
|
.OrderByDescending(j => j.Finished ?? j.Created)
|
|
.Skip(page * pageSize)
|
|
.Take(pageSize)
|
|
.ToListAsync(cancellationToken);
|
|
|
|
return (jobs, total);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task<List<JobRecord>> GetChildrenAsync(Guid parentId, CancellationToken cancellationToken) =>
|
|
context.JobRecords
|
|
.Where(j => j.ParentJobId == parentId)
|
|
.OrderBy(j => j.Created)
|
|
.ToListAsync(cancellationToken);
|
|
|
|
/// <inheritdoc />
|
|
public Task<List<JobRecord>> GetChildrenModifiedSinceAsync(Guid parentId, DateTime since, CancellationToken cancellationToken) =>
|
|
context.JobRecords
|
|
.Where(j => j.ParentJobId == parentId && j.ModifiedAt != null && j.ModifiedAt > since)
|
|
.OrderBy(j => j.Created)
|
|
.ToListAsync(cancellationToken);
|
|
|
|
/// <inheritdoc />
|
|
public async Task<JobRecord?> GetByIdAsync(Guid id, CancellationToken cancellationToken) =>
|
|
await context.JobRecords.FindAsync([id], cancellationToken);
|
|
|
|
/// <inheritdoc />
|
|
public async Task<int> DeleteOldJobsAsync(DateTime cutoff, CancellationToken cancellationToken) {
|
|
var old = await context.JobRecords
|
|
.Where(j => j.Finished != null && j.Finished < cutoff)
|
|
.ToListAsync(cancellationToken);
|
|
var count = old.Count;
|
|
if (count > 0) {
|
|
context.JobRecords.RemoveRange(old);
|
|
}
|
|
return count;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task SaveAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken);
|
|
|
|
/// <inheritdoc />
|
|
public void Dispose() => context.Dispose();
|
|
}
|