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.
@@ -0,0 +1,38 @@
1
+ const { error } = require('../util/error');
2
+
3
+ const MESSAGE_REQUIRED_ATTRIBUTE = 'call to event trigger (route="%s") does not provide required context attribute (name="%s")';
4
+
5
+ /**
6
+ * gell-dispatch middleware that validates event invocation context attributes against the event metadata
7
+ *
8
+ * WIP: use gell-domain here to validate this correctly
9
+ *
10
+ * WIP: this isn't yet re-usable because of the error message
11
+ * - one approach would be to collect validation failures and throw at the end
12
+ * - short circuit
13
+ */
14
+ module.exports = function(event, resume) {
15
+ const { context: values, __invocationSpec } = event;
16
+
17
+ if (!__invocationSpec) return resume(event);
18
+
19
+ const metadata = __invocationSpec.triggerSpec.context || {};
20
+ const route = __invocationSpec.route;
21
+
22
+ const keys = Object.keys(metadata || {});
23
+ keys.forEach(n => {
24
+ const attr = metadata[n];
25
+ const val = values[n];
26
+
27
+ if (val === undefined && !attr.optional) {
28
+ /**
29
+ * WIP: idea here is that we would materialize "error" State
30
+ * - include metadata about the attribute being defined
31
+ * - possibly include the invalid attribute value
32
+ */
33
+ throw error('RequiredAttributeError', MESSAGE_REQUIRED_ATTRIBUTE, { route, attribute: n }, route, n);
34
+ }
35
+ })
36
+
37
+ return resume(event);
38
+ }
@@ -0,0 +1,81 @@
1
+ const assert = require('assert');
2
+ const _ = require('lodash');
3
+
4
+ const { error } = require('../util/error');
5
+
6
+ const MESSAGE_UNAUTHORIZED = 'call to event trigger (route="%s") requires an authorized caller';
7
+ const MESSAGE_FORBIDDEN = 'call to event trigger (route="%s") is not allowed for caller (roles="%s")';
8
+
9
+ /**
10
+ * Returns the roles of a caller
11
+ * - supports a single "role" (e.g. browser session) or a list of "roles" (e.g. USER)
12
+ */
13
+ function callerRoles(caller) {
14
+ if (!caller) return [];
15
+
16
+ const attribute = name => _.isFunction(caller.snapshotAttribute) ? caller.snapshotAttribute(name) : caller[name];
17
+
18
+ const roles = attribute('roles');
19
+ if (_.isArray(roles)) return roles;
20
+
21
+ const role = attribute('role');
22
+
23
+ return role ? [role] : [];
24
+ }
25
+
26
+ function throwError(name, status, route, message, roles) {
27
+ const attributes = { status, route };
28
+ const args = [route];
29
+
30
+ if (roles) {
31
+ attributes.roles = roles.join(',');
32
+ args.push(attributes.roles);
33
+ }
34
+
35
+ throw error(name, message, attributes, ...args);
36
+ }
37
+
38
+ /**
39
+ * gell-dispatch middleware that authorizes callers based on the roles allowed by the event trigger metadata
40
+ * - allowed roles are defined by the "roles" attribute of the trigger (e.g. __metadata.triggers.action.roles)
41
+ * - only checks triggers reachable by external callers (default: action, api)
42
+ * - triggers declaring "public: true" allow any caller, including anonymous ones
43
+ * - the event is responsible for authorizing the call itself (e.g. by validating a token param)
44
+ * - caller without a role is rejected (401)
45
+ * - triggers without "roles" allow any caller with a role
46
+ * - caller without an allowed role is rejected (403)
47
+ *
48
+ * WIP: supports roles only; authorization based on the caller's relationship to the data (e.g. "own" DRIVER) is up to the event
49
+ *
50
+ * @param {*} options
51
+ * - triggers: names of triggers to authorize
52
+ * - rolesOf: function returning the roles of a caller
53
+ */
54
+ module.exports = function({ triggers=['action', 'api'], rolesOf=callerRoles }={}) {
55
+ assert(_.isArray(triggers), 'triggers must be an array');
56
+ assert(_.isFunction(rolesOf), 'rolesOf must be a function');
57
+
58
+ return function(event, resume) {
59
+ const { caller, __invocationSpec } = event;
60
+
61
+ assert(__invocationSpec, 'invocation spec is required');
62
+
63
+ const { route, triggerName, triggerSpec } = __invocationSpec;
64
+
65
+ if (!triggers.includes(triggerName)) return resume(event);
66
+
67
+ if (triggerSpec.public === true) return resume(event);
68
+
69
+ const roles = rolesOf(caller);
70
+
71
+ if (roles.length === 0) throwError('UnauthorizedError', 401, route, MESSAGE_UNAUTHORIZED);
72
+
73
+ const allowed = triggerSpec.roles;
74
+
75
+ if (allowed && !roles.some(r => allowed.includes(r))) throwError('ForbiddenError', 403, route, MESSAGE_FORBIDDEN, roles);
76
+
77
+ return resume(event);
78
+ }
79
+ }
80
+
81
+ module.exports.callerRoles = callerRoles;
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "gell-dispatch",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Event dispatch bus and middleware for gell",
5
+ "scripts": {
6
+ "test": "mocha"
7
+ },
8
+ "keywords": [
9
+ "gell"
10
+ ],
11
+ "author": "Daniel Gay",
12
+ "license": "ISC",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/djghokie/gell-dispatch.git"
16
+ },
17
+ "homepage": "https://github.com/djghokie/gell-dispatch#readme",
18
+ "engines": {
19
+ "node": "^20.19.0 || >=22.12.0"
20
+ },
21
+ "devDependencies": {
22
+ "gell-dependency": "^1.0.0",
23
+ "gell-future": "^1.0.0",
24
+ "mocha": "^8.4.0"
25
+ },
26
+ "dependencies": {
27
+ "gell-domain": "^1.1.2",
28
+ "gell-state": "^1.0.0",
29
+ "lodash": "^4.18.1"
30
+ }
31
+ }
package/registry.js ADDED
@@ -0,0 +1,97 @@
1
+ const assert = require('assert');
2
+ const _ = require('lodash');
3
+
4
+ /**
5
+ * Registry of named declarations of a single kind (e.g. actions, snapshots, types, named queries)
6
+ * - an application has many registries, one per kind of declaration
7
+ * - kind specific behavior is supplied by a kind object
8
+ * - kind: name of the kind, used in error messages
9
+ * - nameOf(decl): returns the declaration's name
10
+ * - validate(decl): optional; throws if the declaration is invalid
11
+ * - describe(decl): optional; returns plain object metadata (no functions) for the declaration
12
+ * - stores the original declaration; callers need it to execute (e.g. query, action)
13
+ *
14
+ * WIP: compile step normalizing declarations (future kind hook)
15
+ */
16
+ class Registry {
17
+
18
+ #kind;
19
+
20
+ #declarations = new Map();
21
+
22
+ constructor(kind) {
23
+ assert(kind && _.isFunction(kind.nameOf), 'kind with nameOf function is required');
24
+
25
+ this.#kind = { kind: 'declaration', ...kind };
26
+ }
27
+
28
+ /**
29
+ * Returns the name of a valid declaration; throws if the declaration can't be registered
30
+ */
31
+ #check(decl, names=this.#declarations) {
32
+ const { kind, nameOf, validate } = this.#kind;
33
+
34
+ assert(_.isObjectLike(decl), `${kind} declaration must be an object`);
35
+
36
+ const name = nameOf(decl);
37
+
38
+ assert(_.isString(name) && name.length > 0, `${kind} must define a name to be registered`);
39
+ assert(!names.has(name), `${kind} (name=${name}) is already registered`);
40
+
41
+ if (validate) validate(decl);
42
+
43
+ return name;
44
+ }
45
+
46
+ register(decl) {
47
+ this.#declarations.set(this.#check(decl), decl);
48
+
49
+ return decl;
50
+ }
51
+
52
+ /**
53
+ * Registers every value of an object (e.g. a module's exports) or every item of an iterable
54
+ * - nothing is registered if any declaration can't be registered
55
+ */
56
+ registerAll(decls) {
57
+ assert(_.isObjectLike(decls), `${this.#kind.kind} declarations must be an object or iterable`);
58
+
59
+ const list = _.isFunction(decls[Symbol.iterator]) ? [...decls] : Object.values(decls);
60
+
61
+ const pending = new Map(this.#declarations);
62
+ list.forEach(decl => pending.set(this.#check(decl, pending), decl));
63
+
64
+ this.#declarations = pending;
65
+
66
+ return list;
67
+ }
68
+
69
+ get(name) {
70
+ return this.#declarations.get(name);
71
+ }
72
+
73
+ has(name) {
74
+ return this.#declarations.has(name);
75
+ }
76
+
77
+ names() {
78
+ return [...this.#declarations.keys()];
79
+ }
80
+
81
+ describe(name) {
82
+ const decl = this.get(name);
83
+
84
+ if (!decl) return;
85
+
86
+ const { describe } = this.#kind;
87
+
88
+ return { ...(describe ? describe(decl) : {}), name };
89
+ }
90
+
91
+ describeAll() {
92
+ return this.names().map(name => this.describe(name));
93
+ }
94
+
95
+ }
96
+
97
+ module.exports = Registry;
package/stream/sink.js ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Stream sink that invokes an event effect. Event trigger is passed as arguments to iterator
3
+ *
4
+ * @param {*} event
5
+ * @param {*} deps
6
+ */
7
+ exports.eventSink = function* (event, deps) {
8
+ const { logger, store } = deps.resolve('logger', 'store');
9
+
10
+ const { __metadata } = event;
11
+
12
+ async function invokeEvent(args={}) {
13
+ logger.info(`invoking event (name=${__metadata.name})`);
14
+
15
+ const $txn = store.write();
16
+
17
+ const { context={} } = args;
18
+
19
+ context.$txn = $txn;
20
+ context.deps = deps;
21
+
22
+ const ret_ = await event.effect({
23
+ context,
24
+ deps
25
+ });
26
+
27
+ await $txn.return().value;
28
+
29
+ return ret_;
30
+ }
31
+
32
+ let args = yield;
33
+
34
+ while (true) args = yield invokeEvent(args);
35
+ }
@@ -0,0 +1,25 @@
1
+ const { default: DependencyContainer } = require('gell-dependency/container');
2
+
3
+ /**
4
+ * Logger that records messages instead of writing them
5
+ */
6
+ function testLogger() {
7
+ const messages = [];
8
+ const log = level => message => messages.push({ level, message });
9
+
10
+ return { messages, debug: log('debug'), info: log('info'), warn: log('warn'), error: log('error') };
11
+ }
12
+
13
+ function setupContext() {
14
+ this.logger = testLogger();
15
+
16
+ this.deps = new DependencyContainer({
17
+ logger: this.logger
18
+ });
19
+ }
20
+
21
+ exports.mochaHooks = {
22
+ beforeEach: [
23
+ setupContext
24
+ ]
25
+ }
@@ -0,0 +1,81 @@
1
+ const assert = require('assert');
2
+
3
+ const Registry = require('../../registry');
4
+
5
+ describe('action kind', function() {
6
+ let registry, MODULE;
7
+
8
+ beforeEach(function() {
9
+ registry = new Registry(require('../../kind/action'));
10
+
11
+ MODULE = {
12
+ __metadata: {
13
+ name: 'session.update',
14
+ description: 'updates a session',
15
+ triggers: {
16
+ action: {
17
+ params: { attr: 'string', count: { type: 'number', optional: true } },
18
+ context: { session$: 'complex' },
19
+ roles: ['admin'],
20
+ },
21
+ effect: {}
22
+ }
23
+ },
24
+
25
+ action: () => {},
26
+ effect: () => {}
27
+ };
28
+ })
29
+
30
+ it('registers by __metadata.name', function() {
31
+ registry.register(MODULE);
32
+
33
+ assert.strictEqual(registry.get('session.update'), MODULE);
34
+ })
35
+
36
+ it('rejects a module without an action function', function() {
37
+ delete MODULE.action;
38
+
39
+ assert.throws(() => registry.register(MODULE), {
40
+ name: 'AssertionError',
41
+ message: 'action (name=session.update) must define an action function'
42
+ });
43
+ })
44
+
45
+ it('rejects a module without __metadata', function() {
46
+ assert.throws(() => registry.register({ action() {} }), { name: 'AssertionError' });
47
+ })
48
+
49
+ it('describes name, description and triggers', function() {
50
+ registry.register(MODULE);
51
+
52
+ assert.deepStrictEqual(registry.describe('session.update'), {
53
+ name: 'session.update',
54
+ description: 'updates a session',
55
+ triggers: {
56
+ action: {
57
+ params: [{ name: 'attr', type: 'string', optional: false }, { name: 'count', type: 'number', optional: true }],
58
+ context: [{ name: 'session$', type: 'complex', optional: false }],
59
+ roles: ['admin'],
60
+ },
61
+ effect: { params: [], context: [] }
62
+ }
63
+ });
64
+ })
65
+
66
+ it('describes a module without triggers', function() {
67
+ delete MODULE.__metadata.triggers;
68
+
69
+ registry.register(MODULE);
70
+
71
+ assert.deepStrictEqual(registry.describe('session.update').triggers, {});
72
+ })
73
+
74
+ it('does not share data with the declaration', function() {
75
+ registry.register(MODULE);
76
+
77
+ registry.describe('session.update').triggers.action.roles.push('driver');
78
+
79
+ assert.deepStrictEqual(MODULE.__metadata.triggers.action.roles, ['admin']);
80
+ })
81
+ })
@@ -0,0 +1,81 @@
1
+ const assert = require('assert');
2
+
3
+ const Registry = require('../../registry');
4
+
5
+ describe('snapshot kind', function() {
6
+ let registry, MODULE;
7
+
8
+ beforeEach(function() {
9
+ registry = new Registry(require('../../kind/snapshot'));
10
+
11
+ MODULE = {
12
+ __metadata: {
13
+ name: 'session.update',
14
+ description: 'updates a session',
15
+ triggers: {
16
+ api: {
17
+ params: { attr: 'string', count: { type: 'number', optional: true } },
18
+ context: { session$: 'complex' },
19
+ roles: ['admin'],
20
+ },
21
+ effect: {}
22
+ }
23
+ },
24
+
25
+ api: () => {},
26
+ effect: () => {}
27
+ };
28
+ })
29
+
30
+ it('registers by __metadata.name', function() {
31
+ registry.register(MODULE);
32
+
33
+ assert.strictEqual(registry.get('session.update'), MODULE);
34
+ })
35
+
36
+ it('rejects a module without an api function', function() {
37
+ delete MODULE.api;
38
+
39
+ assert.throws(() => registry.register(MODULE), {
40
+ name: 'AssertionError',
41
+ message: 'snapshot (name=session.update) must define an api function'
42
+ });
43
+ })
44
+
45
+ it('rejects a module without __metadata', function() {
46
+ assert.throws(() => registry.register({ api() {} }), { name: 'AssertionError' });
47
+ })
48
+
49
+ it('describes name, description and triggers', function() {
50
+ registry.register(MODULE);
51
+
52
+ assert.deepStrictEqual(registry.describe('session.update'), {
53
+ name: 'session.update',
54
+ description: 'updates a session',
55
+ triggers: {
56
+ api: {
57
+ params: [{ name: 'attr', type: 'string', optional: false }, { name: 'count', type: 'number', optional: true }],
58
+ context: [{ name: 'session$', type: 'complex', optional: false }],
59
+ roles: ['admin'],
60
+ },
61
+ effect: { params: [], context: [] }
62
+ }
63
+ });
64
+ })
65
+
66
+ it('describes a module without triggers', function() {
67
+ delete MODULE.__metadata.triggers;
68
+
69
+ registry.register(MODULE);
70
+
71
+ assert.deepStrictEqual(registry.describe('session.update').triggers, {});
72
+ })
73
+
74
+ it('does not share data with the declaration', function() {
75
+ registry.register(MODULE);
76
+
77
+ registry.describe('session.update').triggers.api.roles.push('driver');
78
+
79
+ assert.deepStrictEqual(MODULE.__metadata.triggers.api.roles, ['admin']);
80
+ })
81
+ })
@@ -0,0 +1,54 @@
1
+ const assert = require('assert');
2
+
3
+ const Registry = require('../../registry');
4
+
5
+ describe('type kind', function() {
6
+ let registry, SESSION;
7
+
8
+ beforeEach(function() {
9
+ registry = new Registry(require('../../kind/type'));
10
+
11
+ SESSION = {
12
+ TYPE: 'GELL#SESSION',
13
+ model: { name: 'gell.session', attributes: { type: 'string', parentId: 'uuid' } }
14
+ };
15
+ })
16
+
17
+ it('registers by model.name', function() {
18
+ registry.register(SESSION);
19
+
20
+ assert.strictEqual(registry.get('gell.session'), SESSION);
21
+ })
22
+
23
+ it('rejects a module without TYPE', function() {
24
+ delete SESSION.TYPE;
25
+
26
+ assert.throws(() => registry.register(SESSION), { name: 'AssertionError', message: 'type (name=gell.session) must define TYPE' });
27
+ })
28
+
29
+ it('rejects a module without a model', function() {
30
+ assert.throws(() => registry.register({ TYPE: 'GELL#SESSION' }), { name: 'AssertionError' });
31
+ })
32
+
33
+ it('describes map attributes', function() {
34
+ registry.register(SESSION);
35
+
36
+ assert.deepStrictEqual(registry.describe('gell.session'), { name: 'gell.session', type: 'GELL#SESSION', attributes: ['type', 'parentId'] });
37
+ })
38
+
39
+ it('describes array attributes', function() {
40
+ SESSION.model.attributes = [{ name: 'type' }, { name: 'parentId' }];
41
+
42
+ registry.register(SESSION);
43
+
44
+ assert.deepStrictEqual(registry.describe('gell.session').attributes, ['type', 'parentId']);
45
+ })
46
+
47
+ it('describes a model without attributes', function() {
48
+ delete SESSION.model.attributes;
49
+
50
+ registry.register(SESSION);
51
+
52
+ assert.deepStrictEqual(registry.describe('gell.session').attributes, []);
53
+ })
54
+ })