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 Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<PackAsTool>true</PackAsTool>
<ToolCommandName>magicdb</ToolCommandName>
<PackageId>Magic.IndexedDb.Cli</PackageId>
<Version>4.0.0</Version>
<Version>4.1.0</Version>
<Authors>Magic Man</Authors>
<Description>Code-first, language-independent migration planning, validation, and static publishing for Magic IndexedDB.</Description>
<PackageProjectUrl>https://github.com/magiccodingman/Magic.IndexedDb</PackageProjectUrl>
Expand Down
8 changes: 8 additions & 0 deletions Magic.IndexedDb.UnitTests/PublicApiBaseline.txt
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,14 @@ class Magic.IndexedDb.MagicProjectedQuery<TResult>
method System.Threading.Tasks.Task<System.Collections.Generic.List<TResult>> ToListAsync(System.Threading.CancellationToken cancellationToken = null)
static class Magic.IndexedDb.MagicProjectionExtensions
method static Magic.IndexedDb.MagicProjectedQuery<TResult> Select<T, TResult>(Magic.IndexedDb.IMagicExecute<T> source, System.Linq.Expressions.Expression<System.Func<T, TResult>> selector)
class Magic.IndexedDb.MagicProtectedBatch
ctor Magic.IndexedDb.MagicProtectedBatch()
method Magic.IndexedDb.MagicProtectedBatch Delete<T, TToken>(Magic.IndexedDb.IMagicQuery<T> table, T expected, System.Linq.Expressions.Expression<System.Func<T, TToken>> token)
method Magic.IndexedDb.MagicProtectedBatch ExpectAbsent<T>(Magic.IndexedDb.IMagicQuery<T> table, T record)
method Magic.IndexedDb.MagicProtectedBatch ExpectToken<T, TToken>(Magic.IndexedDb.IMagicQuery<T> table, T expected, System.Linq.Expressions.Expression<System.Func<T, TToken>> token)
method Magic.IndexedDb.MagicProtectedBatch Insert<T>(Magic.IndexedDb.IMagicQuery<T> table, T record)
method Magic.IndexedDb.MagicProtectedBatch Replace<T, TToken>(Magic.IndexedDb.IMagicQuery<T> table, T expected, System.Linq.Expressions.Expression<System.Func<T, TToken>> token, T replacement)
method System.Threading.Tasks.Task<Magic.IndexedDb.MagicConditionalMutationResult> CommitAsync(System.Threading.CancellationToken cancellationToken = null)
class Magic.IndexedDb.MagicTableTool<T>
ctor Magic.IndexedDb.MagicTableTool<T>()
class Magic.IndexedDb.MagicUniqueIndexAttribute : Magic.IndexedDb.Interfaces.IColumnNamed, System.Attribute
Expand Down
4 changes: 2 additions & 2 deletions Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,15 +105,15 @@ private static async Task<MagicConditionalMutationResult> MutateIfCurrent<T, TWo
return applied ? MagicConditionalMutationResult.Applied : MagicConditionalMutationResult.Conflict;
}

private static System.Text.Json.Nodes.JsonObject KeyOf<T>(T item, JsonElement serialized) where T : class
internal static System.Text.Json.Nodes.JsonObject KeyOf<T>(T item, JsonElement serialized) where T : class
{
var key = new System.Text.Json.Nodes.JsonObject();
foreach (var part in AttributeHelpers.GetPrimaryKeys(item))
key[part.JsName] = System.Text.Json.Nodes.JsonNode.Parse(serialized.GetProperty(part.JsName).GetRawText());
return key;
}

