@sourceregistry/node-ovsdb 1.0.0
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 +201 -0
- package/README.md +124 -0
- package/dist/index.cjs.js +4 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.d.ts +82 -0
- package/dist/index.es.js +221 -0
- package/dist/index.es.js.map +1 -0
- package/dist/types/index.d.ts +222 -0
- package/package.json +84 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# @sourceregistry/node-ovsdb
|
|
2
|
+
|
|
3
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
4
|
+
[](https://github.com/SourceRegistry/node-ovsdb/actions/workflows/publish-npm.yml)
|
|
5
|
+
|
|
6
|
+
A lightweight, typesafe TypeScript client for the Open vSwitch Database (OVSDB) Management Protocol, as defined in [RFC 7047](https://datatracker.ietf.org/doc/html/rfc7047).
|
|
7
|
+
|
|
8
|
+
This library provides a low-level wrapper to interact with the OVSDB over a Unix socket, enabling programmatic configuration and management of Open vSwitch instances.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Install the package using npm:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @sourceregistry/node-ovsdb
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
### Getting Started
|
|
21
|
+
|
|
22
|
+
The primary class is `OVSDBClient`, which handles the connection to the OVSDB server (typically located at `/var/run/openvswitch/db.sock`).
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
import { OVSDBClient } from '@sourceregistry/node-ovsdb';
|
|
26
|
+
|
|
27
|
+
async function main() {
|
|
28
|
+
// Create a new client instance
|
|
29
|
+
const client = new OVSDBClient();
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
// Connect to the OVSDB Unix socket
|
|
33
|
+
await client.connect();
|
|
34
|
+
console.log('Connected to OVSDB');
|
|
35
|
+
|
|
36
|
+
// Example: Get the list of available databases
|
|
37
|
+
const databases = await client.listDbs();
|
|
38
|
+
console.log('Databases:', databases);
|
|
39
|
+
|
|
40
|
+
// Example: Get the schema of the 'Open_vSwitch' database
|
|
41
|
+
const schema = await client.getSchema('Open_vSwitch');
|
|
42
|
+
console.log('OVS Version:', schema.version);
|
|
43
|
+
|
|
44
|
+
// Example: Perform a transaction to select all bridges
|
|
45
|
+
const operations = [
|
|
46
|
+
{
|
|
47
|
+
op: 'select',
|
|
48
|
+
table: 'Bridge',
|
|
49
|
+
where: [],
|
|
50
|
+
columns: ['name']
|
|
51
|
+
}
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
const result = await client.transact('Open_vSwitch', operations);
|
|
55
|
+
console.log('Bridges:', result);
|
|
56
|
+
|
|
57
|
+
} catch (error) {
|
|
58
|
+
console.error('An error occurred:', error.message);
|
|
59
|
+
} finally {
|
|
60
|
+
// Always close the connection
|
|
61
|
+
client.close();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
main();
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Using Async Disposable (Recommended)
|
|
69
|
+
|
|
70
|
+
For guaranteed resource cleanup, use the client with the `using` statement (requires Node.js 18+ or the `--harmony-explicit-resource-management` flag):
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
import { OVSDBClient } from '@sourceregistry/node-ovsdb';
|
|
74
|
+
|
|
75
|
+
async function main() {
|
|
76
|
+
// The 'using' statement ensures the client is closed even if an error occurs
|
|
77
|
+
using client = new OVSDBClient();
|
|
78
|
+
|
|
79
|
+
await client.connect();
|
|
80
|
+
console.log('Connected to OVSDB');
|
|
81
|
+
|
|
82
|
+
const dbs = await client.listDbs();
|
|
83
|
+
console.log('Available databases:', dbs);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
main();
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Core Methods
|
|
90
|
+
|
|
91
|
+
The `OVSDBClient` class provides direct access to the core OVSDB RPC methods:
|
|
92
|
+
|
|
93
|
+
- `connect()`: Establishes a connection to the Unix socket.
|
|
94
|
+
- `listDbs()`: Retrieves the names of available databases.
|
|
95
|
+
- `getSchema(dbName)`: Retrieves the schema for a specific database.
|
|
96
|
+
- `transact(dbName, operations)`: Executes a series of database operations atomically.
|
|
97
|
+
- `monitor(...)`: Subscribes to database change notifications.
|
|
98
|
+
- `echo()`: Tests the connection liveness.
|
|
99
|
+
- `close()`: Closes the connection.
|
|
100
|
+
|
|
101
|
+
### Advanced: Entity Wrappers (Coming Soon)
|
|
102
|
+
|
|
103
|
+
For higher-level operations (e.g., `createBridge`, `addPort`), consider building wrapper classes on top of `OVSDBClient`. A future version of this library may include these.
|
|
104
|
+
|
|
105
|
+
## Development
|
|
106
|
+
|
|
107
|
+
### Prerequisites
|
|
108
|
+
|
|
109
|
+
- Node.js (v18 or higher recommended)
|
|
110
|
+
|
|
111
|
+
### Scripts
|
|
112
|
+
|
|
113
|
+
- `npm run dev`: Start the development server.
|
|
114
|
+
- `npm run build`: Compile the TypeScript code and generate the distribution files in the `dist/` directory.
|
|
115
|
+
- `npm run preview`: Preview the built application.
|
|
116
|
+
- `npm run test`: Run the test suite with Vitest.
|
|
117
|
+
|
|
118
|
+
## Contributing
|
|
119
|
+
|
|
120
|
+
Contributions are welcome! Please feel free to submit issues and pull requests.
|
|
121
|
+
|
|
122
|
+
## License
|
|
123
|
+
|
|
124
|
+
This project is licensed under the Apache-2.0 License. See the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("net"),u=require("fs");class l{constructor(e={}){this.socket=null,this.requestId=1,this.pendingRequests=new Map,this.isConnected=!1,this.socketPath=e.socketPath||"/var/run/openvswitch/db.sock",this.timeout=e.timeout||5e3}connect(){return new Promise((e,r)=>{if(this.isConnected){e(this);return}if(!u.existsSync(this.socketPath)){r(new Error(`OVSDB socket not found: ${this.socketPath}`));return}this.socket=a.createConnection(this.socketPath);const t=setTimeout(()=>{this._cleanup(),r(new Error(`Connection timeout after ${this.timeout}ms`))},this.timeout);this.socket.on("connect",()=>{clearTimeout(t),this.isConnected=!0,e(this)}),this.socket.on("error",o=>{clearTimeout(t),this._cleanup(),r(o)}),this.socket.on("close",()=>{this._cleanup()}),this.socket.on("data",o=>{this._handleData(o)})})}request(e,r){return new Promise((t,o)=>{if(!this.isConnected){o(new Error("Not connected to OVSDB"));return}const s=this.requestId++,c=JSON.stringify({method:e,params:r,id:s})+`
|
|
2
|
+
`,n=setTimeout(()=>{this.pendingRequests.delete(s),o(new Error(`Request timeout for method: ${e}`))},this.timeout);this.pendingRequests.set(s,{resolve:t,reject:o,timeoutId:n}),this.socket.write(c,i=>{i&&(clearTimeout(n),this.pendingRequests.delete(s),o(i))})})}async listDbs(){const e=await this.request("list_dbs",[]);if("error"in e&&e.error!==null)throw new Error(`RPC Error: ${e.error}`);const r=e.result;if("error"in r)throw new Error(`OVSDB Error: ${r.error}`);return r}async getSchema(e="Open_vSwitch"){const r=await this.request("get_schema",[e]);if("error"in r&&r.error!==null)throw new Error(`RPC Error: ${r.error}`);const t=r.result;if("error"in t)throw new Error(`OVSDB Error: ${t.error}`);return t}async transact(e,r){const t=await this.request("transact",[e,...r]);if("error"in t&&t.error!==null)throw new Error(`RPC Error: ${t.error}`);return t.result}async monitor(e,r,t){const o=await this.request("monitor",[e,r,t]);if("error"in o&&o.error!==null)throw new Error(`RPC Error: ${o.error}`);const s=o.result;if("error"in s)throw new Error(`OVSDB Error: ${s.error}`);return s}async monitorCancel(e){const r=await this.request("monitor_cancel",[e]);if("error"in r&&r.error!==null)throw new Error(`RPC Error: ${r.error}`);const t=r.result;if("error"in t)throw new Error(`OVSDB Error: ${t.error}`);return t}async echo(e="ping"){const r=await this.request("echo",Array.isArray(e)?e:[e]);if("error"in r&&r.error!==null)throw new Error(`RPC Error: ${r.error}`);const t=r.result;if("error"in t)throw new Error(`OVSDB Error: ${t.error}`);return t}async close(){await this[Symbol.asyncDispose]()}async[Symbol.asyncDispose](){if(this.isConnected){const e=new Promise(r=>{if(this.socket){if(this.socket.destroyed||this.socket.readyState==="closed"){r();return}this.socket.once("close",()=>{r()})}else r()});this._cleanup(),await e}}_cleanup(){this.isConnected=!1,this.socket&&(this.socket.destroy(),this.socket=null),this.pendingRequests.forEach(({reject:e,timeoutId:r})=>{clearTimeout(r),e(new Error("Connection closed"))}),this.pendingRequests.clear()}_handleData(e){e.toString().trim().split(`
|
|
3
|
+
`).forEach(t=>{if(t)try{const o=JSON.parse(t);this._handleResponse(o)}catch(o){console.error("Failed to parse JSON:",o)}})}_handleResponse(e){if(typeof e!="object"||e===null||!("id"in e)){console.error("Invalid response format:",e);return}const r=e.id,t=this.pendingRequests.get(r);if(!t){this._handleNotification(e);return}this.pendingRequests.delete(r),clearTimeout(t.timeoutId),"error"in e&&e.error!==null?t.reject(new Error(`RPC Error: ${e.error}`)):t.resolve(e)}_handleNotification(e){if(typeof e!="object"||e===null||!("method"in e)){console.error("Invalid notification format:",e);return}const r=e.method;switch(r){case"update":console.log("Received update notification:",e.params[0]);break;case"locked":console.log("Received locked notification:",e.params[0]);break;case"stolen":console.log("Received stolen notification:",e.params[0]);break;default:console.log("Received notification:",r)}}}exports.OVSDBClient=l;
|
|
4
|
+
//# sourceMappingURL=index.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/index.ts"],"sourcesContent":["import {createConnection, Socket} from \"net\";\nimport {existsSync} from \"fs\";\n\nimport {\n DatabaseOperation,\n DatabaseSchema, EchoResponse,\n GetSchemaResponse,\n JsonValue,\n ListDbsResponse, LockedNotification, MonitorCancelResponse, MonitorConfig, MonitorResponse, OvsdbResponse,\n OvsdbResult, StolenNotification, TableUpdate,\n TransactResponse, UpdateNotification\n} from \"./types\";\n\n/**\n * Options for configuring the OVSDBClient.\n */\nexport interface OvsdbClientOptions {\n socketPath?: string;\n timeout?: number;\n}\n\n/**\n * A lightweight, typesafe client for interacting with the OVSDB over a Unix socket.\n * Implements the AsyncDisposable interface for resource management.\n * No extra functionality should be added to this client than only interact with the low-level database functions of ovs\n */\nexport class OVSDBClient implements AsyncDisposable {\n private readonly socketPath: string;\n private readonly timeout: number;\n private socket: Socket | null = null;\n private requestId = 1;\n private pendingRequests = new Map<number, {\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n timeoutId: NodeJS.Timeout;\n }>();\n private isConnected = false;\n\n /**\n * Creates a new OVSDBClient instance.\n * @param options - Configuration options for the client.\n */\n constructor(options: OvsdbClientOptions = {}) {\n this.socketPath = options.socketPath || '/var/run/openvswitch/db.sock';\n this.timeout = options.timeout || 5000;\n }\n\n /**\n * Connects to the OVSDB Unix socket.\n * @returns A promise that resolves when connected.\n * @throws An error if the socket file does not exist or the connection fails.\n */\n public connect(): Promise<this> {\n return new Promise((resolve, reject) => {\n if (this.isConnected) {\n resolve(this);\n return;\n }\n\n if (!existsSync(this.socketPath)) {\n reject(new Error(`OVSDB socket not found: ${this.socketPath}`));\n return;\n }\n\n this.socket = createConnection(this.socketPath);\n\n const timeoutId = setTimeout(() => {\n this._cleanup();\n reject(new Error(`Connection timeout after ${this.timeout}ms`));\n }, this.timeout);\n\n this.socket.on('connect', () => {\n clearTimeout(timeoutId);\n this.isConnected = true;\n resolve(this);\n });\n\n this.socket.on('error', (err) => {\n clearTimeout(timeoutId);\n this._cleanup();\n reject(err);\n });\n\n this.socket.on('close', () => {\n this._cleanup();\n });\n\n this.socket.on('data', (data) => {\n this._handleData(data);\n });\n });\n }\n\n /**\n * Sends a JSON-RPC request to the OVSDB server.\n * @param method - The RPC method name.\n * @param params - The parameters for the RPC method.\n * @returns A promise that resolves with the result.\n * @throws An error if not connected, if the request times out, or if there is a network error.\n */\n public request<T>(method: string, params: JsonValue[]): Promise<T> {\n return new Promise((resolve, reject) => {\n if (!this.isConnected) {\n reject(new Error('Not connected to OVSDB'));\n return;\n }\n\n const id = this.requestId++;\n const request = JSON.stringify({\n method,\n params,\n id\n }) + '\\n';\n\n const timeoutId = setTimeout(() => {\n this.pendingRequests.delete(id);\n reject(new Error(`Request timeout for method: ${method}`));\n }, this.timeout);\n\n this.pendingRequests.set(id, {resolve, reject, timeoutId});\n\n this.socket!.write(request, (err) => {\n if (err) {\n clearTimeout(timeoutId);\n this.pendingRequests.delete(id);\n reject(err);\n }\n });\n });\n }\n\n // --- Core OVSDB RPC Methods (Fixed to handle the response structure) ---\n\n public async listDbs(): Promise<string[]> {\n const response = await this.request<ListDbsResponse>('list_dbs', []);\n // Check if the response is an error object\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n // Check if the OvsdbResult itself is an error\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n public async getSchema(dbName: string = 'Open_vSwitch'): Promise<DatabaseSchema> {\n const response = await this.request<GetSchemaResponse>('get_schema', [dbName]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n public async transact(dbName: string, operations: DatabaseOperation[]): Promise<Array<OvsdbResult<unknown>>> {\n const response = await this.request<TransactResponse>('transact', [dbName, ...operations]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n return response.result as Array<OvsdbResult<unknown>>;\n // Note: The result here is already an array of OvsdbResult<unknown>.\n // The caller is responsible for checking each element for errors.\n }\n\n public async monitor(dbName: string, monitorId: JsonValue, monitorRequests: Record<string, MonitorConfig[]>): Promise<Record<string, TableUpdate>> {\n const response = await this.request<MonitorResponse>('monitor', [dbName, monitorId, monitorRequests as JsonValue]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n public async monitorCancel(monitorId: JsonValue): Promise<Record<string, never>> {\n const response = await this.request<MonitorCancelResponse>('monitor_cancel', [monitorId]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n public async echo(payload: JsonValue = 'ping'): Promise<JsonValue[]> {\n const response = await this.request<EchoResponse>('echo', Array.isArray(payload) ? payload : [payload]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n /**\n * Closes the connection to the OVSDB server.\n * @returns A promise that resolves when the connection is closed.\n */\n public async close(): Promise<void> {\n await this[Symbol.asyncDispose]();\n }\n\n /**\n * Implements the AsyncDisposable interface for use with 'using' statements.\n * This method is called automatically when exiting a 'using' block.\n * @returns A promise that resolves when cleanup is complete.\n */\n public async [Symbol.asyncDispose](): Promise<void> {\n if (this.isConnected) {\n const closePromise = new Promise<void>((resolve) => {\n if (this.socket) {\n if (this.socket.destroyed || this.socket.readyState === 'closed') {\n resolve();\n return;\n }\n this.socket.once('close', () => {\n resolve();\n });\n } else {\n resolve();\n }\n });\n\n this._cleanup();\n await closePromise;\n }\n }\n\n /**\n * Cleans up the connection and pending requests.\n * @private\n */\n private _cleanup(): void {\n this.isConnected = false;\n if (this.socket) {\n this.socket.destroy();\n this.socket = null;\n }\n this.pendingRequests.forEach(({reject, timeoutId}) => {\n clearTimeout(timeoutId);\n reject(new Error('Connection closed'));\n });\n this.pendingRequests.clear();\n }\n\n /**\n * Handles incoming data from the socket.\n * @private\n * @param data - The raw data received.\n */\n private _handleData(data: Buffer): void {\n const messages = data.toString().trim().split('\\n');\n messages.forEach(message => {\n if (!message) return;\n try {\n const response = JSON.parse(message);\n this._handleResponse(response);\n } catch (err) {\n console.error('Failed to parse JSON:', err);\n }\n });\n }\n\n /**\n * Handles a parsed JSON-RPC response.\n * @private\n * @param response - The JSON-RPC response object.\n */\n private _handleResponse(response: JsonValue): void {\n if (typeof response !== 'object' || response === null || !('id' in response)) {\n console.error('Invalid response format:', response);\n return;\n }\n\n const id = response.id as number;\n const request = this.pendingRequests.get(id);\n\n if (!request) {\n // This is a notification (e.g., \"update\", \"locked\", \"stolen\")\n this._handleNotification(response);\n return;\n }\n\n this.pendingRequests.delete(id);\n clearTimeout(request.timeoutId);\n\n if ('error' in response && response.error !== null) {\n request.reject(new Error(`RPC Error: ${response.error}`));\n } else {\n request.resolve((response as unknown as OvsdbResponse));\n }\n }\n\n /**\n * Handles JSON-RPC notifications (e.g., \"update\", \"locked\", \"stolen\").\n * This can be overridden by subclasses or event listeners.\n * @private\n * @param notification - The notification object.\n */\n private _handleNotification(notification: JsonValue): void {\n if (typeof notification !== 'object' || notification === null || !('method' in notification)) {\n console.error('Invalid notification format:', notification);\n return;\n }\n\n const method = (notification as { method: string }).method;\n\n switch (method) {\n case 'update':\n console.log('Received update notification:', (notification as UpdateNotification).params[0]);\n break;\n case 'locked':\n console.log('Received locked notification:', (notification as LockedNotification).params[0]);\n break;\n case 'stolen':\n console.log('Received stolen notification:', (notification as StolenNotification).params[0]);\n break;\n default:\n console.log('Received notification:', method);\n }\n }\n}\n\nexport * from \"./types\"\n"],"names":["OVSDBClient","options","resolve","reject","existsSync","createConnection","timeoutId","err","data","method","params","id","request","response","result","dbName","operations","monitorId","monitorRequests","payload","closePromise","message","notification"],"mappings":"uHA0BO,MAAMA,CAAuC,CAgBhD,YAAYC,EAA8B,GAAI,CAb9C,KAAQ,OAAwB,KAChC,KAAQ,UAAY,EACpB,KAAQ,oBAAsB,IAK9B,KAAQ,YAAc,GAOlB,KAAK,WAAaA,EAAQ,YAAc,+BACxC,KAAK,QAAUA,EAAQ,SAAW,GACtC,CAOO,SAAyB,CAC5B,OAAO,IAAI,QAAQ,CAACC,EAASC,IAAW,CACpC,GAAI,KAAK,YAAa,CAClBD,EAAQ,IAAI,EACZ,MACJ,CAEA,GAAI,CAACE,EAAAA,WAAW,KAAK,UAAU,EAAG,CAC9BD,EAAO,IAAI,MAAM,2BAA2B,KAAK,UAAU,EAAE,CAAC,EAC9D,MACJ,CAEA,KAAK,OAASE,mBAAiB,KAAK,UAAU,EAE9C,MAAMC,EAAY,WAAW,IAAM,CAC/B,KAAK,SAAA,EACLH,EAAO,IAAI,MAAM,4BAA4B,KAAK,OAAO,IAAI,CAAC,CAClE,EAAG,KAAK,OAAO,EAEf,KAAK,OAAO,GAAG,UAAW,IAAM,CAC5B,aAAaG,CAAS,EACtB,KAAK,YAAc,GACnBJ,EAAQ,IAAI,CAChB,CAAC,EAED,KAAK,OAAO,GAAG,QAAUK,GAAQ,CAC7B,aAAaD,CAAS,EACtB,KAAK,SAAA,EACLH,EAAOI,CAAG,CACd,CAAC,EAED,KAAK,OAAO,GAAG,QAAS,IAAM,CAC1B,KAAK,SAAA,CACT,CAAC,EAED,KAAK,OAAO,GAAG,OAASC,GAAS,CAC7B,KAAK,YAAYA,CAAI,CACzB,CAAC,CACL,CAAC,CACL,CASO,QAAWC,EAAgBC,EAAiC,CAC/D,OAAO,IAAI,QAAQ,CAACR,EAASC,IAAW,CACpC,GAAI,CAAC,KAAK,YAAa,CACnBA,EAAO,IAAI,MAAM,wBAAwB,CAAC,EAC1C,MACJ,CAEA,MAAMQ,EAA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AAQ,MAAM,+BAAgCA,CAAY,EAC1D,MACJ,CAEA,MAAMb,EAAUa,EAAoC,OAEpD,OAAQb,EAAA,CACJ,IAAK,SACD,QAAQ,IAAI,gCAAkCa,EAAoC,OAAO,CAAC,CAAC,EAC3F,MACJ,IAAK,SACD,QAAQ,IAAI,gCAAkCA,EAAoC,OAAO,CAAC,CAAC,EAC3F,MACJ,IAAK,SACD,QAAQ,IAAI,gCAAkCA,EAAoC,OAAO,CAAC,CAAC,EAC3F,MACJ,QACI,QAAQ,IAAI,yBAA0Bb,CAAM,CAAA,CAExD,CACJ"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { DatabaseOperation, DatabaseSchema, JsonValue, MonitorConfig, OvsdbResult, TableUpdate } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Options for configuring the OVSDBClient.
|
|
4
|
+
*/
|
|
5
|
+
export interface OvsdbClientOptions {
|
|
6
|
+
socketPath?: string;
|
|
7
|
+
timeout?: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A lightweight, typesafe client for interacting with the OVSDB over a Unix socket.
|
|
11
|
+
* Implements the AsyncDisposable interface for resource management.
|
|
12
|
+
* No extra functionality should be added to this client than only interact with the low-level database functions of ovs
|
|
13
|
+
*/
|
|
14
|
+
export declare class OVSDBClient implements AsyncDisposable {
|
|
15
|
+
private readonly socketPath;
|
|
16
|
+
private readonly timeout;
|
|
17
|
+
private socket;
|
|
18
|
+
private requestId;
|
|
19
|
+
private pendingRequests;
|
|
20
|
+
private isConnected;
|
|
21
|
+
/**
|
|
22
|
+
* Creates a new OVSDBClient instance.
|
|
23
|
+
* @param options - Configuration options for the client.
|
|
24
|
+
*/
|
|
25
|
+
constructor(options?: OvsdbClientOptions);
|
|
26
|
+
/**
|
|
27
|
+
* Connects to the OVSDB Unix socket.
|
|
28
|
+
* @returns A promise that resolves when connected.
|
|
29
|
+
* @throws An error if the socket file does not exist or the connection fails.
|
|
30
|
+
*/
|
|
31
|
+
connect(): Promise<this>;
|
|
32
|
+
/**
|
|
33
|
+
* Sends a JSON-RPC request to the OVSDB server.
|
|
34
|
+
* @param method - The RPC method name.
|
|
35
|
+
* @param params - The parameters for the RPC method.
|
|
36
|
+
* @returns A promise that resolves with the result.
|
|
37
|
+
* @throws An error if not connected, if the request times out, or if there is a network error.
|
|
38
|
+
*/
|
|
39
|
+
request<T>(method: string, params: JsonValue[]): Promise<T>;
|
|
40
|
+
listDbs(): Promise<string[]>;
|
|
41
|
+
getSchema(dbName?: string): Promise<DatabaseSchema>;
|
|
42
|
+
transact(dbName: string, operations: DatabaseOperation[]): Promise<Array<OvsdbResult<unknown>>>;
|
|
43
|
+
monitor(dbName: string, monitorId: JsonValue, monitorRequests: Record<string, MonitorConfig[]>): Promise<Record<string, TableUpdate>>;
|
|
44
|
+
monitorCancel(monitorId: JsonValue): Promise<Record<string, never>>;
|
|
45
|
+
echo(payload?: JsonValue): Promise<JsonValue[]>;
|
|
46
|
+
/**
|
|
47
|
+
* Closes the connection to the OVSDB server.
|
|
48
|
+
* @returns A promise that resolves when the connection is closed.
|
|
49
|
+
*/
|
|
50
|
+
close(): Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Implements the AsyncDisposable interface for use with 'using' statements.
|
|
53
|
+
* This method is called automatically when exiting a 'using' block.
|
|
54
|
+
* @returns A promise that resolves when cleanup is complete.
|
|
55
|
+
*/
|
|
56
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
57
|
+
/**
|
|
58
|
+
* Cleans up the connection and pending requests.
|
|
59
|
+
* @private
|
|
60
|
+
*/
|
|
61
|
+
private _cleanup;
|
|
62
|
+
/**
|
|
63
|
+
* Handles incoming data from the socket.
|
|
64
|
+
* @private
|
|
65
|
+
* @param data - The raw data received.
|
|
66
|
+
*/
|
|
67
|
+
private _handleData;
|
|
68
|
+
/**
|
|
69
|
+
* Handles a parsed JSON-RPC response.
|
|
70
|
+
* @private
|
|
71
|
+
* @param response - The JSON-RPC response object.
|
|
72
|
+
*/
|
|
73
|
+
private _handleResponse;
|
|
74
|
+
/**
|
|
75
|
+
* Handles JSON-RPC notifications (e.g., "update", "locked", "stolen").
|
|
76
|
+
* This can be overridden by subclasses or event listeners.
|
|
77
|
+
* @private
|
|
78
|
+
* @param notification - The notification object.
|
|
79
|
+
*/
|
|
80
|
+
private _handleNotification;
|
|
81
|
+
}
|
|
82
|
+
export * from './types';
|
package/dist/index.es.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { createConnection as a } from "net";
|
|
2
|
+
import { existsSync as h } from "fs";
|
|
3
|
+
class m {
|
|
4
|
+
/**
|
|
5
|
+
* Creates a new OVSDBClient instance.
|
|
6
|
+
* @param options - Configuration options for the client.
|
|
7
|
+
*/
|
|
8
|
+
constructor(r = {}) {
|
|
9
|
+
this.socket = null, this.requestId = 1, this.pendingRequests = /* @__PURE__ */ new Map(), this.isConnected = !1, this.socketPath = r.socketPath || "/var/run/openvswitch/db.sock", this.timeout = r.timeout || 5e3;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Connects to the OVSDB Unix socket.
|
|
13
|
+
* @returns A promise that resolves when connected.
|
|
14
|
+
* @throws An error if the socket file does not exist or the connection fails.
|
|
15
|
+
*/
|
|
16
|
+
connect() {
|
|
17
|
+
return new Promise((r, e) => {
|
|
18
|
+
if (this.isConnected) {
|
|
19
|
+
r(this);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
if (!h(this.socketPath)) {
|
|
23
|
+
e(new Error(`OVSDB socket not found: ${this.socketPath}`));
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
this.socket = a(this.socketPath);
|
|
27
|
+
const t = setTimeout(() => {
|
|
28
|
+
this._cleanup(), e(new Error(`Connection timeout after ${this.timeout}ms`));
|
|
29
|
+
}, this.timeout);
|
|
30
|
+
this.socket.on("connect", () => {
|
|
31
|
+
clearTimeout(t), this.isConnected = !0, r(this);
|
|
32
|
+
}), this.socket.on("error", (o) => {
|
|
33
|
+
clearTimeout(t), this._cleanup(), e(o);
|
|
34
|
+
}), this.socket.on("close", () => {
|
|
35
|
+
this._cleanup();
|
|
36
|
+
}), this.socket.on("data", (o) => {
|
|
37
|
+
this._handleData(o);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Sends a JSON-RPC request to the OVSDB server.
|
|
43
|
+
* @param method - The RPC method name.
|
|
44
|
+
* @param params - The parameters for the RPC method.
|
|
45
|
+
* @returns A promise that resolves with the result.
|
|
46
|
+
* @throws An error if not connected, if the request times out, or if there is a network error.
|
|
47
|
+
*/
|
|
48
|
+
request(r, e) {
|
|
49
|
+
return new Promise((t, o) => {
|
|
50
|
+
if (!this.isConnected) {
|
|
51
|
+
o(new Error("Not connected to OVSDB"));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const s = this.requestId++, c = JSON.stringify({
|
|
55
|
+
method: r,
|
|
56
|
+
params: e,
|
|
57
|
+
id: s
|
|
58
|
+
}) + `
|
|
59
|
+
`, n = setTimeout(() => {
|
|
60
|
+
this.pendingRequests.delete(s), o(new Error(`Request timeout for method: ${r}`));
|
|
61
|
+
}, this.timeout);
|
|
62
|
+
this.pendingRequests.set(s, { resolve: t, reject: o, timeoutId: n }), this.socket.write(c, (i) => {
|
|
63
|
+
i && (clearTimeout(n), this.pendingRequests.delete(s), o(i));
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
// --- Core OVSDB RPC Methods (Fixed to handle the response structure) ---
|
|
68
|
+
async listDbs() {
|
|
69
|
+
const r = await this.request("list_dbs", []);
|
|
70
|
+
if ("error" in r && r.error !== null)
|
|
71
|
+
throw new Error(`RPC Error: ${r.error}`);
|
|
72
|
+
const e = r.result;
|
|
73
|
+
if ("error" in e)
|
|
74
|
+
throw new Error(`OVSDB Error: ${e.error}`);
|
|
75
|
+
return e;
|
|
76
|
+
}
|
|
77
|
+
async getSchema(r = "Open_vSwitch") {
|
|
78
|
+
const e = await this.request("get_schema", [r]);
|
|
79
|
+
if ("error" in e && e.error !== null)
|
|
80
|
+
throw new Error(`RPC Error: ${e.error}`);
|
|
81
|
+
const t = e.result;
|
|
82
|
+
if ("error" in t)
|
|
83
|
+
throw new Error(`OVSDB Error: ${t.error}`);
|
|
84
|
+
return t;
|
|
85
|
+
}
|
|
86
|
+
async transact(r, e) {
|
|
87
|
+
const t = await this.request("transact", [r, ...e]);
|
|
88
|
+
if ("error" in t && t.error !== null)
|
|
89
|
+
throw new Error(`RPC Error: ${t.error}`);
|
|
90
|
+
return t.result;
|
|
91
|
+
}
|
|
92
|
+
async monitor(r, e, t) {
|
|
93
|
+
const o = await this.request("monitor", [r, e, t]);
|
|
94
|
+
if ("error" in o && o.error !== null)
|
|
95
|
+
throw new Error(`RPC Error: ${o.error}`);
|
|
96
|
+
const s = o.result;
|
|
97
|
+
if ("error" in s)
|
|
98
|
+
throw new Error(`OVSDB Error: ${s.error}`);
|
|
99
|
+
return s;
|
|
100
|
+
}
|
|
101
|
+
async monitorCancel(r) {
|
|
102
|
+
const e = await this.request("monitor_cancel", [r]);
|
|
103
|
+
if ("error" in e && e.error !== null)
|
|
104
|
+
throw new Error(`RPC Error: ${e.error}`);
|
|
105
|
+
const t = e.result;
|
|
106
|
+
if ("error" in t)
|
|
107
|
+
throw new Error(`OVSDB Error: ${t.error}`);
|
|
108
|
+
return t;
|
|
109
|
+
}
|
|
110
|
+
async echo(r = "ping") {
|
|
111
|
+
const e = await this.request("echo", Array.isArray(r) ? r : [r]);
|
|
112
|
+
if ("error" in e && e.error !== null)
|
|
113
|
+
throw new Error(`RPC Error: ${e.error}`);
|
|
114
|
+
const t = e.result;
|
|
115
|
+
if ("error" in t)
|
|
116
|
+
throw new Error(`OVSDB Error: ${t.error}`);
|
|
117
|
+
return t;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Closes the connection to the OVSDB server.
|
|
121
|
+
* @returns A promise that resolves when the connection is closed.
|
|
122
|
+
*/
|
|
123
|
+
async close() {
|
|
124
|
+
await this[Symbol.asyncDispose]();
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Implements the AsyncDisposable interface for use with 'using' statements.
|
|
128
|
+
* This method is called automatically when exiting a 'using' block.
|
|
129
|
+
* @returns A promise that resolves when cleanup is complete.
|
|
130
|
+
*/
|
|
131
|
+
async [Symbol.asyncDispose]() {
|
|
132
|
+
if (this.isConnected) {
|
|
133
|
+
const r = new Promise((e) => {
|
|
134
|
+
if (this.socket) {
|
|
135
|
+
if (this.socket.destroyed || this.socket.readyState === "closed") {
|
|
136
|
+
e();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
this.socket.once("close", () => {
|
|
140
|
+
e();
|
|
141
|
+
});
|
|
142
|
+
} else
|
|
143
|
+
e();
|
|
144
|
+
});
|
|
145
|
+
this._cleanup(), await r;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Cleans up the connection and pending requests.
|
|
150
|
+
* @private
|
|
151
|
+
*/
|
|
152
|
+
_cleanup() {
|
|
153
|
+
this.isConnected = !1, this.socket && (this.socket.destroy(), this.socket = null), this.pendingRequests.forEach(({ reject: r, timeoutId: e }) => {
|
|
154
|
+
clearTimeout(e), r(new Error("Connection closed"));
|
|
155
|
+
}), this.pendingRequests.clear();
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Handles incoming data from the socket.
|
|
159
|
+
* @private
|
|
160
|
+
* @param data - The raw data received.
|
|
161
|
+
*/
|
|
162
|
+
_handleData(r) {
|
|
163
|
+
r.toString().trim().split(`
|
|
164
|
+
`).forEach((t) => {
|
|
165
|
+
if (t)
|
|
166
|
+
try {
|
|
167
|
+
const o = JSON.parse(t);
|
|
168
|
+
this._handleResponse(o);
|
|
169
|
+
} catch (o) {
|
|
170
|
+
console.error("Failed to parse JSON:", o);
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Handles a parsed JSON-RPC response.
|
|
176
|
+
* @private
|
|
177
|
+
* @param response - The JSON-RPC response object.
|
|
178
|
+
*/
|
|
179
|
+
_handleResponse(r) {
|
|
180
|
+
if (typeof r != "object" || r === null || !("id" in r)) {
|
|
181
|
+
console.error("Invalid response format:", r);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const e = r.id, t = this.pendingRequests.get(e);
|
|
185
|
+
if (!t) {
|
|
186
|
+
this._handleNotification(r);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
this.pendingRequests.delete(e), clearTimeout(t.timeoutId), "error" in r && r.error !== null ? t.reject(new Error(`RPC Error: ${r.error}`)) : t.resolve(r);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Handles JSON-RPC notifications (e.g., "update", "locked", "stolen").
|
|
193
|
+
* This can be overridden by subclasses or event listeners.
|
|
194
|
+
* @private
|
|
195
|
+
* @param notification - The notification object.
|
|
196
|
+
*/
|
|
197
|
+
_handleNotification(r) {
|
|
198
|
+
if (typeof r != "object" || r === null || !("method" in r)) {
|
|
199
|
+
console.error("Invalid notification format:", r);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const e = r.method;
|
|
203
|
+
switch (e) {
|
|
204
|
+
case "update":
|
|
205
|
+
console.log("Received update notification:", r.params[0]);
|
|
206
|
+
break;
|
|
207
|
+
case "locked":
|
|
208
|
+
console.log("Received locked notification:", r.params[0]);
|
|
209
|
+
break;
|
|
210
|
+
case "stolen":
|
|
211
|
+
console.log("Received stolen notification:", r.params[0]);
|
|
212
|
+
break;
|
|
213
|
+
default:
|
|
214
|
+
console.log("Received notification:", e);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
export {
|
|
219
|
+
m as OVSDBClient
|
|
220
|
+
};
|
|
221
|
+
//# sourceMappingURL=index.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/index.ts"],"sourcesContent":["import {createConnection, Socket} from \"net\";\nimport {existsSync} from \"fs\";\n\nimport {\n DatabaseOperation,\n DatabaseSchema, EchoResponse,\n GetSchemaResponse,\n JsonValue,\n ListDbsResponse, LockedNotification, MonitorCancelResponse, MonitorConfig, MonitorResponse, OvsdbResponse,\n OvsdbResult, StolenNotification, TableUpdate,\n TransactResponse, UpdateNotification\n} from \"./types\";\n\n/**\n * Options for configuring the OVSDBClient.\n */\nexport interface OvsdbClientOptions {\n socketPath?: string;\n timeout?: number;\n}\n\n/**\n * A lightweight, typesafe client for interacting with the OVSDB over a Unix socket.\n * Implements the AsyncDisposable interface for resource management.\n * No extra functionality should be added to this client than only interact with the low-level database functions of ovs\n */\nexport class OVSDBClient implements AsyncDisposable {\n private readonly socketPath: string;\n private readonly timeout: number;\n private socket: Socket | null = null;\n private requestId = 1;\n private pendingRequests = new Map<number, {\n resolve: (value: any) => void;\n reject: (reason?: any) => void;\n timeoutId: NodeJS.Timeout;\n }>();\n private isConnected = false;\n\n /**\n * Creates a new OVSDBClient instance.\n * @param options - Configuration options for the client.\n */\n constructor(options: OvsdbClientOptions = {}) {\n this.socketPath = options.socketPath || '/var/run/openvswitch/db.sock';\n this.timeout = options.timeout || 5000;\n }\n\n /**\n * Connects to the OVSDB Unix socket.\n * @returns A promise that resolves when connected.\n * @throws An error if the socket file does not exist or the connection fails.\n */\n public connect(): Promise<this> {\n return new Promise((resolve, reject) => {\n if (this.isConnected) {\n resolve(this);\n return;\n }\n\n if (!existsSync(this.socketPath)) {\n reject(new Error(`OVSDB socket not found: ${this.socketPath}`));\n return;\n }\n\n this.socket = createConnection(this.socketPath);\n\n const timeoutId = setTimeout(() => {\n this._cleanup();\n reject(new Error(`Connection timeout after ${this.timeout}ms`));\n }, this.timeout);\n\n this.socket.on('connect', () => {\n clearTimeout(timeoutId);\n this.isConnected = true;\n resolve(this);\n });\n\n this.socket.on('error', (err) => {\n clearTimeout(timeoutId);\n this._cleanup();\n reject(err);\n });\n\n this.socket.on('close', () => {\n this._cleanup();\n });\n\n this.socket.on('data', (data) => {\n this._handleData(data);\n });\n });\n }\n\n /**\n * Sends a JSON-RPC request to the OVSDB server.\n * @param method - The RPC method name.\n * @param params - The parameters for the RPC method.\n * @returns A promise that resolves with the result.\n * @throws An error if not connected, if the request times out, or if there is a network error.\n */\n public request<T>(method: string, params: JsonValue[]): Promise<T> {\n return new Promise((resolve, reject) => {\n if (!this.isConnected) {\n reject(new Error('Not connected to OVSDB'));\n return;\n }\n\n const id = this.requestId++;\n const request = JSON.stringify({\n method,\n params,\n id\n }) + '\\n';\n\n const timeoutId = setTimeout(() => {\n this.pendingRequests.delete(id);\n reject(new Error(`Request timeout for method: ${method}`));\n }, this.timeout);\n\n this.pendingRequests.set(id, {resolve, reject, timeoutId});\n\n this.socket!.write(request, (err) => {\n if (err) {\n clearTimeout(timeoutId);\n this.pendingRequests.delete(id);\n reject(err);\n }\n });\n });\n }\n\n // --- Core OVSDB RPC Methods (Fixed to handle the response structure) ---\n\n public async listDbs(): Promise<string[]> {\n const response = await this.request<ListDbsResponse>('list_dbs', []);\n // Check if the response is an error object\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n // Check if the OvsdbResult itself is an error\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n public async getSchema(dbName: string = 'Open_vSwitch'): Promise<DatabaseSchema> {\n const response = await this.request<GetSchemaResponse>('get_schema', [dbName]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n public async transact(dbName: string, operations: DatabaseOperation[]): Promise<Array<OvsdbResult<unknown>>> {\n const response = await this.request<TransactResponse>('transact', [dbName, ...operations]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n return response.result as Array<OvsdbResult<unknown>>;\n // Note: The result here is already an array of OvsdbResult<unknown>.\n // The caller is responsible for checking each element for errors.\n }\n\n public async monitor(dbName: string, monitorId: JsonValue, monitorRequests: Record<string, MonitorConfig[]>): Promise<Record<string, TableUpdate>> {\n const response = await this.request<MonitorResponse>('monitor', [dbName, monitorId, monitorRequests as JsonValue]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n public async monitorCancel(monitorId: JsonValue): Promise<Record<string, never>> {\n const response = await this.request<MonitorCancelResponse>('monitor_cancel', [monitorId]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n public async echo(payload: JsonValue = 'ping'): Promise<JsonValue[]> {\n const response = await this.request<EchoResponse>('echo', Array.isArray(payload) ? payload : [payload]);\n if ('error' in response && response.error !== null) {\n throw new Error(`RPC Error: ${response.error}`);\n }\n const result = response.result;\n if ('error' in result) {\n throw new Error(`OVSDB Error: ${result.error}`);\n }\n return result;\n }\n\n /**\n * Closes the connection to the OVSDB server.\n * @returns A promise that resolves when the connection is closed.\n */\n public async close(): Promise<void> {\n await this[Symbol.asyncDispose]();\n }\n\n /**\n * Implements the AsyncDisposable interface for use with 'using' statements.\n * This method is called automatically when exiting a 'using' block.\n * @returns A promise that resolves when cleanup is complete.\n */\n public async [Symbol.asyncDispose](): Promise<void> {\n if (this.isConnected) {\n const closePromise = new Promise<void>((resolve) => {\n if (this.socket) {\n if (this.socket.destroyed || this.socket.readyState === 'closed') {\n resolve();\n return;\n }\n this.socket.once('close', () => {\n resolve();\n });\n } else {\n resolve();\n }\n });\n\n this._cleanup();\n await closePromise;\n }\n }\n\n /**\n * Cleans up the connection and pending requests.\n * @private\n */\n private _cleanup(): void {\n this.isConnected = false;\n if (this.socket) {\n this.socket.destroy();\n this.socket = null;\n }\n this.pendingRequests.forEach(({reject, timeoutId}) => {\n clearTimeout(timeoutId);\n reject(new Error('Connection closed'));\n });\n this.pendingRequests.clear();\n }\n\n /**\n * Handles incoming data from the socket.\n * @private\n * @param data - The raw data received.\n */\n private _handleData(data: Buffer): void {\n const messages = data.toString().trim().split('\\n');\n messages.forEach(message => {\n if (!message) return;\n try {\n const response = JSON.parse(message);\n this._handleResponse(response);\n } catch (err) {\n console.error('Failed to parse JSON:', err);\n }\n });\n }\n\n /**\n * Handles a parsed JSON-RPC response.\n * @private\n * @param response - The JSON-RPC response object.\n */\n private _handleResponse(response: JsonValue): void {\n if (typeof response !== 'object' || response === null || !('id' in response)) {\n console.error('Invalid response format:', response);\n return;\n }\n\n const id = response.id as number;\n const request = this.pendingRequests.get(id);\n\n if (!request) {\n // This is a notification (e.g., \"update\", \"locked\", \"stolen\")\n this._handleNotification(response);\n return;\n }\n\n this.pendingRequests.delete(id);\n clearTimeout(request.timeoutId);\n\n if ('error' in response && response.error !== null) {\n request.reject(new Error(`RPC Error: ${response.error}`));\n } else {\n request.resolve((response as unknown as OvsdbResponse));\n }\n }\n\n /**\n * Handles JSON-RPC notifications (e.g., \"update\", \"locked\", \"stolen\").\n * This can be overridden by subclasses or event listeners.\n * @private\n * @param notification - The notification object.\n */\n private _handleNotification(notification: JsonValue): void {\n if (typeof notification !== 'object' || notification === null || !('method' in notification)) {\n console.error('Invalid notification format:', notification);\n return;\n }\n\n const method = (notification as { method: string }).method;\n\n switch (method) {\n case 'update':\n console.log('Received update notification:', (notification as UpdateNotification).params[0]);\n break;\n case 'locked':\n console.log('Received locked notification:', (notification as LockedNotification).params[0]);\n break;\n case 'stolen':\n console.log('Received stolen notification:', (notification as StolenNotification).params[0]);\n break;\n default:\n console.log('Received notification:', method);\n }\n }\n}\n\nexport * from \"./types\"\n"],"names":["OVSDBClient","options","resolve","reject","existsSync","createConnection","timeoutId","err","data","method","params","id","request","response","result","dbName","operations","monitorId","monitorRequests","payload","closePromise","message","notification"],"mappings":";;AA0BO,MAAMA,EAAuC;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBhD,YAAYC,IAA8B,IAAI;AAb9C,SAAQ,SAAwB,MAChC,KAAQ,YAAY,GACpB,KAAQ,sCAAsB,IAAA,GAK9B,KAAQ,cAAc,IAOlB,KAAK,aAAaA,EAAQ,cAAc,gCACxC,KAAK,UAAUA,EAAQ,WAAW;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,UAAyB;AAC5B,WAAO,IAAI,QAAQ,CAACC,GAASC,MAAW;AACpC,UAAI,KAAK,aAAa;AAClB,QAAAD,EAAQ,IAAI;AACZ;AAAA,MACJ;AAEA,UAAI,CAACE,EAAW,KAAK,UAAU,GAAG;AAC9B,QAAAD,EAAO,IAAI,MAAM,2BAA2B,KAAK,UAAU,EAAE,CAAC;AAC9D;AAAA,MACJ;AAEA,WAAK,SAASE,EAAiB,KAAK,UAAU;AAE9C,YAAMC,IAAY,WAAW,MAAM;AAC/B,aAAK,SAAA,GACLH,EAAO,IAAI,MAAM,4BAA4B,KAAK,OAAO,IAAI,CAAC;AAAA,MAClE,GAAG,KAAK,OAAO;AAEf,WAAK,OAAO,GAAG,WAAW,MAAM;AAC5B,qBAAaG,CAAS,GACtB,KAAK,cAAc,IACnBJ,EAAQ,IAAI;AAAA,MAChB,CAAC,GAED,KAAK,OAAO,GAAG,SAAS,CAACK,MAAQ;AAC7B,qBAAaD,CAAS,GACtB,KAAK,SAAA,GACLH,EAAOI,CAAG;AAAA,MACd,CAAC,GAED,KAAK,OAAO,GAAG,SAAS,MAAM;AAC1B,aAAK,SAAA;AAAA,MACT,CAAC,GAED,KAAK,OAAO,GAAG,QAAQ,CAACC,MAAS;AAC7B,aAAK,YAAYA,CAAI;AAAA,MACzB,CAAC;AAAA,IACL,CAAC;AAAA,EACL;AAAA;AAAA;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boolean | null | JsonValue[] | {
|
|
5
|
+
[key: string]: JsonValue;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* An error object as defined in RFC 7047, Section 3.1.
|
|
9
|
+
*/
|
|
10
|
+
export interface OvsdbError {
|
|
11
|
+
error: string;
|
|
12
|
+
details: string | null;
|
|
13
|
+
[key: string]: JsonValue;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A result that can be either a success value or an error.
|
|
17
|
+
*/
|
|
18
|
+
export type OvsdbResult<T> = T | OvsdbError;
|
|
19
|
+
/**
|
|
20
|
+
* The response to an RPC request as defined in RFC 7047, Section 4.1.
|
|
21
|
+
*/
|
|
22
|
+
export interface OvsdbResponse<T = JsonValue> {
|
|
23
|
+
result: OvsdbResult<T>;
|
|
24
|
+
error: null;
|
|
25
|
+
id: JsonValue;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A monitor request configuration as defined in RFC 7047, Section 4.1.5.
|
|
29
|
+
* Renamed from 'MonitorRequest' to avoid conflict with the top-level request.
|
|
30
|
+
*/
|
|
31
|
+
export interface MonitorConfig {
|
|
32
|
+
columns?: string[];
|
|
33
|
+
select?: {
|
|
34
|
+
initial?: boolean;
|
|
35
|
+
insert?: boolean;
|
|
36
|
+
delete?: boolean;
|
|
37
|
+
modify?: boolean;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The request for the 'list_dbs' method.
|
|
42
|
+
*/
|
|
43
|
+
export type ListDbsRequest = {
|
|
44
|
+
method: 'list_dbs';
|
|
45
|
+
params: [];
|
|
46
|
+
id: JsonValue;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* The response for the 'list_dbs' method.
|
|
50
|
+
*/
|
|
51
|
+
export type ListDbsResponse = OvsdbResponse<string[]>;
|
|
52
|
+
/**
|
|
53
|
+
* The request for the 'get_schema' method.
|
|
54
|
+
*/
|
|
55
|
+
export type GetSchemaRequest = {
|
|
56
|
+
method: 'get_schema';
|
|
57
|
+
params: [string];
|
|
58
|
+
id: JsonValue;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* The response for the 'get_schema' method.
|
|
62
|
+
*/
|
|
63
|
+
export type GetSchemaResponse = OvsdbResponse<DatabaseSchema>;
|
|
64
|
+
/**
|
|
65
|
+
* The request for the 'transact' method.
|
|
66
|
+
*/
|
|
67
|
+
export type TransactRequest = {
|
|
68
|
+
method: 'transact';
|
|
69
|
+
params: [string, DatabaseOperation[]];
|
|
70
|
+
id: JsonValue;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* The response for the 'transact' method.
|
|
74
|
+
*/
|
|
75
|
+
export type TransactResponse = OvsdbResponse<Array<OvsdbResult<unknown>>>;
|
|
76
|
+
/**
|
|
77
|
+
* The request for the 'monitor' method.
|
|
78
|
+
*/
|
|
79
|
+
export type MonitorRequest = {
|
|
80
|
+
method: 'monitor';
|
|
81
|
+
params: [string, JsonValue, Record<string, MonitorConfig[]>];
|
|
82
|
+
id: JsonValue;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* The response for the 'monitor' method.
|
|
86
|
+
*/
|
|
87
|
+
export type MonitorResponse = OvsdbResponse<Record<string, TableUpdate>>;
|
|
88
|
+
/**
|
|
89
|
+
* The request for the 'monitor_cancel' method.
|
|
90
|
+
*/
|
|
91
|
+
export type MonitorCancelRequest = {
|
|
92
|
+
method: 'monitor_cancel';
|
|
93
|
+
params: [JsonValue];
|
|
94
|
+
id: JsonValue;
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* The response for the 'monitor_cancel' method.
|
|
98
|
+
*/
|
|
99
|
+
export type MonitorCancelResponse = OvsdbResponse<Record<string, never>>;
|
|
100
|
+
/**
|
|
101
|
+
* The request for the 'echo' method.
|
|
102
|
+
*/
|
|
103
|
+
export type EchoRequest = {
|
|
104
|
+
method: 'echo';
|
|
105
|
+
params: JsonValue[];
|
|
106
|
+
id: JsonValue;
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* The response for the 'echo' method.
|
|
110
|
+
*/
|
|
111
|
+
export type EchoResponse = OvsdbResponse<JsonValue[]>;
|
|
112
|
+
/**
|
|
113
|
+
* The notification for the 'update' method.
|
|
114
|
+
*/
|
|
115
|
+
export type UpdateNotification = {
|
|
116
|
+
method: 'update';
|
|
117
|
+
params: [JsonValue, Record<string, TableUpdate>];
|
|
118
|
+
id: null;
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* The notification for the 'locked' method.
|
|
122
|
+
*/
|
|
123
|
+
export type LockedNotification = {
|
|
124
|
+
method: 'locked';
|
|
125
|
+
params: [string];
|
|
126
|
+
id: null;
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* The notification for the 'stolen' method.
|
|
130
|
+
*/
|
|
131
|
+
export type StolenNotification = {
|
|
132
|
+
method: 'stolen';
|
|
133
|
+
params: [string];
|
|
134
|
+
id: null;
|
|
135
|
+
};
|
|
136
|
+
export interface DatabaseSchema {
|
|
137
|
+
name: string;
|
|
138
|
+
version: string;
|
|
139
|
+
cksum?: string;
|
|
140
|
+
tables: Record<string, TableSchema>;
|
|
141
|
+
}
|
|
142
|
+
export interface TableSchema {
|
|
143
|
+
columns: Record<string, ColumnSchema>;
|
|
144
|
+
maxRows?: number;
|
|
145
|
+
isRoot?: boolean;
|
|
146
|
+
indexes?: string[][];
|
|
147
|
+
}
|
|
148
|
+
export interface ColumnSchema {
|
|
149
|
+
type: Type;
|
|
150
|
+
ephemeral?: boolean;
|
|
151
|
+
mutable?: boolean;
|
|
152
|
+
}
|
|
153
|
+
export type Type = AtomicType | {
|
|
154
|
+
key: BaseType;
|
|
155
|
+
value?: BaseType;
|
|
156
|
+
min?: number;
|
|
157
|
+
max?: number | 'unlimited';
|
|
158
|
+
};
|
|
159
|
+
export type AtomicType = 'integer' | 'real' | 'boolean' | 'string' | 'uuid';
|
|
160
|
+
export type BaseType = AtomicType | {
|
|
161
|
+
type: AtomicType;
|
|
162
|
+
enum?: JsonValue;
|
|
163
|
+
minInteger?: number;
|
|
164
|
+
maxInteger?: number;
|
|
165
|
+
minReal?: number;
|
|
166
|
+
maxReal?: number;
|
|
167
|
+
minLength?: number;
|
|
168
|
+
maxLength?: number;
|
|
169
|
+
refTable?: string;
|
|
170
|
+
refType?: 'strong' | 'weak';
|
|
171
|
+
};
|
|
172
|
+
export type TableUpdate = Record<string, RowUpdate>;
|
|
173
|
+
export interface RowUpdate {
|
|
174
|
+
old?: Record<string, JsonValue>;
|
|
175
|
+
new?: Record<string, JsonValue>;
|
|
176
|
+
}
|
|
177
|
+
export type DatabaseOperation = {
|
|
178
|
+
op: 'insert';
|
|
179
|
+
table: string;
|
|
180
|
+
row: Record<string, JsonValue>;
|
|
181
|
+
uuidName?: string;
|
|
182
|
+
} | {
|
|
183
|
+
op: 'select';
|
|
184
|
+
table: string;
|
|
185
|
+
where: Condition[];
|
|
186
|
+
columns?: string[];
|
|
187
|
+
} | {
|
|
188
|
+
op: 'update';
|
|
189
|
+
table: string;
|
|
190
|
+
where: Condition[];
|
|
191
|
+
row: Record<string, JsonValue>;
|
|
192
|
+
} | {
|
|
193
|
+
op: 'mutate';
|
|
194
|
+
table: string;
|
|
195
|
+
where: Condition[];
|
|
196
|
+
mutations: Mutation[];
|
|
197
|
+
} | {
|
|
198
|
+
op: 'delete';
|
|
199
|
+
table: string;
|
|
200
|
+
where: Condition[];
|
|
201
|
+
} | {
|
|
202
|
+
op: 'wait';
|
|
203
|
+
timeout?: number;
|
|
204
|
+
table: string;
|
|
205
|
+
where: Condition[];
|
|
206
|
+
columns: string[];
|
|
207
|
+
until: '==' | '!=';
|
|
208
|
+
rows: Record<string, JsonValue>[];
|
|
209
|
+
} | {
|
|
210
|
+
op: 'commit';
|
|
211
|
+
durable: boolean;
|
|
212
|
+
} | {
|
|
213
|
+
op: 'abort';
|
|
214
|
+
} | {
|
|
215
|
+
op: 'comment';
|
|
216
|
+
comment: string;
|
|
217
|
+
} | {
|
|
218
|
+
op: 'assert';
|
|
219
|
+
lock: string;
|
|
220
|
+
};
|
|
221
|
+
export type Condition = [string, string, JsonValue];
|
|
222
|
+
export type Mutation = [string, string, JsonValue];
|
package/package.json
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sourceregistry/node-ovsdb",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Open vSwitch Database Management Protocol typescript client",
|
|
5
|
+
"main": "./dist/index.cjs",
|
|
6
|
+
"module": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"require": "./dist/index.cjs"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"dev": "vite",
|
|
19
|
+
"build": "tsc && vite build",
|
|
20
|
+
"preview": "vite preview",
|
|
21
|
+
"test": "vitest"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/SourceRegistry/node-ovsdb.git"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^24.3.0",
|
|
29
|
+
"typescript": "^5.9.2",
|
|
30
|
+
"vite": "^7.1.3",
|
|
31
|
+
"vite-plugin-dts": "^4.5.4",
|
|
32
|
+
"vitest": "^3.2.4",
|
|
33
|
+
"@semantic-release/commit-analyzer": "^13.0.1",
|
|
34
|
+
"@semantic-release/release-notes-generator": "^14.0.3",
|
|
35
|
+
"@semantic-release/changelog": "^6.0.3",
|
|
36
|
+
"@semantic-release/npm": "^12.0.2",
|
|
37
|
+
"@semantic-release/git": "^10.0.1"
|
|
38
|
+
},
|
|
39
|
+
"keywords": [
|
|
40
|
+
"networking",
|
|
41
|
+
"ovs",
|
|
42
|
+
"Open vSwitch",
|
|
43
|
+
"RFC7047",
|
|
44
|
+
"ISSN2070-1721 "
|
|
45
|
+
],
|
|
46
|
+
"author": "A.P.A. Slaa (a.p.a.slaa@projectsource.nl)",
|
|
47
|
+
"license": "Apache-2.0",
|
|
48
|
+
"bugs": {
|
|
49
|
+
"url": "https://github.com/SourceRegistry/node-ovsdb/issues"
|
|
50
|
+
},
|
|
51
|
+
"homepage": "https://github.com/SourceRegistry/node-ovsdb#readme",
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public"
|
|
54
|
+
},
|
|
55
|
+
"release": {
|
|
56
|
+
"branches": [
|
|
57
|
+
"main"
|
|
58
|
+
],
|
|
59
|
+
"plugins": [
|
|
60
|
+
[
|
|
61
|
+
"@semantic-release/commit-analyzer"
|
|
62
|
+
],
|
|
63
|
+
[
|
|
64
|
+
"@semantic-release/release-notes-generator"
|
|
65
|
+
],
|
|
66
|
+
[
|
|
67
|
+
"@semantic-release/changelog"
|
|
68
|
+
],
|
|
69
|
+
[
|
|
70
|
+
"@semantic-release/npm"
|
|
71
|
+
],
|
|
72
|
+
[
|
|
73
|
+
"@semantic-release/git",
|
|
74
|
+
{
|
|
75
|
+
"assets": [
|
|
76
|
+
"package.json",
|
|
77
|
+
"CHANGELOG.md"
|
|
78
|
+
],
|
|
79
|
+
"message": "node-ovsdb(release): 🚀 ${nextRelease.version} \n\n${nextRelease.notes}"
|
|
80
|
+
}
|
|
81
|
+
]
|
|
82
|
+
]
|
|
83
|
+
}
|
|
84
|
+
}
|