gell-dispatch 0.0.0-stage → 0.1.0
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/.github/workflows/publish.yml +45 -0
- package/.mocharc.json +4 -0
- package/README.md +4 -2
- package/bus.js +169 -0
- package/docs/superpowers/plans/2026-11-25-registry.md +215 -0
- package/docs/superpowers/specs/2026-11-25-registry-design.md +87 -0
- package/kind/action.js +6 -0
- package/kind/event.js +38 -0
- package/kind/snapshot.js +6 -0
- package/kind/type.js +21 -0
- package/middleware/arguments.js +50 -0
- package/middleware/attributes.js +38 -0
- package/middleware/roles.js +81 -0
- package/package.json +29 -4
- package/registry.js +97 -0
- package/stream/sink.js +35 -0
- package/test/bootstrap.js +25 -0
- package/test/kind/test-action.js +81 -0
- package/test/kind/test-snapshot.js +81 -0
- package/test/kind/test-type.js +54 -0
- package/test/middleware/test-arguments.js +565 -0
- package/test/middleware/test-attributes.js +79 -0
- package/test/middleware/test-roles.js +176 -0
- package/test/resolver.js +26 -0
- package/test/stream/test-sink.js +112 -0
- package/test/test-bus.js +383 -0
- package/test/test-registry.js +151 -0
- package/test/util/test-chain.js +164 -0
- package/test/util/test-error.js +33 -0
- package/test/util/test-parameters.js +30 -0
- package/test/util/test-restrict.js +73 -0
- package/util/chain.js +9 -0
- package/util/error.js +15 -0
- package/util/parameters.js +22 -0
- package/util/restrict.js +27 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
name: publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- 'v*'
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
id-token: write
|
|
11
|
+
|
|
12
|
+
jobs:
|
|
13
|
+
publish:
|
|
14
|
+
runs-on: ubuntu-latest
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v5
|
|
17
|
+
|
|
18
|
+
- uses: actions/setup-node@v5
|
|
19
|
+
with:
|
|
20
|
+
node-version: 24
|
|
21
|
+
registry-url: https://registry.npmjs.org
|
|
22
|
+
|
|
23
|
+
- run: npm install -g npm@latest
|
|
24
|
+
|
|
25
|
+
- name: Check tag matches package version
|
|
26
|
+
run: |
|
|
27
|
+
VERSION=$(node -p "require('./package.json').version")
|
|
28
|
+
if [ "v$VERSION" != "$GITHUB_REF_NAME" ]; then
|
|
29
|
+
echo "tag $GITHUB_REF_NAME does not match package.json version $VERSION"
|
|
30
|
+
exit 1
|
|
31
|
+
fi
|
|
32
|
+
|
|
33
|
+
- run: npm ci
|
|
34
|
+
|
|
35
|
+
- run: npm test
|
|
36
|
+
|
|
37
|
+
- name: Publish
|
|
38
|
+
run: |
|
|
39
|
+
NAME=$(node -p "require('./package.json').name")
|
|
40
|
+
VERSION=$(node -p "require('./package.json').version")
|
|
41
|
+
if npm view "$NAME@$VERSION" version > /dev/null 2>&1; then
|
|
42
|
+
echo "$NAME@$VERSION is already published"
|
|
43
|
+
exit 0
|
|
44
|
+
fi
|
|
45
|
+
npm publish
|
package/.mocharc.json
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gell-dispatch
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Event dispatch bus and middleware for gell.
|
|
4
|
+
|
|
5
|
+
Code is being migrated here from `gell-promote/gell-dispatch`.
|
package/bus.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
const assert = require('assert');
|
|
2
|
+
const _ = require('lodash');
|
|
3
|
+
|
|
4
|
+
const { default: State } = require('gell-state');
|
|
5
|
+
|
|
6
|
+
const chain = require('./util/chain');
|
|
7
|
+
const { error } = require('./util/error');
|
|
8
|
+
|
|
9
|
+
const MESSAGE_MISSING_TRIGGER = 'route (name="%s") does not define trigger function (name="%s")';
|
|
10
|
+
|
|
11
|
+
function validateMiddleware(middleware) {
|
|
12
|
+
middleware.forEach(m => {
|
|
13
|
+
assert(_.isFunction(m));
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Trigger execution of an event. Result of the event is yielded
|
|
19
|
+
*
|
|
20
|
+
* NOTE: this is a rewrite of gell-session implementation
|
|
21
|
+
* - implements middleware concept now
|
|
22
|
+
*
|
|
23
|
+
* WIP: bus middleware
|
|
24
|
+
* - outstanding questions
|
|
25
|
+
* - should lookup be outside of dispatcher
|
|
26
|
+
* - middleware use cases
|
|
27
|
+
* - logging
|
|
28
|
+
* - transaction management
|
|
29
|
+
* - parameter validation
|
|
30
|
+
* - argument type wrangling
|
|
31
|
+
* - performance monitoring
|
|
32
|
+
* - audit logging
|
|
33
|
+
* - error handling
|
|
34
|
+
* - item lookups
|
|
35
|
+
* - batch persistence
|
|
36
|
+
* - rate limiting
|
|
37
|
+
* - event should be able to define their own middleware?
|
|
38
|
+
* - inject it in chain?
|
|
39
|
+
* - declarative middleware?
|
|
40
|
+
*
|
|
41
|
+
* WIP: middleware requirements
|
|
42
|
+
* - you are "wrapping" an invocation, so you must eventually call it
|
|
43
|
+
* - how to you "yield" to the chain
|
|
44
|
+
* - middleware will often need to maintain state or configuration
|
|
45
|
+
* - i.e. "batch size" or "log level"
|
|
46
|
+
* - implies we need a generator or object
|
|
47
|
+
* - testable individually
|
|
48
|
+
*
|
|
49
|
+
* WIP: declarative middleware
|
|
50
|
+
* - define functions for different touchpoints
|
|
51
|
+
* - initialize
|
|
52
|
+
* - before
|
|
53
|
+
* - after
|
|
54
|
+
* - error
|
|
55
|
+
*
|
|
56
|
+
* WIP: how to provide event catalog
|
|
57
|
+
* - unclear at this point, but this should probably not use the low level $resolver
|
|
58
|
+
* - use Directory instead
|
|
59
|
+
* - route name scheme?
|
|
60
|
+
* - for now
|
|
61
|
+
* - 'my.event#trigger'
|
|
62
|
+
* - seems like URL like names could work well
|
|
63
|
+
*
|
|
64
|
+
* WIP: implement dispatching features
|
|
65
|
+
* - validate user is authorized to make call
|
|
66
|
+
* - custom, event specific validation
|
|
67
|
+
* - for session update, validate attribute is modifiable
|
|
68
|
+
*
|
|
69
|
+
* WIP: consolidate with dispatcher implementations
|
|
70
|
+
*
|
|
71
|
+
* WIP: how to handle event State
|
|
72
|
+
* - could follow emitter pattern
|
|
73
|
+
* - node events are async tho which causes problem in Next environments
|
|
74
|
+
* - could follow custom emitter pattern
|
|
75
|
+
* - really this is just using the $bus to dispatch event effects
|
|
76
|
+
* - provide callback argument to next
|
|
77
|
+
* - middleware
|
|
78
|
+
*
|
|
79
|
+
* WIP: provide future support
|
|
80
|
+
* - options
|
|
81
|
+
* - short circuit/validation stack
|
|
82
|
+
* - trigger specific middlware
|
|
83
|
+
* - always do X for action triggers
|
|
84
|
+
* - argument to type wrangling
|
|
85
|
+
*/
|
|
86
|
+
module.exports = function*($resolver, middleware, deps) {
|
|
87
|
+
assert($resolver && _.isFunction($resolver.next), '$resolver is required');
|
|
88
|
+
assert(deps, 'deps is required');
|
|
89
|
+
|
|
90
|
+
validateMiddleware(middleware);
|
|
91
|
+
|
|
92
|
+
async function dispatch({ route, caller, source, context={}, params={}, deps, invoke=true }) {
|
|
93
|
+
assert(_.isString(route), 'event route is required');
|
|
94
|
+
|
|
95
|
+
const [eventModule, { f: triggerF }, { resource: eventName, f: triggerName }] = $resolver.next(route).value;
|
|
96
|
+
|
|
97
|
+
assert(eventName, `route (name=${route}) is invalid; missing event name`);
|
|
98
|
+
assert(triggerName && triggerName.length > 0, `route (name=${route}) is invalid; missing trigger name`);
|
|
99
|
+
assert(eventModule, `no event (route=${route})`);
|
|
100
|
+
|
|
101
|
+
const logger = deps.resolveSingle('logger');
|
|
102
|
+
|
|
103
|
+
logger.info(`dispatching event (name=${eventName}, trigger=${triggerName})`);
|
|
104
|
+
|
|
105
|
+
if (!_.isFunction(triggerF)) {
|
|
106
|
+
throw error('InvalidEventModule', MESSAGE_MISSING_TRIGGER, { route, eventName, trigger: triggerName }, eventName, triggerName);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* NOTE: each invocation gets its own dependency container, branched from the deps passed in (or the bus deps)
|
|
111
|
+
* - middleware and triggers can define invocation scoped dependencies (e.g. namespaced types) on it without
|
|
112
|
+
* affecting other invocations or the common container
|
|
113
|
+
* - a nested dispatch passing event.deps branches again, so it inherits (and can override) the outer
|
|
114
|
+
* invocation's dependencies
|
|
115
|
+
*
|
|
116
|
+
* WIP: gell-dependency builds a singleton with the container that first resolves it, so a root singleton first
|
|
117
|
+
* resolved during an invocation is built with that invocation's branch; singleton factories must not resolve
|
|
118
|
+
* (or keep) invocation scoped dependencies such as types
|
|
119
|
+
*/
|
|
120
|
+
const event = {
|
|
121
|
+
caller,
|
|
122
|
+
source,
|
|
123
|
+
params,
|
|
124
|
+
context,
|
|
125
|
+
deps: deps.branch()
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* NOTE: invocation spec is always provided so middleware can identify the event being invoked
|
|
130
|
+
* - triggerSpec is empty if the event module does not define metadata for the trigger
|
|
131
|
+
* - metadata is the event module's __metadata (empty if it does not define any)
|
|
132
|
+
*/
|
|
133
|
+
const { __metadata:md } = eventModule;
|
|
134
|
+
const { triggers={} } = md || {};
|
|
135
|
+
|
|
136
|
+
event.__invocationSpec = {
|
|
137
|
+
route,
|
|
138
|
+
eventName,
|
|
139
|
+
triggerName,
|
|
140
|
+
triggerSpec: triggers[triggerName] || {},
|
|
141
|
+
metadata: md || {},
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const chainFunctions = [...middleware];
|
|
145
|
+
|
|
146
|
+
if (invoke) chainFunctions.push(triggerF);
|
|
147
|
+
else chainFunctions.push(event => event);
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
return chain(...chainFunctions)(event);
|
|
151
|
+
} catch (ex) {
|
|
152
|
+
logger.error(`middleware threw an error`);
|
|
153
|
+
|
|
154
|
+
throw ex;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let args = yield new State();
|
|
159
|
+
|
|
160
|
+
while (true) {
|
|
161
|
+
const defaults = {
|
|
162
|
+
deps
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const t = Object.assign(defaults, _.isString(args) ? { route: args } : (args || {}));
|
|
166
|
+
|
|
167
|
+
args = yield dispatch(t);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# Registry Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
4
|
+
|
|
5
|
+
**Goal:** A generic `Registry` in gell-dispatch, instantiated once per kind of named declaration, plus kinds for actions, snapshots and types.
|
|
6
|
+
|
|
7
|
+
**Architecture:** `Registry` is a plain class backed by a `Map`, configured with a *kind* object (`{ kind, nameOf, validate?, describe? }`) that supplies everything kind specific. Kinds are small modules under `kind/`. A shared `normalizeParameters` helper turns parameter specs into a uniform description.
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** Node (CommonJS, `^20.19.0 || >=22.12.0`), lodash, mocha 8 with `assert`.
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-11-25-registry-design.md`
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- CommonJS modules, 4-space indentation, `assert` + lodash like the existing gell-dispatch code
|
|
16
|
+
- no new dependencies; gell-dispatch must not depend on gell-domain or gell-aws-dynamodb (or `gell`)
|
|
17
|
+
- invalid registrations fail with `assert` (AssertionError)
|
|
18
|
+
- run tests with Node 24: `export PATH=~/.nvm/versions/node/v24.22.3/bin:$PATH; npx mocha` (from the gell-dispatch root)
|
|
19
|
+
- do not commit; the user commits when they ask
|
|
20
|
+
|
|
21
|
+
## Review Focus
|
|
22
|
+
|
|
23
|
+
- `registerAll` where a later entry is invalid or a duplicate (of the registry or of an earlier entry in the same batch): nothing from that batch is registered
|
|
24
|
+
- a declaration missing the structure a kind reads (action module without `__metadata`, type without `model`): AssertionError naming the kind, never a TypeError
|
|
25
|
+
- mutating a `describe` result (e.g. its `params` array) must not change the registered declaration
|
|
26
|
+
- mutating the array returned by `names()` must not change the registry
|
|
27
|
+
- `registerAll` given `null`, `undefined` or a string: AssertionError
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
### Task 1: Parameters helper
|
|
32
|
+
|
|
33
|
+
**Files:**
|
|
34
|
+
- Create: `util/parameters.js`
|
|
35
|
+
- Test: `test/util/test-parameters.js`
|
|
36
|
+
|
|
37
|
+
**Interfaces:**
|
|
38
|
+
- Produces: `normalizeParameters(params) -> Array<{ name, type, optional }>` exported as `module.exports = { normalizeParameters }`
|
|
39
|
+
|
|
40
|
+
- [ ] **Step 1: Write the failing tests**
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
const { normalizeParameters } = require('../../util/parameters');
|
|
44
|
+
|
|
45
|
+
it('normalizes a type name', () =>
|
|
46
|
+
assert.deepStrictEqual(normalizeParameters({ parentId: 'uuid' }), [{ name: 'parentId', type: 'uuid', optional: false }]));
|
|
47
|
+
it('normalizes a spec object', () =>
|
|
48
|
+
assert.deepStrictEqual(normalizeParameters({ type: { type: 'string', optional: true } }), [{ name: 'type', type: 'string', optional: true }]));
|
|
49
|
+
it('defaults optional to false', () =>
|
|
50
|
+
assert.deepStrictEqual(normalizeParameters({ count: { type: 'number' } }), [{ name: 'count', type: 'number', optional: false }]));
|
|
51
|
+
it('keeps declaration order', () =>
|
|
52
|
+
assert.deepStrictEqual(normalizeParameters({ b: 'string', a: 'string' }).map(p => p.name), ['b', 'a']));
|
|
53
|
+
it('returns an empty array for missing parameters', () => {
|
|
54
|
+
assert.deepStrictEqual(normalizeParameters(), []);
|
|
55
|
+
assert.deepStrictEqual(normalizeParameters(null), []);
|
|
56
|
+
});
|
|
57
|
+
it('does not copy other spec attributes', () =>
|
|
58
|
+
assert.deepStrictEqual(normalizeParameters({ m: { type: 'string', maxLength: 10 } }), [{ name: 'm', type: 'string', optional: false }]));
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
- [ ] **Step 2: Run, expect FAIL** with `Cannot find module '../../util/parameters'`
|
|
62
|
+
|
|
63
|
+
- [ ] **Step 3: Implement `normalizeParameters(params={})`** in `util/parameters.js`; `optional` is coerced to a boolean
|
|
64
|
+
|
|
65
|
+
- [ ] **Step 4: Run, expect all tests PASS**
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
### Task 2: Registry
|
|
70
|
+
|
|
71
|
+
**Files:**
|
|
72
|
+
- Create: `registry.js`
|
|
73
|
+
- Test: `test/test-registry.js`
|
|
74
|
+
|
|
75
|
+
**Interfaces:**
|
|
76
|
+
- Consumes: nothing
|
|
77
|
+
- Produces: `module.exports = Registry` (class)
|
|
78
|
+
- `new Registry(kind)`; `kind = { kind: string, nameOf(decl) -> string, validate?(decl), describe?(decl) -> object }`
|
|
79
|
+
- `register(decl) -> decl`
|
|
80
|
+
- `registerAll(decls) -> Array<decl>` (object: its values; iterable: its items)
|
|
81
|
+
- `get(name) -> decl | undefined`, `has(name) -> boolean`, `names() -> Array<string>` (new array, registration order)
|
|
82
|
+
- `describe(name) -> object | undefined` = `{ ...kind.describe(decl), name }` (`{ name }` without `kind.describe`)
|
|
83
|
+
- `describeAll() -> Array<object>` in registration order
|
|
84
|
+
|
|
85
|
+
- [ ] **Step 1: Write the failing tests**, using a test kind `{ kind: 'query', nameOf: d => d && d.name, describe: d => ({ description: d.description }) }`:
|
|
86
|
+
|
|
87
|
+
```js
|
|
88
|
+
it('requires a kind with nameOf', () => {
|
|
89
|
+
assert.throws(() => new Registry(), { name: 'AssertionError' });
|
|
90
|
+
assert.throws(() => new Registry({ kind: 'query' }), { name: 'AssertionError' });
|
|
91
|
+
});
|
|
92
|
+
it('registers and returns the original declaration', ...) // register(d) === d; get('q.one') === d; has true
|
|
93
|
+
it('returns undefined / false for unknown names', ...)
|
|
94
|
+
it('rejects a declaration that is not an object', ...) // register(null), register('q') -> AssertionError
|
|
95
|
+
it('rejects a declaration without a name', ...) // message: 'query must define a name to be registered'
|
|
96
|
+
it('rejects a duplicate name', ...) // message: 'query (name=q.one) is already registered'; also for the same object
|
|
97
|
+
it('validates with the kind', ...) // validate throws -> register throws, has() false
|
|
98
|
+
it('lists names in registration order', ...)
|
|
99
|
+
it('returns a copy of names', ...) // names().push('x') doesn't change names()
|
|
100
|
+
it('registers every value of an object', ...) // registerAll({ a: d1, b: d2 }) -> names ['q.one', 'q.two']; returns [d1, d2]
|
|
101
|
+
it('registers every item of an iterable', ...) // array and a Set
|
|
102
|
+
it('registers nothing if a later declaration is invalid', ...) // registerAll([d1, {}]) throws; has('q.one') false
|
|
103
|
+
it('registers nothing if a batch repeats a name', ...) // registerAll([d1, d1copy]) throws; names() []
|
|
104
|
+
it('registers nothing if a batch repeats a registered name', ...)
|
|
105
|
+
it('rejects null, undefined or a string for registerAll', ...)
|
|
106
|
+
it('describes a declaration with its name', ...) // describe('q.one') deepEquals { description: 'one', name: 'q.one' }
|
|
107
|
+
it('describes with only the name if the kind has no describe', ...)
|
|
108
|
+
it('describe returns undefined for unknown names', ...)
|
|
109
|
+
it('describes all declarations in order', ...)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
- [ ] **Step 2: Run, expect FAIL** with `Cannot find module '../registry'`
|
|
113
|
+
|
|
114
|
+
- [ ] **Step 3: Implement `Registry`** in `registry.js`. `registerAll` checks every declaration (object, name, validate, no duplicates against the registry *and* within the batch) before adding any.
|
|
115
|
+
|
|
116
|
+
- [ ] **Step 4: Run, expect all tests PASS**
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
### Task 3: Action and snapshot kinds
|
|
121
|
+
|
|
122
|
+
**Files:**
|
|
123
|
+
- Create: `kind/event.js`, `kind/action.js`, `kind/snapshot.js`
|
|
124
|
+
- Test: `test/kind/test-action.js`, `test/kind/test-snapshot.js`
|
|
125
|
+
|
|
126
|
+
**Interfaces:**
|
|
127
|
+
- Consumes: `normalizeParameters` (Task 1), `Registry` (Task 2, tests only)
|
|
128
|
+
- Produces:
|
|
129
|
+
- `kind/event.js`: `module.exports = { eventKind(kindName, triggerName) -> kind, describeEvent(__metadata) -> object }`
|
|
130
|
+
- `kind/action.js`: `module.exports = eventKind('action', 'action')`
|
|
131
|
+
- `kind/snapshot.js`: `module.exports = eventKind('snapshot', 'api')`
|
|
132
|
+
- `nameOf: m => m.__metadata.name` guarded so a missing `__metadata` yields `undefined` (Registry then rejects the missing name)
|
|
133
|
+
- `validate`: asserts `m[triggerName]` is a function, message `action (name=<name>) must define an action function` / `snapshot (name=<name>) must define an api function`
|
|
134
|
+
- `describeEvent` returns `{ name, description, triggers }`; each trigger spec is deep-copied with `params` and `context` replaced by `normalizeParameters(...)`, other trigger attributes (`roles`, `public`, `transaction`, ...) copied as is; missing `triggers` -> `{}`
|
|
135
|
+
|
|
136
|
+
- [ ] **Step 1: Write the failing tests** (action shown; snapshot mirrors it with `api`):
|
|
137
|
+
|
|
138
|
+
```js
|
|
139
|
+
const registry = new Registry(require('../../kind/action'));
|
|
140
|
+
const MODULE = {
|
|
141
|
+
__metadata: {
|
|
142
|
+
name: 'session.update', description: 'updates a session',
|
|
143
|
+
triggers: { action: { params: { attr: 'string', count: { type: 'number', optional: true } }, context: { session$: 'complex' }, roles: ['admin'] }, effect: {} }
|
|
144
|
+
},
|
|
145
|
+
action: () => {}, effect: () => {}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
it('registers by __metadata.name', ...) // registry.get('session.update') === MODULE
|
|
149
|
+
it('rejects a module without an action function', ...) // message 'action (name=session.update) must define an action function'
|
|
150
|
+
it('rejects a module without __metadata', ...) // { action() {} } -> AssertionError (not TypeError)
|
|
151
|
+
it('describes name, description and triggers', () =>
|
|
152
|
+
assert.deepStrictEqual(registry.describe('session.update'), {
|
|
153
|
+
name: 'session.update', description: 'updates a session',
|
|
154
|
+
triggers: {
|
|
155
|
+
action: {
|
|
156
|
+
params: [{ name: 'attr', type: 'string', optional: false }, { name: 'count', type: 'number', optional: true }],
|
|
157
|
+
context: [{ name: 'session$', type: 'complex', optional: false }],
|
|
158
|
+
roles: ['admin']
|
|
159
|
+
},
|
|
160
|
+
effect: { params: [], context: [] }
|
|
161
|
+
}
|
|
162
|
+
}));
|
|
163
|
+
it('describes a module without triggers', ...) // triggers: {}
|
|
164
|
+
it('does not share data with the declaration', ...) // mutate describe(...).triggers.action.roles -> MODULE roles unchanged
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
- [ ] **Step 2: Run, expect FAIL** with `Cannot find module '../../kind/action'`
|
|
168
|
+
|
|
169
|
+
- [ ] **Step 3: Implement `kind/event.js`, `kind/action.js`, `kind/snapshot.js`** per the Interfaces block (lodash `cloneDeep` for the copy)
|
|
170
|
+
|
|
171
|
+
- [ ] **Step 4: Run, expect all tests PASS**
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
### Task 4: Type kind
|
|
176
|
+
|
|
177
|
+
**Files:**
|
|
178
|
+
- Create: `kind/type.js`
|
|
179
|
+
- Test: `test/kind/test-type.js`
|
|
180
|
+
|
|
181
|
+
**Interfaces:**
|
|
182
|
+
- Consumes: `Registry` (tests only)
|
|
183
|
+
- Produces: `module.exports = { kind: 'type', nameOf, validate, describe }`
|
|
184
|
+
- `nameOf: m => m.model.name`, guarded like Task 3
|
|
185
|
+
- `validate`: asserts `TYPE` is a string, message `type (name=<name>) must define TYPE`
|
|
186
|
+
- `describe: m -> { name, type: m.TYPE, attributes: [attribute names] }`; `model.attributes` may be a map (keys) or an array of specs (`a.name`); missing -> `[]`
|
|
187
|
+
|
|
188
|
+
- [ ] **Step 1: Write the failing tests**
|
|
189
|
+
|
|
190
|
+
```js
|
|
191
|
+
const registry = new Registry(require('../../kind/type'));
|
|
192
|
+
const SESSION = { TYPE: 'GELL#SESSION', model: { name: 'gell.session', attributes: { type: 'string', parentId: 'uuid' } } };
|
|
193
|
+
|
|
194
|
+
it('registers by model.name', ...) // get('gell.session') === SESSION
|
|
195
|
+
it('rejects a module without TYPE', ...) // message 'type (name=gell.session) must define TYPE'
|
|
196
|
+
it('rejects a module without a model', ...) // AssertionError, not TypeError
|
|
197
|
+
it('describes map attributes', () =>
|
|
198
|
+
assert.deepStrictEqual(registry.describe('gell.session'), { name: 'gell.session', type: 'GELL#SESSION', attributes: ['type', 'parentId'] }));
|
|
199
|
+
it('describes array attributes', ...) // attributes: [{ name: 'type' }, { name: 'parentId' }] -> ['type', 'parentId']
|
|
200
|
+
it('describes a model without attributes', ...) // attributes: []
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
- [ ] **Step 2: Run, expect FAIL** with `Cannot find module '../../kind/type'`
|
|
204
|
+
|
|
205
|
+
- [ ] **Step 3: Implement `kind/type.js`**
|
|
206
|
+
|
|
207
|
+
- [ ] **Step 4: Run, expect all tests PASS**
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
### Task 5: Full verification
|
|
212
|
+
|
|
213
|
+
- [ ] **Step 1:** `npx mocha` from the gell-dispatch root: all tests pass (82 existing + new)
|
|
214
|
+
- [ ] **Step 2:** no-gell guard: `npx mocha -r <guard>` where the guard throws for requires of `gell`, `gell/*` or `when`; all pass
|
|
215
|
+
- [ ] **Step 3:** `git status`: only the files listed in Tasks 1-4 plus `docs/superpowers/` are new; nothing committed
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# Registry design
|
|
2
|
+
|
|
3
|
+
## Intent
|
|
4
|
+
|
|
5
|
+
Applications declare many kinds of named things: actions, snapshots, types, DynamoDB named queries and named
|
|
6
|
+
operations. Each kind is collected, looked up by name, and described (listed with metadata) by discovery snapshots.
|
|
7
|
+
Today this is done ad hoc: gell-aws-dynamodb wraps query/operation maps (losing the definitions), and
|
|
8
|
+
gell-promote/gell-discover has near-identical `Queries`/`Operations` registries plus a catch-all `Registry`.
|
|
9
|
+
|
|
10
|
+
Goal: one registry implementation in gell-dispatch, instantiated once per kind of declaration.
|
|
11
|
+
|
|
12
|
+
## Goals
|
|
13
|
+
|
|
14
|
+
- a generic `Registry` that holds declarations of a single kind
|
|
15
|
+
- kind specific behavior (where the name lives, validation, description) supplied by a *kind* object
|
|
16
|
+
- kinds for the declarations gell-dispatch owns: actions, snapshots
|
|
17
|
+
- a kind for types (gell-domain models), without depending on gell-domain
|
|
18
|
+
- a shared helper normalizing parameter specs (`'string'` or `{ type, optional }`), usable by any kind
|
|
19
|
+
|
|
20
|
+
## Non-goals
|
|
21
|
+
|
|
22
|
+
- a single registry holding every kind (each application has many registries, one per kind)
|
|
23
|
+
- query/operation kinds and gell-aws-dynamodb store integration (follow-up, in gell-aws-dynamodb)
|
|
24
|
+
- discovery snapshots (`gell.queries`, `gell.inspect`, ...) (follow-up)
|
|
25
|
+
- the compile/normalization step (later; the kind gets a hook for it then)
|
|
26
|
+
- replacing the bus resolver with an action registry (later)
|
|
27
|
+
|
|
28
|
+
## Approaches
|
|
29
|
+
|
|
30
|
+
- **A. One class configured with a kind object** (chosen): `new Registry(kind)`; kinds are small objects defined
|
|
31
|
+
where the kind belongs. Keeps the registry generic and gives the future compile step an obvious home.
|
|
32
|
+
- B. Base class with a subclass per kind: a class per kind, re-subclassing to change behavior.
|
|
33
|
+
- C. Plain name -> declaration map with normalization outside: nothing validates declarations, and callers must know
|
|
34
|
+
which describe/compile function goes with which registry.
|
|
35
|
+
|
|
36
|
+
## Design
|
|
37
|
+
|
|
38
|
+
### Kind
|
|
39
|
+
|
|
40
|
+
```js
|
|
41
|
+
{
|
|
42
|
+
kind: 'query', // used in error messages
|
|
43
|
+
nameOf: decl => decl.name, // required
|
|
44
|
+
validate: decl => {}, // optional; throws for an invalid declaration
|
|
45
|
+
describe: decl => ({}), // optional; plain object metadata (no functions); default { name }
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Registry
|
|
50
|
+
|
|
51
|
+
```js
|
|
52
|
+
const registry = new Registry(kind);
|
|
53
|
+
|
|
54
|
+
registry.register(decl) // validates, rejects missing name and duplicates; returns decl
|
|
55
|
+
registry.registerAll(decls) // every value of an object (e.g. a module's exports) or an iterable
|
|
56
|
+
registry.get(name) // the original declaration (undefined if not registered)
|
|
57
|
+
registry.has(name)
|
|
58
|
+
registry.names() // array, in registration order
|
|
59
|
+
registry.describe(name) // kind.describe(decl), with name; undefined if not registered
|
|
60
|
+
registry.describeAll() // describe() for every declaration
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
- stores the original declaration; callers need it to execute (`query()`, `filter()`, `action()`, ...)
|
|
64
|
+
- registering a name twice throws, even for the same declaration
|
|
65
|
+
|
|
66
|
+
### Kinds in gell-dispatch
|
|
67
|
+
|
|
68
|
+
- **action**: event module with `__metadata.name` and an `action` function;
|
|
69
|
+
describes `{ name, description, triggers }`, trigger params normalized
|
|
70
|
+
- **snapshot**: same, with an `api` function
|
|
71
|
+
- **type**: module with `model.name` (and `TYPE`); describes `{ name, type: TYPE, attributes: [names] }`
|
|
72
|
+
|
|
73
|
+
### Parameters helper
|
|
74
|
+
|
|
75
|
+
`normalizeParameters(params)` -> `[{ name, type, optional }]`; `'uuid'` becomes `{ type: 'uuid', optional: false }`.
|
|
76
|
+
|
|
77
|
+
## Calls made by Claude (check these)
|
|
78
|
+
|
|
79
|
+
- the registry is a plain class backed by a `Map`, not a gell-state `State` (gell-discover used `State`; nothing
|
|
80
|
+
here needs snapshots or projections)
|
|
81
|
+
- invalid registrations fail with `assert` (programming errors), like gell-discover
|
|
82
|
+
- module paths: `registry.js`, `kind/action.js`, `kind/snapshot.js`, `kind/type.js`, `util/parameters.js`
|
|
83
|
+
|
|
84
|
+
## Left to the builder
|
|
85
|
+
|
|
86
|
+
- exact describe output for triggers (which trigger attributes beyond params to include)
|
|
87
|
+
- test layout, following the existing `test/` structure
|
package/kind/action.js
ADDED
package/kind/event.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const assert = require('assert');
|
|
2
|
+
const _ = require('lodash');
|
|
3
|
+
|
|
4
|
+
const { normalizeParameters } = require('../util/parameters');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Describes an event module's metadata as plain data
|
|
8
|
+
* - trigger params and context are normalized (see util/parameters)
|
|
9
|
+
* - other trigger attributes (e.g. roles, public, transaction) are copied as is
|
|
10
|
+
*
|
|
11
|
+
* @param {*} __metadata
|
|
12
|
+
*/
|
|
13
|
+
function describeEvent({ name, description, triggers={} }) {
|
|
14
|
+
const described = _.mapValues(_.cloneDeep(triggers), spec => ({
|
|
15
|
+
...spec,
|
|
16
|
+
params: normalizeParameters(spec.params),
|
|
17
|
+
context: normalizeParameters(spec.context),
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
return { name, description, triggers: described };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Creates a registry kind for event modules (__metadata with a name) that define a specific trigger function
|
|
25
|
+
*
|
|
26
|
+
* @param {*} kindName name of the kind (e.g. action)
|
|
27
|
+
* @param {*} triggerName trigger function the module must define (e.g. action)
|
|
28
|
+
*/
|
|
29
|
+
function eventKind(kindName, triggerName) {
|
|
30
|
+
return {
|
|
31
|
+
kind: kindName,
|
|
32
|
+
nameOf: m => m.__metadata && m.__metadata.name,
|
|
33
|
+
validate: m => assert(_.isFunction(m[triggerName]), `${kindName} (name=${m.__metadata.name}) must define an ${triggerName} function`),
|
|
34
|
+
describe: m => describeEvent(m.__metadata),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { eventKind, describeEvent };
|
package/kind/snapshot.js
ADDED
package/kind/type.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const assert = require('assert');
|
|
2
|
+
const _ = require('lodash');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Names of a model's attributes; attributes may be a map or an array of specs ({ name, ... })
|
|
6
|
+
*/
|
|
7
|
+
function attributeNames({ attributes }) {
|
|
8
|
+
if (_.isArray(attributes)) return attributes.map(a => a.name);
|
|
9
|
+
|
|
10
|
+
return Object.keys(attributes || {});
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Registry kind for type modules ({ TYPE, model }, see gell-domain) (see registry)
|
|
15
|
+
*/
|
|
16
|
+
module.exports = {
|
|
17
|
+
kind: 'type',
|
|
18
|
+
nameOf: m => m.model && m.model.name,
|
|
19
|
+
validate: m => assert(_.isString(m.TYPE), `type (name=${m.model.name}) must define TYPE`),
|
|
20
|
+
describe: m => ({ name: m.model.name, type: m.TYPE, attributes: attributeNames(m.model) }),
|
|
21
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const assert = require('assert');
|
|
2
|
+
|
|
3
|
+
const { compileParams } = require('gell-domain/event/compiler');
|
|
4
|
+
const { validate } = require('gell-domain/type/javascript');
|
|
5
|
+
|
|
6
|
+
const { error } = require('../util/error');
|
|
7
|
+
|
|
8
|
+
// NOTE: validation failures are the caller's fault, so the API answers them with 400 (gell-http/next/api uses e.status)
|
|
9
|
+
const STATUS = 400;
|
|
10
|
+
|
|
11
|
+
function doValidate(event, resume, TYPES) {
|
|
12
|
+
const { params: values, __invocationSpec, deps } = event;
|
|
13
|
+
|
|
14
|
+
if (!__invocationSpec) return resume(event);
|
|
15
|
+
|
|
16
|
+
const { route, triggerSpec } = __invocationSpec;
|
|
17
|
+
const params = compileParams(triggerSpec.params);
|
|
18
|
+
|
|
19
|
+
// NOTE: gell-domain names a failure's property; the middleware reports it as the parameter
|
|
20
|
+
const errors = validate(values || {}, params, TYPES, true).map(({ property, ...failure }) => ({ parameter: property, ...failure }));
|
|
21
|
+
|
|
22
|
+
if (errors.length) {
|
|
23
|
+
const logger = deps.resolveSingle('logger');
|
|
24
|
+
|
|
25
|
+
errors.forEach(({ parameter, rule }) => logger.info(`parameter validation failed (route="${route}"; parameter="${parameter}"; rule="${rule}")`));
|
|
26
|
+
|
|
27
|
+
throw error('ParameterValidationError', '%s', { status: STATUS, route, errors }, errors.map(({ message }) => message).join('; '));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return resume(event);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* gell-dispatch middleware that validates event invocation parameters against the event metadata
|
|
35
|
+
* - the params are validated with gell-domain/type/javascript validate (it defines what a param spec can declare:
|
|
36
|
+
* rules, messages, items, a validate function), against the types it is given (the application's compiled
|
|
37
|
+
* types, e.g. gell-domain/type/compiler compile([...appTypes]))
|
|
38
|
+
* - collects every failure of the call, then throws one ParameterValidationError (status 400) whose message joins
|
|
39
|
+
* the readable messages with '; ', and whose errors lists the failures ({ parameter, rule, message })
|
|
40
|
+
* - a mistake in the metadata (e.g. a rule the type does not define) is a bug, not a validation failure: its
|
|
41
|
+
* AssertionError propagates (500)
|
|
42
|
+
*
|
|
43
|
+
* WIP: errors stays server-side (logs, tests, direct callers); per-field form errors need gell-http (or a wrapper)
|
|
44
|
+
* and bh-react useAction to pass errors through to the browser
|
|
45
|
+
*/
|
|
46
|
+
module.exports = function(types) {
|
|
47
|
+
assert(types, 'compiled types is required');
|
|
48
|
+
|
|
49
|
+
return (event, resume) => doValidate(event, resume, types);
|
|
50
|
+
}
|