private static MagicPropertyEntry MappedMember<T, TValue>(Expression<Func<T, TValue>> member)
internal static MagicPropertyEntry MappedMember<T, TValue>(Expression<Func<T, TValue>> member)
{
ArgumentNullException.ThrowIfNull(member);
if (member.Body is not MemberExpression { Member: PropertyInfo property } access ||
Expand Down
89 changes: 89 additions & 0 deletions Magic.IndexedDb/Encryption/MagicProtectedBatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using System.Linq.Expressions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Magic.IndexedDb.Helpers;
using Magic.IndexedDb.LinqTranslation.Models;

namespace Magic.IndexedDb;

/// <summary>Builds an atomic conditional operation across protected tables in one managed database.</summary>
public sealed class MagicProtectedBatch
{
private readonly JsonArray _entries = new();
private IndexedDbManager? _manager;
private string? _database;
private bool _hasWrites;

/// <summary>Requires the exact key represented by the supplied record to be absent.</summary>
public MagicProtectedBatch ExpectAbsent<T>(IMagicQuery<T> table, T record) where T : class =>
Add<T, object>(table, record, null, "check", null);

/// <summary>Requires a row to have the supplied value of a direct persisted property.</summary>
public MagicProtectedBatch ExpectToken<T, TToken>(IMagicQuery<T> table, T expected,
Expression<Func<T, TToken>> token) where T : class =>
Add(table, expected, token, "check", null);

/// <summary>Inserts a record if its primary key is absent.</summary>
public MagicProtectedBatch Insert<T>(IMagicQuery<T> table, T record) where T : class =>
Add<T, object>(table, record, null, "insert", record);

/// <summary>Replaces a record if its token matches. The primary key must remain the same.</summary>
public MagicProtectedBatch Replace<T, TToken>(IMagicQuery<T> table, T expected,
Expression<Func<T, TToken>> token, T replacement) where T : class
{
ArgumentNullException.ThrowIfNull(replacement);
return Add(table, expected, token, "replace", replacement);
}

/// <summary>Deletes a record if its token matches.</summary>
public MagicProtectedBatch Delete<T, TToken>(IMagicQuery<T> table, T expected,
Expression<Func<T, TToken>> token) where T : class =>
Add(table, expected, token, "delete", null);

/// <summary>Commits all mutations or returns a conflict without writing any of them.</summary>
public async Task<MagicConditionalMutationResult> CommitAsync(CancellationToken cancellationToken = default)
{
if (!_hasWrites || _manager is null || _database is null)
throw new InvalidOperationException("A protected batch requires a mutation.");

var json = _entries.ToJsonString();
if (Encoding.UTF8.GetByteCount(json) > 2 * 1024 * 1024)
throw new InvalidOperationException("A protected batch cannot exceed 2 MiB of serialized arguments.");
using var payload = JsonDocument.Parse(json);
return await _manager.ConditionalProtectedBatchAsync(_database, payload.RootElement.Clone(), cancellationToken)
? MagicConditionalMutationResult.Applied : MagicConditionalMutationResult.Conflict;
}

private MagicProtectedBatch Add<T, TToken>(IMagicQuery<T> source, T expected,
Expression<Func<T, TToken>>? token, string operation, T? replacement) where T : class
{
ArgumentNullException.ThrowIfNull(expected);
if (source is not MagicQuery<T> query || (_manager is not null &&
(_manager != query.Manager || _database != query.DatabaseName)))
throw new ArgumentException("All tables must belong to the same managed database context.", nameof(source));
if (_entries.Count == 32)
throw new InvalidOperationException("A protected batch can include at most 32 rows.");
if (token is null && operation is "replace" or "delete")
throw new ArgumentNullException(nameof(token));

var settings = query.Manager.Settings(query.DatabaseName);
var serialized = MagicSerializationHelper.SerializeObjectToJsonElement(expected, settings);
var member = token is null ? null : MagicEncryptedQueryExtensions.MappedMember(token).JsPropertyName;
var entry = new JsonObject
{
["store"] = query.SchemaName,
["key"] = MagicEncryptedQueryExtensions.KeyOf(expected, serialized),
["member"] = member,
["expected"] = member is null ? null : JsonNode.Parse(serialized.GetProperty(member).GetRawText()),
["operation"] = operation,
["replacement"] = replacement is null ? null : JsonNode.Parse(
MagicSerializationHelper.SerializeObjectToJsonElement(replacement, settings).GetRawText())
};
_entries.Add(entry);
_manager = query.Manager;
_database = query.DatabaseName;
_hasWrites |= operation != "check";
return this;
}
}
4 changes: 4 additions & 0 deletions Magic.IndexedDb/IndexDbManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@
};

return await Invocation(dbName).CallJsAsync<int>(Cache.MagicDbJsImportPath,
IndexedDbFunctions.UPDATE_ITEM, cancellationToken, new TypedArgument<UpdateRecord<T?>>(record));

Check warning on line 197 in Magic.IndexedDb/IndexDbManager.cs

View workflow job for this annotation

GitHub Actions / Core validation

Argument of type 'UpdateRecord<T>' cannot be used for parameter 'value' of type 'UpdateRecord<T?>' in 'TypedArgument<UpdateRecord<T?>>.TypedArgument(UpdateRecord<T?>? value)' due to differences in the nullability of reference types.
}

