Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/content-migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ A command runs before any hosted service starts, so nothing migrates on start, l
| `fluentcms schema snapshot [--output <file>]` | The canonical snapshot of the host's schema, whose SHA-256 is the schema hash. |
| `fluentcms schema validate [--schema <file>]` | Builds the host's schema, or a schema file, and prints every `FCMS12xx` error; exits with 1 when there is one (`FCMS3320`). A schema file is checked by the tool without a host, with core's field types, unless `--project` or `--assembly` is given. |
| `fluentcms schema diff --applied \| --schema <file> [--json]` | What differs from the schema in the newest row of the schema history, or from a schema file, to the host's schema, and from the history to a file with both. Destructive changes are marked and possible renames suggested; exits with 1 when anything differs (`FCMS3322`), so CI can gate a deploy. |
| `fluentcms schema apply [--script [--output <file>]] [--dry-run] [--allow-destructive]` | For a host whose types are data and so have no content migrations, such as the [Docker image](docker.md#apply-a-schema-file) with a schema file: compares the schema with the content tables, applies the difference in one transaction (on SQLite, committed in parts around a table rebuild) and records the schema in the schema history, on every provider. A renamed field with `formerNames` keeps its values and its references, as in a content migration, and a rename whose values are kept in JSON counts as lost; a change that loses data is refused (`FCMS3337`) unless `--allow-destructive` is given. The tables of a plugin the host does not add, whose history table the database has, are left alone and listed, and so is a content text column whose collation is not the model's (`C` on PostgreSQL, `Latin1_General_100_BIN2` on SQL Server), such as one of a table made before `1.0.0-preview.2` on PostgreSQL: its sort follows the collation it has until it is altered by hand. `--dry-run` prints the operations, and `--script` writes their SQL, applying nothing. It refuses a host with content migrations (`FCMS3335`) and runs after `fluentcms migrate` (`FCMS3336`). |
| `fluentcms schema apply [--script [--output <file>]] [--dry-run] [--allow-destructive]` | For a host whose types are data and so have no content migrations, such as the [Docker image](docker.md#apply-a-schema-file) with a schema file: compares the schema with the content tables, applies the difference in one transaction (on SQLite, committed in parts around a table rebuild) and records the schema in the schema history, on every provider. A renamed field with `formerNames` keeps its values and its references, as in a content migration, and a rename whose values are kept in JSON counts as lost; a change that loses data is refused (`FCMS3337`) unless `--allow-destructive` is given. The tables of a plugin the host does not add, whose history table the database has, are left alone and listed, and so is a content text column whose collation is not the model's (`C` on PostgreSQL, `Latin1_General_100_BIN2` on SQL Server), such as one of a table made before `1.0.0-preview.2` on PostgreSQL: its sort follows the collation it has until it is altered by hand. An index of expressions made by hand on a content table is left alone too, but on SQLite a run that rebuilds the table, which `--script` shows as `CREATE TABLE "ef_temp_..."`, makes it again from the model, so the index is lost: make it again after the run. `--dry-run` prints the operations, and `--script` writes their SQL, applying nothing. It refuses a host with content migrations (`FCMS3335`) and runs after `fluentcms migrate` (`FCMS3336`). |
| `fluentcms doctor [--json]` | The startup report without starting the host: providers, plugins, assemblies, pending migrations, schema drift and insecure defaults. Exits with 1 when the host would not start (`FCMS3325`) or a migration is pending (`FCMS3303`). |

`schema snapshot`, `schema diff` and `doctor` also take `--url <url>` with a management API key in `--token` or `FLUENTCMS_TOKEN`: the snapshot and the diagnostics of a running instance, and the diff from that instance to the host's schema, or to a schema file with `--schema`. The key needs `schema.read` for the schema and `system.read` for `doctor`.
Expand Down
4 changes: 2 additions & 2 deletions docs/planning/backend-technical-spec.md

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions docs/plugin-migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ public sealed class WebhooksDbContextFactory : IDesignTimeDbContextFactory<Plugi

The factory names every model contributor the plugin adds. It never opens a database. The startup project references `Microsoft.EntityFrameworkCore.Design` with `PrivateAssets` set to `all`. A missing or unknown set name stops the command with the names it takes.

## Names of the model

The tables and views a model contributor maps are named `cms_{plugin}_...`, or the host stops with `FCMS1523`. Each name of the model has at most 63 bytes in UTF-8, the most of a name PostgreSQL keeps, or the host stops in `AddFluentCms` with `FCMS1529`, on every provider ([#3533](https://github.com/fluentcms/FluentCMS/issues/3533)). That holds for each table, view, column, key, foreign key, index and check constraint, with the name the model gives or else the one EF derives, such as `IX_{table}_{columns}` for an index given none. EF cuts a name it derives to 63 characters, which is 63 bytes only in ASCII, so a derived name built from names with other characters can be refused although each name the model gives fits. The refusal then says that EF derived the name and which call gives a shorter one: `HasColumnName`, `HasName` for a key, `HasConstraintName` for a foreign key or `HasDatabaseName` for an index ([#3562](https://github.com/fluentcms/FluentCMS/issues/3562)).

EF cuts a check constraint's given name of more than 63 characters to 63 in the same way before it is measured, so a longer ASCII name passes and PostgreSQL keeps it cut, ending in `~`. Give a check constraint a name of at most 63 bytes to keep the one you chose.

The check maps the contributor on a model without EF's conventions, so what only the conventions find or make is not measured: a property that no call of the contributor configures, and the foreign key that links the table of a TPT type or of an entity splitting fragment to the table it extends, such as `FK_{table}_{main table}_{key}`.

Without conventions that model also has two names that EF never emits, so they are left out ([#3562](https://github.com/fluentcms/FluentCMS/issues/3562)). This is where an owned type maps to its owner's table, or a type maps to its principal's table with a foreign key on its own primary key to the principal's (table splitting): the two types are one row. EF emits no foreign key for that link, and it maps the dependent's key to the principal's key columns, whose names the principal's measure. The model without conventions still has the foreign key, such as `FK_{table}_{table}_OrderId`, and gives an owned type a key column of its own, such as `Address_OrderId`. Every other foreign key is measured: one to another table, an owned type's on a table of its own included, and one to the same table on other columns, such as a parent reference.

## Adding a migration

You need the `dotnet-ef` tool (`dotnet tool install --global dotnet-ef`).
Expand Down
6 changes: 3 additions & 3 deletions src/FluentCMS.Core/Caching/DatabaseDistributedLock.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System.Data.Common;
using FluentCMS.Core.Jobs;
using FluentCMS.Core.DependencyInjection;
using FluentCMS.Core.Storage;
using FluentCMS.Core.Storage.Entities;
using FluentCMS.Providers;
Expand Down Expand Up @@ -406,11 +406,11 @@ public async ValueTask DisposeAsync()
// then, not under one still running.
try
{
await _owner.WaitAsync(loss, JobRunner.DisposeWait);
await _owner.WaitAsync(loss, DisposeWait.Bound);
}
catch (TimeoutException)
{
LockLog.LostCallbackSlow(_owner.Logger, Name, JobRunner.DisposeWait);
LockLog.LostCallbackSlow(_owner.Logger, Name, DisposeWait.Bound);
_ = loss.ContinueWith(_ => _lost.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
return;
}
Expand Down
8 changes: 8 additions & 0 deletions src/FluentCMS.Core/DependencyInjection/DisposeWait.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace FluentCMS.Core.DependencyInjection;

// How long a disposal waits for the work it stops, the job runner's loops or the callbacks on a lock's Lost, before it
// returns without them (#3544).
internal static class DisposeWait
{
public static readonly TimeSpan Bound = TimeSpan.FromSeconds(5);
}
5 changes: 2 additions & 3 deletions src/FluentCMS.Core/Jobs/JobRunner.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using FluentCMS.Core.DependencyInjection;
using FluentCMS.Core.Health;
using FluentCMS.Core.Telemetry;
using FluentCMS.Jobs;
Expand All @@ -15,8 +16,6 @@ internal sealed class JobRunner(
TimeProvider time,
ILogger<JobRunner> logger) : IJobRunner, IDisposable
{
internal static readonly TimeSpan DisposeWait = TimeSpan.FromSeconds(5);

private readonly CancellationTokenSource _stopping = new();

// One for each worker, whose callbacks CancelAsync runs as a thread-pool work item of their own: a job's await can end
Expand Down Expand Up @@ -99,7 +98,7 @@ public void Dispose()

try
{
if (_loops?.Wait(DisposeWait) == false)
if (_loops?.Wait(DisposeWait.Bound) == false)
{
return;
}
Expand Down
92 changes: 71 additions & 21 deletions src/FluentCMS.Core/Plugins/PluginStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,25 +84,54 @@ public IReadOnlyList<string> AddModel(IPluginModelContributor contributor, Func<
// tables, columns and indexes of the model by name, would not find them. Refused on every provider, so that a plugin that
// runs on SQLite does not fail on PostgreSQL later (#3533). The names are read as EF gives them on PostgreSQL: the model
// has its limit of 63, so a name EF derives, such as IX_..., is cut as EF cuts it there, by characters, and one with
// characters of more than a byte can still be too long.
// characters of more than a byte can still be too long. EF cuts a check constraint's given name the same way.
private void CheckLengths(IPluginModelContributor contributor, IMutableEntityType entity)
{
foreach (var (what, name) in NamesOnPostgreSql(entity))
foreach (var name in NamesOnPostgreSql(entity))
{
var bytes = Encoding.UTF8.GetByteCount(name);
if (bytes > StorageNames.MaxIdentifierLength)
var bytes = Encoding.UTF8.GetByteCount(name.Value);
if (bytes <= StorageNames.MaxIdentifierLength)
{
throw new FluentCmsConfigurationException(
PluginErrorCodes.NameTooLong,
$"The plugin '{plugin.Name}' ({plugin.Type.FullName}) gives {what} of {entity.DisplayName()} the name '{name}' in {contributor.GetType().FullName}, which has {bytes} bytes in UTF-8; a name has at most {StorageNames.MaxIdentifierLength}, as PostgreSQL keeps no more of it.");
continue;
}

var where = $"The plugin '{plugin.Name}' ({plugin.Type.FullName}) gives {name.What} of {entity.DisplayName()}";
var limit = $"a name has at most {StorageNames.MaxIdentifierLength}, as PostgreSQL keeps no more of it";
throw new FluentCmsConfigurationException(
PluginErrorCodes.NameTooLong,
name.Call is { } call ? $"{where} no name in {contributor.GetType().FullName}, and the name EF derives for it, '{name.Value}', has {bytes} bytes in UTF-8; {limit}. Give it a shorter one with {call}."
: name.Given is { } given ? $"{where} the name '{given}' in {contributor.GetType().FullName}, which EF cuts to '{name.Value}', of {bytes} bytes in UTF-8; {limit}."
: $"{where} the name '{name.Value}' in {contributor.GetType().FullName}, which has {bytes} bytes in UTF-8; {limit}.");
}
}

// A name as EF emits it. Call is how the model gives one where EF derives it, and Given the name the model gives where EF
// cuts it.
private readonly record struct StoreName(string What, string Value, string? Call = null, string? Given = null)
{
public static StoreName Of(string what, string value, string? derived, string call) =>
new(what, value, value == derived ? call : null);
}

// Each table or view the entity maps to, the fragments of entity splitting and the tables of TPT and TPC included, with
// the columns, keys and indexes it has there, so that a column named for one table alone is read too.
private static IEnumerable<(string What, string Name)> NamesOnPostgreSql(IMutableEntityType entity)
// the columns, keys and indexes it has there, so that a column named for one table alone is read too. The foreign keys
// that EF adds to link the table of a TPT type or an entity splitting fragment to the main table are made by conventions
// only, so they are not on this model and not measured.
private static IEnumerable<StoreName> NamesOnPostgreSql(IMutableEntityType entity)
{
// An owned type on its owner's table, or a type split from its principal's table by a foreign key on its own key, is
// one row with its principal: EF emits no foreign key for that link and maps its properties to the principal's key
// columns, which the principal's names hold. Without conventions the model still has the foreign key, and an owned
// type a key column of its own, such as Address_OrderId, so both are left out here. A foreign key to another table,
// an owned type's on a table of its own included, or to the same table on other columns, is measured.
var table = StoreObjectIdentifier.Create(entity, StoreObjectType.Table);
var links = entity.GetDeclaredForeignKeys()
.Where(foreignKey => table is { } shared
&& StoreObjectIdentifier.Create(foreignKey.PrincipalEntityType, StoreObjectType.Table) == shared
&& (foreignKey.IsOwnership || (foreignKey.PrincipalKey.IsPrimaryKey() && entity.FindPrimaryKey()?.Properties.SequenceEqual(foreignKey.Properties) == true)))
.ToList();
var linkColumns = links.SelectMany(foreignKey => foreignKey.Properties).ToHashSet<IReadOnlyProperty>();

List<StoreObjectIdentifier> stores = [];
foreach (var type in new[] { StoreObjectType.Table, StoreObjectType.View })
{
Expand All @@ -115,38 +144,59 @@ private void CheckLengths(IPluginModelContributor contributor, IMutableEntityTyp
stores.AddRange(entity.GetMappingFragments().Select(fragment => fragment.StoreObject));
foreach (var store in stores.Distinct())
{
yield return (store.StoreObjectType == StoreObjectType.View ? "the view" : "the table", store.Name);
yield return new(store.StoreObjectType == StoreObjectType.View ? "the view" : "the table", store.Name);

foreach (var column in Properties(entity).Select(property => property.GetColumnName(store)).OfType<string>())
foreach (var property in Properties(entity))
{
yield return ("the column", column);
if (store == table && linkColumns.Contains(property))
{
continue;
}

if (property.GetColumnName(store) is { } column)
{
yield return StoreName.Of("the column", column, property.GetDefaultColumnName(store), "HasColumnName");
}
}

if (store.StoreObjectType != StoreObjectType.Table)
{
continue;
}

foreach (var key in entity.GetKeys().Select(key => key.GetName(store)).OfType<string>())
foreach (var key in entity.GetKeys())
{
yield return ("the key", key);
if (key.GetName(store) is { } name)
{
yield return StoreName.Of("the key", name, key.GetDefaultName(store), "HasName");
}
}

foreach (var index in entity.GetIndexes().Select(index => index.GetDatabaseName(store)).OfType<string>())
foreach (var index in entity.GetIndexes())
{
yield return ("the index", index);
if (index.GetDatabaseName(store) is { } name)
{
yield return StoreName.Of("the index", name, index.GetDefaultDatabaseName(store), "HasDatabaseName");
}
}
}

foreach (var foreignKey in entity.GetDeclaredForeignKeys().Select(foreignKey => foreignKey.GetConstraintName()).OfType<string>())
foreach (var foreignKey in entity.GetDeclaredForeignKeys().Except(links))
{
yield return ("the foreign key", foreignKey);
if (foreignKey.GetConstraintName() is { } name)
{
yield return StoreName.Of("the foreign key", name, foreignKey.GetDefaultName(), "HasConstraintName");
}
}

// The name given, or else the one EF derives from the model's name.
foreach (var check in entity.GetDeclaredCheckConstraints().Select(check => check.Name).OfType<string>())
// A check constraint always has a name given, and EF cuts one of more than 63 characters to 63 as it cuts a name it
// derives, so an ASCII name of more passes, as PostgreSQL would keep it cut.
foreach (var check in entity.GetDeclaredCheckConstraints())
{
yield return ("the check constraint", check);
if (check.Name is { } name)
{
yield return new("the check constraint", name, Given: name != check.ModelName && name == check.GetDefaultName() ? check.ModelName : null);
}
}

static IEnumerable<IReadOnlyProperty> Properties(IReadOnlyTypeBase type) =>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.Data.Common;
using System.Diagnostics;
using FluentCMS.Core.Caching;
using FluentCMS.Core.DependencyInjection;
using FluentCMS.Core.IntegrationTests.Diagnostics;
using FluentCMS.Core.IntegrationTests.Testing;
using FluentCMS.Core.Jobs;
using FluentCMS.Core.Storage;
using FluentCMS.Core.Storage.Entities;
using FluentCMS.Providers;
Expand Down Expand Up @@ -704,7 +704,7 @@ await scope.ServiceProvider.GetRequiredService<SystemDbContext>().Set<LockRow>()
public async Task ACallbackOnLostThatDoesNotReturnKeepsTheDisposalWaitingOnlyForItsBound()
{
var clock = new ControllableTimeProvider();
var bound = new HeldTimers(clock, JobRunner.DisposeWait);
var bound = new HeldTimers(clock, DisposeWait.Bound);
var logs = new LogCapture();
var failed = new LoggedSignal(LockLog.LostCallbackFailedId);
var renewals = new LeaseRenewalInterceptor();
Expand Down
Loading