node24-jmx25 0.0.0-stage → 0.8.0-dev

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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2013-2015 Xabier de Zuazo
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # node18-jmx
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node.js client for reading and managing Java applications through JMX. The package runs a small Java sidecar and exchanges newline-delimited JSON messages with it over the child process's standard input and output.
4
+
5
+ ## Requirements
6
+
7
+ - Node.js 24 LTS or later.
8
+ - Java 25 or later at runtime.
9
+ - Maven and JDK 25 to build the Java sidecar from a source checkout. Published npm packages include the built sidecar JAR.
10
+
11
+ ## Installation
12
+
13
+ ```sh
14
+ npm install node24-jmx25
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ The public API exposes both an `async`/`await` surface and the historical callback form. Every operation returns a `Promise` and still invokes the optional trailing callback with the decoded value when the request succeeds.
20
+
21
+ ```js
22
+ const jmx = require("node24-jmx25");
23
+
24
+ async function main() {
25
+ const client = jmx.createClient({ host: "localhost", port: 3000 });
26
+ client.on("error", (error) => console.error(error));
27
+
28
+ await client.connect();
29
+ const memory = await client.getAttribute("java.lang:type=Memory", "HeapMemoryUsage");
30
+ console.log(memory.getSync("used"));
31
+ await client.disconnect();
32
+ }
33
+
34
+ main();
35
+ ```
36
+
37
+ An explicit JMX service URL and credentials may be passed instead:
38
+
39
+ ```js
40
+ const client = jmx.createClient({
41
+ service: "service:jmx:rmi://localhost:3000/jndi/rmi://localhost:3000/jmxrmi",
42
+ username: "monitor",
43
+ password: "secret"
44
+ });
45
+ ```
46
+
47
+ ## Client API
48
+
49
+ `createClient(options)` accepts:
50
+
51
+ - `service`: full JMX service URL. If provided, `host` and `port` are ignored.
52
+ - `host`: hostname (defaults to `localhost`).
53
+ - `port`: JMX port (required when `service` is not provided).
54
+ - `protocol`: JMX protocol (defaults to `rmi`).
55
+ - `urlPath`: optional JMX URL path.
56
+ - `username` and `password`: optional JMX credentials.
57
+ - `classpath`: optional array of local Java classpath entries, needed when operation signatures use application-specific classes.
58
+ - `requestTimeoutMs`: per-request timeout in milliseconds (default `30000`; `0` disables).
59
+ - `stderrFailFastBytes`: cumulative size of JVM stderr output after which the sidecar is terminated and all pending requests reject with a flood error (default `1048576`; `0` disables the guard).
60
+ - `debug`: a function `(label, payload) => void` that receives every protocol send and receive. Pass `true` or set `DEBUG=node24-jmx25` to log through `console.error` instead.
61
+
62
+ The returned EventEmitter exposes:
63
+
64
+ - `connect()` and `disconnect()` manage the sidecar and the JMX connection. Both return a `Promise`. `connect()` additionally emits the `connect` event on success.
65
+ - `getAttribute(mbean, attribute, [callback])`
66
+ - `getAttributes(mbean, attributes, [callback])`
67
+ - `getDefaultDomain([callback])`
68
+ - `getDomains([callback])`
69
+ - `getMBeanCount([callback])`
70
+ - `listMBeans([pattern,] [callback])`
71
+ - `invoke(mbean, methodName, params, [signature,] [callback])`
72
+ - `setAttribute(mbean, attribute, value, [className,] [callback])`
73
+ - `addNotificationListener(mbean)` and `removeNotificationListener(subscriptionId)`
74
+ - Events: `connect`, `disconnect`, `error`, `notification`.
75
+
76
+ Promises reject with the Java error class name in `error.name`; the Java stack trace is attached as `error.javaStack` when the sidecar supplied one. If a callback is provided and the request succeeds, the callback receives the decoded value as its only argument.
77
+
78
+ ### Value decoding
79
+
80
+ - Java `long` values that fit into `Number.MAX_SAFE_INTEGER` are returned as plain JavaScript numbers. Values outside that range are wrapped as `{ longValue: "<decimal>" }` to preserve exactness. The legacy pattern `value.longValue` keeps working for the wrapped form, and plain-number comparisons work for the common case.
81
+ - `CompositeData` values are returned as a wrapper with `getSync(key)`, which throws when `key` is unknown. The wrapper also exposes `keys()` and serializes to its items on `JSON.stringify`.
82
+ - `TabularData` collapses to an array of `CompositeData` rows.
83
+ - Java `Map` values whose keys are all strings are returned as plain objects. Maps with non-string keys are returned as arrays of `[key, value]` pairs to avoid lossy key coercion.
84
+ - Other Java objects are returned as `{ className, value }` where `value` is the result of `toString()`.
85
+ - Java arrays and `Iterable` values are returned as JavaScript arrays.
86
+
87
+ ### Notifications
88
+
89
+ ```js
90
+ const subscriptionId = await client.addNotificationListener("test.jmx:type=Counter");
91
+ client.on("notification", (event) => {
92
+ console.log(event.notification.type, event.notification.message);
93
+ });
94
+ ```
95
+
96
+ Each `notification` payload includes `subscriptionId`, `mbean`, and `notification` with the decoded JMX `Notification` fields.
97
+
98
+ ## Building and testing from source
99
+
100
+ ```sh
101
+ npm test
102
+ ```
103
+
104
+ `npm test` builds the sidecar before running the tests. `npm pack` and `npm publish` also build it automatically through the `prepack` script. Maven downloads the pinned Jackson dependency during the build.
105
+
106
+ Continuous integration is defined in [.github/workflows/ci.yml](.github/workflows/ci.yml) and runs the same build/test pipeline on every push and pull request.
107
+
108
+ ## Debug logging
109
+
110
+ Set the environment variable `DEBUG=node24-jmx25` or pass `debug: true` to `createClient` to log each JSON-RPC request and response to `stderr`. For custom routing supply `debug: (label, payload) => void`.
111
+
112
+ ## Security
113
+
114
+ JMX credentials are sent only through the sidecar's local process pipe and are not written to logs. The pipe content is visible to the user who owns the Node.js process, which includes core dumps and process-memory snapshots of either side; prefer short-lived credentials and restrict access to the host accordingly. Use authenticated, TLS-protected JMX connections when the JMX endpoint is reachable over a network, and restrict network access to JMX ports independently of this client.
115
+
116
+ ## License
117
+
118
+ Apache-2.0. See [LICENSE](LICENSE).
package/index.js ADDED
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+
3
+ const Client = require("./lib/client");
4
+
5
+ /** Checks whether a classpath entry is empty or has an unsupported non-string value. */
6
+ function isInvalidClasspathEntry(entry) {
7
+ return typeof entry !== "string" || entry.length === 0;
8
+ }
9
+
10
+ /** Validates client options and returns a client for the requested JMX service. */
11
+ function createClient(options) {
12
+ if (!options || typeof options !== "object") {
13
+ throw new TypeError("options is required");
14
+ }
15
+ if (options.service !== undefined && typeof options.service !== "string") {
16
+ throw new TypeError("service must be a string");
17
+ }
18
+ if (options.classpath !== undefined
19
+ && (!Array.isArray(options.classpath) || options.classpath.some(isInvalidClasspathEntry))) {
20
+ throw new TypeError("classpath must be an array of Java classpath entries");
21
+ }
22
+ if (!options.service) {
23
+ const validPortInput = typeof options.port === "number"
24
+ || (typeof options.port === "string" && /^\d+$/.test(options.port));
25
+ const port = Number(options.port);
26
+ if (!validPortInput || !Number.isInteger(port) || port < 1 || port > 65535) {
27
+ throw new TypeError("a valid port is required when service is not supplied");
28
+ }
29
+ }
30
+ return new Client(options);
31
+ }
32
+
33
+ module.exports = { createClient };
package/lib/client.js ADDED
@@ -0,0 +1,544 @@
1
+ "use strict";
2
+
3
+ const { spawn } = require("node:child_process");
4
+ const { EventEmitter } = require("node:events");
5
+ const fs = require("node:fs");
6
+ const path = require("node:path");
7
+ const { fromWire, toWire } = require("./javaValues");
8
+
9
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
10
+ const STDERR_TAIL_BYTES = 8192;
11
+ const DEFAULT_STDERR_FAIL_FAST_BYTES = 1048576;
12
+
13
+ /** Creates a Node.js client that communicates with the Java JMX bridge over process pipes. */
14
+ class Client extends EventEmitter {
15
+ /** Stores connection options and initializes sidecar lifecycle and request state. */
16
+ constructor(options) {
17
+ super();
18
+ this.options = options;
19
+ this.service = buildServiceUrl(options);
20
+ this.requestTimeoutMs = options.requestTimeoutMs !== undefined
21
+ ? Number(options.requestTimeoutMs)
22
+ : DEFAULT_REQUEST_TIMEOUT_MS;
23
+ this.stderrFailFastBytes = typeof options.stderrFailFastBytes === "number"
24
+ ? options.stderrFailFastBytes
25
+ : DEFAULT_STDERR_FAIL_FAST_BYTES;
26
+ this.stderrBytes = 0;
27
+ this.debug = resolveDebug(options.debug);
28
+ this.child = null;
29
+ this.connected = false;
30
+ this.closing = false;
31
+ this.nextId = 1;
32
+ this.pending = new Map();
33
+ this.notificationHandlers = new Map();
34
+ this.writeQueue = [];
35
+ this.pumping = false;
36
+ this.drainPending = false;
37
+ this.stdoutBuffer = "";
38
+ this.stderrBuffer = Buffer.alloc(0);
39
+ this.readyPromise = null;
40
+ this.resolveReady = null;
41
+ this.rejectReady = null;
42
+ this.resolveExit = null;
43
+ this.exitPromise = null;
44
+ }
45
+
46
+ /** Starts or reuses the bridge, connects it to JMX, and emits connect on success. */
47
+ async connect() {
48
+ if (this.connected) return;
49
+ try {
50
+ await this.ensureBridge();
51
+ await this.request("connect", {
52
+ service: this.service,
53
+ username: this.options.username,
54
+ password: this.options.password
55
+ });
56
+ this.connected = true;
57
+ this.emit("connect");
58
+ } catch (error) {
59
+ if (this.child && !this.connected) {
60
+ this.closing = true;
61
+ await this.stopBridge();
62
+ this.closing = false;
63
+ }
64
+ throw error;
65
+ }
66
+ }
67
+
68
+ /** Disconnects the JMX connector, closes the sidecar, and emits disconnect after shutdown. */
69
+ async disconnect() {
70
+ if (!this.child || this.closing) return;
71
+ this.closing = true;
72
+ const wasConnected = this.connected;
73
+ let failure;
74
+ try {
75
+ if (wasConnected) {
76
+ await this.request("disconnect", {});
77
+ }
78
+ } catch (error) {
79
+ failure = error;
80
+ } finally {
81
+ this.connected = false;
82
+ await this.stopBridge();
83
+ this.closing = false;
84
+ }
85
+ if (failure) this.safeEmitError(failure);
86
+ if (wasConnected) this.emit("disconnect");
87
+ }
88
+
89
+ /** Closes the sidecar input, waits for process exit, and clears its pending lifecycle state. */
90
+ async stopBridge() {
91
+ if (!this.child) return;
92
+ const child = this.child;
93
+ try { child.stdin.end(); } catch (_) { /* input already closed */ }
94
+ await this.exitPromise;
95
+ this.child = null;
96
+ this.readyPromise = null;
97
+ this.exitPromise = null;
98
+ this.stdoutBuffer = "";
99
+ this.stderrBuffer = Buffer.alloc(0);
100
+ this.stderrBytes = 0;
101
+ this.writeQueue.length = 0;
102
+ this.pumping = false;
103
+ this.drainPending = false;
104
+ }
105
+
106
+ /** Requests one MBean attribute. Returns a Promise and invokes the optional legacy callback. */
107
+ getAttribute(mbean, attribute, callback) {
108
+ return this.dispatch("getAttribute", { mbean, attribute }, callback);
109
+ }
110
+
111
+ /** Requests multiple MBean attributes. Returns a Promise and invokes the optional legacy callback. */
112
+ getAttributes(mbean, attributes, callback) {
113
+ return this.dispatch("getAttributes", { mbean, attributes }, callback);
114
+ }
115
+
116
+ /** Requests the connected server's default domain. */
117
+ getDefaultDomain(callback) {
118
+ return this.dispatch("getDefaultDomain", {}, callback);
119
+ }
120
+
121
+ /** Requests the connected server's domains. */
122
+ getDomains(callback) {
123
+ return this.dispatch("getDomains", {}, callback);
124
+ }
125
+
126
+ /** Requests the connected server's MBean count. */
127
+ getMBeanCount(callback) {
128
+ return this.dispatch("getMBeanCount", {}, callback);
129
+ }
130
+
131
+ /** Invokes an MBean operation while preserving the optional-signature callback overload. */
132
+ invoke(mbean, methodName, params, signatureOrCallback, callback) {
133
+ let signature = signatureOrCallback;
134
+ if (typeof signatureOrCallback === "function") {
135
+ callback = signatureOrCallback;
136
+ signature = undefined;
137
+ }
138
+ let values;
139
+ let types;
140
+ try {
141
+ values = params || [];
142
+ types = signature || values.map(inferJavaType);
143
+ } catch (error) {
144
+ return this.failPromise(error);
145
+ }
146
+ return this.dispatch("invoke", {
147
+ mbean,
148
+ methodName,
149
+ params: values.map(toWire),
150
+ signature: types
151
+ }, callback);
152
+ }
153
+
154
+ /** Lists canonical MBean names, optionally filtered by an ObjectName pattern. */
155
+ listMBeans(mbean, callback) {
156
+ if (typeof mbean === "function") {
157
+ callback = mbean;
158
+ mbean = undefined;
159
+ }
160
+ return this.dispatch("listMBeans", { mbean }, callback);
161
+ }
162
+
163
+ /** Sets an attribute and preserves the optional-class-name callback overload. */
164
+ setAttribute(mbean, attribute, value, classNameOrCallback, callback) {
165
+ let className = classNameOrCallback;
166
+ if (typeof classNameOrCallback === "function") {
167
+ callback = classNameOrCallback;
168
+ className = inferJavaType(value);
169
+ }
170
+ let encoded;
171
+ try {
172
+ encoded = toWire(value);
173
+ } catch (error) {
174
+ return this.failPromise(error);
175
+ }
176
+ return this.dispatch("setAttribute", {
177
+ mbean,
178
+ attribute,
179
+ value: encoded,
180
+ className: className || inferJavaType(value)
181
+ }, callback);
182
+ }
183
+
184
+ /** Subscribes to JMX notifications from an MBean and returns the subscription identifier. */
185
+ async addNotificationListener(mbean) {
186
+ if (typeof mbean !== "string" || mbean.length === 0) {
187
+ throw new TypeError("mbean must be a non-empty ObjectName string");
188
+ }
189
+ const subscriptionId = await this.request("addNotificationListener", { mbean });
190
+ this.notificationHandlers.set(subscriptionId, { mbean });
191
+ return subscriptionId;
192
+ }
193
+
194
+ /** Removes an active JMX notification subscription from both sides of the bridge. */
195
+ async removeNotificationListener(subscriptionId) {
196
+ this.notificationHandlers.delete(subscriptionId);
197
+ await this.request("removeNotificationListener", { subscriptionId });
198
+ }
199
+
200
+ /** Routes an operation through the bridge, decodes the result, and signals both API styles. */
201
+ async dispatch(method, params, callback) {
202
+ const result = await this.request(method, params);
203
+ const decoded = fromWire(result);
204
+ if (typeof callback === "function") callback(decoded);
205
+ return decoded;
206
+ }
207
+
208
+ /** Starts the packaged Java archive once and waits until its protocol is ready. */
209
+ ensureBridge() {
210
+ if (this.child) return this.readyPromise;
211
+ const jarPath = path.join(__dirname, "..", "java-bridge", "target", "jmx-bridge.jar");
212
+ if (!fs.existsSync(jarPath)) {
213
+ return Promise.reject(new Error("JMX bridge JAR is missing; run `npm run build:bridge` first"));
214
+ }
215
+ const javaCommand = process.env.JAVA_HOME
216
+ ? path.join(process.env.JAVA_HOME, "bin", process.platform === "win32" ? "java.exe" : "java")
217
+ : "java";
218
+ const classpath = [jarPath].concat(this.options.classpath || []).join(path.delimiter);
219
+ this.child = spawn(javaCommand, ["-cp", classpath, "com.insider515.jmx.JmxBridge"], {
220
+ stdio: ["pipe", "pipe", "pipe"],
221
+ windowsHide: true
222
+ });
223
+ this.stdoutBuffer = "";
224
+ this.stderrBuffer = Buffer.alloc(0);
225
+ this.stderrBytes = 0;
226
+ this.writeQueue.length = 0;
227
+ this.pumping = false;
228
+ this.drainPending = false;
229
+ this.child.stdout.setEncoding("utf8");
230
+ this.child.stdout.on("data", this.consumeStdout.bind(this));
231
+ this.child.stderr.on("data", this.captureStderr.bind(this));
232
+ this.child.stdin.on("error", this.handleProcessError.bind(this));
233
+ this.child.stdin.on("drain", this.handleStdinDrain.bind(this));
234
+ this.child.on("error", this.handleProcessError.bind(this));
235
+ this.child.on("close", this.handleProcessExit.bind(this));
236
+ this.exitPromise = new Promise(
237
+ /** Stores the process-exit resolver for disconnect cleanup. */
238
+ (resolve) => { this.resolveExit = resolve; }
239
+ );
240
+ this.readyPromise = new Promise(
241
+ /** Stores startup completion handlers until the Java bridge reports readiness. */
242
+ (resolve, reject) => {
243
+ this.resolveReady = resolve;
244
+ this.rejectReady = reject;
245
+ }
246
+ );
247
+ return this.readyPromise;
248
+ }
249
+
250
+ /** Parses sidecar output lines, handles readiness, notifications, and routes RPC responses. */
251
+ consumeStdout(chunk) {
252
+ this.stdoutBuffer += chunk;
253
+ let newline;
254
+ while ((newline = this.stdoutBuffer.indexOf("\n")) !== -1) {
255
+ const line = this.stdoutBuffer.slice(0, newline);
256
+ this.stdoutBuffer = this.stdoutBuffer.slice(newline + 1);
257
+ let message;
258
+ try {
259
+ message = JSON.parse(line);
260
+ } catch (error) {
261
+ const protocolError = new Error("Invalid JSON received from JMX bridge", { cause: error });
262
+ this.rejectPending(protocolError);
263
+ if (this.child) this.child.kill();
264
+ this.safeEmitError(protocolError);
265
+ return;
266
+ }
267
+ if (this.debug) this.debug("recv", redactForDebug(message));
268
+ if (message.event === "ready") {
269
+ if (this.resolveReady) this.resolveReady();
270
+ this.resolveReady = null;
271
+ this.rejectReady = null;
272
+ continue;
273
+ }
274
+ if (message.event === "notification") {
275
+ this.emit("notification", {
276
+ subscriptionId: message.subscriptionId,
277
+ mbean: message.mbean,
278
+ notification: fromWire(message.notification)
279
+ });
280
+ continue;
281
+ }
282
+ const id = message.id;
283
+ const pending = this.pending.get(id);
284
+ if (!pending) {
285
+ if (Number.isSafeInteger(id) && id > 0 && id < this.nextId) {
286
+ continue;
287
+ }
288
+ const protocolError = new Error("JMX bridge returned an unknown request identifier");
289
+ this.rejectPending(protocolError);
290
+ if (this.child) this.child.kill();
291
+ this.safeEmitError(protocolError);
292
+ return;
293
+ }
294
+ this.pending.delete(id);
295
+ if (message.error) {
296
+ const error = new Error(message.error.message);
297
+ error.name = message.error.name || "JmxBridgeError";
298
+ if (typeof message.error.stack === "string") error.javaStack = message.error.stack;
299
+ pending.reject(error);
300
+ } else {
301
+ pending.resolve(message.result);
302
+ }
303
+ }
304
+ }
305
+
306
+ /** Rejects process startup and outstanding requests when the Java process cannot start. */
307
+ handleProcessError(error) {
308
+ if (this.rejectReady) this.rejectReady(error);
309
+ this.rejectReady = null;
310
+ this.resolveReady = null;
311
+ this.rejectPending(error);
312
+ }
313
+
314
+ /** Rejects every unresolved bridge request after the process transport becomes unusable. */
315
+ rejectPending(error) {
316
+ for (const pending of this.pending.values()) pending.reject(error);
317
+ this.pending.clear();
318
+ for (const queued of this.writeQueue) queued.reject(error);
319
+ this.writeQueue.length = 0;
320
+ this.pumping = false;
321
+ this.drainPending = false;
322
+ }
323
+
324
+ /** Retains a bounded byte tail of JVM diagnostics and kills the sidecar when stderr flood exceeds the fail-fast cap. */
325
+ captureStderr(chunk) {
326
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
327
+ const combined = Buffer.concat([this.stderrBuffer, buffer]);
328
+ this.stderrBuffer = combined.length > STDERR_TAIL_BYTES
329
+ ? combined.subarray(combined.length - STDERR_TAIL_BYTES)
330
+ : combined;
331
+ this.stderrBytes += buffer.length;
332
+ if (this.stderrFailFastBytes > 0 && this.stderrBytes > this.stderrFailFastBytes && this.child && !this.closing) {
333
+ const limit = this.stderrFailFastBytes;
334
+ const details = this.stderrBuffer.toString("utf8").trim();
335
+ const suffix = details ? `: ${details}` : "";
336
+ const floodError = new Error(
337
+ `JMX bridge stderr exceeded the fail-fast threshold of ${limit} bytes${suffix}`);
338
+ this.stderrBytes = 0;
339
+ this.rejectPending(floodError);
340
+ try { this.child.kill("SIGKILL"); } catch (_) { /* process already exiting */ }
341
+ this.safeEmitError(floodError);
342
+ }
343
+ }
344
+
345
+ /** Handles sidecar termination and reports unexpected exits to the public error event. */
346
+ handleProcessExit(code, signal) {
347
+ const details = this.stderrBuffer.toString("utf8").trim();
348
+ const suffix = details ? `: ${details}` : "";
349
+ const error = new Error(`JMX bridge exited unexpectedly (code ${code}, signal ${signal})${suffix}`);
350
+ if (this.rejectReady) this.rejectReady(error);
351
+ this.rejectReady = null;
352
+ this.resolveReady = null;
353
+ for (const pending of this.pending.values()) pending.reject(error);
354
+ this.pending.clear();
355
+ for (const queued of this.writeQueue) queued.reject(error);
356
+ this.writeQueue.length = 0;
357
+ this.pumping = false;
358
+ if (this.resolveExit) this.resolveExit();
359
+ this.resolveExit = null;
360
+ const wasUnexpected = !this.closing;
361
+ if (wasUnexpected) {
362
+ this.child = null;
363
+ this.readyPromise = null;
364
+ this.exitPromise = null;
365
+ this.stderrBuffer = Buffer.alloc(0);
366
+ this.stderrBytes = 0;
367
+ this.notificationHandlers.clear();
368
+ }
369
+ if (wasUnexpected && this.connected) {
370
+ this.connected = false;
371
+ this.safeEmitError(error);
372
+ this.emit("disconnect");
373
+ }
374
+ }
375
+
376
+ /** Sends one JSON-RPC request, enforces its optional timeout, and resolves the matching response. */
377
+ async request(method, params) {
378
+ if (!this.child) throw new Error("JMX bridge is not running");
379
+ if (this.readyPromise) await this.readyPromise;
380
+ if (!Number.isSafeInteger(this.nextId)) {
381
+ throw new RangeError("JMX bridge request identifier space is exhausted");
382
+ }
383
+ const id = this.nextId++;
384
+ const line = JSON.stringify({ id, method, params }) + "\n";
385
+ if (this.debug) this.debug("send", { id, method, params: redactForDebug(params) });
386
+ return new Promise(
387
+ /** Registers the response handlers and request timeout for one bridge call. */
388
+ (resolve, reject) => {
389
+ const entry = { settled: false, resolve: null, reject: null };
390
+ const timer = this.requestTimeoutMs > 0
391
+ ? setTimeout(
392
+ /** Rejects the pending request and removes it from the queue if it was still waiting to be sent. */
393
+ () => {
394
+ if (entry.settled) return;
395
+ entry.settled = true;
396
+ this.pending.delete(id);
397
+ this.removeQueuedWrite(id);
398
+ reject(new Error(`JMX bridge request timed out after ${this.requestTimeoutMs}ms (${method})`));
399
+ }, this.requestTimeoutMs)
400
+ : null;
401
+ entry.resolve = /* Resolves one bridge response and cancels its pending timeout. */ (value) => {
402
+ if (entry.settled) return;
403
+ entry.settled = true;
404
+ if (timer) clearTimeout(timer);
405
+ resolve(value);
406
+ };
407
+ entry.reject = /* Rejects one bridge response and cancels its pending timeout. */ (error) => {
408
+ if (entry.settled) return;
409
+ entry.settled = true;
410
+ if (timer) clearTimeout(timer);
411
+ reject(error);
412
+ };
413
+ this.pending.set(id, entry);
414
+ this.enqueueWrite(id, line).catch(/** Fails the pending request when the pipe write cannot be enqueued. */ (error) => {
415
+ if (entry.settled) return;
416
+ entry.settled = true;
417
+ this.pending.delete(id);
418
+ if (timer) clearTimeout(timer);
419
+ reject(error);
420
+ });
421
+ }
422
+ );
423
+ }
424
+
425
+ /** Removes a queued write by request id when the caller cancels before the sidecar reads it. */
426
+ removeQueuedWrite(id) {
427
+ const index = this.writeQueue.findIndex(
428
+ /** Finds the queued write matching the cancelled request id. */
429
+ (entry) => entry.id === id
430
+ );
431
+ if (index === -1) return false;
432
+ this.writeQueue.splice(index, 1);
433
+ return true;
434
+ }
435
+
436
+ /** Serializes writes to the sidecar through a drain-aware queue to prevent runaway buffering. */
437
+ enqueueWrite(id, line) {
438
+ return new Promise(
439
+ /** Adds the write to the serialized queue and starts the pump if idle. */
440
+ (resolve, reject) => {
441
+ this.writeQueue.push({ id, line, resolve, reject });
442
+ this.pumpWriteQueue();
443
+ }
444
+ );
445
+ }
446
+
447
+ /** Flushes queued writes to stdin while honoring the stream's drain backpressure signal. */
448
+ pumpWriteQueue() {
449
+ if (this.pumping || this.drainPending || this.writeQueue.length === 0 || !this.child) return;
450
+ this.pumping = true;
451
+ while (this.writeQueue.length > 0) {
452
+ const entry = this.writeQueue[0];
453
+ let canContinue;
454
+ try {
455
+ canContinue = this.child.stdin.write(entry.line);
456
+ } catch (error) {
457
+ this.writeQueue.shift();
458
+ entry.reject(error);
459
+ continue;
460
+ }
461
+ this.writeQueue.shift();
462
+ entry.resolve();
463
+ if (!canContinue) {
464
+ this.drainPending = true;
465
+ this.pumping = false;
466
+ return;
467
+ }
468
+ }
469
+ this.pumping = false;
470
+ }
471
+
472
+ /** Clears the drain-pending gate so queued writes can resume after the stream drains. */
473
+ handleStdinDrain() {
474
+ this.drainPending = false;
475
+ this.pumpWriteQueue();
476
+ }
477
+
478
+ /** Emits a bridge error only when a listener is attached so Node does not crash the process. */
479
+ safeEmitError(error) {
480
+ if (this.listenerCount("error") > 0) this.emit("error", error);
481
+ }
482
+
483
+ /** Produces a rejected Promise for synchronous validation failures in public methods. */
484
+ failPromise(error) {
485
+ return Promise.reject(error);
486
+ }
487
+ }
488
+
489
+ /** Infers the Java signature for values supported by the legacy API. */
490
+ function inferJavaType(value) {
491
+ if (value && typeof value.longValue !== "undefined") return "long";
492
+ if (typeof value === "string") return "java.lang.String";
493
+ if (typeof value === "boolean") return "boolean";
494
+ if (typeof value === "number") {
495
+ return Number.isInteger(value) && value >= -2147483648 && value <= 2147483647 ? "int" : "double";
496
+ }
497
+ if (Array.isArray(value)) return "[Ljava.lang.String;";
498
+ throw new TypeError(`Cannot infer Java type for ${typeof value}; provide an explicit signature`);
499
+ }
500
+
501
+ /** Creates the service URL format produced by the original Java JMXServiceURL constructor. */
502
+ function buildServiceUrl(options) {
503
+ if (typeof options.service === "string" && options.service.startsWith("service:jmx:")) {
504
+ return options.service;
505
+ }
506
+ if (typeof options.service === "string") {
507
+ throw new TypeError("service must be a JMX service URL");
508
+ }
509
+ const protocol = options.protocol || "rmi";
510
+ const host = options.host || "localhost";
511
+ const port = Number(options.port);
512
+ const pathName = options.urlPath || `/jndi/${protocol}://${host}:${port}/jmx${protocol}`;
513
+ return `service:jmx:${protocol}://${host}:${port}${pathName}`;
514
+ }
515
+
516
+ const SENSITIVE_KEYS = new Set(["password", "username", "credentials", "secret", "token"]);
517
+
518
+ /** Returns a shallow copy of a protocol payload with credential-like fields replaced by a placeholder. */
519
+ function redactForDebug(payload) {
520
+ if (!payload || typeof payload !== "object") return payload;
521
+ if (Array.isArray(payload)) return payload.map(redactForDebug);
522
+ const result = {};
523
+ for (const [key, value] of Object.entries(payload)) {
524
+ if (SENSITIVE_KEYS.has(key.toLowerCase())) {
525
+ result[key] = typeof value === "undefined" ? value : "<redacted>";
526
+ } else {
527
+ result[key] = redactForDebug(value);
528
+ }
529
+ }
530
+ return result;
531
+ }
532
+
533
+ /** Resolves the debug logger from a user hook or the DEBUG environment flag. */
534
+ function resolveDebug(hook) {
535
+ if (typeof hook === "function") return hook;
536
+ if (hook === true) return console.error.bind(console, "[node24-jmx25]");
537
+ const flag = process.env.DEBUG;
538
+ if (typeof flag === "string" && /(^|,)\s*node24-jmx25(\s*,|$)|^\*$/.test(flag)) {
539
+ return console.error.bind(console, "[node24-jmx25]");
540
+ }
541
+ return null;
542
+ }
543
+
544
+ module.exports = Client;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+
3
+ /** Wraps a Java long value while retaining its exact decimal representation. */
4
+ class JavaLong {
5
+ /** Stores the untruncated long value as a decimal string. */
6
+ constructor(value) {
7
+ this.longValue = value;
8
+ }
9
+
10
+ /** Returns the exact decimal value without converting it to a JavaScript number. */
11
+ toString() {
12
+ return this.longValue;
13
+ }
14
+ }
15
+
16
+ /** Wraps a JMX CompositeData value with the legacy synchronous lookup method. */
17
+ class JavaCompositeData {
18
+ /** Stores decoded CompositeData items for callback consumers. */
19
+ constructor(items) {
20
+ this.items = items;
21
+ }
22
+
23
+ /** Returns one named CompositeData item, matching the node-java throw-on-missing-key contract. */
24
+ getSync(key) {
25
+ if (!Object.prototype.hasOwnProperty.call(this.items, key)) {
26
+ const error = new Error(`CompositeData has no item named ${JSON.stringify(key)}`);
27
+ error.name = "CompositeDataKeyError";
28
+ throw error;
29
+ }
30
+ return this.items[key];
31
+ }
32
+
33
+ /** Reports the available CompositeData key names. */
34
+ keys() {
35
+ return Object.keys(this.items);
36
+ }
37
+
38
+ /** Exposes the decoded items when the wrapper is serialized as a plain JSON value. */
39
+ toJSON() {
40
+ return this.items;
41
+ }
42
+ }
43
+
44
+ /** Converts JSON-tagged JMX values into their callback-facing Java-compatible wrappers. */
45
+ function fromWire(value) {
46
+ if (Array.isArray(value)) {
47
+ return value.map(fromWire);
48
+ }
49
+ if (!value || typeof value !== "object") {
50
+ return value;
51
+ }
52
+ if (value.$jmxType === "Long") {
53
+ return new JavaLong(value.value);
54
+ }
55
+ if (value.$jmxType === "CompositeData") {
56
+ const items = {};
57
+ for (const [key, item] of Object.entries(value.items)) {
58
+ items[key] = fromWire(item);
59
+ }
60
+ return new JavaCompositeData(items);
61
+ }
62
+ if (value.$jmxType === "TabularData") {
63
+ return fromWire(value.rows);
64
+ }
65
+ if (value.$jmxType === "Map") {
66
+ const entries = {};
67
+ for (const [key, item] of Object.entries(value.entries)) {
68
+ entries[key] = fromWire(item);
69
+ }
70
+ return entries;
71
+ }
72
+ if (value.$jmxType === "MapTypedKeys") {
73
+ return value.pairs.map(
74
+ /** Decodes a map entry whose non-string key would otherwise be coerced by JSON. */
75
+ (pair) => [fromWire(pair[0]), fromWire(pair[1])]
76
+ );
77
+ }
78
+ if (value.$jmxType === "Object") {
79
+ return { className: value.className, value: value.value };
80
+ }
81
+ const result = {};
82
+ for (const [key, item] of Object.entries(value)) {
83
+ result[key] = fromWire(item);
84
+ }
85
+ return result;
86
+ }
87
+
88
+ /** Encodes supported Java-compatible wrappers and plain JSON values for IPC requests. */
89
+ function toWire(value) {
90
+ if (Array.isArray(value)) {
91
+ return value.map(toWire);
92
+ }
93
+ if (value && typeof value === "object" && typeof value.longValue !== "undefined") {
94
+ return String(value.longValue);
95
+ }
96
+ if (value && typeof value === "object" && typeof value.toJSON === "function") {
97
+ return toWire(value.toJSON());
98
+ }
99
+ if (value && typeof value === "object") {
100
+ const result = {};
101
+ for (const [key, item] of Object.entries(value)) {
102
+ result[key] = toWire(item);
103
+ }
104
+ return result;
105
+ }
106
+ if (typeof value === "bigint") {
107
+ return value.toString();
108
+ }
109
+ return value;
110
+ }
111
+
112
+ module.exports = { fromWire, toWire, JavaLong, JavaCompositeData };
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "node24-jmx25",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.0-dev",
4
+ "description": "Bridge library to communicate with Java applications through JMX.",
5
+ "homepage": "https://github.com/Insider515/node18-jmx",
6
+ "bugs": "https://github.com/Insider515/node18-jmx/issues",
7
+ "main": "index.js",
8
+ "scripts": {
9
+ "build:bridge": "mvn -f java-bridge/pom.xml clean package",
10
+ "prepack": "npm run build:bridge",
11
+ "test": "npm run build:bridge && node --test test/*.test.js"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/Insider515/node18-jmx.git"
16
+ },
17
+ "keywords": [
18
+ "jmx",
19
+ "java",
20
+ "jvm",
21
+ "bridge"
22
+ ],
23
+ "author": {
24
+ "name": "Xabier de Zuazo",
25
+ "email": "xabier@zuazo.org",
26
+ "url": "https://github.com/zuazo"
27
+ },
28
+ "license": "Apache-2.0",
29
+ "readmeFilename": "README.md",
30
+ "engines": {
31
+ "node": ">=24"
32
+ },
33
+ "files": [
34
+ "index.js",
35
+ "lib/client.js",
36
+ "lib/javaValues.js",
37
+ "java-bridge/target/jmx-bridge.jar",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "devDependencies": {}
42
+ }