internal async Task<int> CountEntireTableAsync<T>(string schemaName, string dbName)
Expand Down Expand Up @@ -260,7 +260,7 @@
new TypedArgument<bool>(query?.ForceCursorMode??false),
};

var rows = await Invocation(query.DatabaseName).CallJsAsync<IEnumerable<T>>(

Check warning on line 263 in Magic.IndexedDb/IndexDbManager.cs

View workflow job for this annotation

GitHub Actions / Core validation

Dereference of a possibly null reference.
Cache.MagicDbJsImportPath, IndexedDbFunctions.MAGIC_QUERY_ASYNC, cancellationToken, args);
_lifetime.ThrowIfCancellationRequested();
return rows;
Expand Down Expand Up @@ -292,7 +292,7 @@
};

// Yield results **as they arrive** from JS
await foreach (var item in Invocation(query.DatabaseName).CallYieldJsAsync<T>(Cache.MagicDbJsImportPath, IndexedDbFunctions.MAGIC_QUERY_YIELD, cancellationToken, args))

Check warning on line 295 in Magic.IndexedDb/IndexDbManager.cs

View workflow job for this annotation

GitHub Actions / Core validation

Dereference of a possibly null reference.
{
_lifetime.ThrowIfCancellationRequested();
yield return item; // Stream each item immediately
Expand Down Expand Up @@ -383,6 +383,10 @@
new TypedArgument<string>(workspaceStore), new TypedArgument<JsonElement>(payload.RootElement.Clone()));
}

internal Task<bool> ConditionalProtectedBatchAsync(string database, JsonElement entries, CancellationToken token) =>
Invocation(database).CallJsAsync<bool>(Cache.MagicDbJsImportPath, "conditionalProtectedBatch", token,
new TypedArgument<string>(Route(database)), new TypedArgument<JsonElement>(entries));

internal async Task DeleteAsync<T>(T item, string dbName, CancellationToken cancellationToken = default) where T : class
{
string schemaName = SchemaHelper.GetTableName<T>();
Expand All @@ -397,7 +401,7 @@
Record = item
};

await Invocation(dbName).CallJsAsync(Cache.MagicDbJsImportPath, IndexedDbFunctions.DELETE_ITEM, cancellationToken, new TypedArgument<UpdateRecord<T?>>(record));

Check warning on line 404 in Magic.IndexedDb/IndexDbManager.cs

View workflow job for this annotation

GitHub Actions / Core validation

Argument of type 'UpdateRecord<T>' cannot be used for parameter 'value' of type 'UpdateRecord<T?>' in 'TypedArgument<UpdateRecord<T?>>.TypedArgument(UpdateRecord<T?>? value)' due to differences in the nullability of reference types.
}

