@thzero/library_server_service_grpc 0.19.7 → 0.19.8

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,121 +1,141 @@
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
- ```
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, host)` | Calls a generated stub method as a promise, attaching the correlationId as gRPC metadata, and `host.apiKey` as `authorization` metadata when the host has one. |
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(host)` | Returns the channel credentials: TLS unless `host.secure` is `false`. `host.ca` (PEM) overrides the system root certificates. |
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)` | Checks the `authorization` metadata against `grpc.auth.apiKey` and returns the correlationId. Throws with code `UNAUTHENTICATED` otherwise. |
55
+ | `_authenticateValidate(correlationId, authorization, call)` | The check itself. Override it to authenticate some other way. |
56
+ | `_handleError(correlationId, err, callback)` | Turns an error into the `{ code, message }` shape a gRPC callback expects. An error with a numeric gRPC status `code` keeps it, with `name` and `message` combined. Any other error is logged, and the caller gets `INTERNAL` with `Internal error.` so internal details stay on the server. |
57
+
58
+ The key is compared in constant time, and an optional `Bearer ` prefix is accepted. With no key configured every call is rejected, unless `grpc.auth.required` is explicitly `false`.
59
+
60
+ ## Configuration
61
+
62
+ ### Server
63
+
64
+ ```json
65
+ {
66
+ "app": {
67
+ "grpc": {
68
+ "port": 50051,
69
+ "host": "0.0.0.0",
70
+ "auth": {
71
+ "apiKey": "<key>"
72
+ },
73
+ "tls": {
74
+ "key": "/path/to/server.key",
75
+ "cert": "/path/to/server.crt",
76
+ "ca": "/path/to/ca.crt",
77
+ "clientCertificateRequired": false
78
+ }
79
+ }
80
+ }
81
+ }
82
+ ```
83
+
84
+ A missing `grpc` block or `grpc.port` fails at boot.
85
+
86
+ * **`host`**: the address to bind. Defaults to `0.0.0.0`.
87
+ * **`auth.apiKey`**: the key callers must send. A list is accepted, so a key can be rotated without downtime. Set `auth.required` to `false` to allow unauthenticated calls.
88
+ * **`tls`**: `key` and `cert` are required. Each of `key`, `cert` and `ca` is a file path or a PEM string. With `ca` set, `clientCertificateRequired` turns on mutual TLS.
89
+ * **`insecure`**: without `tls`, the server refuses to start unless `insecure` is `true`. Use it only on a trusted network or behind a proxy that terminates TLS.
90
+
91
+ ### Client
92
+
93
+ Per-backend, read through `_config.getBackend(correlationId, key)`:
94
+
95
+ ```json
96
+ {
97
+ "app": {
98
+ "backend": {
99
+ "<key>": {
100
+ "baseUrl": "service-host:50051",
101
+ "apiKey": "<key>",
102
+ "secure": true,
103
+ "discoverable": {
104
+ "name": "<discovery service name>",
105
+ "enabled": true
106
+ }
107
+ }
108
+ }
109
+ }
110
+ }
111
+ ```
112
+
113
+ * **`baseUrl`** — used directly when discovery is off or unavailable.
114
+ * **`apiKey`**: sent as `authorization` metadata by `_execute` when the host is passed to it.
115
+ * **`secure`**: TLS unless this is `false`. A discovered resource is secure unless its `grpc.secure` is `false`.
116
+ * **`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`.
117
+ * **`discoverable.name`** — the name looked up in discovery. Required once discovery is active.
118
+
119
+ ## Wiring it up
120
+
121
+ ```js
122
+ import BaseClientGrpcService from '@thzero/library_server_service_grpc/client.js';
123
+
124
+ class InventoryClientService extends BaseClientGrpcService {
125
+ async fetch(correlationId, id) {
126
+ const host = await this._host(correlationId, 'inventory');
127
+ const client = new InventoryClient(host.url, this._credentials(host));
128
+ return await this._execute(correlationId, client.fetch, client, { id }, host);
129
+ }
130
+ }
131
+ ```
132
+
133
+ 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.
134
+
135
+ ## Development
136
+
137
+ ```
138
+ npm run lint # eslint .
139
+ npm run lint:fix # eslint . --fix
140
+ npm test # node --test "test/*.test.js"
141
+ ```
package/SECURITY.md ADDED
@@ -0,0 +1,29 @@
1
+ # Security policy
2
+
3
+ ## Supported versions
4
+
5
+ | Version | Supported |
6
+ |---|---|
7
+ | 0.19.x | Yes |
8
+ | Older | No |
9
+
10
+ Only the latest minor release receives security fixes. Upgrade before reporting.
11
+
12
+ ## Reporting a vulnerability
13
+
14
+ Do not open a public issue for a security problem.
15
+
16
+ Report it privately through [GitHub security advisories](https://github.com/thzero/library_server_service_grpc/security/advisories/new). Include:
17
+
18
+ - the version of `@thzero/library_server_service_grpc` affected
19
+ - a description of the problem and its impact
20
+ - steps or code to reproduce it
21
+
22
+ You should get an acknowledgment within 7 days. Once a fix is released the advisory is published with credit to the reporter, unless you ask otherwise.
23
+
24
+ ## Deployment notes
25
+
26
+ - Configure `grpc.auth.apiKey` on the server. With no key, every call is rejected. Setting `grpc.auth.required` to `false` disables the check; do that only on a trusted private network.
27
+ - Configure `grpc.tls` on the server. Without it the server refuses to start unless `grpc.insecure` is `true`, which belongs only behind a proxy that terminates TLS.
28
+ - Clients use TLS unless a backend sets `secure: false`.
29
+ - Treat `apiKey` values as secrets: keep them in environment variables or a secret store.
package/client.js CHANGED
@@ -1,166 +1,181 @@
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;
1
+ import { Buffer } from 'node:buffer';
2
+
3
+ import * as grpc from '@grpc/grpc-js';
4
+
5
+ import LibraryCommonUtility from '@thzero/library_common/utility/index.js';
6
+ import LibraryMomentUtility from '@thzero/library_common/utility/moment.js';
7
+
8
+ import LibraryServerConstants from '@thzero/library_server/constants.js';
9
+
10
+ import Service from '@thzero/library_server/service/index.js';
11
+
12
+ class BaseClientGrpcService extends Service {
13
+ constructor() {
14
+ super();
15
+
16
+ this._serviceDiscoveryResources = null;
17
+
18
+ // key -> discovered host. A failed discovery is remembered by time so a
19
+ // backend that is down is asked about once per retry window rather than on
20
+ // every call, and a discovery in flight is shared by the calls that arrive
21
+ // while it runs.
22
+ this._hosts = new Map();
23
+ this._hostsFailed = new Map();
24
+ this._hostsPending = new Map();
25
+ this._hostsRetryMs = 5 * 1000;
26
+ }
27
+
28
+ async init(injector) {
29
+ await super.init(injector);
30
+
31
+ this._serviceDiscoveryResources = this._injector.getService(LibraryServerConstants.InjectorKeys.SERVICE_DISCOVERY_RESOURCES);
32
+ }
33
+
34
+ async _execute(correlationId, func, client, request, host) {
35
+ this._enforceNotNull('BaseClientGrpcService', '_execute', func, 'func', correlationId);
36
+
37
+ const meta = new grpc.Metadata();
38
+ meta.add('correlationId', correlationId);
39
+ if (host && !String.isNullOrEmpty(host.apiKey))
40
+ meta.add('authorization', host.apiKey);
41
+
42
+ return await new Promise((resolve, reject) => {
43
+ func.call(client, request, meta, function(err, response) {
44
+ if (err) {
45
+ reject(err);
46
+ return;
47
+ }
48
+
49
+ resolve(response);
50
+ });
51
+ });
52
+ }
53
+
54
+ _credentials(host) {
55
+ if (host && (host.secure === false))
56
+ return grpc.credentials.createInsecure();
57
+
58
+ const ca = host && host.ca ? Buffer.from(String(host.ca)) : null;
59
+ return grpc.credentials.createSsl(ca);
60
+ }
61
+
62
+ async _host(correlationId, key, opts) {
63
+ this._enforceNotEmpty('BaseClientGrpcService', '_host', key, 'key', correlationId);
64
+
65
+ let host = {
66
+ url: null,
67
+ secure: true
68
+ };
69
+
70
+ if (opts) {
71
+ if (opts.resource)
72
+ host = await this._hostFromResource(correlationId, host, opts.resource, opts);
73
+ else if (!String.isNullOrEmpty(opts.url)) {
74
+ host.url = opts.url;
75
+ host.secure = opts.secure !== false;
76
+ if (!String.isNullOrEmpty(opts.apiKey))
77
+ host.apiKey = opts.apiKey;
78
+ }
79
+ }
80
+ else
81
+ host = await this._hostFromConfig(correlationId, host, key, opts);
82
+
83
+ return host;
84
+ }
85
+
86
+ async _hostFromConfig(correlationId, host, key, opts) {
87
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', host, 'host', correlationId);
88
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', key, 'key', correlationId);
89
+
90
+ const config = this._config.getBackend(correlationId, key);
91
+ this._enforceNotNull('BaseClientGrpcService', '_hostFromConfig', config, 'config', correlationId);
92
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromConfig', config.baseUrl, 'config.baseUrl', correlationId);
93
+
94
+ host.url = config.baseUrl;
95
+ host.secure = config.secure !== false;
96
+ if (!String.isNullOrEmpty(config.apiKey))
97
+ host.apiKey = config.apiKey;
98
+
99
+ this._logger.debug('BaseServerGrpcService', '_host', 'config.discoverable', config.discoverable, correlationId);
100
+ if (!config.discoverable)
101
+ return host;
102
+
103
+ this._logger.debug('BaseServerGrpcService', '_host', '_serviceDiscoveryResources', LibraryCommonUtility.isNotNull(this._serviceDiscoveryResources), correlationId);
104
+ if (!(this._serviceDiscoveryResources && config.discoverable))
105
+ return host;
106
+
107
+ this._logger.debug('BaseServerGrpcService', '_host', 'config.discoverable.enabled', config.discoverable.enabled, correlationId);
108
+ const enabled = config.discoverable.enabled === false ? false : true;
109
+ this._logger.debug('BaseServerGrpcService', '_host', 'enabled', enabled, correlationId);
110
+ if (!enabled)
111
+ return host;
112
+
113
+ const discovered = this._hosts.get(key);
114
+ if (discovered)
115
+ return discovered;
116
+
117
+ // A failure used to cache nothing, so every call after it took the mutex
118
+ // and asked discovery again, one at a time.
119
+ const failed = this._hostsFailed.get(key);
120
+ if (failed && ((LibraryMomentUtility.getTimestamp() - failed) < this._hostsRetryMs))
121
+ return null;
122
+
123
+ // One discovery per key at a time. Calls for the same key share it; calls
124
+ // for other keys are not held up by it, which the single mutex did.
125
+ let pending = this._hostsPending.get(key);
126
+ if (!pending) {
127
+ pending = this._hostDiscover(correlationId, host, config, key)
128
+ .finally(() => {
129
+ this._hostsPending.delete(key);
130
+ });
131
+ this._hostsPending.set(key, pending);
132
+ }
133
+ return await pending;
134
+ }
135
+
136
+ async _hostDiscover(correlationId, host, config, key) {
137
+ this._enforceNotNull('BaseClientGrpcService', '_host', config.discoverable.name, 'discoveryName', correlationId);
138
+
139
+ const response = await this._serviceDiscoveryResources.getService(correlationId, config.discoverable.name);
140
+ if (this._hasFailed(response)) {
141
+ this._hostsFailed.set(key, LibraryMomentUtility.getTimestamp());
142
+ return null;
143
+ }
144
+
145
+ host = await this._hostFromResource(correlationId, host, response.results);
146
+ if (!String.isNullOrEmpty(config.apiKey))
147
+ host.apiKey = config.apiKey;
148
+
149
+ this._hosts.set(key, host);
150
+ this._hostsFailed.delete(key);
151
+ return host;
152
+ }
153
+
154
+ async _hostFromResource(correlationId, host, resource, opts) {
155
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromResource', host, 'host', correlationId);
156
+ this._enforceNotEmpty('BaseClientGrpcService', '_hostFromResource', resource, 'resource', correlationId);
157
+ this._enforceNotNull('BaseClientGrpcService', '_hostFromResource', resource.grpc, 'resource.grpc', correlationId);
158
+
159
+ let port = resource.grpc.port ? resource.grpc.port : null;
160
+ host.secure = resource.grpc.secure !== false;
161
+
162
+ let address = resource.address;
163
+ if (resource.dns) {
164
+ const temp = [];
165
+ temp.push(resource.dns.label);
166
+ if (!String.isNullOrEmpty(resource.dns.namespace))
167
+ temp.push(resource.dns.namespace);
168
+ if (resource.dns.local)
169
+ temp.push('local');
170
+ address = temp.join('.');
171
+ }
172
+
173
+ this._enforceNotNull('BaseClientGrpcService', '_hostFromResource', address, 'address', correlationId);
174
+
175
+ host.url = `${address}${port ? `:${port}` : ''}`;
176
+
177
+ return host;
178
+ }
179
+ }
180
+
181
+ export default BaseClientGrpcService;