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