@appling/codegen-ash 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -5
- package/out/actors.d.ts +38 -0
- package/out/actors.js +105 -0
- package/out/api.js +4 -1
- package/out/application.d.ts +1 -1
- package/out/application.js +13 -6
- package/out/behavior.d.ts +5 -1
- package/out/behavior.js +20 -10
- package/out/elixir.d.ts +8 -0
- package/out/elixir.js +102 -3
- package/out/index.js +47 -43
- package/out/model-tests.d.ts +47 -0
- package/out/model-tests.js +320 -0
- package/out/naming.d.ts +8 -1
- package/out/naming.js +14 -2
- package/out/pages.js +11 -3
- package/out/policy-tests.d.ts +12 -0
- package/out/policy-tests.js +106 -0
- package/out/resource.d.ts +2 -0
- package/out/resource.js +7 -0
- package/out/roles.d.ts +44 -9
- package/out/roles.js +267 -67
- package/out/scenario-tests.d.ts +13 -0
- package/out/scenario-tests.js +573 -0
- package/out/tenants.d.ts +14 -0
- package/out/tenants.js +87 -0
- package/out/tests.d.ts +9 -3
- package/out/tests.js +8 -4
- package/out/vendors.d.ts +19 -0
- package/out/vendors.js +79 -0
- package/package.json +4 -4
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
import { coveredByScenarios, scenarioCall, UNKNOWN } from '@appling/model';
|
|
2
|
+
import { homeAt, homeFields, homeOf } from './actors.js';
|
|
3
|
+
import { effectChange } from './behavior.js';
|
|
4
|
+
import { elixirString, lastOf, parentOf, validation } from './elixir.js';
|
|
5
|
+
import { defaultValue, enforcedInvariants, sample, simulator, targets } from './model-tests.js';
|
|
6
|
+
import { app, calculation, children, fieldsOf, moduleName, pascal, relationTarget, snake, storedAttributes, task, typeModule } from './naming.js';
|
|
7
|
+
import { checksAnswer, enforced, policyTranslates } from './roles.js';
|
|
8
|
+
import { partitionOf } from './tenants.js';
|
|
9
|
+
const covered = new WeakMap();
|
|
10
|
+
/** Whether a scenario's `when` runs this action or use case, or the action that triggers this transition: its guessed tests give way to the scenario test. */
|
|
11
|
+
export function coveredByScenario(qn, context) {
|
|
12
|
+
let found = covered.get(context.graph);
|
|
13
|
+
if (!found)
|
|
14
|
+
covered.set(context.graph, found = coveredByScenarios(context.graph));
|
|
15
|
+
return found.has(qn);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A scenario becomes an ExUnit test in `test/<app>/<module>/scenarios_test.exs`, which checks out a database
|
|
19
|
+
* sandbox: the given rows are written with `Ash.Seed.seed!` (their values, samples for the other required
|
|
20
|
+
* attributes), the actor is a record of its resource or its struct with the actor's roles, the call runs the
|
|
21
|
+
* action's update action with `Ash.update`, and the test asserts the outcome and reads the rows back for the
|
|
22
|
+
* checks. A scenario whose test the generated project cannot pass yet stays a skipped test and a registry task
|
|
23
|
+
* that says why.
|
|
24
|
+
*/
|
|
25
|
+
export function scenarioSteps(scenario, context) {
|
|
26
|
+
const file = ['test', app(context), ...scenario.module.split('.').map(snake), 'scenarios_test.exs'].join('/');
|
|
27
|
+
const title = `scenario ${lastOf(scenario.qn)}`;
|
|
28
|
+
let body;
|
|
29
|
+
let why = '';
|
|
30
|
+
try {
|
|
31
|
+
body = scenarioBody(scenario, context);
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (!(error instanceof Unsupported))
|
|
35
|
+
throw error;
|
|
36
|
+
why = error.message;
|
|
37
|
+
}
|
|
38
|
+
const does = typeof scenario.data.does === 'string' && scenario.data.does.trim() ? ` # ${scenario.data.does.trim().replace(/\s*\n\s*/g, ' ')}\n` : '';
|
|
39
|
+
const test = body
|
|
40
|
+
? `${does} test ${JSON.stringify(title)} do\n${body.map(l => ` ${l}\n`).join('')} end\n`
|
|
41
|
+
: `${does} @tag skip: ${JSON.stringify(`registry task: ${scenario.qn}`)}\n test ${JSON.stringify(title)}\n`;
|
|
42
|
+
const repo = `${pascal(app(context))}.Repo`;
|
|
43
|
+
return [
|
|
44
|
+
{
|
|
45
|
+
kind: 'template', file, write: existing => existing
|
|
46
|
+
? existing.replace(/end\n?$/, `\n${test}end\n`)
|
|
47
|
+
: [
|
|
48
|
+
`defmodule ${moduleName(scenario.module, context)}.ScenariosTest do`,
|
|
49
|
+
' use ExUnit.Case, async: false',
|
|
50
|
+
'',
|
|
51
|
+
' setup do',
|
|
52
|
+
` pid = Ecto.Adapters.SQL.Sandbox.start_owner!(${repo}, shared: true)`,
|
|
53
|
+
' on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)',
|
|
54
|
+
' :ok',
|
|
55
|
+
' end',
|
|
56
|
+
'',
|
|
57
|
+
`${test}end`,
|
|
58
|
+
''
|
|
59
|
+
].join('\n')
|
|
60
|
+
},
|
|
61
|
+
...(body ? [] : [task(`write the test "${title}" in ${file}: ${why}`)])
|
|
62
|
+
];
|
|
63
|
+
}
|
|
64
|
+
/** Why a scenario's test cannot be written yet. */
|
|
65
|
+
class Unsupported extends Error {
|
|
66
|
+
}
|
|
67
|
+
function fail(why) {
|
|
68
|
+
throw new Unsupported(why);
|
|
69
|
+
}
|
|
70
|
+
const RESERVED = new Set(['and', 'or', 'not', 'in', 'when', 'fn', 'do', 'end', 'catch', 'rescue', 'after', 'else', 'true', 'false', 'nil', 'actor', 'error', 'pid']);
|
|
71
|
+
function scenarioBody(scenario, context) {
|
|
72
|
+
const call = scenarioCall(scenario);
|
|
73
|
+
const action = context.node(call.target);
|
|
74
|
+
if (action.kind === 'UseCase')
|
|
75
|
+
fail(`the use case ${lastOf(action.qn)} is not generated yet (its own registry task)`);
|
|
76
|
+
const entity = action.data.entity ? context.node(action.data.entity) : undefined;
|
|
77
|
+
if (!entity)
|
|
78
|
+
fail(`${lastOf(action.qn)} is not generated yet, it has no entity (its own registry task)`);
|
|
79
|
+
const result = simulator(context).scenario(scenario.qn);
|
|
80
|
+
if (!result.passed)
|
|
81
|
+
fail(`the simulator does not pass it: ${result.failures.join(' ')}`);
|
|
82
|
+
const lines = [];
|
|
83
|
+
const bindings = new Map();
|
|
84
|
+
const vars = new Map();
|
|
85
|
+
const fixtures = (scenario.data.fixtures ?? []);
|
|
86
|
+
fixtures.forEach((fixture, i) => {
|
|
87
|
+
const node = context.node(fixture.entity);
|
|
88
|
+
const home = homeAt(node, context);
|
|
89
|
+
const label = fixture.name ?? `the ${lastOf(node.qn)} row`;
|
|
90
|
+
const given = new Map((fixture.assignments ?? []).map(a => [a.name, a.value]));
|
|
91
|
+
const fields = home?.resource ? homeFields(home, context) : fieldsOf(node, context);
|
|
92
|
+
const { pairs, samples } = attributes(fields, given, label, i + 1, bindings, context);
|
|
93
|
+
// The row as the simulator builds it (defaults, [] for lists, null for optional fields, then the given values), with the samples.
|
|
94
|
+
const record = { $type: node.qn, $id: `${scenario.qn}#${i + 1}` };
|
|
95
|
+
for (const field of fieldsOf(node, context)) {
|
|
96
|
+
const type = field.data.type;
|
|
97
|
+
if (field.data.derived)
|
|
98
|
+
continue;
|
|
99
|
+
const name = lastOf(field.qn);
|
|
100
|
+
if (field.data.default)
|
|
101
|
+
record[name] = simulator(context).evaluate(field.data.default, { self: record, vars });
|
|
102
|
+
else if (type.many)
|
|
103
|
+
record[name] = [];
|
|
104
|
+
else if (type.optional)
|
|
105
|
+
record[name] = null;
|
|
106
|
+
}
|
|
107
|
+
for (const [name, value] of given)
|
|
108
|
+
record[name] = simulator(context).evaluate(value, { vars });
|
|
109
|
+
for (const [name, value] of samples)
|
|
110
|
+
record[name] = value;
|
|
111
|
+
const partition = home?.resource ? undefined : partitionOf(node, context);
|
|
112
|
+
let tenant;
|
|
113
|
+
if (partition) {
|
|
114
|
+
const owner = given.get(partition);
|
|
115
|
+
tenant = owner && bindingOf(owner, bindings) ? `${bindingOf(owner, bindings).variable}.id` : fail(`${label} gives no ${partition}, the tenant of ${lastOf(node.qn)}`);
|
|
116
|
+
}
|
|
117
|
+
const seed = `Ash.Seed.seed!(${typeModule(node, context)}, %{${pairs.map(([n, v]) => `${n}: ${v}`).join(', ')}}${tenant ? `, tenant: ${tenant}` : ''})`;
|
|
118
|
+
if (!fixture.name) {
|
|
119
|
+
lines.push(seed);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const variable = variableFor(fixture.name, bindings);
|
|
123
|
+
lines.push(`${variable} = ${seed}`);
|
|
124
|
+
bindings.set(fixture.name, { variable, entity: node, record, tenant });
|
|
125
|
+
vars.set(fixture.name, record);
|
|
126
|
+
});
|
|
127
|
+
const persona = scenario.data.actor;
|
|
128
|
+
let home;
|
|
129
|
+
const actorVariable = [...bindings.values()].some(b => b.variable === 'actor') ? 'scenario_actor' : 'actor';
|
|
130
|
+
if (persona) {
|
|
131
|
+
const named = context.node(persona.persona);
|
|
132
|
+
const actor = named.kind === 'Role'
|
|
133
|
+
? context.graph.nodes.find(n => n.kind === 'Actor' && (n.data.roles ?? []).includes(named.qn)) ?? fail(`no actor holds the role ${lastOf(named.qn)}`)
|
|
134
|
+
: named;
|
|
135
|
+
home = homeOf(actor, context);
|
|
136
|
+
const roles = `[${(actor.data.roles ?? []).map(r => `:${snake(lastOf(r))}`).join(', ')}]`;
|
|
137
|
+
const given = new Map((persona.assignments ?? []).map(a => [a.name, a.value]));
|
|
138
|
+
if (home.resource) {
|
|
139
|
+
const { pairs } = attributes(homeFields(home, context), given, `the actor ${lastOf(actor.qn)}`, fixtures.length + 1, bindings, context);
|
|
140
|
+
lines.push(`${actorVariable} = Ash.Seed.seed!(${home.module}, %{${[...pairs, ['roles', roles]].map(([n, v]) => `${n}: ${v}`).join(', ')}})`);
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
const keys = [...given].map(([name, value]) => {
|
|
144
|
+
const field = fieldsOf(actor, context).find(f => lastOf(f.qn) === name) ?? fail(`the actor ${lastOf(actor.qn)} has no stored ${name}`);
|
|
145
|
+
return attribute(field, value, bindings, context);
|
|
146
|
+
});
|
|
147
|
+
lines.push(`${actorVariable} = %${home.module}{${[...keys, ['roles', roles]].map(([n, v]) => `${n}: ${v}`).join(', ')}}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const target = bindingOf(call.args[0], bindings);
|
|
151
|
+
if (!target || target.entity.qn !== entity.qn)
|
|
152
|
+
fail(`the first argument of ${lastOf(action.qn)} is not a given ${lastOf(entity.qn)} row`);
|
|
153
|
+
const inputs = children(action, context, 'Param').flatMap((param, i) => {
|
|
154
|
+
const arg = call.args[i + 1];
|
|
155
|
+
if (!arg)
|
|
156
|
+
return [];
|
|
157
|
+
if (relationTarget(param, context))
|
|
158
|
+
fail(`the input ${lastOf(param.qn)} of ${lastOf(action.qn)} is a ${lastOf(relationTarget(param, context).qn)} row, which the generated argument does not take`);
|
|
159
|
+
return [[lastOf(param.qn), elixirValue(arg, param.data.type, context) ?? fail(`the input ${lastOf(param.qn)} does not translate`)]];
|
|
160
|
+
});
|
|
161
|
+
const options = [`action: :${snake(lastOf(action.qn))}`, persona ? `actor: ${actorVariable}` : 'authorize?: false', ...(target.tenant ? [`tenant: ${target.tenant}`] : [])];
|
|
162
|
+
const run = `Ash.update(${target.variable}, %{${inputs.map(([n, v]) => `${n}: ${v}`).join(', ')}}, ${options.join(', ')})`;
|
|
163
|
+
const ash = new UpdateAction(action, entity, target.record, context);
|
|
164
|
+
// Policies decide only for a call with an actor; then Ash's policies must say what the model's say.
|
|
165
|
+
const authorizes = () => {
|
|
166
|
+
if (!persona || !enforced(context))
|
|
167
|
+
return;
|
|
168
|
+
const policies = [
|
|
169
|
+
...children(action, context, 'Policy'),
|
|
170
|
+
...children(entity, context, 'Policy').filter(p => !(p.data.fields ?? []).length && covers(p, 'update'))
|
|
171
|
+
];
|
|
172
|
+
for (const policy of policies) {
|
|
173
|
+
if (!policyTranslates(policy, context))
|
|
174
|
+
fail(`the policy ${policy.qn} does not translate, so Ash forbids the call`);
|
|
175
|
+
if (!checksAnswer(policy.data.condition, home, context))
|
|
176
|
+
fail(`a role check that ${policy.qn} names is a registry task for ${home.module}`);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
if (scenario.data.refused) {
|
|
180
|
+
if (ash.creates)
|
|
181
|
+
fail(`${lastOf(action.qn)} creates rows, whose create policies the simulator checks and Ash does not`);
|
|
182
|
+
ash.passes('Ash checks the policies only after the validations');
|
|
183
|
+
lines.push(`assert {:error, %Ash.Error.Forbidden{}} = ${run}`);
|
|
184
|
+
}
|
|
185
|
+
else if (scenario.data.fails) {
|
|
186
|
+
authorizes();
|
|
187
|
+
const error = scenario.data.error;
|
|
188
|
+
if (error) {
|
|
189
|
+
const precondition = ash.preconditions.find(p => p.error === error)
|
|
190
|
+
?? fail(`the precondition that fails with ${lastOf(error)} does not translate to a validation (a registry task of ${lastOf(action.qn)})`);
|
|
191
|
+
if (!ash.isFalse(precondition.condition))
|
|
192
|
+
fail(`the validation for ${lastOf(error)} is not proven to fail on the given rows`);
|
|
193
|
+
lines.push(`assert {:error, error} = ${run}`, `assert Exception.message(error) =~ ${elixirString(lastOf(error))}`);
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
if (!ash.fails())
|
|
197
|
+
fail(`no validation or state check of the generated action fails like the model: ${result.reasons.join('; ')}`);
|
|
198
|
+
lines.push(`assert {:error, _} = ${run}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
authorizes();
|
|
203
|
+
ash.applies();
|
|
204
|
+
ash.passes('a validation of the generated action may fail');
|
|
205
|
+
lines.push(`assert {:ok, _} = ${run}`);
|
|
206
|
+
const checks = (scenario.data.checks ?? []);
|
|
207
|
+
const translator = new CheckTranslator(bindings, context);
|
|
208
|
+
const asserts = checks.map(check => {
|
|
209
|
+
if (check.$type !== 'Expectation')
|
|
210
|
+
fail(`the generated project does not publish ${lastOf(check.event)} yet (a registry task of the event)`);
|
|
211
|
+
return `assert ${bare(translator.bool(check.condition) ?? fail(`the check ${scenario.props.checks[checks.indexOf(check)]} does not translate`))}`;
|
|
212
|
+
});
|
|
213
|
+
for (const [name, loads] of translator.reads) {
|
|
214
|
+
const variable = bindings.get(name).variable;
|
|
215
|
+
lines.push(`${variable} = Ash.reload!(${variable}, ${loads.size ? `load: [${[...loads].map(l => `:${l}`).join(', ')}], ` : ''}authorize?: false)`);
|
|
216
|
+
}
|
|
217
|
+
lines.push(...asserts);
|
|
218
|
+
}
|
|
219
|
+
return unusedMarked(lines);
|
|
220
|
+
}
|
|
221
|
+
/** A policy without operations covers every operation. */
|
|
222
|
+
function covers(policy, operation) {
|
|
223
|
+
const operations = (policy.data.operations ?? []);
|
|
224
|
+
return !operations.length || operations.includes(operation);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The update action the generator writes for an action, as far as it decides the call: its translated
|
|
228
|
+
* preconditions and guard (validations before the changes), the state check of AshStateMachine, its changes, and
|
|
229
|
+
* the translated invariants of the entity, which Ash checks after the changes.
|
|
230
|
+
*/
|
|
231
|
+
class UpdateAction {
|
|
232
|
+
action;
|
|
233
|
+
entity;
|
|
234
|
+
before;
|
|
235
|
+
context;
|
|
236
|
+
preconditions;
|
|
237
|
+
transitions;
|
|
238
|
+
guard;
|
|
239
|
+
effects;
|
|
240
|
+
state;
|
|
241
|
+
creates;
|
|
242
|
+
constructor(action, entity, before, context) {
|
|
243
|
+
this.action = action;
|
|
244
|
+
this.entity = entity;
|
|
245
|
+
this.before = before;
|
|
246
|
+
this.context = context;
|
|
247
|
+
const stored = storedAttributes(entity, context);
|
|
248
|
+
const translates = (condition) => validation(condition, stored, context.node) !== undefined;
|
|
249
|
+
this.preconditions = (action.data.preconditions ?? []).filter(p => translates(p.condition));
|
|
250
|
+
this.transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
|
|
251
|
+
const guarded = this.transitions.filter(t => t.data.guard);
|
|
252
|
+
// actionSteps writes the guard of a single transition as a validation, every other guard is a task.
|
|
253
|
+
if (this.transitions.length === 1 && guarded.length === 1 && translates(guarded[0].data.guard))
|
|
254
|
+
this.guard = guarded[0].data.guard;
|
|
255
|
+
if (new Set(this.transitions.map(t => t.data.to)).size > 1)
|
|
256
|
+
fail(`${lastOf(action.qn)} has no single target state, which is a registry task`);
|
|
257
|
+
this.effects = [...children(action, context), ...this.transitions.flatMap(t => children(t, context))].filter(c => c.kind.endsWith('Effect'));
|
|
258
|
+
this.creates = this.effects.some(e => e.kind === 'CreateEffect');
|
|
259
|
+
if (this.transitions.length)
|
|
260
|
+
this.state = lastOf(context.node(parentOf(this.transitions[0].qn)).data.field);
|
|
261
|
+
}
|
|
262
|
+
/** Whether the condition is false on the row before the call. */
|
|
263
|
+
isFalse(condition) {
|
|
264
|
+
return simulator(this.context).evaluate(condition, { self: this.before }) === false;
|
|
265
|
+
}
|
|
266
|
+
isTrue(condition, self = this.before) {
|
|
267
|
+
return simulator(this.context).evaluate(condition, { self }) === true;
|
|
268
|
+
}
|
|
269
|
+
/** Whether AshStateMachine lets the row leave its state with this action. */
|
|
270
|
+
leaves() {
|
|
271
|
+
return !this.state || this.transitions.some(t => t.data.from.includes(String(this.before[this.state])));
|
|
272
|
+
}
|
|
273
|
+
/** Fails unless every validation and the state check of the action pass on the given rows. */
|
|
274
|
+
passes(why) {
|
|
275
|
+
if (!this.preconditions.every(p => this.isTrue(p.condition)))
|
|
276
|
+
fail(`${why}: a translated precondition of ${lastOf(this.action.qn)} is not proven true`);
|
|
277
|
+
if (this.guard && !this.isTrue(this.guard))
|
|
278
|
+
fail(`${why}: the guard of ${lastOf(this.action.qn)} is not proven true`);
|
|
279
|
+
if (!this.leaves())
|
|
280
|
+
fail(`${why}: AshStateMachine refuses the state ${String(this.before[this.state])}`);
|
|
281
|
+
const changed = new Set(this.effects.filter(e => e.kind === 'SetEffect').map(e => e.data.field));
|
|
282
|
+
const after = this.state ? { ...this.before, [this.state]: this.transitions[0].data.to } : this.before;
|
|
283
|
+
for (const invariant of enforcedInvariants(this.entity, this.context)) {
|
|
284
|
+
if ([...targets(invariant.data.condition)].some(f => changed.has(f)))
|
|
285
|
+
fail(`${why}: the invariant "${invariant.data.label}" reads a field ${lastOf(this.action.qn)} sets`);
|
|
286
|
+
if (!this.isTrue(invariant.data.condition, after))
|
|
287
|
+
fail(`${why}: the invariant "${invariant.data.label}" is not proven true after the call`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/** Whether a validation or the state check fails on the given rows. */
|
|
291
|
+
fails() {
|
|
292
|
+
return this.preconditions.some(p => this.isFalse(p.condition)) || (!!this.guard && this.isFalse(this.guard)) || !this.leaves();
|
|
293
|
+
}
|
|
294
|
+
/** Fails unless the generated action makes every change the model's action makes. */
|
|
295
|
+
applies() {
|
|
296
|
+
for (const effect of this.effects.filter(e => e.kind === 'SetEffect')) {
|
|
297
|
+
if (!effectChange(effect, this.context))
|
|
298
|
+
fail(`the effect ${lastOf(effect.qn)} of ${lastOf(this.action.qn)} is a registry task`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
/** The `key: value` pairs of a row or an actor record: the given values, then samples for required attributes the scenario does not give. */
|
|
303
|
+
function attributes(fields, given, label, index, bindings, context) {
|
|
304
|
+
const pairs = [];
|
|
305
|
+
const samples = new Map();
|
|
306
|
+
const stored = fields.filter(f => !f.data.derived);
|
|
307
|
+
for (const name of given.keys())
|
|
308
|
+
if (!stored.some(f => lastOf(f.qn) === name))
|
|
309
|
+
fail(`${label} gives ${name}, which is not stored`);
|
|
310
|
+
for (const field of stored) {
|
|
311
|
+
const name = lastOf(field.qn);
|
|
312
|
+
const type = field.data.type;
|
|
313
|
+
const value = given.get(name);
|
|
314
|
+
if (value) {
|
|
315
|
+
pairs.push(attribute(field, value, bindings, context));
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
const target = relationTarget(field, context);
|
|
319
|
+
if (target) {
|
|
320
|
+
if (!type.optional && !type.many)
|
|
321
|
+
fail(`${label} gives no ${name}, a required ${lastOf(target.qn)}`);
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (field.data.default) {
|
|
325
|
+
if (!type.optional && defaultValue(field, context) === undefined)
|
|
326
|
+
fail(`the default of ${name} does not translate`);
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (type.many) {
|
|
330
|
+
pairs.push([name, '[]']);
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
if (type.optional)
|
|
334
|
+
continue;
|
|
335
|
+
const unique = (field.data.modifiers ?? []).includes('unique');
|
|
336
|
+
const value_ = sampleOf(name, type, unique, index, context) ?? fail(`there is no sample for ${name} of ${label}`);
|
|
337
|
+
pairs.push([name, value_.elixir]);
|
|
338
|
+
samples.set(name, value_.value);
|
|
339
|
+
}
|
|
340
|
+
return { pairs, samples };
|
|
341
|
+
}
|
|
342
|
+
/** A given value as the attribute Ash stores: a relationship as the related row's id, everything else as an Elixir value. */
|
|
343
|
+
function attribute(field, value, bindings, context) {
|
|
344
|
+
const name = lastOf(field.qn);
|
|
345
|
+
const type = field.data.type;
|
|
346
|
+
const target = relationTarget(field, context);
|
|
347
|
+
if (target) {
|
|
348
|
+
if (type.many)
|
|
349
|
+
fail(`${name} lists ${lastOf(target.qn)} rows, a relationship the generated project does not model yet`);
|
|
350
|
+
if (value.$type === 'NullExpr')
|
|
351
|
+
return [`${name}_id`, 'nil'];
|
|
352
|
+
const related = bindingOf(value, bindings) ?? fail(`${name} is not a given row`);
|
|
353
|
+
return [`${name}_id`, `${related.variable}.id`];
|
|
354
|
+
}
|
|
355
|
+
return [name, elixirValue(value, type, context) ?? fail(`the value of ${name} does not translate`)];
|
|
356
|
+
}
|
|
357
|
+
/** A literal, an enum value, `now` or a list of them as an Elixir value of the type; undefined for anything else. */
|
|
358
|
+
function elixirValue(expr, type, context) {
|
|
359
|
+
if (type.many) {
|
|
360
|
+
if (expr.$type !== 'ListExpr')
|
|
361
|
+
return undefined;
|
|
362
|
+
const items = (expr.items ?? []).map(i => elixirValue(i, { ...type, many: false }, context));
|
|
363
|
+
return items.every(i => i !== undefined) ? `[${items.join(', ')}]` : undefined;
|
|
364
|
+
}
|
|
365
|
+
const decl = type.decl ? context.node(type.decl) : undefined;
|
|
366
|
+
switch (expr.$type) {
|
|
367
|
+
case 'NullExpr': return 'nil';
|
|
368
|
+
case 'StringExpr': return ['String', 'Text', 'Uuid'].includes(type.primitive ?? '') ? elixirString(String(expr.value)) : undefined;
|
|
369
|
+
case 'BoolExpr': return type.primitive === 'Bool' ? String(String(expr.value) === 'true') : undefined;
|
|
370
|
+
case 'NumberExpr': {
|
|
371
|
+
const number = String(expr.value);
|
|
372
|
+
if (type.primitive === 'Decimal' || type.primitive === 'Money')
|
|
373
|
+
return `Decimal.new(${JSON.stringify(number)})`;
|
|
374
|
+
return type.primitive === 'Int' && /^-?\d+$/.test(number) ? number : undefined;
|
|
375
|
+
}
|
|
376
|
+
case 'NameExpr': {
|
|
377
|
+
if (expr.call)
|
|
378
|
+
return undefined;
|
|
379
|
+
if (decl?.kind === 'Enum' && expr.target && context.node(expr.target)?.kind === 'EnumLiteral')
|
|
380
|
+
return `:${expr.name}`;
|
|
381
|
+
if (expr.name === 'now' && !expr.target)
|
|
382
|
+
return type.primitive === 'DateTime' ? 'DateTime.utc_now()' : type.primitive === 'Date' ? 'Date.utc_today()' : undefined;
|
|
383
|
+
return undefined;
|
|
384
|
+
}
|
|
385
|
+
default: return undefined;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
/** A sample value of a required attribute: unique per row, and a map of samples for a value type. */
|
|
389
|
+
function sampleOf(name, type, unique, index, context) {
|
|
390
|
+
const decl = type.decl ? context.node(type.decl) : undefined;
|
|
391
|
+
if (decl?.kind === 'ValueType') {
|
|
392
|
+
const pairs = [];
|
|
393
|
+
for (const field of fieldsOf(decl, context).filter(f => !f.data.derived)) {
|
|
394
|
+
const fieldType = field.data.type;
|
|
395
|
+
if (fieldType.optional)
|
|
396
|
+
continue;
|
|
397
|
+
const value = fieldType.many ? { elixir: '[]' } : sampleOf(lastOf(field.qn), fieldType, false, index, context);
|
|
398
|
+
if (!value)
|
|
399
|
+
return undefined;
|
|
400
|
+
pairs.push(`${lastOf(field.qn)}: ${value.elixir}`);
|
|
401
|
+
}
|
|
402
|
+
return { elixir: `%{${pairs.join(', ')}}`, value: UNKNOWN };
|
|
403
|
+
}
|
|
404
|
+
if (type.primitive === 'String' || type.primitive === 'Text')
|
|
405
|
+
return { elixir: JSON.stringify(`${name}-${index}`), value: UNKNOWN };
|
|
406
|
+
if (type.primitive === 'Int' && unique)
|
|
407
|
+
return { elixir: String(index), value: index };
|
|
408
|
+
return sample(name, type, context);
|
|
409
|
+
}
|
|
410
|
+
function bindingOf(expr, bindings) {
|
|
411
|
+
return expr?.$type === 'NameExpr' && !expr.target && !expr.call ? bindings.get(expr.name) : undefined;
|
|
412
|
+
}
|
|
413
|
+
function variableFor(name, bindings) {
|
|
414
|
+
let variable = snake(name);
|
|
415
|
+
if (RESERVED.has(variable))
|
|
416
|
+
variable = `${variable}_row`;
|
|
417
|
+
while ([...bindings.values()].some(b => b.variable === variable))
|
|
418
|
+
variable = `${variable}_`;
|
|
419
|
+
return variable;
|
|
420
|
+
}
|
|
421
|
+
/** Prefixes the variables the test assigns and never reads with `_`, so ExUnit does not warn. */
|
|
422
|
+
function unusedMarked(lines) {
|
|
423
|
+
return lines.map((line, i) => {
|
|
424
|
+
const assigned = /^(\w+) = /.exec(line)?.[1];
|
|
425
|
+
if (!assigned)
|
|
426
|
+
return line;
|
|
427
|
+
const rest = lines.slice(i + 1).join('\n');
|
|
428
|
+
return new RegExp(`(^|[^\\w.:])${assigned}\\b`).test(rest) ? line : `_${line}`;
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
/** An expression without its outer parentheses. */
|
|
432
|
+
function bare(code) {
|
|
433
|
+
if (!code.startsWith('(') || !code.endsWith(')'))
|
|
434
|
+
return code;
|
|
435
|
+
let depth = 0;
|
|
436
|
+
for (let i = 0; i < code.length; i++) {
|
|
437
|
+
if (code[i] === '(')
|
|
438
|
+
depth++;
|
|
439
|
+
else if (code[i] === ')')
|
|
440
|
+
depth--;
|
|
441
|
+
if (depth === 0 && i < code.length - 1)
|
|
442
|
+
return code;
|
|
443
|
+
}
|
|
444
|
+
return code.slice(1, -1);
|
|
445
|
+
}
|
|
446
|
+
const DECIMAL_COMPARE = { '==': '== :eq', '!=': '!= :eq', '<': '== :lt', '>': '== :gt', '<=': 'in [:lt, :eq]', '>=': 'in [:gt, :eq]' };
|
|
447
|
+
/**
|
|
448
|
+
* Translates a scenario check to an Elixir condition over the rows read back after the call: attributes of the
|
|
449
|
+
* given rows, relationships as ids, calculations the generator writes (loaded on reload), literals and enum
|
|
450
|
+
* values; decimals compare with `Decimal.compare`. Undefined for anything else.
|
|
451
|
+
*/
|
|
452
|
+
class CheckTranslator {
|
|
453
|
+
bindings;
|
|
454
|
+
context;
|
|
455
|
+
/** The given rows the checks read, by binding name, with the calculations to load. */
|
|
456
|
+
reads = new Map();
|
|
457
|
+
constructor(bindings, context) {
|
|
458
|
+
this.bindings = bindings;
|
|
459
|
+
this.context = context;
|
|
460
|
+
}
|
|
461
|
+
bool(expr) {
|
|
462
|
+
switch (expr.$type) {
|
|
463
|
+
case 'BoolExpr': return String(String(expr.value) === 'true');
|
|
464
|
+
case 'UnaryExpr': {
|
|
465
|
+
const operand = expr.op === '!' ? this.bool(expr.operand) : undefined;
|
|
466
|
+
return operand && `not ${wrap(operand)}`;
|
|
467
|
+
}
|
|
468
|
+
case 'NameExpr': {
|
|
469
|
+
if (!expr.call || expr.name !== 'has' || !expr.args?.[0])
|
|
470
|
+
return undefined;
|
|
471
|
+
const term = this.term(expr.args[0]);
|
|
472
|
+
return term && term.kind !== 'nil' ? `not is_nil(${term.code})` : undefined;
|
|
473
|
+
}
|
|
474
|
+
case 'MemberExpr': {
|
|
475
|
+
const term = this.term(expr);
|
|
476
|
+
return term && expr.type === 'Bool' ? `${term.code} == true` : undefined;
|
|
477
|
+
}
|
|
478
|
+
case 'BinaryExpr': break;
|
|
479
|
+
default: return undefined;
|
|
480
|
+
}
|
|
481
|
+
if (expr.op === '&&' || expr.op === '||') {
|
|
482
|
+
const [left, right] = [this.bool(expr.left), this.bool(expr.right)];
|
|
483
|
+
return left && right && `(${wrap(left)} ${expr.op === '&&' ? 'and' : 'or'} ${wrap(right)})`;
|
|
484
|
+
}
|
|
485
|
+
if (expr.op === 'in') {
|
|
486
|
+
const left = this.term(expr.left);
|
|
487
|
+
const items = expr.right?.$type === 'ListExpr' ? (expr.right.items ?? []).map(i => this.term(i)) : undefined;
|
|
488
|
+
if (!left || !items || items.some(i => !i) || left.kind !== 'value' || items.some(i => i.kind !== 'value'))
|
|
489
|
+
return undefined;
|
|
490
|
+
return `(${left.code} in [${items.map(i => i.code).join(', ')}])`;
|
|
491
|
+
}
|
|
492
|
+
const op = expr.op;
|
|
493
|
+
if (!(op in DECIMAL_COMPARE))
|
|
494
|
+
return undefined;
|
|
495
|
+
const [left, right] = [this.term(expr.left), this.term(expr.right)];
|
|
496
|
+
if (!left || !right)
|
|
497
|
+
return undefined;
|
|
498
|
+
if (left.kind === 'nil' || right.kind === 'nil') {
|
|
499
|
+
const other = left.kind === 'nil' ? right : left;
|
|
500
|
+
if (other.kind === 'nil')
|
|
501
|
+
return undefined;
|
|
502
|
+
return op === '==' ? `is_nil(${other.code})` : op === '!=' ? `not is_nil(${other.code})` : undefined;
|
|
503
|
+
}
|
|
504
|
+
if (left.kind === 'record' || right.kind === 'record') {
|
|
505
|
+
return left.kind === right.kind && (op === '==' || op === '!=') ? `(${left.code} ${op} ${right.code})` : undefined;
|
|
506
|
+
}
|
|
507
|
+
if (left.kind === 'decimal' || right.kind === 'decimal') {
|
|
508
|
+
const decimal = (t) => t.kind === 'number' ? `Decimal.new(${JSON.stringify(t.code)})` : t.kind === 'decimal' ? t.code : undefined;
|
|
509
|
+
const [a, b] = [decimal(left), decimal(right)];
|
|
510
|
+
return a && b && `(Decimal.compare(${a}, ${b}) ${DECIMAL_COMPARE[op]})`;
|
|
511
|
+
}
|
|
512
|
+
if (left.kind === 'time' || right.kind === 'time')
|
|
513
|
+
return undefined;
|
|
514
|
+
const ordered = op !== '==' && op !== '!=';
|
|
515
|
+
if (ordered && !(numeric(expr.left) && numeric(expr.right)))
|
|
516
|
+
return undefined;
|
|
517
|
+
return `(${left.code} ${op} ${right.code})`;
|
|
518
|
+
}
|
|
519
|
+
term(expr) {
|
|
520
|
+
switch (expr.$type) {
|
|
521
|
+
case 'NullExpr': return { code: 'nil', kind: 'nil' };
|
|
522
|
+
case 'StringExpr': return { code: elixirString(String(expr.value)), kind: 'value' };
|
|
523
|
+
case 'BoolExpr': return { code: String(String(expr.value) === 'true'), kind: 'value' };
|
|
524
|
+
case 'NumberExpr': return { code: String(expr.value), kind: 'number' };
|
|
525
|
+
case 'NameExpr': {
|
|
526
|
+
if (expr.call)
|
|
527
|
+
return undefined;
|
|
528
|
+
const binding = !expr.target ? this.bindings.get(expr.name) : undefined;
|
|
529
|
+
// A given row as a whole compares by id, which the call does not change.
|
|
530
|
+
if (binding)
|
|
531
|
+
return { code: `${binding.variable}.id`, kind: 'record' };
|
|
532
|
+
return expr.target && this.context.node(expr.target)?.kind === 'EnumLiteral' ? { code: `:${expr.name}`, kind: 'value' } : undefined;
|
|
533
|
+
}
|
|
534
|
+
case 'MemberExpr': {
|
|
535
|
+
const receiver = expr.receiver;
|
|
536
|
+
const binding = !expr.call && receiver?.$type === 'NameExpr' && !receiver.target && !receiver.call ? this.bindings.get(receiver.name) : undefined;
|
|
537
|
+
const field = binding && expr.target ? this.context.node(expr.target) : undefined;
|
|
538
|
+
if (!binding || field?.kind !== 'Field')
|
|
539
|
+
return undefined;
|
|
540
|
+
const type = field.data.type;
|
|
541
|
+
if (type.many)
|
|
542
|
+
return undefined;
|
|
543
|
+
const loads = this.read(receiver.name);
|
|
544
|
+
const access = `${binding.variable}.${expr.member}`;
|
|
545
|
+
if (relationTarget(field, this.context))
|
|
546
|
+
return field.data.derived ? undefined : { code: `${access}_id`, kind: 'record' };
|
|
547
|
+
if (field.data.derived) {
|
|
548
|
+
if (!calculation(field, this.context))
|
|
549
|
+
return undefined;
|
|
550
|
+
loads.add(expr.member);
|
|
551
|
+
}
|
|
552
|
+
if (type.primitive === 'Decimal' || type.primitive === 'Money')
|
|
553
|
+
return { code: access, kind: 'decimal' };
|
|
554
|
+
if (['Date', 'DateTime', 'Duration'].includes(type.primitive ?? ''))
|
|
555
|
+
return { code: access, kind: 'time' };
|
|
556
|
+
return { code: access, kind: 'value' };
|
|
557
|
+
}
|
|
558
|
+
default: return undefined;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
read(name) {
|
|
562
|
+
let loads = this.reads.get(name);
|
|
563
|
+
if (!loads)
|
|
564
|
+
this.reads.set(name, loads = new Set());
|
|
565
|
+
return loads;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
function numeric(expr) {
|
|
569
|
+
return expr.type.replace(/\?$/, '') === 'Int';
|
|
570
|
+
}
|
|
571
|
+
function wrap(code) {
|
|
572
|
+
return /^[\w.:]+$/.test(code) || (code.startsWith('(') && bare(code) !== code) ? code : `(${code})`;
|
|
573
|
+
}
|
package/out/tenants.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { MapContext, Step } from '@appling/codegen';
|
|
2
|
+
import type { GraphNode } from '@appling/model';
|
|
3
|
+
/**
|
|
4
|
+
* A tenant becomes Ash attribute multitenancy: every resource with a relationship to the tenant's entity is
|
|
5
|
+
* partitioned by that relationship's id, so `tenant: id` scopes every query and change and `^tenant()` reads it.
|
|
6
|
+
* Actor resources stay readable without a tenant (`global? true`), so an actor can be looked up before its tenant
|
|
7
|
+
* is known. Resources that reach the tenant only through other relationships are a task.
|
|
8
|
+
*/
|
|
9
|
+
export declare function tenantSteps(tenant: GraphNode, context: MapContext): Step[];
|
|
10
|
+
/**
|
|
11
|
+
* The relationship that partitions a resource by a tenant, as `tenantSteps` writes it, or undefined when the
|
|
12
|
+
* resource is not partitioned. Actor resources are partitioned too, but stay readable without a tenant.
|
|
13
|
+
*/
|
|
14
|
+
export declare function partitionOf(resource: GraphNode, context: MapContext): string | undefined;
|
package/out/tenants.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { homeAt, homeFields, homes } from './actors.js';
|
|
2
|
+
import { lastOf } from './elixir.js';
|
|
3
|
+
import { fieldsOf, fileOf, patch, relationTarget, task } from './naming.js';
|
|
4
|
+
import { addToSection } from './resource.js';
|
|
5
|
+
/**
|
|
6
|
+
* A tenant becomes Ash attribute multitenancy: every resource with a relationship to the tenant's entity is
|
|
7
|
+
* partitioned by that relationship's id, so `tenant: id` scopes every query and change and `^tenant()` reads it.
|
|
8
|
+
* Actor resources stay readable without a tenant (`global? true`), so an actor can be looked up before its tenant
|
|
9
|
+
* is known. Resources that reach the tenant only through other relationships are a task.
|
|
10
|
+
*/
|
|
11
|
+
export function tenantSteps(tenant, context) {
|
|
12
|
+
const entity = tenant.data.entity;
|
|
13
|
+
const tenantEntities = new Set(context.graph.nodes.filter(n => n.kind === 'Tenant').map(n => n.data.entity));
|
|
14
|
+
const steps = [];
|
|
15
|
+
const partitioned = new Set();
|
|
16
|
+
const ambiguous = [];
|
|
17
|
+
for (const resource of resources(context)) {
|
|
18
|
+
if (resource.qn === entity)
|
|
19
|
+
continue;
|
|
20
|
+
const fields = storedRelations(resource, context);
|
|
21
|
+
const own = fields.filter(f => relationTarget(f, context).qn === entity);
|
|
22
|
+
if (!own.length)
|
|
23
|
+
continue;
|
|
24
|
+
if (own.length > 1 || fields.some(f => relationTarget(f, context).qn !== entity && tenantEntities.has(relationTarget(f, context).qn))) {
|
|
25
|
+
ambiguous.push(resource.qn);
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
partitioned.add(resource.qn);
|
|
29
|
+
const global = homeAt(resource, context) ? ['global? true'] : [];
|
|
30
|
+
steps.push(patch(fileOf(resource, context), existing => addToSection(existing, 'multitenancy', ['strategy :attribute', `attribute :${lastOf(own[0].qn)}_id`, ...global])));
|
|
31
|
+
}
|
|
32
|
+
const indirect = reaching(new Set([...partitioned, ...ambiguous]), entity, context);
|
|
33
|
+
if (ambiguous.length)
|
|
34
|
+
steps.push(task(`pick the tenant attribute of ${ambiguous.map(lastOf).join(', ')} for ${lastOf(tenant.qn)}`));
|
|
35
|
+
if (indirect.length)
|
|
36
|
+
steps.push(task(`partition ${indirect.map(lastOf).join(', ')} by ${lastOf(tenant.qn)}, which they reach only through relationships, for example with a tenant attribute set from the relationship`));
|
|
37
|
+
return steps;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The relationship that partitions a resource by a tenant, as `tenantSteps` writes it, or undefined when the
|
|
41
|
+
* resource is not partitioned. Actor resources are partitioned too, but stay readable without a tenant.
|
|
42
|
+
*/
|
|
43
|
+
export function partitionOf(resource, context) {
|
|
44
|
+
const tenants = context.graph.nodes.filter(n => n.kind === 'Tenant').map(n => n.data.entity);
|
|
45
|
+
const fields = storedRelations(resource, context);
|
|
46
|
+
for (const entity of tenants) {
|
|
47
|
+
const own = fields.filter(f => relationTarget(f, context).qn === entity);
|
|
48
|
+
if (resource.qn === entity || !own.length)
|
|
49
|
+
continue;
|
|
50
|
+
if (own.length > 1 || fields.some(f => relationTarget(f, context).qn !== entity && tenants.includes(relationTarget(f, context).qn)))
|
|
51
|
+
continue;
|
|
52
|
+
return lastOf(own[0].qn);
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
/** Every resource: the entities and the human actors without `is`. */
|
|
57
|
+
function resources(context) {
|
|
58
|
+
return [
|
|
59
|
+
...context.graph.nodes.filter(n => n.kind === 'Entity'),
|
|
60
|
+
...homes(context).filter(h => h.resource && h.node.kind === 'Actor').map(h => h.node)
|
|
61
|
+
];
|
|
62
|
+
}
|
|
63
|
+
/** The stored single valued relationships of a resource, including the fields of actors bound to it. */
|
|
64
|
+
function storedRelations(resource, context) {
|
|
65
|
+
const home = homeAt(resource, context);
|
|
66
|
+
const fields = home?.resource ? homeFields(home, context) : fieldsOf(resource, context);
|
|
67
|
+
return fields.filter(f => !f.data.derived && !f.data.type.many && relationTarget(f, context));
|
|
68
|
+
}
|
|
69
|
+
/** The resources outside `partitioned` whose relationships lead to a partitioned one, directly or through others. */
|
|
70
|
+
function reaching(partitioned, entity, context) {
|
|
71
|
+
const reached = new Set(partitioned);
|
|
72
|
+
const found = [];
|
|
73
|
+
let grew = true;
|
|
74
|
+
while (grew) {
|
|
75
|
+
grew = false;
|
|
76
|
+
for (const resource of resources(context)) {
|
|
77
|
+
if (reached.has(resource.qn) || resource.qn === entity)
|
|
78
|
+
continue;
|
|
79
|
+
if (storedRelations(resource, context).some(f => reached.has(relationTarget(f, context).qn))) {
|
|
80
|
+
reached.add(resource.qn);
|
|
81
|
+
found.push(resource.qn);
|
|
82
|
+
grew = true;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return found;
|
|
87
|
+
}
|