internal async Task<int> DeleteRangeAsync<T>(
Expand Down
4 changes: 2 additions & 2 deletions Magic.IndexedDb/Magic.IndexedDb.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseFile>LICENSE.txt</PackageLicenseFile>
<FileVersion>4.0.0.0</FileVersion>
<Version>4.0.0</Version>
<FileVersion>4.1.0.0</FileVersion>
<Version>4.1.0</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
11 changes: 11 additions & 0 deletions Magic.IndexedDb/wwwroot/magicDB.js
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,17 @@ export function conditionalProtectedMutation(name, store, workspaceStore, { reco
return table.conditionalMutation(record, revision, workspace, generation, replacement);
}

export function conditionalProtectedBatch(name, entries) {
if (!Array.isArray(entries) || entries.length < 1 || entries.length > 32)
throw new Error("MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: Expected 1 to 32 batch rows.");
const rows = entries.map(entry => {
const table = protectedTable(name, entry.store);
if (!table) throw new Error("MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: Protected tables are required.");
return { ...entry, table };
});
return rows[0].table.conditionalBatch(rows);
}

export function patchPublicRecord(name, store, key, changes) {
const table = protectedTable(name, store);
if (!table) throw new Error("A public patch requires a protected table.");
Expand Down
66 changes: 66 additions & 0 deletions Magic.IndexedDb/wwwroot/utilities/protectedStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,72 @@ class ProtectedTable {
});
}

conditionalBatch(entries) {
const unsupported = message => new Error(`MAGIC_CONDITIONAL_WRITE_UNSUPPORTED: ${message}`);
const rows = [];
const tables = new Map();
for (const { table, key, member, expected, operation, replacement } of entries) {
if (!table.managed || table.db !== this.db ||
(table.policy.exposed === null && table.policy.fields.size === 0))
throw unsupported("Conditions require one protected managed database.");
if (member !== null) {
validateMember(member);
if (table.isPublic(member))
throw unsupported("Batch tokens must be encrypted persisted members.");
if (typeof expected !== "string" && !Number.isSafeInteger(expected))
throw unsupported("Expected tokens must be strings or safe integers.");
}
if (!((operation === "check" && replacement === null) ||
(operation === "insert" && member === null && replacement !== null) ||
(operation === "replace" && member !== null && replacement !== null) ||
(operation === "delete" && member !== null && replacement === null)))
throw unsupported("The mutation requires a matching target guard.");
const primaryKey = table.key(key);
indexedDB.cmp(primaryKey, primaryKey);
if (rows.some(row => row.table.table.name === table.table.name &&
indexedDB.cmp(row.primaryKey, primaryKey) === 0))
throw unsupported("Represent each store and primary key once.");
if (replacement !== null && indexedDB.cmp(primaryKey, table.key(replacement)) !== 0)
throw unsupported("A replacement must retain the primary key.");
rows.push({ table, primaryKey, member, expected, operation, replacement });
if (table.table.name !== this.table.name) tables.set(table.table.name, table.table);
}
if (!rows.some(row => row.operation !== "check"))
throw unsupported("A batch requires a mutation.");

return this.access(async (keys, assertCurrent) => {
await this.assertPolicy(true);
for (const row of rows) {
assertCurrent();
row.snapshot = await row.table.table.get(row.primaryKey);
if (row.member === null) {
if (row.snapshot !== undefined) return false;
} else {
if (row.snapshot === undefined) return false;
const opened = await row.table.openStoredRecord(row.snapshot, row.primaryKey, keys);
if (!Object.hasOwn(opened, row.member) || opened[row.member] !== row.expected) return false;
}
if (row.replacement !== null) {
row.sealed = await sealRecord(row.replacement, row.table.policy, keys.key, keys.keyId,
row.table.context(row.primaryKey));
}
}
assertCurrent();
return this.fencedWrite(async () => {
for (const row of rows) {
if (!sameStoredValue(row.snapshot, await row.table.table.get(row.primaryKey))) return false;
}
assertCurrent();
for (const row of rows) {
if (row.operation === "insert") await row.table.table.add(row.sealed);
else if (row.operation === "replace") await row.table.table.put(row.sealed);
else if (row.operation === "delete") await row.table.table.delete(row.primaryKey);
}
return true;
}, assertCurrent, [...tables.values()]);
});
}

async patch(primaryKey, changes) {
const names = Object.keys(changes);
for (const name of names) validateMember(name);
Expand Down
39 changes: 39 additions & 0 deletions docs/guides/managed-key-rotation.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,42 @@ Full trimming still requires the app to preserve persisted model members used
through reflection. Root the relevant model types in the application linker
descriptor and mark infrastructure-only properties with `[MagicNotMapped]` so
the exporter and runtime agree on the persisted schema.

### Conditional batches across protected stores

Starting with Magic IndexedDB 4.1, use `MagicProtectedBatch` for coordinated changes inside one unlocked, managed
database. Each entry addresses an exact primary key. Query filters and ordering do
not participate. Guard-only entries use `ExpectAbsent` or `ExpectToken`. Insert
implies an absence guard. Replace and delete require a token guard on the target.

```csharp
var result = await new MagicProtectedBatch()
.ExpectToken(documents, expectedDocument, row => row.Revision)
.ExpectToken(epochs, expectedEpoch, row => row.Generation)
.Insert(references, newReference)
.Replace(referenceStates, expectedState, row => row.Revision, updatedState)
.CommitAsync(cancellationToken);
```

The example assumes that every writer updates the authoritative reference state
with its reference mutation. An eviction can guard the epoch and delete both
the document and its zero-reference state in one batch. Build the new batch from
fresh state after a conflict. Change tokens on every logical replacement and each new incarnation of a reused
key. Existing writers that bypass the reference state must be fenced
before relying on it for eviction.

One batch accepts up to 32 distinct rows and 2 MiB of serialized arguments.
Specify each store and primary key once, including rows used only as guards.
Use direct encrypted members as tokens. Their values must encode as strings
or JavaScript safe integers. Magic authenticates those values and compares the
stored snapshots again inside a single read-write transaction. If a guard fails,
the result is `Conflict`. Storage, authorization, and format errors are failures,
and the browser rolls back an aborted transaction.

The batch snapshots its arguments as entries are added. Use a new builder for
each attempt. Protected data is processed in browser memory before opening the
write transaction. Larger batches hold more snapshots and ciphertext in memory
and lock more stores for longer. Keep each batch scoped to one logical change.
Cancellation of the .NET wait does not establish that a previously dispatched
browser transaction aborted. Re-read the affected rows and reconcile whether that exact operation committed
before retrying.
10 changes: 10 additions & 0 deletions tests/migrations/ProtectedWasm/App/App.razor
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,16 @@
table = await database.Query<RotationRow>();
var rows = await table.ToListAsync();
Require(rows.Count == 3 && rows.All(row => row.Secret == "Document " + row.Id), "Rotation changed typed data.");
var references = await database.Query<ReferenceRow>();
var reference = new ReferenceRow { Id = 1, Target = "document" };
Require(await new MagicProtectedBatch().ExpectToken(table, oldFence, row => row.Generation)
.Insert(references, reference).CommitAsync() == MagicConditionalMutationResult.Conflict,
"A retired fence allowed a batch insert.");
Require(await new MagicProtectedBatch().ExpectToken(table, advancedFence, row => row.Generation)
.Insert(references, reference).CommitAsync() == MagicConditionalMutationResult.Applied,
"The cross-store batch insert failed.");
Require((await references.ToListAsync()).Single().Target == "document",
"The protected batch failed to persist the typed value.");
await Contexts.DeactivateAsync();
}

Expand Down
1 change: 1 addition & 0 deletions tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
<assembly fullname="App">
<type fullname="ProtectedRow" preserve="all" />
<type fullname="RotationRow" preserve="all" />
<type fullname="ReferenceRow" preserve="all" />
</assembly>
</linker>
2 changes: 1 addition & 1 deletion tests/migrations/ProtectedWasm/App/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<ProtectedFixture.App>("#app");
builder.Services.AddMagicBlazorDB(BlazorInteropMode.WASM, false,
[typeof(ProtectedRow), typeof(RotationRow)], [typeof(ProtectedRepository)]);
[typeof(ProtectedRow), typeof(RotationRow), typeof(ReferenceRow)], [typeof(ProtectedRepository)]);
builder.Services.AddMagicIndexedDbEncryption<FixtureKeys>(_ =>
[new MagicEncryptionOptions("protected-wasm", "published-account", "fixture-key")
{ PhysicalDatabaseName = ProtectedRepository.PhysicalName }]);
Expand Down
2 changes: 1 addition & 1 deletion tests/migrations/ProtectedWasm/Exporter/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Magic.IndexedDb.Migrations;

