@thzero/library_server_service_grpc 0.18.20 → 0.19.1

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 CHANGED
@@ -1,15 +1,121 @@
1
- ![GitHub package.json version](https://img.shields.io/github/package-json/v/thzero/library_server_service_grpc)
2
- ![David](https://img.shields.io/david/thzero/library_server_service_grpc)
3
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
-
5
- # library_server_service_grpc
6
-
7
- ## Requirements
8
-
9
- ### NodeJs
10
-
11
- [NodeJs](https://nodejs.org) version 18+
12
-
13
- ## Installation
14
-
15
- [![NPM](https://nodei.co/npm/@thzero/library_server_service_grpc.png?compact=true)](https://npmjs.org/package/@thzero/library_server_service_grpc)
1
+ ![GitHub package.json version](https://img.shields.io/github/package-json/v/thzero/library_server_service_grpc)
2
+ ![David](https://img.shields.io/david/thzero/library_server_service_grpc)
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ # library_server_service_grpc
6
+
7
+ gRPC client and server bases for [@thzero/library_server](https://github.com/thzero/library_server), built on [@grpc/grpc-js](https://github.com/grpc/grpc-node).
8
+
9
+ For service-to-service calls inside a deployment, alongside the REST communication service used for outward-facing traffic. Host resolution goes through the framework's service discovery when it is configured, and falls back to a configured base url when it is not.
10
+
11
+ ## Requirements
12
+
13
+ ### NodeJs
14
+
15
+ [NodeJs](https://nodejs.org) version 22+
16
+
17
+ ### Installation
18
+
19
+ [![NPM](https://nodei.co/npm/@thzero/library_server_service_grpc.png?compact=true)](https://npmjs.org/package/@thzero/library_server_service_grpc)
20
+
21
+ ```
22
+ npm install @thzero/library_server_service_grpc
23
+ ```
24
+
25
+ #### Peer dependencies
26
+
27
+ * `@thzero/library_common`
28
+ * `@thzero/library_common_service`
29
+ * `@thzero/library_server`
30
+
31
+ ## What it provides
32
+
33
+ ### `client.js` — `BaseClientGrpcService`
34
+
35
+ | Method | Purpose |
36
+ |---|---|
37
+ | `_execute(correlationId, func, client, request)` | Calls a generated stub method as a promise, attaching the correlationId as gRPC metadata. |
38
+ | `_host(correlationId, key, opts)` | Resolves the host for a backend. |
39
+ | `_hostFromConfig(correlationId, host, key, opts)` | Resolves from config, consulting service discovery when enabled. Discovered hosts are cached per key. |
40
+ | `_hostFromResource(correlationId, host, resource, opts)` | Builds `address:port` from a discovery resource, assembling a DNS name from `label`, `namespace` and `local` when present. |
41
+ | `_credentials(correlationId)` | Returns the channel credentials. Insecure by default — **override this for anything crossing a trust boundary.** |
42
+
43
+ `_host` takes the url straight from `opts` when one is supplied, prefers `opts.resource` over it, and only falls back to config when `opts` is absent entirely. Note that `opts` carrying neither a resource nor a url yields an empty host rather than the config fallback.
44
+
45
+ Every call sends `correlationId` as metadata, so a request can be traced across service boundaries the same way it is over HTTP.
46
+
47
+ ### `server.js` — `BaseServerGrpcService`
48
+
49
+ | Method | Purpose |
50
+ |---|---|
51
+ | `_initServices(grpc)` | **Override this.** Add your generated service implementations to the server. |
52
+ | `_start(correlationId)` | Binds to `0.0.0.0:<grpc.port>` and starts. Called during `init`. |
53
+ | `_correlationId(call)` | Reads the correlationId from the call metadata. |
54
+ | `_authenticate(call)` | Reads the `authorization` metadata and returns the correlationId. |
55
+ | `_handleError(correlationId, err, callback)` | Turns an error into the `{ message }` shape a gRPC callback expects, combining `name` and `message`. |
56
+
57
+ **`_authenticate` does not currently reject anything** — the authorization metadata is read and logged, but the validity check is a `TODO` in the source. Do not rely on it as a security boundary; override it, or authenticate at another layer.
58
+
59
+ ## Configuration
60
+
61
+ ### Server
62
+
63
+ ```json
64
+ {
65
+ "app": {
66
+ "grpc": {
67
+ "port": 50051
68
+ }
69
+ }
70
+ }
71
+ ```
72
+
73
+ A missing `grpc` block or `grpc.port` fails at boot.
74
+
75
+ ### Client
76
+
77
+ Per-backend, read through `_config.getBackend(correlationId, key)`:
78
+
79
+ ```json
80
+ {
81
+ "app": {
82
+ "backend": {
83
+ "<key>": {
84
+ "baseUrl": "service-host:50051",
85
+ "discoverable": {
86
+ "name": "<discovery service name>",
87
+ "enabled": true
88
+ }
89
+ }
90
+ }
91
+ }
92
+ }
93
+ ```
94
+
95
+ * **`baseUrl`** — used directly when discovery is off or unavailable.
96
+ * **`discoverable`** — omit it to skip discovery entirely. With it present, discovery is used only when a `SERVICE_DISCOVERY_RESOURCES` service is registered **and** `discoverable.enabled` is not `false`.
97
+ * **`discoverable.name`** — the name looked up in discovery. Required once discovery is active.
98
+
99
+ ## Wiring it up
100
+
101
+ ```js
102
+ import BaseClientGrpcService from '@thzero/library_server_service_grpc/client.js';
103
+
104
+ class InventoryClientService extends BaseClientGrpcService {
105
+ async fetch(correlationId, id) {
106
+ const host = await this._host(correlationId, 'inventory');
107
+ const client = new InventoryClient(host.url, this._credentials(correlationId));
108
+ return await this._execute(correlationId, client.fetch, client, { id });
109
+ }
110
+ }
111
+ ```
112
+
113
+ Register client and server services with the injector from `_initServices` in your `BootMain` derived class, or from a boot plugin's `initServices`. The client resolves `SERVICE_DISCOVERY_RESOURCES` during `init`, which may legitimately be absent.
114
+
115
+ ## Development
116
+
117
+ ```
118
+ npm run lint # eslint .
119
+ npm run lint:fix # eslint . --fix
120
+ npm test # node --test "test/*.test.js"
121
+ ```
package/client.js CHANGED
@@ -1,147 +1,149 @@
1
- import * as grpc from '@grpc/grpc-js';
2
- import { Mutex as asyncMutex } from 'async-mutex';
3
-
4
- import LibraryServerConstants from '@thzero/library_server/constants.js';
5
-
6
- import Service from '@thzero/library_server/service/index.js';
7
-
8
- class BaseClientGrpcService extends Service {
9
- constructor() {
10
- super();
11
-
12
- this._mutex = new asyncMutex();
13
-
14
- this._serviceDiscoveryResources = null;
15
-
16
- this._hosts = new Map();
17
- }
18
-
19
- async init(injector) {
20
- await super.init(injector);
21
-
22
- this._serviceDiscoveryResources = this._injector.getService(LibraryServerConstants.InjectorKeys.SERVICE_DISCOVERY_RESOURCES);
23
- }
24
-
25
- async _execute(correlationId, func, client, request) {
26
- this._enforceNotNull('BaseClientGrpcService', '_execute', func, 'func', correlationId);
27
-
28
- const meta = new grpc.Metadata();
29
- meta.add('correlationId', correlationId);
30
-
31
- return await new Promise((resolve, reject) => {
32
- func.call(client, request, meta, function(err, response) {
33
- if (err) {
34
- reject(err);
35
- return;
36
- }
37
-
38
- resolve(response);
39
- });
40
- });
41
- }
42
-
43
- _credentials(correlationId) {
44
- return grpc.credentials.createInsecure();
45
- }
46
-
47
- async _host(correlationId, key, opts) {
48
- this._enforceNotEmpty('BaseClientGrpcService', '_host', key, 'key', correlationId);
49
-
50
- let host = {
51
- url: null,
52
- secure: false
53
- };
54
-
55
- if (opts) {
56
- if (opts.resource)
57
- host = await this._hostFromResource(correlationId, host, opts.resource, opts);
58
- else if (!String.url(opts.url)) {
59
- host.url = opts.url;
60
- host.secure = opts.secure;
61
- }
62
- }
63
- else
64
- host = await this._hostFromConfig(correlationId, host, key, opts);
65
-
66
- return host;
67
- }
68
-
69
- async _hostFromConfig(correlationId, host, key, opts) {
70
- this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', host, 'host', correlationId);
71
- this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', key, 'key', correlationId);
72
-
73
- const config = this._config.getBackend(key);
74
- this._enforceNotNull('BaseClientGrpcService', '_hostFromConfig', config, 'config', correlationId);
75
- this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', config.baseUrl, 'config.baseUrl', correlationId);
76
-
77
- host.url = config.baseUrl;
78
-
79
- this._logger.debug('BaseServerGrpcService', '_host', 'config.discoverable', config.discoverable, correlationId);
80
- if (!config.discoverable)
81
- return host;
82
-
83
- this._logger.debug('BaseServerGrpcService', '_host', '_serviceDiscoveryResources', (this._serviceDiscoveryResources != null), correlationId);
84
- if (!(this._serviceDiscoveryResources && config.discoverable))
85
- return host;
86
-
87
- this._logger.debug('BaseServerGrpcService', '_host', 'config.discoverable.enabled', config.discoverable.enabled, correlationId);
88
- const enabled = config.discoverable.enabled === false ? false : true;
89
- this._logger.debug('BaseServerGrpcService', '_host', 'enabled', enabled, correlationId);
90
- if (!enabled)
91
- return host;
92
-
93
- host = this._hosts.get(key);
94
- if (host)
95
- return host;
96
-
97
- const release = await this._mutex.acquire();
98
- try {
99
- host = this._hosts.get(key);
100
- if (host)
101
- return host;
102
-
103
- this._enforceNotNull('BaseClientGrpcService', '_host', config.discoverable.name, 'discoveryName', correlationId);
104
-
105
- const response = await this._serviceDiscoveryResources.getService(correlationId, config.discoverable.name);
106
- if (this._hasFailed(response))
107
- return null;
108
-
109
- host = await this._hostFromResource(correlationId, host, response.results);
110
-
111
- this._hosts.set(key, host);
112
- }
113
- finally {
114
- release();
115
- }
116
-
117
- return host;
118
- }
119
-
120
- async _hostFromResource(correlationId, host, resource, opts) {
121
- this._enforceNotEmpty('BaseClientGrpcService', '_hostFromResource', host, 'host', correlationId);
122
- this._enforceNotEmpty('BaseClientGrpcService', '_hostFromResource', resource, 'resource', correlationId);
123
- this._enforceNotNull('BaseClientGrpcService', '_hostFromResource', resource.grpc, 'resource.grpc', correlationId);
124
-
125
- let port = resource.grpc.port ? resource.grpc.port : null;
126
- host.secure = resource.grpc.secure ? resource.grpc.secure : false;
127
-
128
- let address = resource.address;
129
- if (resource.dns) {
130
- const temp = [];
131
- temp.push(resource.dns.label);
132
- if (!String.isNullOrEmpty(resource.dns.namespace))
133
- temp.push(resource.dns.namespace);
134
- if (resource.dns.local)
135
- temp.push('local');
136
- address = temp.join('.');
137
- }
138
-
139
- this._enforceNotNull('BaseClientGrpcService', '_hostFromResource', address, 'address', correlationId);
140
-
141
- host.url = `${address}${port ? `:${port}` : ''}`;
142
-
143
- return host;
144
- }
145
- }
146
-
147
- export default BaseClientGrpcService;
1
+ import * as grpc from '@grpc/grpc-js';
2
+ import { Mutex as asyncMutex } from 'async-mutex';
3
+
4
+ import LibraryCommonUtility from '@thzero/library_common/utility/index.js';
5
+
6
+ import LibraryServerConstants from '@thzero/library_server/constants.js';
7
+
8
+ import Service from '@thzero/library_server/service/index.js';
9
+
10
+ class BaseClientGrpcService extends Service {
11
+ constructor() {
12
+ super();
13
+
14
+ this._mutex = new asyncMutex();
15
+
16
+ this._serviceDiscoveryResources = null;
17
+
18
+ this._hosts = new Map();
19
+ }
20
+
21
+ async init(injector) {
22
+ await super.init(injector);
23
+
24
+ this._serviceDiscoveryResources = this._injector.getService(LibraryServerConstants.InjectorKeys.SERVICE_DISCOVERY_RESOURCES);
25
+ }
26
+
27
+ async _execute(correlationId, func, client, request) {
28
+ this._enforceNotNull('BaseClientGrpcService', '_execute', func, 'func', correlationId);
29
+
30
+ const meta = new grpc.Metadata();
31
+ meta.add('correlationId', correlationId);
32
+
33
+ return await new Promise((resolve, reject) => {
34
+ func.call(client, request, meta, function(err, response) {
35
+ if (err) {
36
+ reject(err);
37
+ return;
38
+ }
39
+
40
+ resolve(response);
41
+ });
42
+ });
43
+ }
44
+
45
+ _credentials(correlationId) {
46
+ return grpc.credentials.createInsecure();
47
+ }
48
+
49
+ async _host(correlationId, key, opts) {
50
+ this._enforceNotEmpty('BaseClientGrpcService', '_host', key, 'key', correlationId);
51
+
52
+ let host = {
53
+ url: null,
54
+ secure: false
55
+ };
56
+
57
+ if (opts) {
58
+ if (opts.resource)
59
+ host = await this._hostFromResource(correlationId, host, opts.resource, opts);
60
+ else if (!String.isNullOrEmpty(opts.url)) {
61
+ host.url = opts.url;
62
+ host.secure = opts.secure;
63
+ }
64
+ }
65
+ else
66
+ host = await this._hostFromConfig(correlationId, host, key, opts);
67
+
68
+ return host;
69
+ }
70
+
71
+ async _hostFromConfig(correlationId, host, key, opts) {
72
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', host, 'host', correlationId);
73
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', key, 'key', correlationId);
74
+
75
+ const config = this._config.getBackend(correlationId, key);
76
+ this._enforceNotNull('BaseClientGrpcService', '_hostFromConfig', config, 'config', correlationId);
77
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', config.baseUrl, 'config.baseUrl', correlationId);
78
+
79
+ host.url = config.baseUrl;
80
+
81
+ this._logger.debug('BaseServerGrpcService', '_host', 'config.discoverable', config.discoverable, correlationId);
82
+ if (!config.discoverable)
83
+ return host;
84
+
85
+ this._logger.debug('BaseServerGrpcService', '_host', '_serviceDiscoveryResources', LibraryCommonUtility.isNotNull(this._serviceDiscoveryResources), correlationId);
86
+ if (!(this._serviceDiscoveryResources && config.discoverable))
87
+ return host;
88
+
89
+ this._logger.debug('BaseServerGrpcService', '_host', 'config.discoverable.enabled', config.discoverable.enabled, correlationId);
90
+ const enabled = config.discoverable.enabled === false ? false : true;
91
+ this._logger.debug('BaseServerGrpcService', '_host', 'enabled', enabled, correlationId);
92
+ if (!enabled)
93
+ return host;
94
+
95
+ let discovered = this._hosts.get(key);
96
+ if (discovered)
97
+ return discovered;
98
+
99
+ const release = await this._mutex.acquire();
100
+ try {
101
+ discovered = this._hosts.get(key);
102
+ if (discovered)
103
+ return discovered;
104
+
105
+ this._enforceNotNull('BaseClientGrpcService', '_host', config.discoverable.name, 'discoveryName', correlationId);
106
+
107
+ const response = await this._serviceDiscoveryResources.getService(correlationId, config.discoverable.name);
108
+ if (this._hasFailed(response))
109
+ return null;
110
+
111
+ host = await this._hostFromResource(correlationId, host, response.results);
112
+
113
+ this._hosts.set(key, host);
114
+ }
115
+ finally {
116
+ release();
117
+ }
118
+
119
+ return host;
120
+ }
121
+
122
+ async _hostFromResource(correlationId, host, resource, opts) {
123
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromResource', host, 'host', correlationId);
124
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromResource', resource, 'resource', correlationId);
125
+ this._enforceNotNull('BaseClientGrpcService', '_hostFromResource', resource.grpc, 'resource.grpc', correlationId);
126
+
127
+ let port = resource.grpc.port ? resource.grpc.port : null;
128
+ host.secure = resource.grpc.secure ? resource.grpc.secure : false;
129
+
130
+ let address = resource.address;
131
+ if (resource.dns) {
132
+ const temp = [];
133
+ temp.push(resource.dns.label);
134
+ if (!String.isNullOrEmpty(resource.dns.namespace))
135
+ temp.push(resource.dns.namespace);
136
+ if (resource.dns.local)
137
+ temp.push('local');
138
+ address = temp.join('.');
139
+ }
140
+
141
+ this._enforceNotNull('BaseClientGrpcService', '_hostFromResource', address, 'address', correlationId);
142
+
143
+ host.url = `${address}${port ? `:${port}` : ''}`;
144
+
145
+ return host;
146
+ }
147
+ }
148
+
149
+ export default BaseClientGrpcService;
@@ -0,0 +1,61 @@
1
+ // Rules earned their place: each one catches a defect found in this codebase.
2
+ // See AUDIT_SERVER.md in the parent workspace for the catalogue.
3
+ export default [
4
+ {
5
+ files: ['**/*.js'],
6
+ ignores: ['node_modules/**', 'dist/**'],
7
+ languageOptions: {
8
+ ecmaVersion: 2022,
9
+ sourceType: 'module',
10
+ globals: {
11
+ // library_common installs these onto the global String
12
+ String: 'writable',
13
+ console: 'readonly',
14
+ process: 'readonly',
15
+ performance: 'readonly',
16
+ navigator: 'readonly',
17
+ setTimeout: 'readonly',
18
+ clearTimeout: 'readonly'
19
+ }
20
+ },
21
+ rules: {
22
+ // undeclared identifiers - caught MomentUtility in utility/checksum.js
23
+ // and cmd in library_cli_build/boot/cli.js
24
+ 'no-undef': 'error',
25
+ // === NaN is always false - caught the --major validation in cli.js
26
+ 'use-isnan': 'error',
27
+ // Unused locals. This is what caught the loop variable in
28
+ // `for (const value of values) valid &= values`.
29
+ // args is 'none' deliberately: the codebase is built on abstract base
30
+ // classes whose methods declare a signature for subclasses and use none
31
+ // of it - 58 such parameters in library_common_service alone. Dead
32
+ // trailing parameters (idName, index) need a targeted read, not this rule.
33
+ 'no-unused-vars': ['error', { args: 'none', ignoreRestSiblings: true }],
34
+ // the &= boolean accumulator in the _enforce* block
35
+ 'no-bitwise': 'error',
36
+ // C17
37
+ 'eqeqeq': 'error',
38
+ 'no-dupe-class-members': 'error',
39
+ 'no-dupe-keys': 'error',
40
+ 'no-unreachable': 'error',
41
+ 'no-constant-condition': ['error', { checkLoops: false }],
42
+ 'no-self-compare': 'error',
43
+ // the comma operator - caught `this._logger.exception(a, b, err), correlationId;`
44
+ // in library_server_messaging_slack, which silently dropped the correlationId
45
+ 'no-sequences': 'error',
46
+ // caught `catch (err) { throw err; }` in library_server_repository_redis
47
+ 'no-useless-catch': 'error',
48
+ // caught `resource.authentication = resource.authentication;` in
49
+ // library_server_service_rest_axios
50
+ 'no-self-assign': 'error',
51
+ // an expression statement that does nothing is almost always a dropped call
52
+ 'no-unused-expressions': 'error'
53
+ }
54
+ },
55
+ {
56
+ files: ['test/**/*.js'],
57
+ languageOptions: {
58
+ globals: { process: 'readonly', console: 'readonly', setTimeout: 'readonly' }
59
+ }
60
+ }
61
+ ];
package/license.md CHANGED
@@ -1,9 +1,9 @@
1
- MIT License
2
-
3
- Copyright (c) 2020-2026 thZero.com
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
-
1
+ MIT License
2
+
3
+ Copyright (c) 2020-2026 thZero.com
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
9
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json CHANGED
@@ -1,37 +1,42 @@
1
- {
2
- "name": "@thzero/library_server_service_grpc",
3
- "type": "module",
4
- "version": "0.18.20",
5
- "version_major": 0,
6
- "version_minor": 18,
7
- "version_patch": 20,
8
- "version_date": "05/21/2026",
9
- "description": "",
10
- "author": "thZero",
11
- "author_url": "https://www.thzero.com",
12
- "copyright": "2020-2026",
13
- "license": "MIT",
14
- "repository": {
15
- "type": "git",
16
- "url": "git+https://github.com/thzero/library_server_service_grpc.git"
17
- },
18
- "bugs": {
19
- "url": "https://github.com/thzero/library_server_service_grpc/issues"
20
- },
21
- "engines": {
22
- "node": ">=22"
23
- },
24
- "main": "index.js",
25
- "scripts": {
26
- "cli-update": "library-cli --updateversion --pi",
27
- "test": "echo \"Error: no test specified\" && exit 1"
28
- },
29
- "dependencies": {
30
- "@grpc/grpc-js": "^1.14.3"
31
- },
32
- "peerDependencies": {
33
- "@thzero/library_common": "^0.18",
34
- "@thzero/library_common_service": "^0.18",
35
- "@thzero/library_server": "^0.18"
36
- }
1
+ {
2
+ "name": "@thzero/library_server_service_grpc",
3
+ "type": "module",
4
+ "version": "0.19.1",
5
+ "version_major": 0,
6
+ "version_minor": 19,
7
+ "version_patch": 1,
8
+ "version_date": "09/15/2026",
9
+ "description": "",
10
+ "author": "thZero",
11
+ "author_url": "https://www.thzero.com",
12
+ "copyright": "2020-2026",
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/thzero/library_server_service_grpc.git"
17
+ },
18
+ "bugs": {
19
+ "url": "https://github.com/thzero/library_server_service_grpc/issues"
20
+ },
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "main": "index.js",
25
+ "scripts": {
26
+ "cli-update": "library-cli --updateversion --pi",
27
+ "test": "node --test \"test/*.test.js\"",
28
+ "lint": "eslint .",
29
+ "lint:fix": "eslint . --fix"
30
+ },
31
+ "dependencies": {
32
+ "@grpc/grpc-js": "^1.14.4"
33
+ },
34
+ "peerDependencies": {
35
+ "@thzero/library_common": "^0.19",
36
+ "@thzero/library_common_service": "^0.19",
37
+ "@thzero/library_server": "^0.19"
38
+ },
39
+ "devDependencies": {
40
+ "eslint": "^9.39.5"
41
+ }
37
42
  }
package/server.js CHANGED
@@ -1,92 +1,92 @@
1
- import * as grpc from '@grpc/grpc-js';
2
-
3
- import Service from '@thzero/library_server/service/index.js';
4
-
5
- class BaseServerGrpcService extends Service {
6
- constructor() {
7
- super();
8
-
9
- this._configGrpc = null;
10
-
11
- this._grpc = null;
12
- }
13
-
14
- async init(injector) {
15
- await super.init(injector);
16
-
17
- try {
18
- this._configGrpc = this._config.get(`grpc`);
19
-
20
- this._grpc = new grpc.Server();
21
- await this._initServices(this._grpc);
22
- await this._start();
23
- }
24
- catch (err) {
25
- this._logger.error('BaseServerGrpcService', 'init', null, err);
26
- }
27
- }
28
-
29
- _authenticate(call) {
30
- const correlationId = this._correlationId(call);
31
- this._logger.debug('BaseServerGrpcService', '_authenticate', 'correlationId', correlationId, correlationId);
32
-
33
- const meta = call.metadata.get('authorization');
34
- this._logger.debug('BaseServerGrpcService', '_authenticate', 'meta', meta, correlationId);
35
- const authorization = (meta && (meta.length > 0)) ? meta[0] : null;
36
- this._logger.debug('BaseServerGrpcService', '_authenticate', 'authorization', authorization, correlationId);
37
-
38
- const valid = true; // TODO
39
- if (!valid)
40
- throw Error('Unauthorized.');
41
-
42
- return correlationId;
43
- }
44
-
45
- _correlationId(call) {
46
- this._enforceNotNull('BaseServerGrpcService', '_correlationId', call, 'call');
47
-
48
- const meta = call.metadata.get('correlationId');
49
- this._logger.debug('BaseServerGrpcService', '_correlationId', 'meta', meta);
50
- return (meta && (meta.length > 0)) ? meta[0] : null;
51
- }
52
-
53
- _handleError(correlationId, err, callback) {
54
- this._enforceNotNull('BaseServerGrpcService', '_handleError', callback, 'callback', correlationId);
55
-
56
- if (!err)
57
- return;
58
-
59
- let message = '';
60
- if (err.name)
61
- message += err.name + ' ';
62
- if (err.message)
63
- message += err.message;
64
- message = message.trim();
65
-
66
- callback({ message: message }, null);
67
- }
68
-
69
- async _initServices(grpc) {
70
- }
71
-
72
- async _start(correlationId) {
73
- this._enforceNotNull('BaseServerGrpcService', '_start', this._configGrpc, 'config.grpc', correlationId);
74
- this._enforceNotNull('BaseServerGrpcService', '_start', this._configGrpc.port, 'config.grpc.port', correlationId);
75
-
76
- return await new Promise((resolve, reject) => {
77
- this._grpc.bindAsync('0.0.0.0:' + this._configGrpc.port, grpc.ServerCredentials.createInsecure(), (err, port) => {
78
- if (err) {
79
- reject(this._error('BaseServerGrpcService', '_start', null, err, null, null, correlationId));
80
- return;
81
- }
82
-
83
- this._logger.info2(`GRPC: starting server on port '${this._configGrpc.port}'...`, null, correlationId);
84
- this._grpc.start();
85
-
86
- resolve(this._success(correlationId));
87
- });
88
- });
89
- }
90
- }
91
-
92
- export default BaseServerGrpcService;
1
+ import * as grpc from '@grpc/grpc-js';
2
+
3
+ import Service from '@thzero/library_server/service/index.js';
4
+
5
+ class BaseServerGrpcService extends Service {
6
+ constructor() {
7
+ super();
8
+
9
+ this._configGrpc = null;
10
+
11
+ this._grpc = null;
12
+ }
13
+
14
+ async init(injector) {
15
+ await super.init(injector);
16
+
17
+ try {
18
+ this._configGrpc = this._config.get(`grpc`);
19
+
20
+ this._grpc = new grpc.Server();
21
+ await this._initServices(this._grpc);
22
+ await this._start();
23
+ }
24
+ catch (err) {
25
+ this._logger.error('BaseServerGrpcService', 'init', null, err);
26
+ }
27
+ }
28
+
29
+ _authenticate(call) {
30
+ const correlationId = this._correlationId(call);
31
+ this._logger.debug('BaseServerGrpcService', '_authenticate', 'correlationId', correlationId, correlationId);
32
+
33
+ const meta = call.metadata.get('authorization');
34
+ this._logger.debug('BaseServerGrpcService', '_authenticate', 'meta', meta, correlationId);
35
+ const authorization = (meta && (meta.length > 0)) ? meta[0] : null;
36
+ this._logger.debug('BaseServerGrpcService', '_authenticate', 'authorization', authorization, correlationId);
37
+
38
+ const valid = true; // TODO
39
+ if (!valid)
40
+ throw Error('Unauthorized.');
41
+
42
+ return correlationId;
43
+ }
44
+
45
+ _correlationId(call) {
46
+ this._enforceNotNull('BaseServerGrpcService', '_correlationId', call, 'call');
47
+
48
+ const meta = call.metadata.get('correlationId');
49
+ this._logger.debug('BaseServerGrpcService', '_correlationId', 'meta', meta);
50
+ return (meta && (meta.length > 0)) ? meta[0] : null;
51
+ }
52
+
53
+ _handleError(correlationId, err, callback) {
54
+ this._enforceNotNull('BaseServerGrpcService', '_handleError', callback, 'callback', correlationId);
55
+
56
+ if (!err)
57
+ return;
58
+
59
+ let message = '';
60
+ if (err.name)
61
+ message += err.name + ' ';
62
+ if (err.message)
63
+ message += err.message;
64
+ message = message.trim();
65
+
66
+ callback({ message: message }, null);
67
+ }
68
+
69
+ async _initServices(grpc) {
70
+ }
71
+
72
+ async _start(correlationId) {
73
+ this._enforceNotNull('BaseServerGrpcService', '_start', this._configGrpc, 'config.grpc', correlationId);
74
+ this._enforceNotNull('BaseServerGrpcService', '_start', this._configGrpc.port, 'config.grpc.port', correlationId);
75
+
76
+ return await new Promise((resolve, reject) => {
77
+ this._grpc.bindAsync('0.0.0.0:' + this._configGrpc.port, grpc.ServerCredentials.createInsecure(), (err, port) => {
78
+ if (err) {
79
+ reject(this._error('BaseServerGrpcService', '_start', null, err, null, null, correlationId));
80
+ return;
81
+ }
82
+
83
+ this._logger.info2(`GRPC: starting server on port '${this._configGrpc.port}'...`, null, correlationId);
84
+ this._grpc.start();
85
+
86
+ resolve(this._success(correlationId));
87
+ });
88
+ });
89
+ }
90
+ }
91
+
92
+ export default BaseServerGrpcService;
@@ -0,0 +1,168 @@
1
+ import assert from 'node:assert/strict';
2
+ import { beforeEach, describe, it } from 'node:test';
3
+
4
+ import '@thzero/library_common/utility/string.js';
5
+ import BaseClientGrpcService from '../client.js';
6
+
7
+ const inject = (target, name, value) => {
8
+ Object.defineProperty(target, name, { value, writable: true, configurable: true });
9
+ return target;
10
+ };
11
+
12
+ const newLogger = () => ({ debug() {}, info() {}, info2() {}, warn() {}, error() {}, exception() {}, fatal() {}, trace() {} });
13
+
14
+ let service;
15
+
16
+ beforeEach(() => {
17
+ service = new BaseClientGrpcService();
18
+ inject(service, '_logger', newLogger());
19
+ inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1' }) });
20
+ });
21
+
22
+ describe('_host', () => {
23
+ it('requires a key', async () => {
24
+ await assert.rejects(() => service._host('cid', null, null), /key is empty/);
25
+ });
26
+
27
+ // Regression: the guard read `!String.url(opts.url)`, and String.url does not
28
+ // exist - library_common/utility/string.js declares capitalize, isNullOrEmpty,
29
+ // isString and trim. Every call carrying a url threw
30
+ // `TypeError: String.url is not a function`.
31
+ it('takes the url straight from opts', async () => {
32
+ const host = await service._host('cid', 'key', { url: 'http://given:1', secure: true });
33
+ assert.deepEqual(host, { url: 'http://given:1', secure: true });
34
+ });
35
+
36
+ it('prefers a resource in opts over a url', async () => {
37
+ const host = await service._host('cid', 'key', {
38
+ url: 'http://ignored:1',
39
+ resource: { address: 'from-resource', grpc: { port: 9000 } }
40
+ });
41
+ assert.equal(host.url, 'from-resource:9000');
42
+ });
43
+
44
+ it('falls back to config when there are no opts at all', async () => {
45
+ const host = await service._host('cid', 'key', null);
46
+ assert.equal(host.url, 'http://backend:1');
47
+ });
48
+
49
+ // Known gap: opts that carry neither a resource nor a url do NOT fall back to
50
+ // config - the host comes back empty. Pinning current behaviour.
51
+ it('returns an empty host for opts with neither a resource nor a url', async () => {
52
+ assert.deepEqual(await service._host('cid', 'key', {}), { url: null, secure: false });
53
+ });
54
+ });
55
+
56
+ describe('_hostFromConfig', () => {
57
+ const host = () => ({ url: null, secure: false });
58
+
59
+ it('uses the configured base url when discovery is off', async () => {
60
+ const result = await service._hostFromConfig('cid', host(), 'key', null);
61
+ assert.equal(result.url, 'http://backend:1');
62
+ });
63
+
64
+ it('uses the configured base url when no discovery service is wired up', async () => {
65
+ inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc' } }) });
66
+ const result = await service._hostFromConfig('cid', host(), 'key', null);
67
+ assert.equal(result.url, 'http://backend:1');
68
+ });
69
+
70
+ it('uses the configured base url when discovery is explicitly disabled', async () => {
71
+ inject(service, '_config', {
72
+ getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc', enabled: false } })
73
+ });
74
+ service._serviceDiscoveryResources = { getService: async () => { throw new Error('must not be called'); } };
75
+ const result = await service._hostFromConfig('cid', host(), 'key', null);
76
+ assert.equal(result.url, 'http://backend:1');
77
+ });
78
+
79
+ it('resolves and caches a discovered host', async () => {
80
+ let lookups = 0;
81
+ inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc' } }) });
82
+ service._serviceDiscoveryResources = {
83
+ getService: async () => { lookups++; return { success: true, results: { address: 'discovered', grpc: { port: 9000 } } }; }
84
+ };
85
+ const first = await service._hostFromConfig('cid', host(), 'key', null);
86
+ const second = await service._hostFromConfig('cid', host(), 'key', null);
87
+ assert.equal(first.url, 'discovered:9000');
88
+ assert.equal(lookups, 1, 'the second call came from the cache');
89
+ assert.equal(second, first);
90
+ });
91
+
92
+ it('returns null when discovery fails', async () => {
93
+ inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc' } }) });
94
+ service._serviceDiscoveryResources = { getService: async () => ({ success: false }) };
95
+ assert.equal(await service._hostFromConfig('cid', host(), 'key', null), null);
96
+ });
97
+
98
+ it('rejects a config without a base url', async () => {
99
+ inject(service, '_config', { getBackend: () => ({}) });
100
+ await assert.rejects(() => service._hostFromConfig('cid', host(), 'key', null), /config.baseUrl is empty/);
101
+ });
102
+ });
103
+
104
+ describe('_hostFromResource', () => {
105
+ const host = () => ({ url: null, secure: false });
106
+
107
+ it('joins address and port', async () => {
108
+ const result = await service._hostFromResource('cid', host(), { address: 'a', grpc: { port: 1 } });
109
+ assert.equal(result.url, 'a:1');
110
+ });
111
+
112
+ it('omits a missing port', async () => {
113
+ const result = await service._hostFromResource('cid', host(), { address: 'a', grpc: {} });
114
+ assert.equal(result.url, 'a');
115
+ });
116
+
117
+ it('carries the secure flag off the grpc block', async () => {
118
+ assert.equal((await service._hostFromResource('cid', host(), { address: 'a', grpc: { secure: true } })).secure, true);
119
+ assert.equal((await service._hostFromResource('cid', host(), { address: 'a', grpc: {} })).secure, false);
120
+ });
121
+
122
+ it('assembles a dns name from label, namespace and local', async () => {
123
+ const result = await service._hostFromResource('cid', host(),
124
+ { dns: { label: 'svc', namespace: 'ns', local: true }, grpc: { port: 1 } });
125
+ assert.equal(result.url, 'svc.ns.local:1');
126
+ });
127
+
128
+ it('assembles a dns name that is neither namespaced nor local', async () => {
129
+ const result = await service._hostFromResource('cid', host(), { dns: { label: 'svc' }, grpc: {} });
130
+ assert.equal(result.url, 'svc');
131
+ });
132
+
133
+ it('rejects a resource with no grpc block and one with no address', async () => {
134
+ await assert.rejects(() => service._hostFromResource('cid', host(), { address: 'a' }), /resource.grpc is null/);
135
+ await assert.rejects(() => service._hostFromResource('cid', host(), { grpc: {} }), /address is null/);
136
+ });
137
+ });
138
+
139
+ describe('_execute', () => {
140
+ it('requires a function', async () => {
141
+ await assert.rejects(() => service._execute('cid', null, {}, {}), /func is null/);
142
+ });
143
+
144
+ it('resolves with the response the callback is given', async () => {
145
+ const func = function (request, meta, callback) { callback(null, { echoed: request.a }); };
146
+ assert.deepEqual(await service._execute('cid', func, {}, { a: 1 }), { echoed: 1 });
147
+ });
148
+
149
+ it('rejects with the error the callback is given', async () => {
150
+ const func = function (request, meta, callback) { callback(new Error('boom')); };
151
+ await assert.rejects(() => service._execute('cid', func, {}, {}), /boom/);
152
+ });
153
+
154
+ it('sends the correlationId as metadata', async () => {
155
+ let seen = null;
156
+ const func = function (request, meta, callback) { seen = meta.get('correlationId'); callback(null, {}); };
157
+ await service._execute('cid-123', func, {}, {});
158
+ assert.deepEqual(seen, [ 'cid-123' ]);
159
+ });
160
+
161
+ it('calls the function with the client as its receiver', async () => {
162
+ const client = { marker: 'me' };
163
+ let receiver = null;
164
+ const func = function (request, meta, callback) { receiver = this; callback(null, {}); };
165
+ await service._execute('cid', func, client, {});
166
+ assert.equal(receiver, client);
167
+ });
168
+ });
@@ -0,0 +1,85 @@
1
+ import assert from 'node:assert/strict';
2
+ import { beforeEach, describe, it } from 'node:test';
3
+
4
+ import '@thzero/library_common/utility/string.js';
5
+ import BaseServerGrpcService from '../server.js';
6
+
7
+ const inject = (target, name, value) => {
8
+ Object.defineProperty(target, name, { value, writable: true, configurable: true });
9
+ return target;
10
+ };
11
+
12
+ const newLogger = () => ({ debug() {}, info() {}, info2() {}, warn() {}, error() {}, exception() {}, fatal() {}, trace() {} });
13
+
14
+ // grpc metadata exposes get(key) -> array of values
15
+ const newCall = (metadata = {}) => ({ metadata: { get: (key) => metadata[key] ?? [] } });
16
+
17
+ let service;
18
+
19
+ beforeEach(() => {
20
+ service = new BaseServerGrpcService();
21
+ inject(service, '_logger', newLogger());
22
+ inject(service, '_config', { get: () => null });
23
+ });
24
+
25
+ describe('_correlationId', () => {
26
+ it('reads the first correlationId from the call metadata', () => {
27
+ assert.equal(service._correlationId(newCall({ correlationId: [ 'cid-123' ] })), 'cid-123');
28
+ });
29
+
30
+ it('returns null when the metadata carries none', () => {
31
+ assert.equal(service._correlationId(newCall()), null);
32
+ });
33
+
34
+ it('throws on a missing call', () => {
35
+ assert.throws(() => service._correlationId(null), /call is null/);
36
+ });
37
+ });
38
+
39
+ describe('_authenticate', () => {
40
+ it('returns the correlationId off the call', () => {
41
+ assert.equal(service._authenticate(newCall({ correlationId: [ 'cid-123' ] })), 'cid-123');
42
+ });
43
+
44
+ // Known gap: `const valid = true; // TODO` - the authorization metadata is read
45
+ // and logged but never checked, so nothing is ever rejected here. Pinning that
46
+ // so it is visible rather than assumed.
47
+ it('does not currently reject anything (TODO in the source)', () => {
48
+ assert.doesNotThrow(() => service._authenticate(newCall({ authorization: [ 'Bearer nonsense' ] })));
49
+ });
50
+ });
51
+
52
+ describe('_handleError', () => {
53
+ it('requires a callback', () => {
54
+ assert.throws(() => service._handleError('cid', new Error('boom'), null), /callback is null/);
55
+ });
56
+
57
+ it('does nothing when there is no error', () => {
58
+ let called = false;
59
+ service._handleError('cid', null, () => { called = true; });
60
+ assert.equal(called, false);
61
+ });
62
+
63
+ it('reports the name and message together', () => {
64
+ let payload = null;
65
+ service._handleError('cid', new Error('boom'), (err) => { payload = err; });
66
+ assert.deepEqual(payload, { message: 'Error boom' });
67
+ });
68
+
69
+ it('trims when only one of name and message is present', () => {
70
+ let payload = null;
71
+ service._handleError('cid', { message: 'boom' }, (err) => { payload = err; });
72
+ assert.deepEqual(payload, { message: 'boom' });
73
+
74
+ service._handleError('cid', { name: 'Bad' }, (err) => { payload = err; });
75
+ assert.deepEqual(payload, { message: 'Bad' });
76
+ });
77
+ });
78
+
79
+ describe('_start', () => {
80
+ it('requires a grpc config with a port', async () => {
81
+ await assert.rejects(() => service._start('cid'), /config.grpc is null/);
82
+ service._configGrpc = {};
83
+ await assert.rejects(() => service._start('cid'), /config.grpc.port is null/);
84
+ });
85
+ });