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>3.0.0</Version>
<Version>3.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
7 changes: 7 additions & 0 deletions Magic.IndexedDb.UnitTests/PublicApiBaseline.txt
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,14 @@ enum Magic.IndexedDb.LinqTranslation.Models.FilterNodeType : System.IComparable,
field System.Int32 value__
field static Magic.IndexedDb.LinqTranslation.Models.FilterNodeType Condition = 1
field static Magic.IndexedDb.LinqTranslation.Models.FilterNodeType Logical = 0
enum Magic.IndexedDb.MagicConditionalMutationResult : System.IComparable, System.IConvertible, System.IFormattable, System.ISpanFormattable
field System.Int32 value__
field static Magic.IndexedDb.MagicConditionalMutationResult Applied = 1
field static Magic.IndexedDb.MagicConditionalMutationResult Conflict = 0
static class Magic.IndexedDb.MagicEncryptedQueryExtensions
method static System.Threading.Tasks.Task<Magic.IndexedDb.MagicConditionalMutationResult> DeleteProtectedIfCurrentAsync<T, TWorkspace, TRevision, TGeneration>(Magic.IndexedDb.IMagicQuery<T> source, T expectedRecord, System.Linq.Expressions.Expression<System.Func<T, TRevision>> revision, Magic.IndexedDb.IMagicQuery<TWorkspace> workspace, TWorkspace expectedWorkspace, System.Linq.Expressions.Expression<System.Func<TWorkspace, TGeneration>> generation, System.Threading.CancellationToken cancellationToken = null)
method static System.Threading.Tasks.Task<Magic.IndexedDb.MagicConditionalMutationResult> InsertProtectedIfCurrentAsync<T, TWorkspace, TGeneration>(Magic.IndexedDb.IMagicQuery<T> source, T record, Magic.IndexedDb.IMagicQuery<TWorkspace> workspace, TWorkspace expectedWorkspace, System.Linq.Expressions.Expression<System.Func<TWorkspace, TGeneration>> generation, System.Threading.CancellationToken cancellationToken = null)
method static System.Threading.Tasks.Task<Magic.IndexedDb.MagicConditionalMutationResult> ReplaceProtectedIfCurrentAsync<T, TWorkspace, TRevision, TGeneration>(Magic.IndexedDb.IMagicQuery<T> source, T expectedRecord, T replacement, System.Linq.Expressions.Expression<System.Func<T, TRevision>> revision, Magic.IndexedDb.IMagicQuery<TWorkspace> workspace, TWorkspace expectedWorkspace, System.Linq.Expressions.Expression<System.Func<TWorkspace, TGeneration>> generation, System.Threading.CancellationToken cancellationToken = null)
method static System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<TValue>> SelectPublicAsync<T, TValue>(Magic.IndexedDb.IMagicExecute<T> source, System.Linq.Expressions.Expression<System.Func<T, TValue>> member, System.Threading.CancellationToken cancellationToken = null)
method static System.Threading.Tasks.Task<System.Int32> PatchPublicAsync<T, TValue>(Magic.IndexedDb.IMagicQuery<T> source, T recordWithKey, System.Linq.Expressions.Expression<System.Func<T, TValue>> member, System.Threading.CancellationToken cancellationToken = null)
class Magic.IndexedDb.MagicEncryptionContext : System.IEquatable<Magic.IndexedDb.MagicEncryptionContext>
Expand Down
2 changes: 1 addition & 1 deletion Magic.IndexedDb.UnitTests/WireProtocolTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public async Task VersionTwoEnvelope_WritesArgumentsAsJsonValues()
};

await using var stream = new MemoryStream();
await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, settings);
await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package);
stream.Position = 0;
using var document = await JsonDocument.ParseAsync(stream);
var root = document.RootElement;
Expand Down
41 changes: 25 additions & 16 deletions Magic.IndexedDb/Encryption/EncryptionConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Reflection;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Nodes;
using Magic.IndexedDb.Helpers;
using Magic.IndexedDb.SchemaAnnotations;

Expand Down Expand Up @@ -106,35 +107,43 @@ public JsonElement CreateDatabase(IEnumerable<(Type Type, StoreSchema Schema)> s
"Configure whole-record encryption with an explicit public allowlist instead.");
}

