diff --git a/Notesnook.API/EventSources/SyncEventCounterSource.cs b/Notesnook.API/EventSources/SyncEventCounterSource.cs index 6c72d12..64d6c14 100644 --- a/Notesnook.API/EventSources/SyncEventCounterSource.cs +++ b/Notesnook.API/EventSources/SyncEventCounterSource.cs @@ -16,6 +16,8 @@ public sealed class SyncEventCounterSource : EventSource private readonly Counter fetchV2Failures; private readonly Counter connectionRejections; private readonly Histogram fetchV2Duration; + private readonly Histogram fetchV2ServerDuration; + private readonly Histogram fetchV2ClientDuration; private readonly Histogram pushV2Duration; private readonly Counter purgeFailures; private SyncEventCounterSource() @@ -27,6 +29,8 @@ private SyncEventCounterSource() fetchV2Failures = meter.CreateCounter("sync.v2.fetch_failures", "fetches", "Fetches that threw, by reason: disconnected, timeout, client_error or server_error"); connectionRejections = meter.CreateCounter("sync.v2.connection_rejections", "connections", "Connections refused, by reason: unauthorized, account, hub or error"); fetchV2Duration = meter.CreateHistogram("sync.v2.fetch_duration"); + fetchV2ServerDuration = meter.CreateHistogram("sync.v2.fetch_server_duration"); + fetchV2ClientDuration = meter.CreateHistogram("sync.v2.fetch_client_duration"); pushV2Duration = meter.CreateHistogram("sync.v2.push_duration"); // no unit, which the Prometheus exporter would append to the name the alert rule uses purgeFailures = meter.CreateCounter("users.purge_failures", null, "Deleted or reset users whose data failed to purge"); @@ -38,7 +42,13 @@ private SyncEventCounterSource() public void ConnectionRejected(string reason) => connectionRejections.Add(1, new KeyValuePair("reason", reason)); public void PushV2() => pushV2Counter.Add(1); public void Push() => pushCounter.Add(1); - public void RecordFetchDuration(long durationMs) => fetchV2Duration.Record(durationMs); + public void RecordFetchDuration(long durationMs, long clientDurationMs, bool fullSync) + { + var kind = new KeyValuePair("kind", fullSync ? "full" : "incremental"); + fetchV2Duration.Record(durationMs, kind); + fetchV2ServerDuration.Record(durationMs - clientDurationMs, kind); + fetchV2ClientDuration.Record(clientDurationMs, kind); + } public void RecordPushDuration(long durationMs) => pushV2Duration.Record(durationMs); public void PurgeFailed() => purgeFailures.Add(1); // a counter is only exported once it has a value, and increase() can't count the failure that creates it diff --git a/Notesnook.API/Hubs/FetchSender.cs b/Notesnook.API/Hubs/FetchSender.cs new file mode 100644 index 0000000..21e7dd0 --- /dev/null +++ b/Notesnook.API/Hubs/FetchSender.cs @@ -0,0 +1,156 @@ +/* +This file is part of the Notesnook Sync Server project (https://notesnook.com/) + +Copyright (C) 2023 Streetwriters (Private) Limited + +This program is free software: you can redistribute it and/or modify +it under the terms of the Affero GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +Affero GNU General Public License for more details. + +You should have received a copy of the Affero GNU General Public License +along with this program. If not, see . +*/ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.SignalR; +using MongoDB.Bson; +using Notesnook.API.Models; +using Notesnook.API.Repositories; +using Notesnook.API.Services; + +namespace Notesnook.API.Hubs +{ + public record CollectionDef(string Key, SyncItemsRepository Repository); + + public sealed class FetchSender(string userId, IReadOnlyList collections, ISyncV2HubClient client) + { + private const long MaxChunkBytes = 3 * 1024 * 1024; + // clients apply each chunk as one batch, so small items must not pack thousands into one + private const int MaxChunkItems = 500; + private static readonly TimeSpan AckTimeout = TimeSpan.FromMinutes(10); + + private readonly Stopwatch clientStopwatch = new(); + + public long ClientMilliseconds => clientStopwatch.ElapsedMilliseconds; + + public async IAsyncEnumerable> SendItemsAsync(IEnumerable ids, bool fullSync) + { + var idsByType = ids.GroupBy((id) => id.Type).ToDictionary((g) => g.Key, (g) => g.Select((id) => id.ItemId).ToArray()); + await using var chunks = PrepareChunks(idsByType, fullSync).GetAsyncEnumerator(); + + // the next chunk is read while the client applies the current one: reads mostly wait on the disk + var next = ReadChunkAsync(chunks); + try + { + var itemsProcessed = 0; + var sent = Send(await next, itemsProcessed); + next = ReadChunkAsync(chunks); + while (sent is { } current) + { + if (!await WaitForClientAsync(current.Ack)) throw new HubException("Client rejected sent items."); + itemsProcessed += current.SentIds.Count; + // the next chunk goes out before these ids are handed back, so the client applies it while the caller handles them + sent = Send(await next, itemsProcessed); + next = ReadChunkAsync(chunks); + if (current.SentIds.Count > 0) yield return current.SentIds; + } + } + finally + { + // the enumerator can't be disposed while a read is still using it, and if sending + // already failed, the read's own failure isn't the one to report + try { await next; } catch { } + } + } + + public async Task SendMonographsAsync(IReadOnlyCollection monographs) + { + if (monographs.Count > 0 && !await WaitForClientAsync(client.SendMonographs(monographs))) throw new HubException("Client rejected monographs."); + } + + public async Task SendInboxItemsAsync(IReadOnlyCollection inboxItems) + { + if (inboxItems.Count > 0 && !await WaitForClientAsync(client.SendInboxItems(inboxItems))) throw new HubException("Client rejected inbox items."); + } + + private async Task WaitForClientAsync(Task ack) + { + clientStopwatch.Start(); + try + { + return await ack.WaitAsync(AckTimeout); + } + finally + { + clientStopwatch.Stop(); + } + } + + /// + /// Groups the items to send into chunks by their stored size, reading only ids and sizes, so a fetch + /// holds one chunk of items at a time instead of a whole cursor batch. + /// + private async IAsyncEnumerable<(CollectionDef Def, List Ids)> PrepareChunks(Dictionary idsByType, bool fullSync) + { + foreach (var def in collections) + { + var filteredIds = idsByType.GetValueOrDefault(def.Key) ?? []; + if (!fullSync && filteredIds.Length == 0) continue; + + using var cursor = await def.Repository.FindItemSizes(userId, filteredIds, fullSync); + + var chunk = new List(); + long totalBytes = 0; + + while (await cursor.MoveNextAsync()) + { + foreach (var item in cursor.Current) + { + chunk.Add(item.Id); + totalBytes += item.Size; + if (totalBytes >= MaxChunkBytes || chunk.Count >= MaxChunkItems) + { + yield return (def, chunk); + totalBytes = 0; + chunk = []; + } + } + } + if (chunk.Count > 0) yield return (def, chunk); + } + } + + private async Task<(CollectionDef Def, List Items)?> ReadChunkAsync(IAsyncEnumerator<(CollectionDef Def, List Ids)> chunks) + { + if (!await chunks.MoveNextAsync()) return null; + var (def, objectIds) = chunks.Current; + return (def, await def.Repository.FindItemsByObjectIds(userId, objectIds)); + } + + private (Task Ack, List SentIds)? Send((CollectionDef Def, List Items)? chunk, int itemsProcessed) + { + if (chunk is not { } c) return null; + var sentIds = c.Items.Select((i) => new ItemKey(i.ItemId, c.Def.Key)).ToList(); + // items deleted since their sizes were read + if (c.Items.Count == 0) return (Task.FromResult(true), sentIds); + + var ack = client.SendItems(new SyncTransferRawItemV2 + { + Items = c.Items, + Type = c.Def.Key, + Count = itemsProcessed + c.Items.Count + }); + return (ack, sentIds); + } + } +} diff --git a/Notesnook.API/Hubs/SyncV2Hub.cs b/Notesnook.API/Hubs/SyncV2Hub.cs index 32b323a..b88e4f9 100644 --- a/Notesnook.API/Hubs/SyncV2Hub.cs +++ b/Notesnook.API/Hubs/SyncV2Hub.cs @@ -158,60 +158,6 @@ public async Task PushCompletedV2(string deviceId) return true; } - /// - /// Groups the items to send into chunks by their stored size, reading only ids and sizes, so a fetch - /// holds one chunk of items at a time instead of a whole cursor batch. - /// - private static async IAsyncEnumerable<(CollectionDef Def, List Ids)> PrepareChunks(string userId, HashSet ids, bool resetSync, long maxBytes, int maxItems, CollectionDef[] collectionDefs) - { - foreach (var def in collectionDefs) - { - var filteredIds = ids.Where((id) => id.Type == def.Key).Select((id) => id.ItemId).ToArray(); - if (!resetSync && filteredIds.Length == 0) continue; - - using var cursor = await def.Repository.FindItemSizes(userId, filteredIds, resetSync); - - var chunk = new List(); - long totalBytes = 0; - - while (await cursor.MoveNextAsync()) - { - foreach (var item in cursor.Current) - { - chunk.Add(item.Id); - totalBytes += item.Size; - if (totalBytes >= maxBytes || chunk.Count >= maxItems) - { - yield return (def, chunk); - totalBytes = 0; - chunk = []; - } - } - } - if (chunk.Count > 0) yield return (def, chunk); - } - } - - /// - /// Loads and sends one chunk, and returns without awaiting the client's ack so that the items - /// aren't kept alive while the client applies them. - /// - private async Task<(Task Ack, List SentIds)> SendChunkAsync(string userId, CollectionDef def, List objectIds, int itemsProcessed) - { - var items = await def.Repository.FindItemsByObjectIds(userId, objectIds); - var sentIds = items.Select((i) => new ItemKey(i.ItemId, def.Key)).ToList(); - // items deleted since their sizes were read - if (items.Count == 0) return (Task.FromResult(true), sentIds); - - var ack = Clients.Caller.SendItems(new SyncTransferRawItemV2 - { - Items = items, - Type = def.Key, - Count = itemsProcessed + items.Count - }); - return (ack, sentIds); - } - public async Task RequestFetch(string deviceId) { return await HandleRequestFetch(deviceId, false, false, CollectionDefs(includeV4: false)); @@ -243,92 +189,29 @@ private async Task HandleRequestFetch(string deviceId, bool incl if (device == null) device = await SyncDeviceService.RegisterDeviceAsync(userId, deviceId); else - await SyncDeviceService.UpdateLastAccessTimeAsync(userId, deviceId); + await SyncDeviceService.UpdateLastAccessTimeAsync(device); var stopwatch = Stopwatch.StartNew(); + var sender = new FetchSender(userId, collectionDefs, Clients.Caller); try { - var ids = await SyncDeviceService.FetchUnsyncedIdsAsync(userId, deviceId); + var ids = await SyncDeviceService.FetchUnsyncedIdsAsync(device); if (!device.IsSyncReset && ids.Count == 0) return new SyncV2Metadata { Synced = true }; - var chunks = PrepareChunks( - userId, - ids, - resetSync: device.IsSyncReset, - maxBytes: 3 * 1024 * 1024, - // clients apply each chunk as one batch, so small items must not pack thousands into one - maxItems: 500, - collectionDefs - ); - - var itemsProcessed = 0; - await foreach (var (def, objectIds) in chunks) + await foreach (var sentIds in sender.SendItemsAsync(ids, device.IsSyncReset)) { - var (ack, sentIds) = await SendChunkAsync(userId, def, objectIds, itemsProcessed); - if (!await ack.WaitAsync(TimeSpan.FromMinutes(10))) throw new HubException("Client rejected sent items."); - itemsProcessed += sentIds.Count; - - if (!device.IsSyncReset && sentIds.Count > 0) - { - ids.ExceptWith(sentIds); - await SyncDeviceService.RemovePendingIdsAsync(userId, deviceId, sentIds); - } + if (!device.IsSyncReset) await SyncDeviceService.RemovePendingIdsAsync(userId, deviceId, sentIds); } if (includeMonographs) - { - var unsyncedMonographIds = ids.Where(k => k.Type == "monograph").Select(k => k.ItemId).ToList(); - // _id is stored as an ObjectId, so string IDs would never match it - var unsyncedMonographObjectIds = unsyncedMonographIds.Where(id => ObjectId.TryParse(id, out _)).Select(ObjectId.Parse); - FilterDefinition filter = device.IsSyncReset - ? Builders.Filter.Eq(m => m.UserId, userId) - : Builders.Filter.And( - Builders.Filter.Eq(m => m.UserId, userId), - Builders.Filter.Or( - Builders.Filter.In(m => m.ItemId, unsyncedMonographIds), - Builders.Filter.In("_id", unsyncedMonographObjectIds) - ) - ); - var userMonographs = await Repositories.Monographs.Collection - .Find(filter) - .Project((m) => new MonographMetadata - { - DatePublished = m.DatePublished, - Deleted = m.Deleted, - Password = m.Password, - SelfDestruct = m.SelfDestruct, - Title = m.Title, - ItemId = m.ItemId ?? m.Id.ToString(), - PublishUrl = m.Slug // this will be converted to full url in the end, but we only need slug for now - }) - .ToListAsync(); - - userMonographs = userMonographs.Select((p) => - { - p.PublishUrl = UrlHelper.ConstructPublishUrl(p); - return p; - }).ToList(); - - if (userMonographs.Count > 0 && !await Clients.Caller.SendMonographs(userMonographs).WaitAsync(TimeSpan.FromMinutes(10))) - throw new HubException("Client rejected monographs."); - } - + await sender.SendMonographsAsync(await FindMonographsAsync(userId, IdsOfType(ids, "monograph"), device.IsSyncReset)); if (includeInboxItems) - { - var unsyncedInboxItemIds = ids.Where(k => k.Type == "inbox_item").Select(k => k.ItemId); - var userInboxItems = device.IsSyncReset - ? await Repositories.InboxItems.FindAsync(m => m.UserId == userId) - : await Repositories.InboxItems.FindAsync(m => m.UserId == userId && unsyncedInboxItemIds.Contains(m.ItemId)); - if (userInboxItems.Any() && !await Clients.Caller.SendInboxItems(userInboxItems).WaitAsync(TimeSpan.FromMinutes(10))) - { - throw new HubException("Client rejected inbox items."); - } - } + await sender.SendInboxItemsAsync(await FindInboxItemsAsync(userId, IdsOfType(ids, "inbox_item"), device.IsSyncReset)); // a device that fetched across a reset re-registered after its deletion, and must still do a full sync after logging in again if (await Repositories.Generations.IsCurrentAsync(userId)) - await SyncDeviceService.ResetAsync(userId, deviceId); + await SyncDeviceService.ResetAsync(userId, deviceId, device.IsSyncReset); return new SyncV2Metadata { @@ -350,14 +233,53 @@ private async Task HandleRequestFetch(string deviceId, bool incl } finally { - SyncEventCounterSource.Log.RecordFetchDuration(stopwatch.ElapsedMilliseconds); + SyncEventCounterSource.Log.RecordFetchDuration(stopwatch.ElapsedMilliseconds, sender.ClientMilliseconds, device.IsSyncReset); } } + private static List IdsOfType(IEnumerable ids, string type) => [.. ids.Where((k) => k.Type == type).Select((k) => k.ItemId)]; + + private async Task> FindMonographsAsync(string userId, List ids, bool fullSync) + { + if (!fullSync && ids.Count == 0) return []; + // _id is stored as an ObjectId, so string IDs would never match it + var objectIds = ids.Where(id => ObjectId.TryParse(id, out _)).Select(ObjectId.Parse); + FilterDefinition filter = fullSync + ? Builders.Filter.Eq(m => m.UserId, userId) + : Builders.Filter.And( + Builders.Filter.Eq(m => m.UserId, userId), + Builders.Filter.Or( + Builders.Filter.In(m => m.ItemId, ids), + Builders.Filter.In("_id", objectIds) + ) + ); + var monographs = await Repositories.Monographs.Collection + .Find(filter) + .Project((m) => new MonographMetadata + { + DatePublished = m.DatePublished, + Deleted = m.Deleted, + Password = m.Password, + SelfDestruct = m.SelfDestruct, + Title = m.Title, + ItemId = m.ItemId ?? m.Id.ToString(), + PublishUrl = m.Slug // this will be converted to full url in the end, but we only need slug for now + }) + .ToListAsync(); + foreach (var monograph in monographs) monograph.PublishUrl = UrlHelper.ConstructPublishUrl(monograph); + return monographs; + } + + private async Task> FindInboxItemsAsync(string userId, List ids, bool fullSync) + { + if (fullSync) return [.. await Repositories.InboxItems.FindAsync(m => m.UserId == userId)]; + if (ids.Count == 0) return []; + return [.. await Repositories.InboxItems.FindAsync(m => m.UserId == userId && ids.Contains(m.ItemId))]; + } + private CollectionDef[] CollectionDefs(bool includeV4) => [.. Repositories.SyncItemCollections.Where((c) => c.Type != null && (includeV4 || !c.RequiresV4)).Select((c) => new CollectionDef(c.Type!, c.Repository))]; - private record CollectionDef(string Key, SyncItemsRepository Repository); } public struct SyncV2Metadata diff --git a/Notesnook.API/Services/SyncDeviceService.cs b/Notesnook.API/Services/SyncDeviceService.cs index 6df4108..f5da85e 100644 --- a/Notesnook.API/Services/SyncDeviceService.cs +++ b/Notesnook.API/Services/SyncDeviceService.cs @@ -108,7 +108,12 @@ public async Task WriteIdsAsync(string userId, string deviceId, string key, IEnu public async Task> FetchUnsyncedIdsAsync(string userId, string deviceId) { var device = await GetDeviceAsync(userId, deviceId); - if (device == null) return []; + return device == null ? [] : await FetchUnsyncedIdsAsync(device); + } + + public async Task> FetchUnsyncedIdsAsync(SyncDevice device) + { + var (userId, deviceId) = (device.UserId, device.DeviceId); if (device.IsSyncReset) { // starting a full sync: it will send every item as it is now, so ids recorded @@ -138,10 +143,11 @@ await collection.BulkWriteAsync( ]); } - public async Task ResetAsync(string userId, string deviceId) + public async Task ResetAsync(string userId, string deviceId, bool isSyncReset = true) { - await repositories.SyncDevices.Collection.UpdateOneAsync(DeviceFilter(userId, deviceId), Builders.Update - .Set(x => x.IsSyncReset, false)); + if (isSyncReset) + await repositories.SyncDevices.Collection.UpdateOneAsync(DeviceFilter(userId, deviceId), Builders.Update + .Set(x => x.IsSyncReset, false)); await repositories.DeviceIdsChunks.Collection.DeleteManyAsync(DeviceIdsChunkFilter(userId, deviceId, "pending")); } @@ -156,12 +162,23 @@ public async Task ResetDevicesAsync(string userId) await repositories.DeviceIdsChunks.Collection.DeleteManyAsync(DeviceIdsChunkFilter(userId)); } + // devices are only pruned after months without a sync, and writing on every push and fetch + // made a device's concurrent calls conflict on its document and retry for up to seconds + private static readonly long LastAccessTimeResolution = (long)TimeSpan.FromMinutes(5).TotalMilliseconds; + public async Task UpdateLastAccessTimeAsync(string userId, string deviceId) { - await repositories.SyncDevices.Collection.UpdateOneAsync(DeviceFilter(userId, deviceId), Builders.Update - .Set(x => x.LastAccessTime, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())); + var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + await repositories.SyncDevices.Collection.UpdateOneAsync( + DeviceFilter(userId, deviceId) & Builders.Filter.Lt(x => x.LastAccessTime, now - LastAccessTimeResolution), + Builders.Update.Set(x => x.LastAccessTime, now)); } + public Task UpdateLastAccessTimeAsync(SyncDevice device) => + device.LastAccessTime < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - LastAccessTimeResolution + ? UpdateLastAccessTimeAsync(device.UserId, device.DeviceId) + : Task.CompletedTask; + public async Task AddIdsToOtherDevicesAsync(string userId, string deviceId, IEnumerable ids) { await UpdateLastAccessTimeAsync(userId, deviceId); diff --git a/tests/Notesnook.API.Tests/FetchSenderTests.cs b/tests/Notesnook.API.Tests/FetchSenderTests.cs new file mode 100644 index 0000000..c15a03e --- /dev/null +++ b/tests/Notesnook.API.Tests/FetchSenderTests.cs @@ -0,0 +1,176 @@ +using Microsoft.AspNetCore.SignalR; +using MongoDB.Driver; +using Notesnook.API.Hubs; +using Notesnook.API.Models; +using Notesnook.API.Services; + +namespace Notesnook.API.Tests; + +public class FetchSenderTests(TestDatabase db) : IClassFixture +{ + private async Task<(string UserId, List Notes)> InsertNotesAsync(int count, int cipherLength) + { + var userId = Guid.NewGuid().ToString("N"); + var notes = Enumerable.Range(0, count).Select((_) => new SyncItem + { + UserId = userId, + ItemId = Guid.NewGuid().ToString("N"), + Cipher = new string('a', cipherLength), + IV = "iv", + Length = cipherLength, + Version = 5.9, + Algorithm = Algorithms.Default + }).ToList(); + await db.CreateScope().Repositories.Notes.Collection.InsertManyAsync(notes); + return (userId, notes); + } + + private CollectionDef[] Notes() => [new("note", db.CreateScope().Repositories.Notes)]; + + private FetchSender Sender(string userId, Func> sendItems) => + new(userId, Notes(), Stub.Create(("SendItems", (args) => sendItems((SyncTransferRawItemV2)args[0]!)))); + + private FetchSender Sender(params (string Method, Func Handler)[] handlers) => + new("user", Notes(), Stub.Create(handlers)); + + private static async Task>> SendItemsAsync(FetchSender sender, IEnumerable ids, bool fullSync) + { + var sent = new List>(); + await foreach (var sentIds in sender.SendItemsAsync(ids, fullSync)) sent.Add(sentIds); + return sent; + } + + [Fact] + public async Task The_next_chunk_is_read_while_the_client_applies_the_current_one() + { + // 1MB items, so 3 per chunk + var (userId, _) = await InsertNotesAsync(9, 1024 * 1024); + var sent = new List(); + var sender = Sender(userId, async (chunk) => + { + sent.Add(chunk); + if (sent.Count > 1) return true; + // the second chunk was read while this one was applied, so deleting its items now doesn't change it + await Task.Delay(500); + await db.CreateScope().Repositories.Notes.Collection.DeleteManyAsync((n) => n.UserId == userId); + return true; + }); + + await SendItemsAsync(sender, [], fullSync: true); + + Assert.Equal([3, 3], sent.Select((c) => c.Items.Count())); + } + + [Fact] + public async Task A_chunk_is_not_kept_alive_while_the_client_applies_it() + { + var (userId, _) = await InsertNotesAsync(6, 1024 * 1024); + var sentItems = new List(); + var aliveWhileApplying = new List(); + // the ack can't capture the chunk, as a client that keeps a chunk alive would fail this too + async Task ApplyAsync(WeakReference items) + { + await Task.Delay(200); + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + aliveWhileApplying.Add(items.IsAlive); + return true; + } + var sender = Sender(userId, (chunk) => + { + var items = new WeakReference(chunk.Items); + sentItems.Add(items); + return ApplyAsync(items); + }); + + await SendItemsAsync(sender, [], fullSync: true); + + Assert.Equal([false, false], aliveWhileApplying); + } + + [Fact] + public async Task Only_the_given_ids_are_sent_and_reported_per_chunk() + { + var (userId, notes) = await InsertNotesAsync(8, 1024 * 1024); + var pending = notes.Take(5).Select((n) => new ItemKey(n.ItemId!, "note")).ToHashSet(); + var sender = Sender(userId, (_) => Task.FromResult(true)); + + var reported = new List>(); + await foreach (var ids in sender.SendItemsAsync(pending, fullSync: false)) + { + reported.Add(ids); + pending.ExceptWith(ids); + } + + Assert.Equal([3, 2], reported.Select((r) => r.Count)); + Assert.Equal(notes.Take(5).Select((n) => n.ItemId).Order(), reported.SelectMany((r) => r).Select((k) => k.ItemId).Order()); + Assert.Empty(pending); + } + + [Fact] + public async Task The_next_chunk_is_sent_before_the_ids_of_the_current_one_are_handed_back() + { + var (userId, notes) = await InsertNotesAsync(8, 1024 * 1024); + var sent = 0; + var sender = Sender(userId, (_) => { sent++; return Task.FromResult(true); }); + var sentWhenHandedBack = new List(); + + await foreach (var _ in sender.SendItemsAsync(notes.Select((n) => new ItemKey(n.ItemId!, "note")), fullSync: false)) + sentWhenHandedBack.Add(sent); + + Assert.Equal([2, 3, 3], sentWhenHandedBack); + } + + [Fact] + public async Task A_rejected_chunk_fails_without_reporting_it() + { + var (userId, notes) = await InsertNotesAsync(6, 1024 * 1024); + var reported = new List(); + var sender = Sender(userId, (_) => Task.FromResult(false)); + + await Assert.ThrowsAsync(async () => + { + await foreach (var ids in sender.SendItemsAsync(notes.Select((n) => new ItemKey(n.ItemId!, "note")), fullSync: false)) reported.AddRange(ids); + }); + + Assert.Empty(reported); + } + + [Theory] + [InlineData(0, false)] + [InlineData(2, true)] + public async Task Monographs_are_sent_only_if_there_are_any(int count, bool sent) + { + var calls = 0; + var sender = Sender(("SendMonographs", (_) => { calls++; return Task.FromResult(true); })); + + await sender.SendMonographsAsync(Enumerable.Range(0, count).Select((_) => new MonographMetadata { ItemId = "monograph" }).ToList()); + + Assert.Equal(sent ? 1 : 0, calls); + } + + [Fact] + public async Task Rejected_inbox_items_fail_the_fetch() + { + var sender = Sender(("SendInboxItems", (_) => Task.FromResult(false))); + + var error = await Assert.ThrowsAsync(() => sender.SendInboxItemsAsync([new InboxSyncItem()])); + + Assert.Equal("Client rejected inbox items.", error.Message); + } + + [Fact] + public async Task Waiting_for_the_client_is_timed() + { + var (userId, _) = await InsertNotesAsync(6, 1024 * 1024); + var sender = new FetchSender(userId, Notes(), Stub.Create( + ("SendItems", (_) => Task.Delay(150).ContinueWith((_) => true)), + ("SendMonographs", (_) => Task.Delay(150).ContinueWith((_) => true)))); + + await SendItemsAsync(sender, [], fullSync: true); + await sender.SendMonographsAsync([new MonographMetadata { ItemId = "monograph" }]); + + Assert.InRange(sender.ClientMilliseconds, 3 * 140, 3 * 1000); + } +} diff --git a/tests/Notesnook.API.Tests/SyncDeviceServiceTests.cs b/tests/Notesnook.API.Tests/SyncDeviceServiceTests.cs index 43ab86e..1fa22b4 100644 --- a/tests/Notesnook.API.Tests/SyncDeviceServiceTests.cs +++ b/tests/Notesnook.API.Tests/SyncDeviceServiceTests.cs @@ -35,6 +35,24 @@ await collection.Indexes.CreateOneAsync(new CreateIndexModel( Assert.True(Assert.Single(stored).IsSyncReset); } + [Theory] + [InlineData(1, false)] + [InlineData(10, true)] + public async Task The_last_access_time_is_only_written_once_it_is_minutes_old(int minutesAgo, bool written) + { + var userId = NewUserId(); + var devices = db.CreateScope().Devices; + await devices.RegisterDeviceAsync(userId, "A"); + var before = DateTimeOffset.UtcNow.AddMinutes(-minutesAgo).ToUnixTimeMilliseconds(); + var collection = db.CreateScope().Repositories.SyncDevices.Collection; + await collection.UpdateOneAsync((d) => d.UserId == userId, Builders.Update.Set((d) => d.LastAccessTime, before)); + + await devices.UpdateLastAccessTimeAsync(userId, "A"); + + var stored = (await collection.Find((d) => d.UserId == userId).SingleAsync()).LastAccessTime; + Assert.Equal(written, stored != before); + } + [Fact] public async Task Fetch_merges_unsynced_into_pending() { diff --git a/tests/Notesnook.API.Tests/SyncV2HubTests.cs b/tests/Notesnook.API.Tests/SyncV2HubTests.cs index 269ab93..7722dfa 100644 --- a/tests/Notesnook.API.Tests/SyncV2HubTests.cs +++ b/tests/Notesnook.API.Tests/SyncV2HubTests.cs @@ -169,7 +169,10 @@ public async Task A_monograph_without_an_item_id_is_sent_by_its_object_id() Assert.Equal(monograph.Id, Assert.Single(sent).ItemId); } - private async Task> InsertNotesAsync(string userId, int count, int cipherLength, long length) + private Task> InsertNotesAsync(string userId, int count, int cipherLength, long length) => + InsertItemsAsync(userId, count, cipherLength, length, (r) => r.Notes); + + private async Task> InsertItemsAsync(string userId, int count, int cipherLength, long length, Func collection) { var notes = Enumerable.Range(0, count).Select((_) => new SyncItem { @@ -181,7 +184,7 @@ private async Task> InsertNotesAsync(string userId, int count, in Version = 5.9, Algorithm = Algorithms.Default }).ToList(); - await db.CreateScope().Repositories.Notes.Collection.InsertManyAsync(notes); + await collection(db.CreateScope().Repositories).Collection.InsertManyAsync(notes); return notes; } @@ -250,6 +253,71 @@ public async Task An_incremental_fetch_sends_only_the_pending_items_and_clears_t Assert.Empty(await devices.GetIdsAsync(userId, "device", "unsynced")); } + private SyncV2Hub HubWithSlowClient(string userId, List sent, TimeSpan delay) + { + var client = Stub.Create( + ("SendItems", (args) => + { + lock (sent) sent.Add((SyncTransferRawItemV2)args[0]!); + return Task.Delay(delay).ContinueWith((_) => true); + }), + ("SendMonographs", (_) => Task.FromResult(true)), + ("SendInboxItems", (_) => Task.FromResult(true))); + var hub = Hub(userId); + hub.Clients = Stub>.Create(("get_Caller", (_) => client)); + return hub; + } + + [Fact] + public async Task An_incremental_fetch_across_collections_sends_every_pending_item_once() + { + var userId = Guid.NewGuid().ToString("N"); + var notes = await InsertNotesAsync(userId, 8, 1024 * 1024, length: 1024 * 1024); + var relations = await InsertItemsAsync(userId, 3, 100, 100, (r) => r.Relations); + var devices = db.CreateScope().Devices; + await devices.RegisterDeviceAsync(userId, "device"); + await devices.ResetAsync(userId, "device"); + await devices.AddIdsToAllDevicesAsync(userId, [.. notes.Select((n) => new ItemKey(n.ItemId!, "note")), .. relations.Select((r) => new ItemKey(r.ItemId!, "relation"))]); + var sent = new List(); + + await HubWithSlowClient(userId, sent, TimeSpan.FromMilliseconds(20)).RequestFetchV4("device"); + + Assert.Equal(["note", "note", "note", "relation"], sent.Select((c) => c.Type)); + Assert.Equal(notes.Concat(relations).Select((n) => n.ItemId).Order(), sent.SelectMany((c) => c.Items).Select((i) => i.ItemId).Order()); + Assert.Empty(await devices.GetIdsAsync(userId, "device", "pending")); + } + + [Fact] + public async Task A_fetch_records_how_long_it_waited_for_the_client() + { + var userId = Guid.NewGuid().ToString("N"); + await InsertNotesAsync(userId, 8, 1024 * 1024, length: 1024 * 1024); + await db.CreateScope().Devices.RegisterDeviceAsync(userId, "new"); + var recorded = new List<(string Instrument, long Value, string? Kind)>(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (i, l) => + { + if (i.Meter.Name == "Notesnook.API.Metrics.Sync" && i.Name.StartsWith("sync.v2.fetch_")) l.EnableMeasurementEvents(i); + }; + listener.SetMeasurementEventCallback((i, value, tags, _) => + { + string? kind = null; + foreach (var tag in tags) if (tag.Key == "kind") kind = (string?)tag.Value; + lock (recorded) recorded.Add((i.Name, value, kind)); + }); + listener.Start(); + + await HubWithSlowClient(userId, [], TimeSpan.FromMilliseconds(400)).RequestFetchV4("new"); + + // other tests' fetches show up too, but none of them waits anywhere near 3 x 400ms for its client + List<(string Instrument, long Value, string? Kind)> measurements; + lock (recorded) measurements = [.. recorded]; + var client = Assert.Single(measurements, (m) => m.Instrument == "sync.v2.fetch_client_duration" && m.Value >= 1000); + Assert.Equal("full", client.Kind); + Assert.Contains(measurements, (total) => total.Instrument == "sync.v2.fetch_duration" && measurements.Any((server) => + server.Instrument == "sync.v2.fetch_server_duration" && server.Kind == "full" && server.Value == total.Value - client.Value)); + } + [Fact] public async Task A_rejected_chunk_is_sent_again_on_the_next_fetch() {