Skip to content
28 changes: 15 additions & 13 deletions Notesnook.API/Accessors/SyncItemsRepositoryAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public class SyncItemsRepositoryAccessor : ISyncItemsRepositoryAccessor
public Repository<InboxSyncItem> InboxItems { get; }
public Repository<SyncDevice> SyncDevices { get; }
public Repository<DeviceIdsChunk> DeviceIdsChunks { get; }
public UserGenerations Generations { get; }
public IReadOnlyList<SyncItemCollection> SyncItemCollections { get; }

public SyncItemsRepositoryAccessor(IDbContext dbContext,
Expand Down Expand Up @@ -95,19 +96,20 @@ public SyncItemsRepositoryAccessor(IDbContext dbContext,
InboxItems = inboxItems;
SyncDevices = syncDevices;
DeviceIdsChunks = deviceIdsChunks;
Notebooks = new SyncItemsRepository(dbContext, notebooks, logger);
Notes = new SyncItemsRepository(dbContext, notes, logger);
Contents = new SyncItemsRepository(dbContext, content, logger);
Settings = new SyncItemsRepository(dbContext, settings, logger);
LegacySettings = new SyncItemsRepository(dbContext, legacySettings, logger);
Attachments = new SyncItemsRepository(dbContext, attachments, logger);
Shortcuts = new SyncItemsRepository(dbContext, shortcuts, logger);
Reminders = new SyncItemsRepository(dbContext, reminders, logger);
Relations = new SyncItemsRepository(dbContext, relations, logger);
Colors = new SyncItemsRepository(dbContext, colors, logger);
Vaults = new SyncItemsRepository(dbContext, vaults, logger);
Tags = new SyncItemsRepository(dbContext, tags, logger);
InboxItemsHistory = new SyncItemsRepository(dbContext, inboxItemsHistory, logger);
Generations = new UserGenerations(usersSettings.Collection);
Notebooks = new SyncItemsRepository(dbContext, notebooks, Generations, logger);
Notes = new SyncItemsRepository(dbContext, notes, Generations, logger);
Contents = new SyncItemsRepository(dbContext, content, Generations, logger);
Settings = new SyncItemsRepository(dbContext, settings, Generations, logger);
LegacySettings = new SyncItemsRepository(dbContext, legacySettings, Generations, logger);
Attachments = new SyncItemsRepository(dbContext, attachments, Generations, logger);
Shortcuts = new SyncItemsRepository(dbContext, shortcuts, Generations, logger);
Reminders = new SyncItemsRepository(dbContext, reminders, Generations, logger);
Relations = new SyncItemsRepository(dbContext, relations, Generations, logger);
Colors = new SyncItemsRepository(dbContext, colors, Generations, logger);
Vaults = new SyncItemsRepository(dbContext, vaults, Generations, logger);
Tags = new SyncItemsRepository(dbContext, tags, Generations, logger);
InboxItemsHistory = new SyncItemsRepository(dbContext, inboxItemsHistory, Generations, logger);

SyncItemCollections = [
new("settingitem", Settings),
Expand Down
5 changes: 2 additions & 3 deletions Notesnook.API/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,9 +263,8 @@ public async Task<IActionResult> Reset([FromForm] bool removeAttachments)
{
var userId = this.User.GetUserId();

if (await UserService.ResetUserAsync(userId, removeAttachments))
return Ok();
return BadRequest();
await UserService.ResetUserAsync(userId, removeAttachments);
return Ok();
}

[HttpPost("delete")]
Expand Down
11 changes: 10 additions & 1 deletion Notesnook.API/Hubs/SyncAuthorizationHubFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using MongoDB.Driver;
using Notesnook.API.Authorization;
using Notesnook.API.Interfaces;
using Streetwriters.Common.Exceptions;

namespace Notesnook.API.Hubs
{
Expand All @@ -21,7 +22,15 @@ public class SyncAuthorizationHubFilter(IMemoryCache cache) : IHubFilter
public async ValueTask<object?> InvokeMethodAsync(HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object?>> next)
{
await EnsureNotDeletedAsync(invocationContext.Context, invocationContext.ServiceProvider);
return await next(invocationContext);
try
{
return await next(invocationContext);
}
// SignalR hides the message of any other exception from clients outside development
catch (ClientException ex)
{
throw new HubException(ex.Message, ex);
}
}

public async Task OnConnectedAsync(HubLifetimeContext context, Func<HubLifetimeContext, Task> next)
Expand Down
1 change: 1 addition & 0 deletions Notesnook.API/Interfaces/ISyncItemsRepositoryAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public interface ISyncItemsRepositoryAccessor
Repository<InboxSyncItem> InboxItems { get; }
Repository<SyncDevice> SyncDevices { get; }
Repository<DeviceIdsChunk> DeviceIdsChunks { get; }
UserGenerations Generations { get; }

/// <summary>
/// Every collection of a user's sync items, in the order they are synced.
Expand Down
2 changes: 1 addition & 1 deletion Notesnook.API/Interfaces/IUserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public interface IUserService
Task<SignupResponse> CreateUserAsync(SignupForm form);
Task DeleteUserAsync(string userId);
Task DeleteUserAsync(string userId, string? jti, string password);
Task<bool> ResetUserAsync(string userId, bool removeAttachments);
Task ResetUserAsync(string userId, bool removeAttachments);
Task<UserResponse> GetUserAsync(string userId);
Task<EncryptedData?> GetEncryptionVerifier(string userId);
}
Expand Down
34 changes: 34 additions & 0 deletions Notesnook.API/Jobs/UserPurgeJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,40 @@ public async Task Execute(IJobExecutionContext context)
logger.LogError(ex, "Failed to purge user {UserId}", user.UserId);
}
}

var resets = await repositories.UsersSettings.Collection
.Find(Builders<UserSettings>.Filter.And(
Builders<UserSettings>.Filter.Eq((s) => s.PurgePending, true),
Builders<UserSettings>.Filter.Eq((s) => s.DeletedAt, null)))
.Project((s) => new { s.UserId, s.Generation })
.ToListAsync(context.CancellationToken);

foreach (var user in resets)
{
context.CancellationToken.ThrowIfCancellationRequested();
try
{
await PurgeResetAsync(user.UserId, user.Generation);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to purge the reset data of user {UserId}", user.UserId);
}
}
}