return new
return new JsonObject
{
entry.Schema.TableName,
entry.Schema.PrimaryKeyAuto,
entry.Schema.ColumnNamesInCompoundKey,
entry.Schema.Indexes,
entry.Schema.UniqueIndexes,
entry.Schema.ColumnNamesInCompoundIndex,
EncryptedFields = protectedFields,
ExposedFields = exposedFields
["tableName"] = entry.Schema.TableName,
["primaryKeyAuto"] = entry.Schema.PrimaryKeyAuto,
["columnNamesInCompoundKey"] = Strings(entry.Schema.ColumnNamesInCompoundKey),
["indexes"] = Strings(entry.Schema.Indexes),
["uniqueIndexes"] = Strings(entry.Schema.UniqueIndexes),
["columnNamesInCompoundIndex"] = new JsonArray(entry.Schema.ColumnNamesInCompoundIndex.Select(Strings).ToArray()),
["encryptedFields"] = Strings(protectedFields),
["exposedFields"] = exposedFields is null ? null : Strings(exposedFields)
};
}).ToArray();

if (_recordPolicies.Keys.Any(table => !rows.Any(row => row.TableName == table)))
if (_recordPolicies.Keys.Any(table => !rows.Any(row => row["tableName"]!.GetValue<string>() == table)))
throw new InvalidOperationException("A Magic record policy names an unregistered table.");

var payload = new Dictionary<string, object?>
var payload = new JsonObject
{
["name"] = Route,
["version"] = 1,
["storeSchemas"] = rows,
["encryption"] = new { Account = Request.AccountScope, PhysicalName,
ExplicitPhysicalBinding = HasExplicitPhysicalBinding }
["storeSchemas"] = new JsonArray(rows),
["encryption"] = new JsonObject
{
["account"] = Request.AccountScope,
["physicalName"] = PhysicalName,
["explicitPhysicalBinding"] = HasExplicitPhysicalBinding
}
};
if (_numericMode == MagicNumericStorageMode.Lossless)
{
payload["numericStorage"] = NumericStorageConfiguration.Policy;
payload["numericStorage"] = new JsonObject { ["version"] = 1, ["mode"] = "lossless" };
payload["numericLegacyName"] = _legacyPhysicalName;
}
return JsonSerializer.SerializeToElement(payload, new JsonSerializerOptions(JsonSerializerDefaults.Web));
using var document = JsonDocument.Parse(payload.ToJsonString());
return document.RootElement.Clone();
}

private static JsonArray Strings(IEnumerable<string> values) =>
new(values.Select(value => (JsonNode?)JsonValue.Create(value)).ToArray());
}
62 changes: 62 additions & 0 deletions Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,61 @@ public static Task<int> PatchPublicAsync<T, TValue>(
JsonSerializer.SerializeToElement(new Dictionary<string, JsonElement> { [name] = value }), cancellationToken);
}

/// <summary>Replaces a protected record if its revision and the workspace generation still match.</summary>
public static Task<MagicConditionalMutationResult> ReplaceProtectedIfCurrentAsync<T, TWorkspace, TRevision, TGeneration>(
this IMagicQuery<T> source, T expectedRecord, T replacement, Expression<Func<T, TRevision>> revision,
IMagicQuery<TWorkspace> workspace, TWorkspace expectedWorkspace, Expression<Func<TWorkspace, TGeneration>> generation,
CancellationToken cancellationToken = default) where T : class where TWorkspace : class
{
ArgumentNullException.ThrowIfNull(replacement);
return MutateIfCurrent(source, expectedRecord, replacement, revision, workspace, expectedWorkspace, generation, cancellationToken);
}

/// <summary>Deletes a protected record if its revision and the workspace generation still match.</summary>
public static Task<MagicConditionalMutationResult> DeleteProtectedIfCurrentAsync<T, TWorkspace, TRevision, TGeneration>(
this IMagicQuery<T> source, T expectedRecord, Expression<Func<T, TRevision>> revision,
IMagicQuery<TWorkspace> workspace, TWorkspace expectedWorkspace, Expression<Func<TWorkspace, TGeneration>> generation,
CancellationToken cancellationToken = default) where T : class where TWorkspace : class =>
MutateIfCurrent(source, expectedRecord, null, revision, workspace, expectedWorkspace, generation, cancellationToken);

