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
8 changes: 6 additions & 2 deletions Notesnook.API/EventSources/SyncEventCounterSource.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Diagnostics.Tracing;

Expand All @@ -13,6 +14,7 @@ public sealed class SyncEventCounterSource : EventSource
private readonly Counter<int> pushV2Counter;
private readonly Counter<int> fetchV2Counter;
private readonly Counter<int> fetchV2Failures;
private readonly Counter<int> connectionRejections;
private readonly Histogram<long> fetchV2Duration;
private readonly Histogram<long> pushV2Duration;
private readonly Counter<int> purgeFailures;
Expand All @@ -22,7 +24,8 @@ private SyncEventCounterSource()
pushCounter = meter.CreateCounter<int>("sync.pushes", "pushes", "Total pushes");
fetchV2Counter = meter.CreateCounter<int>("sync.v2.fetches", "fetches", "Total v2 fetches");
pushV2Counter = meter.CreateCounter<int>("sync.v2.pushes", "pushes", "Total v2 pushes");
fetchV2Failures = meter.CreateCounter<int>("sync.v2.fetch_failures", "fetches", "Fetches that threw, including chunks the client rejected");
fetchV2Failures = meter.CreateCounter<int>("sync.v2.fetch_failures", "fetches", "Fetches that threw, by reason: disconnected, timeout, client_error or server_error");
connectionRejections = meter.CreateCounter<int>("sync.v2.connection_rejections", "connections", "Connections refused, by reason: unauthorized, account, hub or error");
fetchV2Duration = meter.CreateHistogram<long>("sync.v2.fetch_duration");
pushV2Duration = meter.CreateHistogram<long>("sync.v2.push_duration");
// no unit, which the Prometheus exporter would append to the name the alert rule uses
Expand All @@ -31,7 +34,8 @@ private SyncEventCounterSource()

public void Fetch() => fetchCounter.Add(1);
public void FetchV2() => fetchV2Counter.Add(1);
public void FetchV2Failed() => fetchV2Failures.Add(1);
public void FetchV2Failed(string reason) => fetchV2Failures.Add(1, new KeyValuePair<string, object?>("reason", reason));
public void ConnectionRejected(string reason) => connectionRejections.Add(1, new KeyValuePair<string, object?>("reason", reason));
public void PushV2() => pushV2Counter.Add(1);
public void Push() => pushCounter.Add(1);
public void RecordFetchDuration(long durationMs) => fetchV2Duration.Record(durationMs);
Expand Down
37 changes: 30 additions & 7 deletions Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using Notesnook.API.Authorization;
using Notesnook.API.Interfaces;

