@thzero/library_server_service_grpc 0.18.21 → 0.19.2
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 +121 -15
- package/client.js +166 -147
- package/eslint.config.mjs +61 -0
- package/license.md +8 -8
- package/package.json +41 -36
- package/server.js +92 -92
- package/test/client.test.js +236 -0
- package/test/server.test.js +85 -0
package/README.md
CHANGED
|
@@ -1,15 +1,121 @@
|
|
|
1
|
-

|
|
2
|
-

|
|
3
|
-
[](https://opensource.org/licenses/MIT)
|
|
4
|
-
|
|
5
|
-
# library_server_service_grpc
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
[
|
|
1
|
+

|
|
2
|
+

|
|
3
|
+
[](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
|
+
[](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,166 @@
|
|
|
1
|
-
import * as grpc from '@grpc/grpc-js';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
this._serviceDiscoveryResources = null;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
this.
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
1
|
+
import * as grpc from '@grpc/grpc-js';
|
|
2
|
+
|
|
3
|
+
import LibraryCommonUtility from '@thzero/library_common/utility/index.js';
|
|
4
|
+
import LibraryMomentUtility from '@thzero/library_common/utility/moment.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._serviceDiscoveryResources = null;
|
|
15
|
+
|
|
16
|
+
// key -> discovered host. A failed discovery is remembered by time so a
|
|
17
|
+
// backend that is down is asked about once per retry window rather than on
|
|
18
|
+
// every call, and a discovery in flight is shared by the calls that arrive
|
|
19
|
+
// while it runs.
|
|
20
|
+
this._hosts = new Map();
|
|
21
|
+
this._hostsFailed = new Map();
|
|
22
|
+
this._hostsPending = new Map();
|
|
23
|
+
this._hostsRetryMs = 5 * 1000;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async init(injector) {
|
|
27
|
+
await super.init(injector);
|
|
28
|
+
|
|
29
|
+
this._serviceDiscoveryResources = this._injector.getService(LibraryServerConstants.InjectorKeys.SERVICE_DISCOVERY_RESOURCES);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async _execute(correlationId, func, client, request) {
|
|
33
|
+
this._enforceNotNull('BaseClientGrpcService', '_execute', func, 'func', correlationId);
|
|
34
|
+
|
|
35
|
+
const meta = new grpc.Metadata();
|
|
36
|
+
meta.add('correlationId', correlationId);
|
|
37
|
+
|
|
38
|
+
return await new Promise((resolve, reject) => {
|
|
39
|
+
func.call(client, request, meta, function(err, response) {
|
|
40
|
+
if (err) {
|
|
41
|
+
reject(err);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
resolve(response);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
_credentials(correlationId) {
|
|
51
|
+
return grpc.credentials.createInsecure();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async _host(correlationId, key, opts) {
|
|
55
|
+
this._enforceNotEmpty('BaseClientGrpcService', '_host', key, 'key', correlationId);
|
|
56
|
+
|
|
57
|
+
let host = {
|
|
58
|
+
url: null,
|
|
59
|
+
secure: false
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
if (opts) {
|
|
63
|
+
if (opts.resource)
|
|
64
|
+
host = await this._hostFromResource(correlationId, host, opts.resource, opts);
|
|
65
|
+
else if (!String.isNullOrEmpty(opts.url)) {
|
|
66
|
+
host.url = opts.url;
|
|
67
|
+
host.secure = opts.secure;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
else
|
|
71
|
+
host = await this._hostFromConfig(correlationId, host, key, opts);
|
|
72
|
+
|
|
73
|
+
return host;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async _hostFromConfig(correlationId, host, key, opts) {
|
|
77
|
+
this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', host, 'host', correlationId);
|
|
78
|
+
this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', key, 'key', correlationId);
|
|
79
|
+
|
|
80
|
+
const config = this._config.getBackend(correlationId, key);
|
|
81
|
+
this._enforceNotNull('BaseClientGrpcService', '_hostFromConfig', config, 'config', correlationId);
|
|
82
|
+
this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', config.baseUrl, 'config.baseUrl', correlationId);
|
|
83
|
+
|
|
84
|
+
host.url = config.baseUrl;
|
|
85
|
+
|
|
86
|
+
this._logger.debug('BaseServerGrpcService', '_host', 'config.discoverable', config.discoverable, correlationId);
|
|
87
|
+
if (!config.discoverable)
|
|
88
|
+
return host;
|
|
89
|
+
|
|
90
|
+
this._logger.debug('BaseServerGrpcService', '_host', '_serviceDiscoveryResources', LibraryCommonUtility.isNotNull(this._serviceDiscoveryResources), correlationId);
|
|
91
|
+
if (!(this._serviceDiscoveryResources && config.discoverable))
|
|
92
|
+
return host;
|
|
93
|
+
|
|
94
|
+
this._logger.debug('BaseServerGrpcService', '_host', 'config.discoverable.enabled', config.discoverable.enabled, correlationId);
|
|
95
|
+
const enabled = config.discoverable.enabled === false ? false : true;
|
|
96
|
+
this._logger.debug('BaseServerGrpcService', '_host', 'enabled', enabled, correlationId);
|
|
97
|
+
if (!enabled)
|
|
98
|
+
return host;
|
|
99
|
+
|
|
100
|
+
const discovered = this._hosts.get(key);
|
|
101
|
+
if (discovered)
|
|
102
|
+
return discovered;
|
|
103
|
+
|
|
104
|
+
// A failure used to cache nothing, so every call after it took the mutex
|
|
105
|
+
// and asked discovery again, one at a time.
|
|
106
|
+
const failed = this._hostsFailed.get(key);
|
|
107
|
+
if (failed && ((LibraryMomentUtility.getTimestamp() - failed) < this._hostsRetryMs))
|
|
108
|
+
return null;
|
|
109
|
+
|
|
110
|
+
// One discovery per key at a time. Calls for the same key share it; calls
|
|
111
|
+
// for other keys are not held up by it, which the single mutex did.
|
|
112
|
+
let pending = this._hostsPending.get(key);
|
|
113
|
+
if (!pending) {
|
|
114
|
+
pending = this._hostDiscover(correlationId, host, config, key)
|
|
115
|
+
.finally(() => {
|
|
116
|
+
this._hostsPending.delete(key);
|
|
117
|
+
});
|
|
118
|
+
this._hostsPending.set(key, pending);
|
|
119
|
+
}
|
|
120
|
+
return await pending;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async _hostDiscover(correlationId, host, config, key) {
|
|
124
|
+
this._enforceNotNull('BaseClientGrpcService', '_host', config.discoverable.name, 'discoveryName', correlationId);
|
|
125
|
+
|
|
126
|
+
const response = await this._serviceDiscoveryResources.getService(correlationId, config.discoverable.name);
|
|
127
|
+
if (this._hasFailed(response)) {
|
|
128
|
+
this._hostsFailed.set(key, LibraryMomentUtility.getTimestamp());
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
host = await this._hostFromResource(correlationId, host, response.results);
|
|
133
|
+
|
|
134
|
+
this._hosts.set(key, host);
|
|
135
|
+
this._hostsFailed.delete(key);
|
|
136
|
+
return host;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async _hostFromResource(correlationId, host, resource, opts) {
|
|
140
|
+
this._enforceNotEmpty('BaseClientGrpcService', '_hostFromResource', host, 'host', correlationId);
|
|
141
|
+
this._enforceNotEmpty('BaseClientGrpcService', '_hostFromResource', resource, 'resource', correlationId);
|
|
142
|
+
this._enforceNotNull('BaseClientGrpcService', '_hostFromResource', resource.grpc, 'resource.grpc', correlationId);
|
|
143
|
+
|
|
144
|
+
let port = resource.grpc.port ? resource.grpc.port : null;
|
|
145
|
+
host.secure = resource.grpc.secure ? resource.grpc.secure : false;
|
|
146
|
+
|
|
147
|
+
let address = resource.address;
|
|
148
|
+
if (resource.dns) {
|
|
149
|
+
const temp = [];
|
|
150
|
+
temp.push(resource.dns.label);
|
|
151
|
+
if (!String.isNullOrEmpty(resource.dns.namespace))
|
|
152
|
+
temp.push(resource.dns.namespace);
|
|
153
|
+
if (resource.dns.local)
|
|
154
|
+
temp.push('local');
|
|
155
|
+
address = temp.join('.');
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
this._enforceNotNull('BaseClientGrpcService', '_hostFromResource', address, 'address', correlationId);
|
|
159
|
+
|
|
160
|
+
host.url = `${address}${port ? `:${port}` : ''}`;
|
|
161
|
+
|
|
162
|
+
return host;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
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.
|
|
5
|
-
"version_major": 0,
|
|
6
|
-
"version_minor":
|
|
7
|
-
"version_patch":
|
|
8
|
-
"version_date": "
|
|
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": "
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
"@thzero/
|
|
36
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@thzero/library_server_service_grpc",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.19.2",
|
|
5
|
+
"version_major": 0,
|
|
6
|
+
"version_minor": 19,
|
|
7
|
+
"version_patch": 2,
|
|
8
|
+
"version_date": "09/23/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,236 @@
|
|
|
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 LibraryMomentUtility from '@thzero/library_common/utility/moment.js';
|
|
6
|
+
import BaseClientGrpcService from '../client.js';
|
|
7
|
+
|
|
8
|
+
// dayjs.utc() only exists once the plugins are registered; the app does this at
|
|
9
|
+
// boot, so anything calling getTimestamp() outside a booted app must do it too.
|
|
10
|
+
LibraryMomentUtility.initDateTime();
|
|
11
|
+
|
|
12
|
+
const inject = (target, name, value) => {
|
|
13
|
+
Object.defineProperty(target, name, { value, writable: true, configurable: true });
|
|
14
|
+
return target;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const newLogger = () => ({ debug() {}, info() {}, info2() {}, warn() {}, error() {}, exception() {}, fatal() {}, trace() {} });
|
|
18
|
+
|
|
19
|
+
let service;
|
|
20
|
+
|
|
21
|
+
beforeEach(() => {
|
|
22
|
+
service = new BaseClientGrpcService();
|
|
23
|
+
inject(service, '_logger', newLogger());
|
|
24
|
+
inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1' }) });
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe('_host', () => {
|
|
28
|
+
it('requires a key', async () => {
|
|
29
|
+
await assert.rejects(() => service._host('cid', null, null), /key is empty/);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// Regression: the guard read `!String.url(opts.url)`, and String.url does not
|
|
33
|
+
// exist - library_common/utility/string.js declares capitalize, isNullOrEmpty,
|
|
34
|
+
// isString and trim. Every call carrying a url threw
|
|
35
|
+
// `TypeError: String.url is not a function`.
|
|
36
|
+
it('takes the url straight from opts', async () => {
|
|
37
|
+
const host = await service._host('cid', 'key', { url: 'http://given:1', secure: true });
|
|
38
|
+
assert.deepEqual(host, { url: 'http://given:1', secure: true });
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('prefers a resource in opts over a url', async () => {
|
|
42
|
+
const host = await service._host('cid', 'key', {
|
|
43
|
+
url: 'http://ignored:1',
|
|
44
|
+
resource: { address: 'from-resource', grpc: { port: 9000 } }
|
|
45
|
+
});
|
|
46
|
+
assert.equal(host.url, 'from-resource:9000');
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('falls back to config when there are no opts at all', async () => {
|
|
50
|
+
const host = await service._host('cid', 'key', null);
|
|
51
|
+
assert.equal(host.url, 'http://backend:1');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
// Known gap: opts that carry neither a resource nor a url do NOT fall back to
|
|
55
|
+
// config - the host comes back empty. Pinning current behaviour.
|
|
56
|
+
it('returns an empty host for opts with neither a resource nor a url', async () => {
|
|
57
|
+
assert.deepEqual(await service._host('cid', 'key', {}), { url: null, secure: false });
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe('_hostFromConfig', () => {
|
|
62
|
+
const host = () => ({ url: null, secure: false });
|
|
63
|
+
|
|
64
|
+
it('uses the configured base url when discovery is off', async () => {
|
|
65
|
+
const result = await service._hostFromConfig('cid', host(), 'key', null);
|
|
66
|
+
assert.equal(result.url, 'http://backend:1');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('uses the configured base url when no discovery service is wired up', async () => {
|
|
70
|
+
inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc' } }) });
|
|
71
|
+
const result = await service._hostFromConfig('cid', host(), 'key', null);
|
|
72
|
+
assert.equal(result.url, 'http://backend:1');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('uses the configured base url when discovery is explicitly disabled', async () => {
|
|
76
|
+
inject(service, '_config', {
|
|
77
|
+
getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc', enabled: false } })
|
|
78
|
+
});
|
|
79
|
+
service._serviceDiscoveryResources = { getService: async () => { throw new Error('must not be called'); } };
|
|
80
|
+
const result = await service._hostFromConfig('cid', host(), 'key', null);
|
|
81
|
+
assert.equal(result.url, 'http://backend:1');
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('resolves and caches a discovered host', async () => {
|
|
85
|
+
let lookups = 0;
|
|
86
|
+
inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc' } }) });
|
|
87
|
+
service._serviceDiscoveryResources = {
|
|
88
|
+
getService: async () => { lookups++; return { success: true, results: { address: 'discovered', grpc: { port: 9000 } } }; }
|
|
89
|
+
};
|
|
90
|
+
const first = await service._hostFromConfig('cid', host(), 'key', null);
|
|
91
|
+
const second = await service._hostFromConfig('cid', host(), 'key', null);
|
|
92
|
+
assert.equal(first.url, 'discovered:9000');
|
|
93
|
+
assert.equal(lookups, 1, 'the second call came from the cache');
|
|
94
|
+
assert.equal(second, first);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('returns null when discovery fails', async () => {
|
|
98
|
+
inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc' } }) });
|
|
99
|
+
service._serviceDiscoveryResources = { getService: async () => ({ success: false }) };
|
|
100
|
+
assert.equal(await service._hostFromConfig('cid', host(), 'key', null), null);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
// Regression: a failure cached nothing, so every call after it took the mutex
|
|
104
|
+
// and asked discovery again, one at a time.
|
|
105
|
+
it('does not ask discovery again for a failed key within the retry window', async () => {
|
|
106
|
+
let lookups = 0;
|
|
107
|
+
inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc' } }) });
|
|
108
|
+
service._serviceDiscoveryResources = { getService: async () => { lookups++; return { success: false }; } };
|
|
109
|
+
assert.equal(await service._hostFromConfig('cid', host(), 'key', null), null);
|
|
110
|
+
assert.equal(await service._hostFromConfig('cid', host(), 'key', null), null);
|
|
111
|
+
assert.equal(await service._hostFromConfig('cid', host(), 'key', null), null);
|
|
112
|
+
assert.equal(lookups, 1);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('asks again once the retry window has passed, and forgets the failure on success', async () => {
|
|
116
|
+
let lookups = 0;
|
|
117
|
+
let succeed = false;
|
|
118
|
+
inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc' } }) });
|
|
119
|
+
service._serviceDiscoveryResources = {
|
|
120
|
+
getService: async () => { lookups++; return succeed ? { success: true, results: { address: 'up', grpc: { port: 1 } } } : { success: false }; }
|
|
121
|
+
};
|
|
122
|
+
service._hostsRetryMs = 0;
|
|
123
|
+
assert.equal(await service._hostFromConfig('cid', host(), 'key', null), null);
|
|
124
|
+
succeed = true;
|
|
125
|
+
const result = await service._hostFromConfig('cid', host(), 'key', null);
|
|
126
|
+
assert.equal(result.url, 'up:1');
|
|
127
|
+
assert.equal(lookups, 2);
|
|
128
|
+
assert.equal(service._hostsFailed.has('key'), false);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('shares one discovery between concurrent calls for the same key', async () => {
|
|
132
|
+
let lookups = 0;
|
|
133
|
+
let release;
|
|
134
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
135
|
+
inject(service, '_config', { getBackend: () => ({ baseUrl: 'http://backend:1', discoverable: { name: 'svc' } }) });
|
|
136
|
+
service._serviceDiscoveryResources = {
|
|
137
|
+
getService: async () => { lookups++; await gate; return { success: true, results: { address: 'discovered', grpc: { port: 9000 } } }; }
|
|
138
|
+
};
|
|
139
|
+
const pending = Promise.all([ service._hostFromConfig('a', host(), 'key', null), service._hostFromConfig('b', host(), 'key', null) ]);
|
|
140
|
+
release();
|
|
141
|
+
const [ first, second ] = await pending;
|
|
142
|
+
assert.equal(lookups, 1);
|
|
143
|
+
assert.equal(second, first);
|
|
144
|
+
assert.equal(service._hostsPending.size, 0);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
// The single mutex serialized every key behind whichever was in flight.
|
|
148
|
+
it('does not hold one key\'s discovery behind another\'s', async () => {
|
|
149
|
+
let release;
|
|
150
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
151
|
+
inject(service, '_config', { getBackend: (correlationId, key) => ({ baseUrl: 'http://backend:1', discoverable: { name: key } }) });
|
|
152
|
+
service._serviceDiscoveryResources = {
|
|
153
|
+
getService: async (correlationId, name) => {
|
|
154
|
+
if (name === 'slow')
|
|
155
|
+
await gate;
|
|
156
|
+
return { success: true, results: { address: name, grpc: { port: 1 } } };
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
const slow = service._hostFromConfig('cid', host(), 'slow', null);
|
|
160
|
+
const fast = await service._hostFromConfig('cid', host(), 'fast', null);
|
|
161
|
+
assert.equal(fast.url, 'fast:1', 'resolved while the slow one is still in flight');
|
|
162
|
+
release();
|
|
163
|
+
assert.equal((await slow).url, 'slow:1');
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it('rejects a config without a base url', async () => {
|
|
167
|
+
inject(service, '_config', { getBackend: () => ({}) });
|
|
168
|
+
await assert.rejects(() => service._hostFromConfig('cid', host(), 'key', null), /config.baseUrl is empty/);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
describe('_hostFromResource', () => {
|
|
173
|
+
const host = () => ({ url: null, secure: false });
|
|
174
|
+
|
|
175
|
+
it('joins address and port', async () => {
|
|
176
|
+
const result = await service._hostFromResource('cid', host(), { address: 'a', grpc: { port: 1 } });
|
|
177
|
+
assert.equal(result.url, 'a:1');
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it('omits a missing port', async () => {
|
|
181
|
+
const result = await service._hostFromResource('cid', host(), { address: 'a', grpc: {} });
|
|
182
|
+
assert.equal(result.url, 'a');
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it('carries the secure flag off the grpc block', async () => {
|
|
186
|
+
assert.equal((await service._hostFromResource('cid', host(), { address: 'a', grpc: { secure: true } })).secure, true);
|
|
187
|
+
assert.equal((await service._hostFromResource('cid', host(), { address: 'a', grpc: {} })).secure, false);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('assembles a dns name from label, namespace and local', async () => {
|
|
191
|
+
const result = await service._hostFromResource('cid', host(),
|
|
192
|
+
{ dns: { label: 'svc', namespace: 'ns', local: true }, grpc: { port: 1 } });
|
|
193
|
+
assert.equal(result.url, 'svc.ns.local:1');
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it('assembles a dns name that is neither namespaced nor local', async () => {
|
|
197
|
+
const result = await service._hostFromResource('cid', host(), { dns: { label: 'svc' }, grpc: {} });
|
|
198
|
+
assert.equal(result.url, 'svc');
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('rejects a resource with no grpc block and one with no address', async () => {
|
|
202
|
+
await assert.rejects(() => service._hostFromResource('cid', host(), { address: 'a' }), /resource.grpc is null/);
|
|
203
|
+
await assert.rejects(() => service._hostFromResource('cid', host(), { grpc: {} }), /address is null/);
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
describe('_execute', () => {
|
|
208
|
+
it('requires a function', async () => {
|
|
209
|
+
await assert.rejects(() => service._execute('cid', null, {}, {}), /func is null/);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it('resolves with the response the callback is given', async () => {
|
|
213
|
+
const func = function (request, meta, callback) { callback(null, { echoed: request.a }); };
|
|
214
|
+
assert.deepEqual(await service._execute('cid', func, {}, { a: 1 }), { echoed: 1 });
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it('rejects with the error the callback is given', async () => {
|
|
218
|
+
const func = function (request, meta, callback) { callback(new Error('boom')); };
|
|
219
|
+
await assert.rejects(() => service._execute('cid', func, {}, {}), /boom/);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it('sends the correlationId as metadata', async () => {
|
|
223
|
+
let seen = null;
|
|
224
|
+
const func = function (request, meta, callback) { seen = meta.get('correlationId'); callback(null, {}); };
|
|
225
|
+
await service._execute('cid-123', func, {}, {});
|
|
226
|
+
assert.deepEqual(seen, [ 'cid-123' ]);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it('calls the function with the client as its receiver', async () => {
|
|
230
|
+
const client = { marker: 'me' };
|
|
231
|
+
let receiver = null;
|
|
232
|
+
const func = function (request, meta, callback) { receiver = this; callback(null, {}); };
|
|
233
|
+
await service._execute('cid', func, client, {});
|
|
234
|
+
assert.equal(receiver, client);
|
|
235
|
+
});
|
|
236
|
+
});
|
|
@@ -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
|
+
});
|