/// <summary>Inserts a protected record with an unused key if the workspace generation still matches.</summary>
public static Task<MagicConditionalMutationResult> InsertProtectedIfCurrentAsync<T, TWorkspace, TGeneration>(
this IMagicQuery<T> source, T record, IMagicQuery<TWorkspace> workspace, TWorkspace expectedWorkspace,
Expression<Func<TWorkspace, TGeneration>> generation, CancellationToken cancellationToken = default)
where T : class where TWorkspace : class =>
MutateIfCurrent<T, TWorkspace, object, TGeneration>(source, record, record, null, workspace, expectedWorkspace,
generation, cancellationToken);

private static async Task<MagicConditionalMutationResult> MutateIfCurrent<T, TWorkspace, TRevision, TGeneration>(
IMagicQuery<T> source, T expectedRecord, T? replacement, Expression<Func<T, TRevision>>? revision,
IMagicQuery<TWorkspace> workspace, TWorkspace expectedWorkspace, Expression<Func<TWorkspace, TGeneration>> generation,
CancellationToken token) where T : class where TWorkspace : class
{
if (source is not MagicQuery<T> query || workspace is not MagicQuery<TWorkspace> workspaceQuery ||
query.Manager != workspaceQuery.Manager || query.DatabaseName != workspaceQuery.DatabaseName)
throw new ArgumentException("Both tables must belong to the same managed database context.");
ArgumentNullException.ThrowIfNull(expectedRecord);
ArgumentNullException.ThrowIfNull(expectedWorkspace);
var settings = query.Manager.Settings(query.DatabaseName);
var record = MagicSerializationHelper.SerializeObjectToJsonElement(expectedRecord, settings);
var workspaceRecord = MagicSerializationHelper.SerializeObjectToJsonElement(expectedWorkspace, settings);
var revisionName = revision is null ? null : MappedMember(revision).JsPropertyName;
var generationName = MappedMember(generation).JsPropertyName;
var next = replacement is null ? (JsonElement?)null : MagicSerializationHelper.SerializeObjectToJsonElement(replacement, settings);
var applied = await query.Manager.ConditionalProtectedMutationAsync(query, workspaceQuery.SchemaName,
KeyOf(expectedRecord, record), revisionName, revisionName is null ? null : record.GetProperty(revisionName),
KeyOf(expectedWorkspace, workspaceRecord), generationName, workspaceRecord.GetProperty(generationName), next, token);
return applied ? MagicConditionalMutationResult.Applied : MagicConditionalMutationResult.Conflict;
}

private 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)
{
ArgumentNullException.ThrowIfNull(member);
Expand All @@ -72,3 +127,10 @@ private static MagicPropertyEntry MappedMember<T, TValue>(Expression<Func<T, TVa
return entry;
}
}

/// <summary>The outcome of an atomic conditional protected mutation.</summary>
public enum MagicConditionalMutationResult
{
Conflict,
Applied
}
4 changes: 2 additions & 2 deletions Magic.IndexedDb/Extensions/MagicJsInvoke.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ internal async Task CallInvokeVoidDefaultJsAsync(string modulePath, string funct
string instanceId = Guid.NewGuid().ToString();

using var stream = new MemoryStream();
await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, settings, token);
await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, token);

stream.Position = 0;

Expand Down Expand Up @@ -146,7 +146,7 @@ internal async Task CallInvokeVoidDefaultJsAsync(string modulePath, string funct
string instanceId = Guid.NewGuid().ToString();

using var stream = new MemoryStream();
await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, settings, token);
await MagicSerializationHelper.SerializeJsPackageToStreamAsync(stream, package, token);

stream.Position = 0;
using var streamRef = new DotNetStreamReference(stream);
Expand Down
7 changes: 4 additions & 3 deletions Magic.IndexedDb/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Magic.IndexedDb.Factories;
using System.Diagnostics.CodeAnalysis;
using Magic.IndexedDb.Factories;
using Magic.IndexedDb.Helpers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
Expand Down Expand Up @@ -63,7 +64,7 @@ public static IServiceCollection AddMagicBlazorDB(this IServiceCollection servic
}

