Skip to content

Commit

Permalink
migrate to using a db context defined in LcmCrdt instead of one provi…
Browse files Browse the repository at this point in the history
…ded by Harmony
  • Loading branch information
hahn-kev committed Jul 9, 2024
1 parent 6f03d24 commit 9989f13
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 37 deletions.
4 changes: 2 additions & 2 deletions backend/LcmCrdt.Tests/LexboxApiTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class BasicApiTests : IAsyncLifetime

protected readonly AsyncServiceScope _services;
public DataModel DataModel = null!;
private readonly CrdtDbContext _crdtDbContext;
private readonly LcmCrdtDbContext _crdtDbContext;

public BasicApiTests()
{
Expand All @@ -30,7 +30,7 @@ public BasicApiTests()
.AddSingleton<ProjectContext>(new MockProjectContext(new CrdtProject("sena-3", ":memory:")))
.BuildServiceProvider();
_services = services.CreateAsyncScope();
_crdtDbContext = _services.ServiceProvider.GetRequiredService<CrdtDbContext>();
_crdtDbContext = _services.ServiceProvider.GetRequiredService<LcmCrdtDbContext>();
}

public virtual async Task InitializeAsync()
Expand Down
4 changes: 2 additions & 2 deletions backend/LcmCrdt/CurrentProjectService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace LcmCrdt;

