| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | using Elsa.Persistence.VNext.Document; |
| | | 4 | | using Elsa.UserTasks.Contracts; |
| | | 5 | | using Elsa.UserTasks.Models; |
| | | 6 | | |
| | | 7 | | namespace Elsa.UserTasks.Persistence.VNext.Repositories; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Provider-neutral document implementation. The aggregate is stored as one document while the schema |
| | | 11 | | /// provider advertises the same logical units and indexes as the relational providers. |
| | | 12 | | /// </summary> |
| | 2 | 13 | | public sealed class VNextUserTaskRepository(IDocumentStore documentStore) : IUserTaskRepository |
| | | 14 | | { |
| | | 15 | | public const string StorageUnitName = "UserTasks"; |
| | 1 | 16 | | private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) |
| | 1 | 17 | | { |
| | 1 | 18 | | Converters = { new JsonStringEnumConverter() } |
| | 1 | 19 | | }; |
| | | 20 | | |
| | | 21 | | public async Task<UserTask?> GetAsync(string tenantId, string taskId, CancellationToken cancellationToken = default) |
| | | 22 | | { |
| | 22 | 23 | | var document = await documentStore.LoadAsync(StorageUnitName, DocumentId(tenantId, taskId), cancellationToken); |
| | 22 | 24 | | return document is null ? null : Deserialize(document); |
| | 22 | 25 | | } |
| | | 26 | | |
| | | 27 | | public async Task<UserTaskQueryResult> QueryAsync(UserTaskQuery query, CancellationToken cancellationToken = default |
| | | 28 | | { |
| | 106 | 29 | | var tasks = new List<UserTask>(); |
| | 2120 | 30 | | foreach (var status in Enum.GetValues<UserTaskStatus>()) |
| | | 31 | | { |
| | 954 | 32 | | var documents = await documentStore.QueryAsync( |
| | 954 | 33 | | new DocumentQuery(StorageUnitName, new Dictionary<string, string?> |
| | 954 | 34 | | { |
| | 954 | 35 | | ["TenantId"] = query.TenantId, |
| | 954 | 36 | | ["Status"] = status.ToString() |
| | 954 | 37 | | }), cancellationToken); |
| | 954 | 38 | | tasks.AddRange(documents.Select(Deserialize)); |
| | | 39 | | } |
| | | 40 | | |
| | 1346 | 41 | | var filtered = tasks.Where(x => Matches(x, query)).Where(x => query.Scope is null || IsVisible(x, query.Scope)). |
| | 106 | 42 | | int? totalCount = query.IncludeTotalCount ? filtered.Count : null; |
| | 106 | 43 | | filtered = ApplyOrdering(filtered, query).ToList(); |
| | 106 | 44 | | filtered = ApplyCursor(filtered, query).ToList(); |
| | 106 | 45 | | var limit = Math.Clamp(query.Limit <= 0 ? 50 : query.Limit, 1, 200); |
| | 106 | 46 | | var hasMore = filtered.Count > limit; |
| | 106 | 47 | | var page = filtered.Take(limit).ToList(); |
| | 106 | 48 | | return new UserTaskQueryResult(page, hasMore ? CreateCursor(page[^1], query.Sort) : null, totalCount); |
| | 106 | 49 | | } |
| | | 50 | | |
| | 255 | 51 | | public Task<UserTask?> FindByMaterializationKeyAsync(string tenantId, string key, CancellationToken cancellationToke |
| | | 52 | | |
| | 3 | 53 | | public Task<UserTask?> FindByBookmarkIdAsync(string tenantId, string bookmarkId, CancellationToken cancellationToken |
| | | 54 | | |
| | | 55 | | public async Task<(UserTask Task, UserTaskInvitation Invitation)?> FindByInvitationTokenHashAsync(string tokenHash, |
| | | 56 | | { |
| | | 57 | | // The document store has no cross-tenant secondary index for invitation hashes, so this scans the |
| | | 58 | | // storage unit. Verification is rate limited and rare; correctness matters more than the scan here. |
| | 217 | 59 | | foreach (var task in await LoadAllAsync(cancellationToken)) |
| | | 60 | | { |
| | 109 | 61 | | var invitation = task.Invitations.FirstOrDefault(x => string.Equals(x.TokenHash, tokenHash, StringComparison |
| | 107 | 62 | | if (invitation != null) |
| | 1 | 63 | | return (task, invitation); |
| | | 64 | | } |
| | 1 | 65 | | return null; |
| | 2 | 66 | | } |
| | | 67 | | |
| | | 68 | | public async Task SaveAsync(UserTask task, int expectedRevision, CancellationToken cancellationToken = default) |
| | | 69 | | { |
| | 6 | 70 | | var existing = await LoadDocumentAsync(task.TenantId, task.Id, cancellationToken); |
| | 6 | 71 | | if (existing is null) |
| | 0 | 72 | | throw new KeyNotFoundException($"User task '{task.Id}' was not found."); |
| | 6 | 73 | | var loaded = existing.Value; |
| | 6 | 74 | | if (loaded.Task.Revision != expectedRevision) |
| | 2 | 75 | | throw new UserTaskRevisionConflictException(task.Id, expectedRevision); |
| | | 76 | | |
| | 4 | 77 | | task.Revision = expectedRevision + 1; |
| | 4 | 78 | | task.UpdatedAt = DateTimeOffset.UtcNow; |
| | | 79 | | try |
| | | 80 | | { |
| | 4 | 81 | | await documentStore.SaveAsync(CreateRequest(task, loaded.Document.Version), cancellationToken); |
| | 4 | 82 | | } |
| | 0 | 83 | | catch (DocumentStoreConcurrencyException exception) |
| | | 84 | | { |
| | | 85 | | // A writer won the race between the read above and this save. Same contract as the other |
| | | 86 | | // providers so the caller sees one exception type regardless of the installed store. |
| | 0 | 87 | | throw new UserTaskRevisionConflictException(task.Id, expectedRevision, exception); |
| | | 88 | | } |
| | 4 | 89 | | } |
| | | 90 | | |
| | | 91 | | public async Task AddProjectionAsync(UserTask task, CancellationToken cancellationToken = default) |
| | | 92 | | { |
| | 80 | 93 | | if (await FindByMaterializationKeyAsync(task.TenantId, task.MaterializationKey, cancellationToken) is not null) |
| | 1 | 94 | | return; |
| | | 95 | | try |
| | | 96 | | { |
| | 79 | 97 | | await documentStore.SaveAsync(CreateRequest(task, expectedVersion: 0), cancellationToken); |
| | 79 | 98 | | } |
| | 0 | 99 | | catch (DocumentStoreConcurrencyException) |
| | | 100 | | { |
| | | 101 | | // Projection is idempotent when the same aggregate ID was committed concurrently. |
| | 0 | 102 | | } |
| | 80 | 103 | | } |
| | | 104 | | |
| | | 105 | | public async Task AppendEventAsync(string tenantId, string taskId, UserTaskEvent @event, CancellationToken cancellat |
| | | 106 | | { |
| | 3 | 107 | | var existing = await LoadDocumentAsync(tenantId, taskId, cancellationToken); |
| | 3 | 108 | | if (existing is null) |
| | 1 | 109 | | return; |
| | | 110 | | |
| | | 111 | | // The document store has no separate audit stream, so the entry is written back with the aggregate. |
| | | 112 | | // The revision is deliberately left as-is: an audited read must not consume the concurrency token. |
| | 2 | 113 | | var loaded = existing.Value; |
| | 2 | 114 | | loaded.Task.Events.Add(@event); |
| | | 115 | | try |
| | | 116 | | { |
| | 2 | 117 | | await documentStore.SaveAsync(CreateRequest(loaded.Task, loaded.Document.Version), cancellationToken); |
| | 2 | 118 | | } |
| | 0 | 119 | | catch (DocumentStoreConcurrencyException) |
| | | 120 | | { |
| | | 121 | | // A concurrent writer won. The audit entry is advisory, so losing this race is not an error. |
| | 0 | 122 | | } |
| | 3 | 123 | | } |
| | | 124 | | |
| | | 125 | | public async Task<bool> TryMutateAsync(string tenantId, string taskId, int expectedRevision, Func<UserTask, bool> mu |
| | | 126 | | { |
| | 2 | 127 | | var existing = await LoadDocumentAsync(tenantId, taskId, cancellationToken); |
| | 2 | 128 | | if (existing is null) |
| | 0 | 129 | | return false; |
| | 2 | 130 | | var loaded = existing.Value; |
| | 2 | 131 | | if (loaded.Task.Revision != expectedRevision || !mutation(loaded.Task)) |
| | 2 | 132 | | return false; |
| | 0 | 133 | | loaded.Task.Revision = expectedRevision + 1; |
| | 0 | 134 | | loaded.Task.UpdatedAt = DateTimeOffset.UtcNow; |
| | | 135 | | try |
| | | 136 | | { |
| | 0 | 137 | | await documentStore.SaveAsync(CreateRequest(loaded.Task, loaded.Document.Version), cancellationToken); |
| | 0 | 138 | | return true; |
| | | 139 | | } |
| | 0 | 140 | | catch (DocumentStoreConcurrencyException) |
| | | 141 | | { |
| | 0 | 142 | | return false; |
| | | 143 | | } |
| | 2 | 144 | | } |
| | | 145 | | |
| | | 146 | | /// <summary> |
| | | 147 | | /// Loads every stored task across tenants. Only the invitation-hash lookup uses this: an anonymous |
| | | 148 | | /// holder presents a secret and no tenant, so the scan cannot be narrowed by an index. |
| | | 149 | | /// </summary> |
| | | 150 | | private async Task<IReadOnlyCollection<UserTask>> LoadAllAsync(CancellationToken cancellationToken) |
| | | 151 | | { |
| | 2 | 152 | | var tasks = new List<UserTask>(); |
| | 40 | 153 | | foreach (var status in Enum.GetValues<UserTaskStatus>()) |
| | | 154 | | { |
| | 18 | 155 | | var documents = await documentStore.QueryAsync(new DocumentQuery(StorageUnitName, new Dictionary<string, str |
| | 18 | 156 | | { |
| | 18 | 157 | | ["Status"] = status.ToString() |
| | 18 | 158 | | }), cancellationToken); |
| | 18 | 159 | | tasks.AddRange(documents.Select(Deserialize)); |
| | | 160 | | } |
| | 2 | 161 | | return tasks; |
| | 2 | 162 | | } |
| | | 163 | | |
| | | 164 | | private async Task<UserTask?> FindByIndexAsync(string tenantId, Func<UserTask, bool> predicate, CancellationToken ca |
| | | 165 | | { |
| | 1635 | 166 | | foreach (var status in Enum.GetValues<UserTaskStatus>()) |
| | | 167 | | { |
| | 735 | 168 | | var documents = await documentStore.QueryAsync(new DocumentQuery(StorageUnitName, new Dictionary<string, str |
| | 735 | 169 | | { |
| | 735 | 170 | | ["TenantId"] = tenantId, |
| | 735 | 171 | | ["Status"] = status.ToString() |
| | 735 | 172 | | }), cancellationToken); |
| | 735 | 173 | | var task = documents.Select(Deserialize).FirstOrDefault(predicate); |
| | 735 | 174 | | if (task is not null) |
| | 3 | 175 | | return task; |
| | | 176 | | } |
| | 81 | 177 | | return null; |
| | 84 | 178 | | } |
| | | 179 | | |
| | | 180 | | private async Task<(StoredDocument Document, UserTask Task)?> LoadDocumentAsync(string tenantId, string taskId, Canc |
| | | 181 | | { |
| | 11 | 182 | | var document = await documentStore.LoadAsync(StorageUnitName, DocumentId(tenantId, taskId), cancellationToken); |
| | 11 | 183 | | return document is null ? null : (document, Deserialize(document)); |
| | 11 | 184 | | } |
| | | 185 | | |
| | 85 | 186 | | private static SaveDocumentRequest CreateRequest(UserTask task, long expectedVersion) => new( |
| | 85 | 187 | | StorageUnitName, |
| | 85 | 188 | | DocumentId(task.TenantId, task.Id), |
| | 85 | 189 | | JsonSerializer.Serialize(task, JsonOptions), |
| | 85 | 190 | | new Dictionary<string, string?> |
| | 85 | 191 | | { |
| | 85 | 192 | | ["TenantId"] = task.TenantId, |
| | 85 | 193 | | ["Status"] = task.Status.ToString(), |
| | 85 | 194 | | ["MaterializationKey"] = task.MaterializationKey, |
| | 85 | 195 | | ["BookmarkId"] = task.BookmarkId, |
| | 85 | 196 | | ["TaskType"] = task.TaskType, |
| | 85 | 197 | | // Every index the schema provider declares must be supplied on save; the store rejects the |
| | 85 | 198 | | // write outright when one is absent, so an omission here disables the provider entirely |
| | 85 | 199 | | // rather than merely losing an index. |
| | 85 | 200 | | ["WorkflowDefinitionId"] = task.WorkflowDefinitionId, |
| | 85 | 201 | | ["WorkflowInstanceId"] = task.WorkflowInstanceId, |
| | 85 | 202 | | ["ActivityInstanceId"] = task.ActivityInstanceId, |
| | 85 | 203 | | ["CreatedAt"] = task.CreatedAt.ToString("O", System.Globalization.CultureInfo.InvariantCulture), |
| | 85 | 204 | | ["CompletedAt"] = task.CompletedAt?.ToString("O", System.Globalization.CultureInfo.InvariantCulture), |
| | 85 | 205 | | ["AssigneeProvider"] = task.Assignee?.Provider, |
| | 85 | 206 | | ["AssigneeType"] = task.Assignee?.Type.ToString(), |
| | 85 | 207 | | ["AssigneeId"] = task.Assignee?.Id, |
| | 85 | 208 | | ["HealthSeverity"] = task.HealthSeverity?.ToString(), |
| | 85 | 209 | | ["Priority"] = task.Priority.ToString(System.Globalization.CultureInfo.InvariantCulture), |
| | 85 | 210 | | ["DueAt"] = task.DueAt?.ToString("O", System.Globalization.CultureInfo.InvariantCulture) |
| | 85 | 211 | | }, expectedVersion); |
| | | 212 | | |
| | 955 | 213 | | private static UserTask Deserialize(StoredDocument document) => JsonSerializer.Deserialize<UserTask>(document.Conten |
| | 955 | 214 | | ?? throw new DocumentStoreValidationException($"Stored User Task document '{document.Id}' could not be deseriali |
| | | 215 | | |
| | 118 | 216 | | private static string DocumentId(string tenantId, string taskId) => $"{tenantId}:{taskId}"; |
| | | 217 | | |
| | | 218 | | private static bool Matches(UserTask task, UserTaskQuery query) |
| | | 219 | | { |
| | 620 | 220 | | var search = query.Search?.Trim(); |
| | 620 | 221 | | return task.TenantId == query.TenantId && (query.Statuses.Count == 0 || query.Statuses.Contains(task.Status)) && |
| | 620 | 222 | | (!query.OnlyOverdue || task.IsOverdue) && (!query.OnlyWithoutDueDate || task.DueAt is null) && |
| | 620 | 223 | | (string.IsNullOrWhiteSpace(query.TaskType) || task.TaskType == query.TaskType) && |
| | 620 | 224 | | (!query.PriorityFrom.HasValue || task.Priority >= query.PriorityFrom) && (!query.PriorityTo.HasValue || t |
| | 620 | 225 | | (!query.DueFrom.HasValue || task.DueAt >= query.DueFrom) && (!query.DueTo.HasValue || task.DueAt <= query |
| | 620 | 226 | | (string.IsNullOrWhiteSpace(query.WorkflowDefinitionId) || task.WorkflowDefinitionId == query.WorkflowDefi |
| | 620 | 227 | | (string.IsNullOrWhiteSpace(query.WorkflowInstanceId) || task.WorkflowInstanceId == query.WorkflowInstance |
| | 620 | 228 | | (string.IsNullOrWhiteSpace(query.Reference) || task.Reference == query.Reference) && |
| | 620 | 229 | | (string.IsNullOrWhiteSpace(search) || task.Title.Contains(search, StringComparison.OrdinalIgnoreCase) || |
| | | 230 | | } |
| | | 231 | | |
| | | 232 | | private static bool IsVisible(UserTask task, UserTaskQueryScope scope) |
| | | 233 | | { |
| | 620 | 234 | | if (!string.Equals(scope.TenantId, task.TenantId, StringComparison.Ordinal) || |
| | 620 | 235 | | !string.Equals(scope.Subject.TenantId, task.TenantId, StringComparison.Ordinal) || |
| | 620 | 236 | | scope.Groups.Any(group => !string.Equals(group.TenantId, task.TenantId, StringComparison.Ordinal))) |
| | 1 | 237 | | return false; |
| | 619 | 238 | | if (scope.ExcludeBlocking && task.HealthSeverity == UserTaskHealthSeverity.Blocking) |
| | 0 | 239 | | return false; |
| | | 240 | | // Manager-only scopes were already rejected by the policy for non-managers. |
| | 619 | 241 | | if (scope.RequiresManager) |
| | 0 | 242 | | return scope.IsManager && (scope.Kind != UserTaskQueryScopeKind.NeedsAttention || NeedsAttention(task)); |
| | | 243 | | |
| | 619 | 244 | | var subject = scope.Subject; |
| | 619 | 245 | | var groups = scope.Groups; |
| | 619 | 246 | | return scope.Kind switch |
| | 619 | 247 | | { |
| | 0 | 248 | | UserTaskQueryScopeKind.Assigned => task.Assignee?.Matches(subject) == true, |
| | 619 | 249 | | UserTaskQueryScopeKind.Available => task.IsOpen && task.Assignee is null && IsEligible(task, subject, groups |
| | 0 | 250 | | UserTaskQueryScopeKind.History => task.IsTerminal && |
| | 0 | 251 | | (task.CompletedBy?.Matches(subject) == true || task.Events.Any(x => x.Acto |
| | 0 | 252 | | _ => false |
| | 619 | 253 | | }; |
| | | 254 | | } |
| | | 255 | | |
| | | 256 | | private static bool IsEligible(UserTask task, ParticipantReference subject, IReadOnlyCollection<ParticipantReference |
| | | 257 | | { |
| | 622 | 258 | | if (task.ExcludedUsers.Any(x => x.Matches(subject))) |
| | 3 | 259 | | return false; |
| | 616 | 260 | | if (task.MembershipResolutionMode == UserTaskMembershipResolutionMode.Snapshot) |
| | 0 | 261 | | return task.SnapshotMembers.Any(x => x.Matches(subject)) || task.SnapshotGroups.Any(x => groups.Any(x.Matche |
| | 1232 | 262 | | return task.CandidateUsers.Any(x => x.Matches(subject)) || task.CandidateGroups.Any(x => groups.Any(x.Matches)); |
| | | 263 | | } |
| | | 264 | | |
| | | 265 | | private static bool NeedsAttention(UserTask task) => |
| | 0 | 266 | | task.HealthSeverity == UserTaskHealthSeverity.Blocking |
| | 0 | 267 | | || task.IsOverdue |
| | 0 | 268 | | || (task.IsOpen && task.Assignee is null) |
| | 0 | 269 | | || task.Status is UserTaskStatus.Completing or UserTaskStatus.TimingOut or UserTaskStatus.Cancelling; |
| | | 270 | | |
| | 106 | 271 | | private static IEnumerable<UserTask> ApplyOrdering(IEnumerable<UserTask> tasks, UserTaskQuery query) => query.Sort.T |
| | 106 | 272 | | { |
| | 312 | 273 | | "priority" => query.Descending ? tasks.OrderByDescending(x => x.Priority).ThenBy(x => x.Id) : tasks.OrderBy(x => |
| | 312 | 274 | | "title" => query.Descending ? tasks.OrderByDescending(x => x.Title).ThenBy(x => x.Id) : tasks.OrderBy(x => x.Tit |
| | 494 | 275 | | "due" => query.Descending ? tasks.OrderBy(x => x.DueAt == null).ThenByDescending(x => x.DueAt).ThenBy(x => x.Id) |
| | 368 | 276 | | _ => query.Descending ? tasks.OrderByDescending(x => x.CreatedAt).ThenBy(x => x.Id) : tasks.OrderBy(x => x.Creat |
| | 106 | 277 | | }; |
| | | 278 | | |
| | | 279 | | private static IEnumerable<UserTask> ApplyCursor(IEnumerable<UserTask> tasks, UserTaskQuery query) |
| | | 280 | | { |
| | 106 | 281 | | if (!TryReadCursor(query.Cursor, out var value, out var id)) |
| | 41 | 282 | | return tasks; |
| | | 283 | | return query.Sort.ToLowerInvariant() switch |
| | | 284 | | { |
| | 128 | 285 | | "priority" when int.TryParse(value, out var priority) => tasks.Where(x => query.Descending ? x.Priority < pr |
| | 112 | 286 | | "title" => tasks.Where(x => query.Descending ? string.Compare(x.Title, value) < 0 || x.Title == value && str |
| | 30 | 287 | | "due" when value == "~null" => tasks.Where(x => x.DueAt == null && string.Compare(x.Id, id) > 0), |
| | 112 | 288 | | "due" when DateTimeOffset.TryParse(value, out var due) => tasks.Where(x => x.DueAt == null || query.Descendi |
| | 132 | 289 | | _ when DateTimeOffset.TryParse(value, out var created) => tasks.Where(x => query.Descending ? x.CreatedAt < |
| | 0 | 290 | | _ => tasks |
| | | 291 | | }; |
| | | 292 | | } |
| | | 293 | | |
| | | 294 | | private static string CreateCursor(UserTask task, string sort) |
| | | 295 | | { |
| | 66 | 296 | | var value = sort.ToLowerInvariant() switch |
| | 66 | 297 | | { |
| | 16 | 298 | | "priority" => task.Priority.ToString(System.Globalization.CultureInfo.InvariantCulture), |
| | 16 | 299 | | "title" => task.Title, |
| | 16 | 300 | | "due" => task.DueAt?.ToString("O", System.Globalization.CultureInfo.InvariantCulture) ?? "~null", |
| | 18 | 301 | | _ => task.CreatedAt.ToString("O", System.Globalization.CultureInfo.InvariantCulture) |
| | 66 | 302 | | }; |
| | 66 | 303 | | return Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(new[] { value, task.Id }, JsonOptions)).TrimEn |
| | | 304 | | } |
| | | 305 | | |
| | | 306 | | private static bool TryReadCursor(string? cursor, out string value, out string id) |
| | | 307 | | { |
| | 106 | 308 | | value = id = ""; |
| | 106 | 309 | | if (string.IsNullOrWhiteSpace(cursor)) |
| | 40 | 310 | | return false; |
| | | 311 | | try |
| | | 312 | | { |
| | 66 | 313 | | var padded = cursor.Replace('-', '+').Replace('_', '/') + new string('=', (4 - cursor.Length % 4) % 4); |
| | 66 | 314 | | var values = JsonSerializer.Deserialize<string[]>(Convert.FromBase64String(padded), JsonOptions); |
| | 65 | 315 | | if (values is not [var parsedValue, var parsedId]) |
| | 0 | 316 | | return false; |
| | 65 | 317 | | value = parsedValue; |
| | 65 | 318 | | id = parsedId; |
| | 65 | 319 | | return true; |
| | | 320 | | } |
| | 0 | 321 | | catch (FormatException) { return false; } |
| | 2 | 322 | | catch (JsonException) { return false; } |
| | 66 | 323 | | } |
| | | 324 | | } |