return MagicSchemaExporter.Run(args, [typeof(ProtectedRow), typeof(RotationRow)], [typeof(ProtectedRepository)],
return MagicSchemaExporter.Run(args, [typeof(ProtectedRow), typeof(RotationRow), typeof(ReferenceRow)], [typeof(ProtectedRepository)],
new MagicSchemaOptions { ProtectedDatabases = ["protected-wasm", "rotation-wasm"] });
13 changes: 13 additions & 0 deletions tests/migrations/ProtectedWasm/Model.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,16 @@ public sealed class RotationRow : MagicTableTool<RotationRow>, IMagicTable<Prote
public int Generation { get; set; }
public string Secret { get; set; } = "";
}

[MagicEncryptRecord(nameof(Id))]
public sealed class ReferenceRow : MagicTableTool<ReferenceRow>, IMagicTable<ProtectedRepository>
{
[MagicNotMapped]
public ProtectedRepository Databases { get; } = new();
public IndexedDbSet GetDefaultDatabase() => ProtectedRepository.RotationRecords;
public string GetTableName() => "references";
public IMagicCompoundKey GetKeys() => CreatePrimaryKey(row => row.Id, false);
public List<IMagicCompoundIndex> GetCompoundIndexes() => [];
public int Id { get; set; }
public string Target { get; set; } = "";
}
Loading
Loading