diff --git a/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj b/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj
index d29aac8..7be280d 100644
--- a/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj
+++ b/Magic.IndexedDb.Cli/Magic.IndexedDb.Cli.csproj
@@ -7,7 +7,7 @@
true
magicdb
Magic.IndexedDb.Cli
- 4.0.0
+ 4.1.0
Magic Man
Code-first, language-independent migration planning, validation, and static publishing for Magic IndexedDB.
https://github.com/magiccodingman/Magic.IndexedDb
diff --git a/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt b/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt
index 7bb2419..9de37a3 100644
--- a/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt
+++ b/Magic.IndexedDb.UnitTests/PublicApiBaseline.txt
@@ -368,6 +368,14 @@ class Magic.IndexedDb.MagicProjectedQuery
method System.Threading.Tasks.Task> ToListAsync(System.Threading.CancellationToken cancellationToken = null)
static class Magic.IndexedDb.MagicProjectionExtensions
method static Magic.IndexedDb.MagicProjectedQuery Select(Magic.IndexedDb.IMagicExecute source, System.Linq.Expressions.Expression> selector)
+class Magic.IndexedDb.MagicProtectedBatch
+ ctor Magic.IndexedDb.MagicProtectedBatch()
+ method Magic.IndexedDb.MagicProtectedBatch Delete(Magic.IndexedDb.IMagicQuery table, T expected, System.Linq.Expressions.Expression> token)
+ method Magic.IndexedDb.MagicProtectedBatch ExpectAbsent(Magic.IndexedDb.IMagicQuery table, T record)
+ method Magic.IndexedDb.MagicProtectedBatch ExpectToken(Magic.IndexedDb.IMagicQuery table, T expected, System.Linq.Expressions.Expression> token)
+ method Magic.IndexedDb.MagicProtectedBatch Insert(Magic.IndexedDb.IMagicQuery table, T record)
+ method Magic.IndexedDb.MagicProtectedBatch Replace(Magic.IndexedDb.IMagicQuery table, T expected, System.Linq.Expressions.Expression> token, T replacement)
+ method System.Threading.Tasks.Task CommitAsync(System.Threading.CancellationToken cancellationToken = null)
class Magic.IndexedDb.MagicTableTool
ctor Magic.IndexedDb.MagicTableTool()
class Magic.IndexedDb.MagicUniqueIndexAttribute : Magic.IndexedDb.Interfaces.IColumnNamed, System.Attribute
diff --git a/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs b/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs
index dd98768..d80b51a 100644
--- a/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs
+++ b/Magic.IndexedDb/Encryption/MagicEncryptedQueryExtensions.cs
@@ -105,7 +105,7 @@ private static async Task MutateIfCurrent(T item, JsonElement serialized) where T : class
+ internal static System.Text.Json.Nodes.JsonObject KeyOf(T item, JsonElement serialized) where T : class
{
var key = new System.Text.Json.Nodes.JsonObject();
foreach (var part in AttributeHelpers.GetPrimaryKeys(item))
@@ -113,7 +113,7 @@ private static System.Text.Json.Nodes.JsonObject KeyOf(T item, JsonElement se
return key;
}
- private static MagicPropertyEntry MappedMember(Expression> member)
+ internal static MagicPropertyEntry MappedMember(Expression> member)
{
ArgumentNullException.ThrowIfNull(member);
if (member.Body is not MemberExpression { Member: PropertyInfo property } access ||
diff --git a/Magic.IndexedDb/Encryption/MagicProtectedBatch.cs b/Magic.IndexedDb/Encryption/MagicProtectedBatch.cs
new file mode 100644
index 0000000..3ca8889
--- /dev/null
+++ b/Magic.IndexedDb/Encryption/MagicProtectedBatch.cs
@@ -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;
+
+/// Builds an atomic conditional operation across protected tables in one managed database.
+public sealed class MagicProtectedBatch
+{
+ private readonly JsonArray _entries = new();
+ private IndexedDbManager? _manager;
+ private string? _database;
+ private bool _hasWrites;
+
+ /// Requires the exact key represented by the supplied record to be absent.
+ public MagicProtectedBatch ExpectAbsent(IMagicQuery table, T record) where T : class =>
+ Add(table, record, null, "check", null);
+
+ /// Requires a row to have the supplied value of a direct persisted property.
+ public MagicProtectedBatch ExpectToken(IMagicQuery table, T expected,
+ Expression> token) where T : class =>
+ Add(table, expected, token, "check", null);
+
+ /// Inserts a record if its primary key is absent.
+ public MagicProtectedBatch Insert(IMagicQuery table, T record) where T : class =>
+ Add(table, record, null, "insert", record);
+
+ /// Replaces a record if its token matches. The primary key must remain the same.
+ public MagicProtectedBatch Replace(IMagicQuery table, T expected,
+ Expression> token, T replacement) where T : class
+ {
+ ArgumentNullException.ThrowIfNull(replacement);
+ return Add(table, expected, token, "replace", replacement);
+ }
+
+ /// Deletes a record if its token matches.
+ public MagicProtectedBatch Delete(IMagicQuery table, T expected,
+ Expression> token) where T : class =>
+ Add(table, expected, token, "delete", null);
+
+ /// Commits all mutations or returns a conflict without writing any of them.
+ public async Task 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(IMagicQuery source, T expected,
+ Expression>? token, string operation, T? replacement) where T : class
+ {
+ ArgumentNullException.ThrowIfNull(expected);
+ if (source is not MagicQuery 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;
+ }
+}
diff --git a/Magic.IndexedDb/IndexDbManager.cs b/Magic.IndexedDb/IndexDbManager.cs
index 01ba212..1a18ff9 100644
--- a/Magic.IndexedDb/IndexDbManager.cs
+++ b/Magic.IndexedDb/IndexDbManager.cs
@@ -383,6 +383,10 @@ internal Task ConditionalProtectedMutationAsync(MagicQuery query, st
new TypedArgument(workspaceStore), new TypedArgument(payload.RootElement.Clone()));
}
+ internal Task ConditionalProtectedBatchAsync(string database, JsonElement entries, CancellationToken token) =>
+ Invocation(database).CallJsAsync(Cache.MagicDbJsImportPath, "conditionalProtectedBatch", token,
+ new TypedArgument(Route(database)), new TypedArgument(entries));
+
internal async Task DeleteAsync(T item, string dbName, CancellationToken cancellationToken = default) where T : class
{
string schemaName = SchemaHelper.GetTableName();
diff --git a/Magic.IndexedDb/Magic.IndexedDb.csproj b/Magic.IndexedDb/Magic.IndexedDb.csproj
index 45dd9ac..8462594 100644
--- a/Magic.IndexedDb/Magic.IndexedDb.csproj
+++ b/Magic.IndexedDb/Magic.IndexedDb.csproj
@@ -15,8 +15,8 @@
4.0.0.0
README.md
LICENSE.txt
- 4.0.0.0
- 4.0.0
+ 4.1.0.0
+ 4.1.0
diff --git a/Magic.IndexedDb/wwwroot/magicDB.js b/Magic.IndexedDb/wwwroot/magicDB.js
index 7d8ff15..d83488b 100644
--- a/Magic.IndexedDb/wwwroot/magicDB.js
+++ b/Magic.IndexedDb/wwwroot/magicDB.js
@@ -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.");
diff --git a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js
index ad9d893..a73981b 100644
--- a/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js
+++ b/Magic.IndexedDb/wwwroot/utilities/protectedStorage.js
@@ -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);
diff --git a/docs/guides/managed-key-rotation.md b/docs/guides/managed-key-rotation.md
index 2456297..5dec50c 100644
--- a/docs/guides/managed-key-rotation.md
+++ b/docs/guides/managed-key-rotation.md
@@ -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.
diff --git a/tests/migrations/ProtectedWasm/App/App.razor b/tests/migrations/ProtectedWasm/App/App.razor
index 1e202f4..f9ba7f5 100644
--- a/tests/migrations/ProtectedWasm/App/App.razor
+++ b/tests/migrations/ProtectedWasm/App/App.razor
@@ -178,6 +178,16 @@
table = await database.Query();
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();
+ 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();
}
diff --git a/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml b/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml
index 3b26052..11a0b6b 100644
--- a/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml
+++ b/tests/migrations/ProtectedWasm/App/ILLink.Descriptors.xml
@@ -2,5 +2,6 @@
+
diff --git a/tests/migrations/ProtectedWasm/App/Program.cs b/tests/migrations/ProtectedWasm/App/Program.cs
index c766fd8..a437018 100644
--- a/tests/migrations/ProtectedWasm/App/Program.cs
+++ b/tests/migrations/ProtectedWasm/App/Program.cs
@@ -5,7 +5,7 @@
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("#app");
builder.Services.AddMagicBlazorDB(BlazorInteropMode.WASM, false,
- [typeof(ProtectedRow), typeof(RotationRow)], [typeof(ProtectedRepository)]);
+ [typeof(ProtectedRow), typeof(RotationRow), typeof(ReferenceRow)], [typeof(ProtectedRepository)]);
builder.Services.AddMagicIndexedDbEncryption(_ =>
[new MagicEncryptionOptions("protected-wasm", "published-account", "fixture-key")
{ PhysicalDatabaseName = ProtectedRepository.PhysicalName }]);
diff --git a/tests/migrations/ProtectedWasm/Exporter/Program.cs b/tests/migrations/ProtectedWasm/Exporter/Program.cs
index 5d7fc41..de90f00 100644
--- a/tests/migrations/ProtectedWasm/Exporter/Program.cs
+++ b/tests/migrations/ProtectedWasm/Exporter/Program.cs
@@ -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"] });
diff --git a/tests/migrations/ProtectedWasm/Model.cs b/tests/migrations/ProtectedWasm/Model.cs
index 9af73f8..674a0a9 100644
--- a/tests/migrations/ProtectedWasm/Model.cs
+++ b/tests/migrations/ProtectedWasm/Model.cs
@@ -42,3 +42,16 @@ public sealed class RotationRow : MagicTableTool, IMagicTable, IMagicTable
+{
+ [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 GetCompoundIndexes() => [];
+ public int Id { get; set; }
+ public string Target { get; set; } = "";
+}
diff --git a/tests/migrations/ReleasedUpgrade/protected-batch.mjs b/tests/migrations/ReleasedUpgrade/protected-batch.mjs
new file mode 100644
index 0000000..4d89b2f
--- /dev/null
+++ b/tests/migrations/ReleasedUpgrade/protected-batch.mjs
@@ -0,0 +1,166 @@
+import assert from 'node:assert/strict';
+
+export async function exerciseProtectedBatch(context, origin) {
+ const manifestUrl = new URL('/releases/rotation/rotation-wasm/manifest.json', origin).href;
+ const documents = 'rotation-records';
+ const references = 'references';
+ const route = '__magic_protected__:batch-fixture';
+ const open = async initialize => {
+ const page = await context.newPage();
+ assert.ok((await page.goto(manifestUrl)).ok());
+ await page.evaluate(async ({ manifestUrl, route, documents, references, initialize }) => {
+ window.batchApi = await import('/_content/Magic.IndexedDb/magicDB.js');
+ const manifest = await (await fetch(manifestUrl)).json();
+ const target = manifest.schemas.find(item => item.revision === manifest.targetRevision);
+ const model = await (await fetch(new URL(target.path, manifestUrl))).json();
+ await batchApi.createDb({
+ name: route,
+ migrationManifestUrl: manifestUrl, migrationSchema: model,
+ encryption: { account: 'batch-test', physicalName: route, explicitPhysicalBinding: true },
+ storeSchemas: [documents, references].map(tableName => ({
+ tableName, primaryKeyAuto: false, columnNamesInCompoundKey: ['Id'],
+ indexes: ['Id'], uniqueIndexes: [], columnNamesInCompoundIndex: [], exposedFields: ['Id']
+ }))
+ });
+ await batchApi.unlockProtectedDatabase(route, 'batch-key', new Uint8Array(32).fill(79), initialize);
+ await batchApi.ensureProtectedMigration(route);
+ }, { manifestUrl, route, documents, references, initialize });
+ return page;
+ };
+
+ const tabA = await open(true);
+ const tabB = await open(false);
+ const write = (page, storeName, record) =>
+ page.evaluate(({ route, storeName, record }) => batchApi.addItem({ dbName: route, storeName, record }),
+ { route, storeName, record });
+ const read = (page, store, key) =>
+ page.evaluate(({ route, store, key }) => batchApi.findItem(route, store, key), { route, store, key });
+ const commit = (page, entries) =>
+ page.evaluate(({ route, entries }) => batchApi.conditionalProtectedBatch(route, entries), { route, entries });
+ const entry = (store, Id, operation, member = null, expected = null, replacement = null) =>
+ ({ store, key: { Id }, operation, member, expected, replacement });
+
+ await write(tabA, documents, { Id: 100, Revision: 1, Generation: 7, Secret: 'Epoch' });
+ const epoch = entry(documents, 100, 'check', 'Generation', 7);
+ for (const [id, saveFirst] of [[1, true], [3, false]]) {
+ const marker = id + 1;
+ await write(tabA, documents, { Id: id, Revision: 1, Secret: 'Prepared document' });
+ await write(tabA, documents, { Id: marker, Revision: 1, Generation: 0, Secret: 'Reference count' });
+ // Both tabs finish making their decision before either tab is allowed to write.
+ async function prepare(page) {
+ const [record, state, fence] = await Promise.all([
+ read(page, documents, id), read(page, documents, marker), read(page, documents, 100)
+ ]);
+ assert.equal(record.Revision, 1);
+ assert.equal(state.Generation, 0);
+ assert.equal(fence.Generation, 7);
+ }
+ await Promise.all([prepare(tabA), prepare(tabB)]);
+ const eviction = [epoch, entry(documents, id, 'delete', 'Revision', 1),
+ entry(documents, marker, 'delete', 'Revision', 1)];
+ const save = [epoch, entry(documents, id, 'check', 'Revision', 1),
+ entry(references, id, 'insert', null, null, { Id: id, Target: 'Secret reference' }),
+ entry(documents, marker, 'replace', 'Revision', 1,
+ { Id: marker, Revision: 2, Generation: 1, Secret: 'Reference count' })];
+ if (saveFirst) {
+ assert.equal(await commit(tabB, save), true);
+ assert.equal(await commit(tabA, eviction), false);
+ assert.equal((await read(tabA, documents, marker)).Generation, 1);
+ assert.equal((await read(tabA, references, id)).Target, 'Secret reference');
+ } else {
+ assert.equal(await commit(tabA, eviction), true);
+ assert.equal(await commit(tabB, save), false);
+ assert.ok(!await read(tabB, references, id));
+ assert.ok(!await read(tabB, documents, marker));
+ await write(tabA, documents, { Id: id, Revision: 9, Secret: 'Different incarnation' });
+ assert.equal(await commit(tabB, save), false);
+ }
+ }
+
+ const insert = entry(references, 98, 'insert', null, null, { Id: 98, Target: 'Must not commit' });
+ await assert.rejects(() => commit(tabA, [epoch, epoch, insert]), /Represent each store and primary key once/);
+ await assert.rejects(() => commit(tabA, [entry(documents, 100, 'check', 'Id', 100), insert]),
+ /Batch tokens must be encrypted/);
+ assert.equal(await commit(tabA, [entry(documents, 100, 'check', 'Generation', 8), insert]), false);
+ assert.equal(await commit(tabA, [entry(documents, 1, 'check'), insert]), false);
+ assert.ok(!await read(tabA, references, 98));
+
+ // Pause at sealing the new reference, after the epoch snapshot was
+ // authenticated and before the first tab can open its write transaction.
+ await tabA.evaluate(() => {
+ const original = SubtleCrypto.prototype.encrypt;
+ let resume;
+ const resumed = new Promise(resolve => { resume = resolve; });
+ let markPaused;
+ window.batchPaused = new Promise(resolve => { markPaused = resolve; });
+ window.resumeBatch = resume;
+ SubtleCrypto.prototype.encrypt = async function (...args) {
+ SubtleCrypto.prototype.encrypt = original;
+ markPaused();
+ await resumed;
+ return original.apply(this, args);
+ };
+ });
+ const racing = commit(tabA, [epoch, insert]);
+ try {
+ await tabA.evaluate(() => batchPaused);
+ assert.equal(await commit(tabB, [entry(documents, 100, 'replace', 'Generation', 7,
+ { Id: 100, Revision: 2, Generation: 8, Secret: 'New epoch' })]), true);
+ } finally {
+ await tabA.evaluate(() => resumeBatch());
+ }
+ assert.equal(await racing, false, 'A guard changed after authentication and before native commit.');
+ assert.ok(!await read(tabA, references, 98), 'The stale snapshot must leave zero writes.');
+
+ const aborted = await tabA.evaluate(async ({ route, documents, references, epoch }) => {
+ const original = IDBObjectStore.prototype.add;
+ let staged = false;
+ IDBObjectStore.prototype.add = function (...args) {
+ const request = original.apply(this, args);
+ if (this.name === references && args[0].Id === 99) {
+ request.addEventListener('success', () => {
+ staged = true;
+ this.transaction.abort();
+ });
+ }
+ return request;
+ };
+ try {
+ await batchApi.conditionalProtectedBatch(route, [
+ epoch,
+ { store: documents, key: { Id: 1 }, operation: 'replace', member: 'Revision', expected: 1,
+ replacement: { Id: 1, Revision: 2, Secret: 'Must roll back' } },
+ { store: references, key: { Id: 99 }, operation: 'insert', member: null, expected: null,
+ replacement: { Id: 99, Target: 'Must roll back' } }
+ ]);
+ return false;
+ } catch {
+ return staged;
+ } finally {
+ IDBObjectStore.prototype.add = original;
+ }
+ }, { route, documents, references, epoch: { ...epoch, expected: 8 } });
+ assert.equal(aborted, true, 'The native transaction must abort after staging its final write.');
+ await tabA.close();
+ await tabB.close();
+
+ const reopened = await open(false);
+ assert.equal((await read(reopened, documents, 1)).Secret, 'Prepared document');
+ assert.equal((await read(reopened, references, 1)).Target, 'Secret reference');
+ assert.ok(!await read(reopened, references, 99));
+ const raw = await reopened.evaluate(({ route, references }) => new Promise((resolve, reject) => {
+ const request = indexedDB.open(route);
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => {
+ const db = request.result;
+ const get = db.transaction(references).objectStore(references).get(1);
+ get.onsuccess = () => {
+ db.close();
+ resolve(Object.keys(get.result).sort());
+ };
+ get.onerror = () => reject(get.error);
+ };
+ }), { route, references });
+ assert.deepEqual(raw, ['Id', '__magic_record']);
+ await reopened.close();
+}
diff --git a/tests/migrations/ReleasedUpgrade/run.mjs b/tests/migrations/ReleasedUpgrade/run.mjs
index 3af2dcc..1f29cf2 100644
--- a/tests/migrations/ReleasedUpgrade/run.mjs
+++ b/tests/migrations/ReleasedUpgrade/run.mjs
@@ -1,4 +1,5 @@
import assert from 'node:assert/strict';
+import { exerciseProtectedBatch } from './protected-batch.mjs';
import { platform, release, arch, version as osVersion } from 'node:os';
import { execFileSync } from 'node:child_process';
import { createServer } from 'node:http';
@@ -106,7 +107,7 @@ async function load(context, query = '') {
const results = [];
const cutoverCases = versions.includes('2.0.7') ? ['uncooperative-v2-writer', 'cooperative-v2-bridge'] : [];
-const expected = versions.length + cutoverCases.length + 2 + (versions.includes('2.0.7') ? 2 : 0);
+const expected = versions.length + cutoverCases.length + 3 + (versions.includes('2.0.7') ? 2 : 0);
async function runCase(name, action) {
const result = { name, state: 'failed' };
@@ -281,6 +282,11 @@ try {
}
});
+ await runCase('atomic-protected-batches-in-two-tabs', async context => {
+ deployment = buildMode + '/protected';
+ await exerciseProtectedBatch(context, origin);
+ });
+
if (versions.includes('2.0.7')) for (const legacyProtected of [false, true]) {
const scenario = legacyProtected ? 'released-numeric-vault' : 'released-numeric-enrollment';
await runCase(scenario, async (context, result) => {