/// <summary>Registers account-bound encryption policies and an application-supplied key provider.</summary>
public static IServiceCollection AddMagicIndexedDbEncryption<TProvider>(this IServiceCollection services,
public static IServiceCollection AddMagicIndexedDbEncryption<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TProvider>(this IServiceCollection services,
Func<IServiceProvider, IEnumerable<MagicEncryptionOptions>> configure)
where TProvider : class, IMagicEncryptionKeyProvider
{
Expand All @@ -81,7 +82,7 @@ public static IServiceCollection AddMagicIndexedDbEncryption<TProvider>(this ISe
}

/// <summary>Registers an application key provider for runtime account activation.</summary>
public static IServiceCollection AddMagicIndexedDbEncryption<TProvider>(this IServiceCollection services)
public static IServiceCollection AddMagicIndexedDbEncryption<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TProvider>(this IServiceCollection services)
where TProvider : class, IMagicEncryptionKeyProvider =>
services.AddMagicIndexedDbEncryption<TProvider>(_ => []);

Expand Down
3 changes: 2 additions & 1 deletion Magic.IndexedDb/Factories/MagicDbFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,8 @@ private async Task CreateDatabaseAsync(ResolvedMagicDatabase resolved, string in
var document = JsonNode.Parse(payload.GetRawText())!.AsObject();
document["migrationSchema"] = JsonNode.Parse(MagicSchemaJson.Serialize(resolved.Schema));
document["migrationManifestUrl"] = resolved.Definition.ManifestUrl;
payload = JsonSerializer.SerializeToElement(document);
using var wireDocument = JsonDocument.Parse(document.ToJsonString());
payload = wireDocument.RootElement.Clone();
var module = await _jsModule!.Value;
if (_encryption.ContainsKey(name) || _numericStorage.Mode(name) == MagicNumericStorageMode.Lossless)
await EncryptionUnlock.InvokeAsync<bool>(module, IndexedDbFunctions.CREATE_LEGACY, true, payload);
Expand Down
29 changes: 24 additions & 5 deletions Magic.IndexedDb/Helpers/MagicSerializationHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using Magic.IndexedDb.Interfaces;
using Magic.IndexedDb.Models;
using System.Text.Json;
using System.Diagnostics.CodeAnalysis;
using Magic.IndexedDb.LinqTranslation.Models;
using Magic.IndexedDb.Models.UniversalOperations;

namespace Magic.IndexedDb.Helpers;

Expand Down Expand Up @@ -28,6 +31,12 @@ public static string[] SerializeObjectsToString(ITypedArgument[] objs, MagicJson
return objs.Select(arg => arg.SerializeToJsonString(settings)).ToArray();
}

[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(StoreRecord<>))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(UpdateRecord<>))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(PrimaryKeys))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(FilterNode))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(FilterCondition))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(StoredMagicQuery))]
public static JsonElement SerializeObjectToJsonElement<T>(T value, MagicJsonSerializationSettings? settings = null)
{
if (settings == null)
Expand Down Expand Up @@ -70,16 +79,26 @@ public static async Task SerializeObjectToStreamAsync<T>(Stream stream, T value,
internal static async Task SerializeJsPackageToStreamAsync(
Stream stream,
MagicJsPackage package,
MagicJsonSerializationSettings settings,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(package);

// The envelope is infrastructure JSON. Its JsonElement parameters have already
// been serialized with Magic's contracts and must be written as raw JSON values.
var options = new JsonSerializerOptions(settings.Options);
await JsonSerializer.SerializeAsync(stream, package, options, cancellationToken);
// The wire envelope has stable names under both the standard and
// fully linked runtimes. Arguments already carry their own contracts.
using var writer = new Utf8JsonWriter(stream);
writer.WriteStartObject();
writer.WriteNumber("protocolVersion", package.ProtocolVersion);
writer.WriteBoolean("yieldResults", package.YieldResults);
writer.WriteString("modulePath", package.ModulePath);
writer.WriteString("methodName", package.MethodName);
writer.WriteBoolean("isVoid", package.IsVoid);
writer.WriteStartArray("parameters");
foreach (var parameter in package.Parameters)
parameter.WriteTo(writer);
writer.WriteEndArray();
writer.WriteEndObject();
await writer.FlushAsync(cancellationToken);
await stream.FlushAsync(cancellationToken);
}

Expand Down
Loading
Loading