public class CurrentProjectService(CrdtDbContext dbContext, ProjectContext projectContext, IMemoryCache memoryCache)
public class CurrentProjectService(LcmCrdtDbContext dbContext, ProjectContext projectContext, IMemoryCache memoryCache)
{
public CrdtProject Project =>
projectContext.Project ?? throw new NullReferenceException("Not in the context of a project");
Expand All @@ -19,7 +19,7 @@ public async ValueTask<ProjectData> GetProjectData()
{
using var entry = memoryCache.CreateEntry(key);
entry.SlidingExpiration = TimeSpan.FromMinutes(10);
result = await dbContext.Set<ProjectData>().AsNoTracking().FirstAsync();
result = await dbContext.ProjectData.AsNoTracking().FirstAsync();
entry.Value = result;
}
if (result is null) throw new InvalidOperationException("Project data not found");
Expand Down
37 changes: 37 additions & 0 deletions backend/LcmCrdt/LcmCrdtDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System.Text.Json;
using Crdt;
using Crdt.Db;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.Extensions.Options;

namespace LcmCrdt;

public class LcmCrdtDbContext(IOptions<CrdtConfig> options): DbContext, ICrdtDbContext
{
public DbSet<ProjectData> ProjectData => Set<ProjectData>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.UseCrdt(options.Value);

modelBuilder.Entity<ProjectData>().HasKey(p => p.Id);
}

protected override void ConfigureConventions(ModelConfigurationBuilder builder)
{
builder.Properties<MiniLcm.MultiString>()
.HaveColumnType("jsonb")
.HaveConversion<MultiStringDbConverter>();
builder.Properties<MiniLcm.WritingSystemId>()
.HaveConversion<WritingSystemIdConverter>();
}

private class MultiStringDbConverter() : ValueConverter<MiniLcm.MultiString, string>(
mul => JsonSerializer.Serialize(mul, (JsonSerializerOptions?)null),
json => JsonSerializer.Deserialize<MiniLcm.MultiString>(json, (JsonSerializerOptions?)null) ?? new());

private class WritingSystemIdConverter() : ValueConverter<MiniLcm.WritingSystemId, string>(
id => id.Code,
code => new MiniLcm.WritingSystemId(code));
}
27 changes: 3 additions & 24 deletions backend/LcmCrdt/LcmCrdtKernel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ public static IServiceCollection AddLcmCrdtClient(this IServiceCollection servic
{
LinqToDBForEFTools.Initialize();
services.AddMemoryCache();
services.AddDbContext<LcmCrdtDbContext>(ConfigureDbOptions);

services.AddCrdtData(
ConfigureDbOptions,
services.AddCrdtData<LcmCrdtDbContext>(
ConfigureCrdt
);
services.AddScoped<MiniLcm.ILexboxApi, CrdtLexboxApi>();
Expand Down Expand Up @@ -61,19 +61,7 @@ private static void ConfigureDbOptions(IServiceProvider provider, DbContextOptio
private static void ConfigureCrdt(CrdtConfig config)
{
config.EnableProjectedTables = true;
config.ObjectTypeListBuilder.AddDbModelConfig(builder =>
{
builder.Entity<ProjectData>().HasKey(p => p.Id);
// builder.Owned<MultiString>();
})
.AddDbModelConvention(builder =>
{
builder.Properties<MiniLcm.MultiString>()
.HaveColumnType("jsonb")
.HaveConversion<MultiStringDbConverter>();
builder.Properties<MiniLcm.WritingSystemId>()
.HaveConversion<WritingSystemIdConverter>();
})
config.ObjectTypeListBuilder
.Add<Entry>(builder =>
{
// builder.OwnsOne(e => e.Note, n => n.ToJson());
Expand Down Expand Up @@ -127,13 +115,4 @@ private static void ConfigureCrdt(CrdtConfig config)
.Add<CreateSemanticDomainChange>()
.Add<CreateWritingSystemChange>();
}


private class MultiStringDbConverter() : ValueConverter<MiniLcm.MultiString, string>(
mul => JsonSerializer.Serialize(mul, (JsonSerializerOptions?)null),
json => JsonSerializer.Deserialize<MiniLcm.MultiString>(json, (JsonSerializerOptions?)null) ?? new());

private class WritingSystemIdConverter() : ValueConverter<MiniLcm.WritingSystemId, string>(
id => id.Code,
code => new MiniLcm.WritingSystemId(code));
}
6 changes: 3 additions & 3 deletions backend/LcmCrdt/ProjectsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public async Task<CrdtProject> CreateProject(string name,
if (File.Exists(sqliteFile)) throw new InvalidOperationException("Project already exists");
var crdtProject = new CrdtProject(name, sqliteFile);
await using var serviceScope = CreateProjectScope(crdtProject);
var db = serviceScope.ServiceProvider.GetRequiredService<CrdtDbContext>();
var db = serviceScope.ServiceProvider.GetRequiredService<LcmCrdtDbContext>();
var projectData = new ProjectData(name, id ?? Guid.NewGuid(), ProjectData.GetOriginDomain(domain), Guid.NewGuid());
await InitProjectDb(db, projectData);
await serviceScope.ServiceProvider.GetRequiredService<CurrentProjectService>().PopulateProjectDataCache();
Expand All @@ -47,10 +47,10 @@ public async Task<CrdtProject> CreateProject(string name,
return crdtProject;
}

internal static async Task InitProjectDb(CrdtDbContext db, ProjectData data)
internal static async Task InitProjectDb(LcmCrdtDbContext db, ProjectData data)
{
await db.Database.EnsureCreatedAsync();
db.Set<ProjectData>().Add(data);
db.ProjectData.Add(data);
await db.SaveChangesAsync();
}

Expand Down
3 changes: 2 additions & 1 deletion backend/LocalWebApp/Routes/ActivityRoutes.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Crdt.Changes;
using Crdt.Core;
using Crdt.Db;
using LcmCrdt;
using LocalWebApp.Hubs;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
Expand All @@ -22,7 +23,7 @@ public static IEndpointConventionBuilder MapActivities(this WebApplication app)
return operation;
});
group.MapGet("/",
(CrdtDbContext dbcontext) =>
(ICrdtDbContext dbcontext) =>
{
return dbcontext.Commits.DefaultOrder().Take(10).Select(c => new Activity(c.Id, c.HybridDateTime.DateTime, ChangeName(c.ChangeEntities), c.ChangeEntities)).AsAsyncEnumerable();
});
Expand Down
6 changes: 3 additions & 3 deletions backend/LocalWebApp/Routes/HistoryRoutes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static IEndpointConventionBuilder MapHistoryRoutes(this WebApplication ap
return operation;
});
group.MapGet("/snapshot/{snapshotId:guid}",
async (Guid snapshotId, CrdtDbContext dbcontext) =>
async (Guid snapshotId, ICrdtDbContext dbcontext) =>
{
return await dbcontext.Snapshots.Where(s => s.Id == snapshotId).SingleOrDefaultAsync();
});
Expand All @@ -35,12 +35,12 @@ public static IEndpointConventionBuilder MapHistoryRoutes(this WebApplication ap
return await dataModel.GetEntitySnapshotAtTime(new DateTimeOffset(timestamp), entityId);
});
group.MapGet("/{entityId}",
(Guid entityId, CrdtDbContext dbcontext) =>
(Guid entityId, ICrdtDbContext dbcontext) =>
{
var query = from commit in dbcontext.Commits.DefaultOrder()
from snapshot in dbcontext.Snapshots.LeftJoin(
s => s.CommitId == commit.Id && s.EntityId == entityId)
from change in dbcontext.ChangeEntities.LeftJoin(c =>
from change in dbcontext.Set<ChangeEntity<IChange>>().LeftJoin(c =>
c.CommitId == commit.Id && c.EntityId == entityId)
where snapshot.Id != null || change.EntityId != null
select new HistoryLineItem(commit.Id,
Expand Down
3 changes: 1 addition & 2 deletions backend/LocalWebApp/Routes/TestRoutes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@ public static IEndpointConventionBuilder MapTest(this WebApplication app)
return operation;
});
group.MapGet("/entries",
(CrdtDbContext dbContext, ILexboxApi api) =>
(ILexboxApi api) =>
{
return api.GetEntries();
return dbContext.Set<Entry>().Take(1000).AsAsyncEnumerable();
});
return group;
}
Expand Down

0 comments on commit 9989f13

Please sign in to comment.