namespace Notesnook.API.Hubs
{
// hub connections outlive their token, so a deleted or reset user's open connection is cut off here instead
public class SyncAuthorizationHubFilter : IHubFilter
public class SyncAuthorizationHubFilter(ILogger<SyncAuthorizationHubFilter> logger) : IHubFilter
{
private const string GenerationKey = "generation";

Expand All @@ -22,16 +23,38 @@ public class SyncAuthorizationHubFilter : IHubFilter
return await next(invocationContext);
}

// HubConnectionHandler's own logging is turned off in appsettings.json: it logs every rejection below
// (e.g. unconfirmed emails) as an error, so connection failures are logged and counted here instead.
// Rejections are logged at Information, which production filters out, so the counter is what shows them.
public async Task OnConnectedAsync(HubLifetimeContext context, Func<HubLifetimeContext, Task> next)
{
var result = new SyncRequirement().IsAuthorized(context.Context.User, new PathString("/hubs/sync/v2"));
if (!result.Succeeded)
var stage = "unauthorized";
try
{
var reason = result.AuthorizationFailure?.FailureReasons.FirstOrDefault();
throw new HubException(reason?.Message ?? "Unauthorized");
var result = new SyncRequirement().IsAuthorized(context.Context.User, new PathString("/hubs/sync/v2"));
if (!result.Succeeded)
{
var reason = result.AuthorizationFailure?.FailureReasons.FirstOrDefault();
// clients read this message from the close error, so it must stay a HubException
throw new HubException(reason?.Message ?? "Unauthorized");
}
stage = "account";
await EnsureCurrentAsync(context.Context, context.ServiceProvider);
stage = "hub";
await next(context);
}
catch (HubException ex)
{
SyncEventCounterSource.Log.ConnectionRejected(stage);
logger.LogInformation("Connection {ConnectionId} rejected: {Reason}", context.Context.ConnectionId, ex.Message);
throw;
}
catch (Exception ex)
{
SyncEventCounterSource.Log.ConnectionRejected("error");
logger.LogError(ex, "OnConnectedAsync failed for connection {ConnectionId}", context.Context.ConnectionId);
throw;
}
await EnsureCurrentAsync(context.Context, context.ServiceProvider);
await next(context);
}

// uncached, since a connection must not write under its generation once a reset has ended it
Expand Down
122 changes: 72 additions & 50 deletions Notesnook.API/Hubs/SyncV2Hub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ You should have received a copy of the Affero GNU General Public License
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
Expand All @@ -34,14 +35,15 @@ You should have received a copy of the Affero GNU General Public License
using Notesnook.API.Helpers;
using Notesnook.API.Interfaces;
using Notesnook.API.Models;
using Notesnook.API.Repositories;
using Notesnook.API.Services;
using Streetwriters.Data.Interfaces;

namespace Notesnook.API.Hubs
{
public interface ISyncV2HubClient
{
Task<bool> SendItems(SyncTransferItemV2 transferItem);
Task<bool> SendItems(SyncTransferRawItemV2 transferItem);
Task<bool> SendVaultKey(EncryptedData vaultKey);
Task<bool> SendMonographs(IEnumerable<MonographMetadata> monographs);
Task<bool> SendInboxItems(IEnumerable<InboxSyncItem> inboxItems);
Expand All @@ -68,8 +70,8 @@ public SyncV2Hub(ISyncItemsRepositoryAccessor syncItemsRepositoryAccessor, IUnit
SyncDeviceService = syncDeviceService;

var synced = Repositories.SyncItemCollections.Where((c) => c.Type != null).ToArray();
BaseCollectionDefs = [.. synced.Where((c) => !c.RequiresV4).Select((c) => new CollectionDef(c.Type!, c.Repository.FindItemsById))];
V4CollectionDefs = [.. synced.Select((c) => new CollectionDef(c.Type!, c.Repository.FindItemsById))];
BaseCollectionDefs = [.. synced.Where((c) => !c.RequiresV4).Select((c) => new CollectionDef(c.Type!, c.Repository))];
V4CollectionDefs = [.. synced.Select((c) => new CollectionDef(c.Type!, c.Repository))];
UpsertActionsMap = synced.ToFrozenDictionary((c) => c.Type!, (c) => (Action<IEnumerable<SyncItem>, string>)c.Repository.UpsertMany);
}

Expand Down Expand Up @@ -156,56 +158,60 @@ public async Task<bool> PushCompletedV2(string deviceId)
return true;
}

private async IAsyncEnumerable<SyncTransferItemV2> PrepareChunks(string userId, HashSet<ItemKey> ids, int size, bool resetSync, long maxBytes, CollectionDef[] collectionDefs)
/// <summary>
/// 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.
/// </summary>
private static async IAsyncEnumerable<(CollectionDef Def, List<ObjectId> Ids)> PrepareChunks(string userId, HashSet<ItemKey> ids, bool resetSync, long maxBytes, int maxItems, CollectionDef[] collectionDefs)
{
var itemsProcessed = 0;
foreach (var def in collectionDefs)
{
var type = def.Key;

var filteredIds = ids.Where((id) => id.Type == type).Select((id) => id.ItemId).ToArray();
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.FindItems(userId, filteredIds, resetSync, size);
using var cursor = await def.Repository.FindItemSizes(userId, filteredIds, resetSync);

var chunk = new List<SyncItem>();
var chunk = new List<ObjectId>();
long totalBytes = 0;
long METADATA_BYTES = 5 * 1024;

while (await cursor.MoveNextAsync())
{
foreach (var item in cursor.Current)
{
chunk.Add(item);
totalBytes += item.Length + METADATA_BYTES;
if (totalBytes >= maxBytes)
chunk.Add(item.Id);
totalBytes += item.Size;
if (totalBytes >= maxBytes || chunk.Count >= maxItems)
{
itemsProcessed += chunk.Count;
yield return new SyncTransferItemV2
{
Items = chunk,
Type = type,
Count = itemsProcessed
};

yield return (def, chunk);
totalBytes = 0;
chunk.Clear();
chunk = [];
}
}
}
if (chunk.Count > 0)
{
itemsProcessed += chunk.Count;
yield return new SyncTransferItemV2
{
Items = chunk,
Type = type,
Count = itemsProcessed
};
}
if (chunk.Count > 0) yield return (def, chunk);
}
}

/// <summary>
/// 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.
/// </summary>
private async Task<(Task<bool> Ack, List<ItemKey> SentIds)> SendChunkAsync(string userId, CollectionDef def, List<ObjectId> 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<SyncV2Metadata> RequestFetch(string deviceId)
{
return await HandleRequestFetch(deviceId, false, false, BaseCollectionDefs);
Expand Down Expand Up @@ -249,19 +255,22 @@ private async Task<SyncV2Metadata> HandleRequestFetch(string deviceId, bool incl
var chunks = PrepareChunks(
userId,
ids,
size: 100,
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
);

await foreach (var chunk in chunks)
var itemsProcessed = 0;
await foreach (var (def, objectIds) in chunks)
{
if (!await Clients.Caller.SendItems(chunk).WaitAsync(TimeSpan.FromMinutes(10))) throw new HubException("Client rejected sent items.");
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)
if (!device.IsSyncReset && sentIds.Count > 0)
{
var sentIds = chunk.Items.Select(i => new ItemKey(i.ItemId, chunk.Type)).ToList();
ids.ExceptWith(sentIds);
await SyncDeviceService.RemovePendingIdsAsync(userId, deviceId, sentIds);
}
Expand Down Expand Up @@ -326,9 +335,17 @@ private async Task<SyncV2Metadata> HandleRequestFetch(string deviceId, bool incl
Synced = true,
};
}
catch
catch (Exception ex)
{
SyncEventCounterSource.Log.FetchV2Failed();
SyncEventCounterSource.Log.FetchV2Failed(ex switch
{
_ when Context.ConnectionAborted.IsCancellationRequested => "disconnected",
IOException or OperationCanceledException => "disconnected",
TimeoutException => "timeout",
// the client threw while handling what we sent, or acked it with false
HubException => "client_error",
_ => "server_error",
});
throw;
}
finally
Expand All @@ -337,31 +354,36 @@ private async Task<SyncV2Metadata> HandleRequestFetch(string deviceId, bool incl
}
}

private record CollectionDef(
string Key,
Func<string, IEnumerable<string>, bool, int, Task<IAsyncCursor<SyncItem>>> FindItems
);
private record CollectionDef(string Key, SyncItemsRepository Repository);
}

[MessagePack.MessagePackObject]
public struct SyncV2Metadata
{
[MessagePack.Key("synced")]
[JsonPropertyName("synced")]
public bool Synced { get; set; }
}

[MessagePack.MessagePackObject]
public struct SyncTransferItemV2
{
[MessagePack.Key("items")]
[JsonPropertyName("items")]
public IEnumerable<SyncItem> Items { get; set; }

[MessagePack.Key("type")]
[JsonPropertyName("type")]
public string Type { get; set; }
[MessagePack.Key("count")]
[JsonPropertyName("count")]
public int Count { get; set; }
}

/// <summary>
/// What <see cref="SyncTransferItemV2"/> is on the wire, with items that are sent from their stored bytes.
/// </summary>
public struct SyncTransferRawItemV2
{
[JsonPropertyName("items")]
public IEnumerable<RawSyncItem> Items { get; set; }

[JsonPropertyName("type")]
public string Type { get; set; }
[JsonPropertyName("count")]
public int Count { get; set; }
}
Expand Down
5 changes: 0 additions & 5 deletions Notesnook.API/Models/EncryptedData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,28 +25,23 @@

namespace Notesnook.API.Models
{
[MessagePack.MessagePackObject]
public class EncryptedData

Check warning on line 28 in Notesnook.API/Models/EncryptedData.cs

View workflow job for this annotation

GitHub Actions / Run tests

'EncryptedData' overrides Object.Equals(object o) but does not override Object.GetHashCode()
{
[MessagePack.Key("iv")]
[JsonPropertyName("iv")]
[BsonElement("iv")]
[DataMember(Name = "iv")]
public required string IV { get; set; }

[MessagePack.Key("cipher")]
[JsonPropertyName("cipher")]
[BsonElement("cipher")]
[DataMember(Name = "cipher")]
public required string Cipher { get; set; }

[MessagePack.Key("length")]
[JsonPropertyName("length")]
[BsonElement("length")]
[DataMember(Name = "length")]
public long Length { get; set; }

[MessagePack.Key("salt")]
[JsonPropertyName("salt")]
[BsonElement("salt")]
[DataMember(Name = "salt")]
Expand Down
1 change: 0 additions & 1 deletion Notesnook.API/Models/InboxApiKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ public InboxApiKey()
[BsonIgnoreIfDefault]
[BsonRepresentation(BsonType.ObjectId)]
[JsonIgnore]
[MessagePack.IgnoreMember]
public string Id { get; set; } = string.Empty;

[JsonPropertyName("userId")]
Expand Down
Loading
Loading