private async Task PurgeResetAsync(string userId, long generation)
{
logger.LogInformation("Purging reset data of user {UserId}", userId);

foreach (var collection in repositories.SyncItemCollections)
await collection.Repository.DeleteOlderGenerationsAsync(userId, generation);

// only the generation we purged, so a reset made meanwhile stays pending
await repositories.UsersSettings.Collection.UpdateOneAsync(
(s) => s.UserId == userId && s.Generation == generation,
Builders<UserSettings>.Update.Unset((s) => s.PurgePending));
logger.LogInformation("Purged reset data of user {UserId}", userId);
}

// no transaction, since one this large outlives Mongo's time limit; every step is idempotent so a failed purge is retried
Expand Down
9 changes: 9 additions & 0 deletions Notesnook.API/Models/SyncItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ public string? UserId
get; set;
}

[IgnoreDataMember]
[MessagePack.IgnoreMember]
[JsonIgnore]
[BsonIgnoreIfDefault]
public long Generation
{
get; set;
}

[JsonPropertyName("iv")]
[DataMember(Name = "iv")]
[MessagePack.Key("iv")]
Expand Down
12 changes: 12 additions & 0 deletions Notesnook.API/Models/UserSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ public UserSettings()
public UserKeys? PendingKeys { get; set; }
public long? PendingKeysSince { get; set; }
public long? DeletedAt { get; set; }
/// <summary>
/// Incremented on every reset.
/// </summary>
public long Generation { get; set; }
/// <summary>
/// Set by a reset until UserPurgeJob has deleted the sync items of older generations.
/// </summary>
public bool? PurgePending { get; set; }
/// <summary>
/// Incremented on every push, so a reset committed during the push conflicts with it.
/// </summary>
public long WriteRevision { get; set; }

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
Expand Down
31 changes: 22 additions & 9 deletions Notesnook.API/Repositories/SyncItemsRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ You should have received a copy of the Affero GNU General Public License
using Notesnook.API.Interfaces;
using Notesnook.API.Models;
using Streetwriters.Common;
using Streetwriters.Common.Exceptions;
using Streetwriters.Data.DbContexts;
using Streetwriters.Data.Interfaces;
using Streetwriters.Data.Repositories;
Expand All @@ -44,10 +45,12 @@ public class SyncItemsRepository : Repository<SyncItem>
{
private readonly string collectionName;
private readonly ILogger<SyncItemsRepository> logger;
public SyncItemsRepository(IDbContext dbContext, IMongoCollection<SyncItem> collection, ILogger<SyncItemsRepository> logger) : base(dbContext, collection)
private readonly UserGenerations generations;
public SyncItemsRepository(IDbContext dbContext, IMongoCollection<SyncItem> collection, UserGenerations generations, ILogger<SyncItemsRepository> logger) : base(dbContext, collection)
{
this.collectionName = collection.CollectionNamespace.CollectionName;
this.logger = logger;
this.generations = generations;
}

private readonly List<string> ALGORITHMS = [Algorithms.Default];
Expand All @@ -56,13 +59,13 @@ private bool IsValidAlgorithm(string algorithm)
return ALGORITHMS.Contains(algorithm);
}

