forked from votrongdao/FlowX
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomSchemaCapabilities.cs
More file actions
506 lines (436 loc) · 19.6 KB
/
Copy pathCustomSchemaCapabilities.cs
File metadata and controls
506 lines (436 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
using FlowX;
namespace Crm;
/// <summary>
/// Declares an entity this build has never heard of.
/// </summary>
/// <remarks>
/// <strong><c>crm.admin</c> and not <c>crm.write</c>, and the split is the point.</strong>
/// Writing a lead and changing what a lead <em>is</em> are different acts with different blast
/// radii: a required field declared here is a field every future record must carry, including
/// ones written by flows that have never heard of it. A representative may do the first and not
/// the second, and the refusal is on the step, so it holds over a broker and from an agent too.
/// </remarks>
[Capability("crm.custom.define_object", Version = "1.0.0",
Authorization = Authorization.Permission, Permission = "crm.admin",
Idempotent = true)]
public sealed class DefineCustomObject : ICapability<DefineObject, ObjectDefined>
{
private readonly CustomSchemaStore _store;
/// <summary>Creates the capability.</summary>
/// <param name="store">Writes the declaration.</param>
/// <exception cref="ArgumentNullException"><paramref name="store"/> is null.</exception>
public DefineCustomObject(CustomSchemaStore store)
{
ArgumentNullException.ThrowIfNull(store);
_store = store;
}
/// <inheritdoc />
public async ValueTask<Result<ObjectDefined>> ExecuteAsync(
DefineObject input,
CapabilityContext ctx,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(ctx);
if (!CustomValues.IsUsableName(input.Name))
{
return Result.Fail<ObjectDefined>(CustomSchemaErrors.NameIsNotUsable(input.Name));
}
var id = await _store
.DeclareObjectAsync(ctx.TenantId, ctx.NewId(), input, ctx.UtcNow, ct)
.ConfigureAwait(false);
return id is null
? Result.Fail<ObjectDefined>(CustomSchemaErrors.NameIsTaken(input.Name))
: Result.Ok(new ObjectDefined(id.Value, input.Name));
}
}
/// <summary>
/// Declares a field on a built-in entity kind or on a custom object.
/// </summary>
/// <remarks>
/// <strong>The owner is checked here and constrained by the schema.</strong> Migration
/// <c>0005</c>'s <c>CHECK ((applies_to IS NULL) <> (object_id IS NULL))</c> is what makes
/// a field with two owners or none impossible; this is what turns that into an error naming the
/// problem. The pair is the pattern migration <c>0003</c> established for the activity trigger.
/// </remarks>
[Capability("crm.custom.define_field", Version = "1.0.0",
Authorization = Authorization.Permission, Permission = "crm.admin",
Idempotent = true)]
public sealed class DefineCustomField : ICapability<DefineField, FieldDefined>
{
private readonly CustomSchemaStore _store;
/// <summary>Creates the capability.</summary>
/// <param name="store">Writes the declaration.</param>
/// <exception cref="ArgumentNullException"><paramref name="store"/> is null.</exception>
public DefineCustomField(CustomSchemaStore store)
{
ArgumentNullException.ThrowIfNull(store);
_store = store;
}
/// <inheritdoc />
public async ValueTask<Result<FieldDefined>> ExecuteAsync(
DefineField input,
CapabilityContext ctx,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(ctx);
if (input.AppliesTo is null == input.Target is null)
{
return Result.Fail<FieldDefined>(CustomSchemaErrors.FieldHasNoOwner());
}
if (!CustomValues.IsUsableName(input.Name))
{
return Result.Fail<FieldDefined>(CustomSchemaErrors.NameIsNotUsable(input.Name));
}
if (input.Target is { } objectId &&
!await _store.HasObjectAsync(ctx.TenantId, objectId, ct).ConfigureAwait(false))
{
return Result.Fail<FieldDefined>(CustomSchemaErrors.ObjectNotFound(objectId));
}
// A picklist with no values accepts nothing, so declaring one is a mistake worth naming
// rather than a field somebody discovers is unusable on the first write.
// Both closed types, and both useless without their set: a multi-select with no options
// is a form control with nothing in it.
if (input.Type is CustomFieldType.Picklist or CustomFieldType.MultiPicklist
&& input.Options is not { Count: > 0 })
{
return Result.Fail<FieldDefined>(CustomSchemaErrors.PicklistHasNoOptions(input.Name));
}
foreach (var option in input.Options ?? [])
{
if (!CustomValues.IsUsableName(option.Value))
{
return Result.Fail<FieldDefined>(
CustomSchemaErrors.NameIsNotUsable(option.Value));
}
}
// The CHECK of migration 0006 makes a Reference with no target impossible; this is what
// turns it into an error naming the field, and what checks the target is this tenant's.
if (input.Type == CustomFieldType.Reference)
{
if (input.References is not { } target)
{
return Result.Fail<FieldDefined>(CustomSchemaErrors.FieldHasNoOwner());
}
if (!await _store.HasObjectAsync(ctx.TenantId, target, ct).ConfigureAwait(false))
{
return Result.Fail<FieldDefined>(CustomSchemaErrors.ObjectNotFound(target));
}
}
var id = await _store
.DeclareFieldAsync(ctx.TenantId, ctx.NewId(), input, ctx.UtcNow, ct)
.ConfigureAwait(false);
return id is null
? Result.Fail<FieldDefined>(CustomSchemaErrors.NameIsTaken(input.Name))
: Result.Ok(new FieldDefined(id.Value, input.Name));
}
}
/// <summary>
/// Declares a named edge between two custom objects.
/// </summary>
[Capability("crm.custom.define_relationship", Version = "1.0.0",
Authorization = Authorization.Permission, Permission = "crm.admin",
Idempotent = true)]
public sealed class DefineCustomRelationship : ICapability<DefineRelationship, RelationshipDefined>
{
private readonly CustomSchemaStore _store;
/// <summary>Creates the capability.</summary>
/// <param name="store">Writes the declaration.</param>
/// <exception cref="ArgumentNullException"><paramref name="store"/> is null.</exception>
public DefineCustomRelationship(CustomSchemaStore store)
{
ArgumentNullException.ThrowIfNull(store);
_store = store;
}
/// <inheritdoc />
public async ValueTask<Result<RelationshipDefined>> ExecuteAsync(
DefineRelationship input,
CapabilityContext ctx,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(ctx);
if (!CustomValues.IsUsableName(input.Name))
{
return Result.Fail<RelationshipDefined>(CustomSchemaErrors.NameIsNotUsable(input.Name));
}
foreach (var end in new[] { input.From, input.To })
{
if (!await _store.HasObjectAsync(ctx.TenantId, end, ct).ConfigureAwait(false))
{
return Result.Fail<RelationshipDefined>(CustomSchemaErrors.ObjectNotFound(end));
}
}
var id = await _store
.DeclareRelationshipAsync(ctx.TenantId, ctx.NewId(), input, ct)
.ConfigureAwait(false);
return id is null
? Result.Fail<RelationshipDefined>(CustomSchemaErrors.NameIsTaken(input.Name))
: Result.Ok(new RelationshipDefined(id.Value, input.Name));
}
}
/// <summary>
/// Writes a row of an object an administrator invented.
/// </summary>
/// <remarks>
/// <strong><c>crm.write</c>, because this is data.</strong> Whoever may write a lead may write a
/// row of a custom object; what they may not do is decide what its columns are.
/// </remarks>
[Capability("crm.custom.create_record", Version = "1.0.0",
Authorization = Authorization.Permission, Permission = "crm.write",
Idempotent = true)]
public sealed class CreateCustomRecord : ICapability<WriteObjectRecord, RecordCreated>
{
private readonly CustomSchemaStore _store;
private readonly FieldPolicyStore _policy;
private readonly FormulaStore _formulas;
/// <summary>Creates the capability.</summary>
/// <param name="store">Reads the declarations and writes the row.</param>
/// <param name="policy">Reads the rules, and claims the unique values.</param>
/// <param name="formulas">Reads the formulas whose answers this write computes.</param>
/// <exception cref="ArgumentNullException">Any argument is null.</exception>
public CreateCustomRecord(
CustomSchemaStore store,
FieldPolicyStore policy,
FormulaStore formulas)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(policy);
ArgumentNullException.ThrowIfNull(formulas);
_store = store;
_policy = policy;
_formulas = formulas;
}
/// <inheritdoc />
public async ValueTask<Result<RecordCreated>> ExecuteAsync(
WriteObjectRecord input,
CapabilityContext ctx,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(ctx);
if (!await _store.HasObjectAsync(ctx.TenantId, input.Target, ct).ConfigureAwait(false))
{
return Result.Fail<RecordCreated>(CustomSchemaErrors.ObjectNotFound(input.Target));
}
var declared = await _store
.FieldsForAsync(ctx.TenantId, input.Target, ct)
.ConfigureAwait(false);
var id = ctx.NewId();
// Minted here rather than derived, because a request that arrives twice is two records
// unless the caller said otherwise with an idempotency key. The bulk import derives its
// ids instead, for the opposite reason.
if (await RecordWriter
.WriteAsync(
_store, _policy, _formulas, id, input.Target,
declared, input.Values, input.Scopes, ctx, ct)
.ConfigureAwait(false) is { } refused)
{
return Result.Fail<RecordCreated>(refused);
}
return Result.Ok(new RecordCreated(id));
}
}
/// <summary>
/// Joins two records along a relationship an administrator declared.
/// </summary>
/// <remarks>
/// <strong>Both ends are checked to be of the objects the edge joins</strong>, because the
/// foreign keys of migration <c>0005</c> hold a record to <em>a</em> record and cannot say which
/// object it belongs to. Without this a <c>site</c> could be linked as though it were a
/// <c>contract</c>, and every reader of the edge would have to re-check.
/// </remarks>
[Capability("crm.custom.link_records", Version = "1.0.0",
Authorization = Authorization.Permission, Permission = "crm.write",
Idempotent = true)]
public sealed class LinkCustomRecords : ICapability<LinkRecords, RecordsLinked>
{
private readonly CustomSchemaStore _store;
private readonly RollupStore _rollups;
/// <summary>Creates the capability.</summary>
/// <param name="store">Reads the relationship and writes the link.</param>
/// <param name="rollups">Recomputes what the new child changed.</param>
/// <exception cref="ArgumentNullException">Any argument is null.</exception>
public LinkCustomRecords(CustomSchemaStore store, RollupStore rollups)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(rollups);
_store = store;
_rollups = rollups;
}
/// <inheritdoc />
public async ValueTask<Result<RecordsLinked>> ExecuteAsync(
LinkRecords input,
CapabilityContext ctx,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(ctx);
if (await _store.ReadRelationshipAsync(ctx.TenantId, input.Relationship, ct).ConfigureAwait(false)
is not { } edge)
{
return Result.Fail<RecordsLinked>(
CustomSchemaErrors.RelationshipNotFound(input.Relationship));
}
if (await _store.ObjectOfAsync(ctx.TenantId, input.From, ct).ConfigureAwait(false) != edge.From)
{
return Result.Fail<RecordsLinked>(CustomSchemaErrors.RecordNotFound(input.From));
}
if (await _store.ObjectOfAsync(ctx.TenantId, input.To, ct).ConfigureAwait(false) != edge.To)
{
return Result.Fail<RecordsLinked>(CustomSchemaErrors.RecordNotFound(input.To));
}
var id = ctx.NewId();
if (!await _store.LinkAsync(ctx.TenantId, id, input, ctx.UtcNow, ct).ConfigureAwait(false))
{
return Result.Fail<RecordsLinked>(
CustomSchemaErrors.CardinalityWouldBreak(edge.Cardinality));
}
// The parent gained a child, so every roll-up over this edge is now stale. Recomputed
// here rather than on read, because a transition guard reads `custom_fields` out of the
// row and a value computed at read time would not be there for it.
await _rollups.RecomputeAsync(ctx.TenantId, input.Relationship, input.From, ct)
.ConfigureAwait(false);
return Result.Ok(new RecordsLinked(id));
}
}
/// <summary>
/// Sets the custom values of a built-in entity.
/// </summary>
/// <remarks>
/// <strong>A merge and not a replacement.</strong> The values a caller sends are written over
/// the ones with the same names and the rest are left alone, because a partial update that
/// erased what it did not mention would make two clients editing different fields of the same
/// lead destroy each other's work.
/// </remarks>
[Capability("crm.custom.set_fields", Version = "1.0.0",
Authorization = Authorization.Permission, Permission = "crm.write",
Idempotent = true)]
public sealed class SetEntityCustomFields : ICapability<WriteEntityFields, CustomFieldsSet>
{
private readonly CustomSchemaStore _store;
private readonly FieldPolicyStore _policy;
/// <summary>Creates the capability.</summary>
/// <param name="store">Reads the declarations and merges the values.</param>
/// <param name="policy">Reads the rules and records what changed.</param>
/// <exception cref="ArgumentNullException">Any argument is null.</exception>
public SetEntityCustomFields(CustomSchemaStore store, FieldPolicyStore policy)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(policy);
_store = store;
_policy = policy;
}
/// <inheritdoc />
public async ValueTask<Result<CustomFieldsSet>> ExecuteAsync(
WriteEntityFields input,
CapabilityContext ctx,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(ctx);
var declared = await _store.FieldsForAsync(ctx.TenantId, input.Kind, ct).ConfigureAwait(false);
// requireComplete: false — see the remarks on the class. A field the caller did not
// mention keeps whatever the row already held, so it is not missing.
if (CustomValues.Validate(declared, input.Values, requireComplete: false) is { Count: > 0 } faults)
{
return Result.Fail<CustomFieldsSet>(faults[0]);
}
if (await CustomReferences
.UnresolvableAsync(_store, declared, input.Values, ctx, ct)
.ConfigureAwait(false) is { } dangling)
{
return Result.Fail<CustomFieldsSet>(dangling);
}
if (CustomFieldPolicy.FirstComputedField(declared, input.Values) is { } computed)
{
return Result.Fail<CustomFieldsSet>(computed);
}
if (CustomFieldPolicy.FirstForbiddenField(declared, input.Values, input.Scopes) is { } forbidden)
{
return Result.Fail<CustomFieldsSet>(forbidden);
}
// Read before the merge, for two reasons that happen to want the same call: a rule over a
// field this update did not mention has to be evaluated against what is already there,
// and the history needs to know what it used to be.
if (await _store.ReadCustomFieldsAsync(ctx.TenantId, input.Kind, input.Id, ct)
.ConfigureAwait(false) is not { } before)
{
return Result.Fail<CustomFieldsSet>(
CustomSchemaErrors.EntityNotFound(input.Kind, input.Id));
}
var rules = await _policy.RulesForAsync(ctx.TenantId, input.Kind, ct).ConfigureAwait(false);
if (CustomFieldPolicy.FirstViolation(rules, input.Values, before) is { } refused)
{
return Result.Fail<CustomFieldsSet>(refused);
}
var merged = await _store
.MergeCustomFieldsAsync(
ctx.TenantId, input.Kind, input.Id, CustomValues.ToJson(declared, input.Values), ct)
.ConfigureAwait(false);
if (merged is null)
{
return Result.Fail<CustomFieldsSet>(
CustomSchemaErrors.EntityNotFound(input.Kind, input.Id));
}
await _policy
.RecordAsync(
ctx.TenantId, input.Kind, input.Id, before, merged,
input.ChangedBy, ctx.UtcNow, ct)
.ConfigureAwait(false);
return Result.Ok(new CustomFieldsSet(input.Id, merged));
}
}
/// <summary>
/// Whether the references in a set of values point at anything.
/// </summary>
/// <remarks>
/// <strong>A helper both capabilities compose, and not a call between them.</strong>
/// <c>CapabilitiesDoNotCallCapabilities</c> is an architecture gate and it is right: a capability
/// reaching into another is a dependency the manifest does not describe and the engine cannot
/// authorise. <c>LeadDeliveries</c> in <c>Intake.cs</c> exists for the same reason.
/// </remarks>
public static class CustomReferences
{
/// <summary>The first reference that points at nothing, or null when they all resolve.</summary>
/// <param name="store">Reads which object a record belongs to.</param>
/// <param name="declared">The fields declared for the entity, by name.</param>
/// <param name="values">What was sent.</param>
/// <param name="ctx">The invocation, for its tenant.</param>
/// <param name="ct">Cancels the call.</param>
/// <returns>The error, or null.</returns>
/// <exception cref="ArgumentNullException">Any argument is null.</exception>
/// <remarks>
/// The half <see cref="CustomValues.Validate"/> cannot answer. It needs a read, and putting
/// one behind a pure function would make the whole of it depend on when it was asked.
/// </remarks>
public static async ValueTask<Error?> UnresolvableAsync(
CustomSchemaStore store,
IReadOnlyDictionary<string, CustomFieldRow> declared,
IReadOnlyDictionary<string, string?> values,
CapabilityContext ctx,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(declared);
ArgumentNullException.ThrowIfNull(values);
ArgumentNullException.ThrowIfNull(ctx);
foreach (var (name, value) in values)
{
if (value is null ||
!declared.TryGetValue(name, out var field) ||
field.Type != CustomFieldType.Reference ||
field.References is not { } target)
{
continue;
}
if (await store.ObjectOfAsync(ctx.TenantId, Guid.Parse(value), ct).ConfigureAwait(false)
!= target)
{
return CustomSchemaErrors.ReferenceIsNotResolvable(name, value);
}
}
return null;
}
}