public Task<IAsyncCursor<SyncItem>> FindItemsById(string userId, IEnumerable<string> ids, bool all, int batchSize)
public async Task<IAsyncCursor<SyncItem>> FindItemsById(string userId, IEnumerable<string> ids, bool all, int batchSize)
{
var filters = new List<FilterDefinition<SyncItem>>(new[] { Builders<SyncItem>.Filter.Eq("UserId", userId) });
var filters = new List<FilterDefinition<SyncItem>>(new[] { Builders<SyncItem>.Filter.Eq("UserId", userId), UserGenerations.Filter(await generations.GetAsync(userId)) });
Comment thread
thecodrr marked this conversation as resolved.
Resolved

if (!all) filters.Add(Builders<SyncItem>.Filter.In("ItemId", ids));

return Collection.FindAsync(Builders<SyncItem>.Filter.And(filters), new FindOptions<SyncItem>
return await Collection.FindAsync(Builders<SyncItem>.Filter.And(filters), new FindOptions<SyncItem>
{
BatchSize = batchSize,
AllowDiskUse = true,
Expand All @@ -71,16 +74,15 @@ public Task<IAsyncCursor<SyncItem>> FindItemsById(string userId, IEnumerable<str
});
}

public void DeleteByUserId(string userId)
public Task DeleteOlderGenerationsAsync(string userId, long generation)
{
var filter = Builders<SyncItem>.Filter.Eq("UserId", userId);
dbContext.AddCommand((handle, ct) => Collection.DeleteManyAsync(handle, filter, null, ct));
return Collection.DeleteManyAsync(Builders<SyncItem>.Filter.And(Builders<SyncItem>.Filter.Eq("UserId", userId), UserGenerations.OlderThan(generation)));
}

public void UpsertMany(IEnumerable<SyncItem> items, string userId)
{
var userIdFilter = Builders<SyncItem>.Filter.Eq("UserId", userId);
var writes = new List<WriteModel<SyncItem>>();
var writes = new List<ReplaceOneModel<SyncItem>>();
foreach (var item in items)
{
if (item.Length > 15 * 1024 * 1024)
Expand Down Expand Up @@ -118,7 +120,18 @@ public void UpsertMany(IEnumerable<SyncItem> items, string userId)
});
}
if (writes.Count == 0) return;
dbContext.AddCommand((handle, ct) => Collection.BulkWriteAsync(handle, writes, options: new BulkWriteOptions { IsOrdered = false }, ct));

// kept across retries, since a retry after a conflicting reset still carries data encrypted with the reset's keys
long? expected = null;
dbContext.AddCommand(async (handle, ct) =>
{
expected ??= await generations.GetAsync(handle, userId, ct);
var generation = await generations.StampAsync(handle, userId, ct);
if (generation != expected)
throw new ConflictException("Your account was reset during this sync. Please sync again.");
foreach (var write in writes) write.Replacement.Generation = generation;
await Collection.BulkWriteAsync(handle, writes, options: new BulkWriteOptions { IsOrdered = false }, ct);
Comment on lines +125 to +127
});
}

private static bool IsBase64String(string value)
Expand Down
55 changes: 55 additions & 0 deletions Notesnook.API/Repositories/UserGenerations.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
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 <http://www.gnu.org/licenses/>.
*/

using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using Notesnook.API.Models;

namespace Notesnook.API.Repositories
{
/// <summary>
/// Every reset starts a new generation of the user's sync items. Items from an older one are hidden until UserPurgeJob deletes them.
/// </summary>
public class UserGenerations(IMongoCollection<UserSettings> settings)
{
public Task<long> GetAsync(string userId) =>
settings.Find((s) => s.UserId == userId).Project((s) => s.Generation).FirstOrDefaultAsync();

public Task<long> GetAsync(IClientSessionHandle session, string userId, CancellationToken ct) =>
settings.Find(session, (s) => s.UserId == userId).Project((s) => s.Generation).FirstOrDefaultAsync(ct);

// a write rather than a read, since only a write conflicts with a reset committed during the transaction
public Task<long> StampAsync(IClientSessionHandle session, string userId, CancellationToken ct) =>
settings.FindOneAndUpdateAsync(session,
Builders<UserSettings>.Filter.Eq((s) => s.UserId, userId),
Builders<UserSettings>.Update.Inc((s) => s.WriteRevision, 1),
new FindOneAndUpdateOptions<UserSettings, long> { Projection = Builders<UserSettings>.Projection.Expression((s) => s.Generation) }, ct);

// items stored before generations existed have no Generation, so they belong to generation 0
public static FilterDefinition<SyncItem> Filter(long generation) => generation == 0
? Builders<SyncItem>.Filter.In("Generation", new BsonValue[] { 0, BsonNull.Value })
: Builders<SyncItem>.Filter.Eq("Generation", generation);

public static FilterDefinition<SyncItem> OlderThan(long generation) => Builders<SyncItem>.Filter.Or(
Builders<SyncItem>.Filter.Lt("Generation", generation),
Builders<SyncItem>.Filter.Eq("Generation", BsonNull.Value));
}
}
2 changes: 1 addition & 1 deletion Notesnook.API/Services/MongoIndexesHostedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class MongoIndexesHostedService(IMongoClient client, ILogger<MongoIndexes
["notes"] = [.. SyncIndexes, I("Length_1", ("Length", 1))],
["sync_devices"] = [I("UserId_1_DeviceId_1", true, false, ("UserId", 1), ("DeviceId", 1)), I("LastAccessTime_1", ("LastAccessTime", 1)),
I("UserId_1", ("UserId", 1)), I("idx_device_user_activity", ("UserId", 1), ("LastAccessTime", -1))],
["user_settings"] = [I("UserId_1", true, false, ("UserId", 1)), I("DeletedAt_1", ("DeletedAt", 1))]
["user_settings"] = [I("UserId_1", true, false, ("UserId", 1)), I("DeletedAt_1", ("DeletedAt", 1)), I("PurgePending_1", ("PurgePending", 1))]
};

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
Expand Down
Loading
Loading