@0xobelisk/grpc-client 1.2.0-pre.68

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,92 @@
1
+ Business Source License 1.1
2
+
3
+ License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved.
4
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
5
+
6
+ -----------------------------------------------------------------------------
7
+
8
+ Parameters
9
+
10
+ Licensor: Obelisk Labs
11
+
12
+ Licensed Work: Dubhe
13
+ The Licensed Work is (c) 2023 Obelisk Labs
14
+
15
+ -----------------------------------------------------------------------------
16
+
17
+ Terms
18
+
19
+ The Licensor hereby grants you the right to copy, modify, create derivative
20
+ works, redistribute, and make non-production use of the Licensed Work. The
21
+ Licensor may make an Additional Use Grant, above, permitting limited
22
+ production use.
23
+
24
+ Effective on the Change Date, or the fourth anniversary of the first publicly
25
+ available distribution of a specific version of the Licensed Work under this
26
+ License, whichever comes first, the Licensor hereby grants you rights under
27
+ the terms of the Change License, and the rights granted in the paragraph
28
+ above terminate.
29
+
30
+ If your use of the Licensed Work does not comply with the requirements
31
+ currently in effect as described in this License, you must purchase a
32
+ commercial license from the Licensor, its affiliated entities, or authorized
33
+ resellers, or you must refrain from using the Licensed Work.
34
+
35
+ All copies of the original and modified Licensed Work, and derivative works
36
+ of the Licensed Work, are subject to this License. This License applies
37
+ separately for each version of the Licensed Work and the Change Date may vary
38
+ for each version of the Licensed Work released by Licensor.
39
+
40
+ You must conspicuously display this License on each original or modified copy
41
+ of the Licensed Work. If you receive the Licensed Work in original or
42
+ modified form from a third party, the terms and conditions set forth in this
43
+ License apply to your use of that work.
44
+
45
+ Any use of the Licensed Work in violation of this License will automatically
46
+ terminate your rights under this License for the current and all other
47
+ versions of the Licensed Work.
48
+
49
+ This License does not grant you any right in any trademark or logo of
50
+ Licensor or its affiliates (provided that you may use a trademark or logo of
51
+ Licensor as expressly required by this License).
52
+
53
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
54
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
55
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
56
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
57
+ TITLE.
58
+
59
+ MariaDB hereby grants you permission to use this License’s text to license
60
+ your works, and to refer to it using the trademark "Business Source License",
61
+ as long as you comply with the Covenants of Licensor below.
62
+
63
+ -----------------------------------------------------------------------------
64
+
65
+ Covenants of Licensor
66
+
67
+ In consideration of the right to use this License’s text and the "Business
68
+ Source License" name and trademark, Licensor covenants to MariaDB, and to all
69
+ other recipients of the licensed work to be provided by Licensor:
70
+
71
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
72
+ or a license that is compatible with GPL Version 2.0 or a later version,
73
+ where "compatible" means that software provided under the Change License can
74
+ be included in a program with software provided under GPL Version 2.0 or a
75
+ later version. Licensor may specify additional Change Licenses without
76
+ limitation.
77
+
78
+ 2. To either: (a) specify an additional grant of rights to use that does not
79
+ impose any additional restriction on the right granted in this License, as
80
+ the Additional Use Grant; or (b) insert the text "None".
81
+
82
+ 3. To specify a Change Date.
83
+
84
+ 4. Not to modify this License in any other way.
85
+
86
+ -----------------------------------------------------------------------------
87
+
88
+ Notice
89
+
90
+ The Business Source License (this document, or the "License") is not an Open
91
+ Source license. However, the Licensed Work will eventually be made available
92
+ under an Open Source License, as stated in this License.
package/README.md ADDED
@@ -0,0 +1,407 @@
1
+ # @0xobelisk/grpc-client
2
+
3
+ TypeScript gRPC client for interacting with the Dubhe Indexer using protobuf-ts.
4
+
5
+ ## Features
6
+
7
+ - 🔍 **Advanced Querying**: Query table data with comprehensive filtering, sorting, and pagination
8
+ - 📡 **Real-time Subscription**: Subscribe to table updates and receive real-time data changes
9
+ - 🛠️ **Flexible API**: Both simple and advanced query APIs with fluent query builder
10
+ - 🔧 **Type-Safe**: Full TypeScript support with generated protobuf types
11
+ - 📊 **Rich Filtering**: Support for various filter operators (equals, like, in, between, etc.)
12
+ - 📄 **Pagination**: Built-in pagination support with page-based navigation
13
+ - 🛠️ **Utility Functions**: Rich utility functions for data processing and filtering
14
+ - 🌐 **Web Compatible**: Uses gRPC-Web transport for browser compatibility
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @0xobelisk/grpc-client
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ### Basic Connection
25
+
26
+ ```typescript
27
+ import { createDubheGrpcClient } from '@0xobelisk/grpc-client';
28
+
29
+ const client = createDubheGrpcClient({
30
+ endpoint: '127.0.0.1:8080', // gRPC server endpoint (without http://)
31
+ timeout: 10000,
32
+ enableRetry: true,
33
+ retryAttempts: 3
34
+ });
35
+
36
+ await client.connect();
37
+ console.log('Connected successfully!');
38
+ ```
39
+
40
+ ### Simple Querying
41
+
42
+ ```typescript
43
+ // Basic query - get all data with pagination
44
+ const response = await client.query('users', {
45
+ pageSize: 10,
46
+ includeTotalCount: true
47
+ });
48
+
49
+ // Query with field selection
50
+ const response = await client.query('users', {
51
+ select: ['id', 'name', 'email'],
52
+ pageSize: 20
53
+ });
54
+
55
+ // Query with filtering
56
+ const response = await client.query('users', {
57
+ where: {
58
+ status: 'active',
59
+ role: ['admin', 'user'], // IN operator
60
+ age: { min: 18, max: 65 } // BETWEEN operator
61
+ },
62
+ orderBy: [
63
+ { field: 'created_at', direction: 'desc' },
64
+ { field: 'name', direction: 'asc' }
65
+ ],
66
+ page: 1,
67
+ pageSize: 20,
68
+ includeTotalCount: true
69
+ });
70
+ ```
71
+
72
+ ### Advanced Querying
73
+
74
+ ```typescript
75
+ import { FilterOperator, SortDirection } from '@0xobelisk/grpc-client';
76
+
77
+ const response = await client.queryTable({
78
+ tableName: 'users',
79
+ selectFields: ['id', 'name', 'created_at'],
80
+ filters: [
81
+ {
82
+ fieldName: 'name',
83
+ operator: FilterOperator.LIKE,
84
+ value: { stringValue: '%john%' }
85
+ },
86
+ {
87
+ fieldName: 'age',
88
+ operator: FilterOperator.GREATER_THAN,
89
+ value: { intValue: 18 }
90
+ },
91
+ {
92
+ fieldName: 'status',
93
+ operator: FilterOperator.IN,
94
+ value: { stringList: { values: ['active', 'pending'] } }
95
+ }
96
+ ],
97
+ sorts: [
98
+ {
99
+ fieldName: 'created_at',
100
+ direction: SortDirection.DESCENDING,
101
+ priority: 0
102
+ }
103
+ ],
104
+ pagination: {
105
+ page: 1,
106
+ pageSize: 10
107
+ },
108
+ includeTotalCount: true
109
+ });
110
+ ```
111
+
112
+ ### Query Builder (Fluent API)
113
+
114
+ ```typescript
115
+ const response = await client
116
+ .createQueryBuilder()
117
+ .tableName('users')
118
+ .select('id', 'name', 'email')
119
+ .where({
120
+ status: 'active',
121
+ role: ['admin', 'user']
122
+ })
123
+ .orderBy('created_at', 'desc')
124
+ .page(1, 15)
125
+ .includeTotalCount(true)
126
+ .execute();
127
+ ```
128
+
129
+ ### Real-time Subscriptions
130
+
131
+ ```typescript
132
+ const subscriptionId = client.subscribeTable(
133
+ ['users', 'posts'], // table names to subscribe to
134
+ {
135
+ onUpdate: (change) => {
136
+ console.log(`Table updated: ${change.table_id}`);
137
+ console.log('New data:', change.data);
138
+ },
139
+ onError: (error) => {
140
+ console.error('Subscription error:', error);
141
+ },
142
+ onConnect: () => {
143
+ console.log('Subscription connected');
144
+ },
145
+ onDisconnect: () => {
146
+ console.log('Subscription disconnected');
147
+ }
148
+ }
149
+ );
150
+
151
+ console.log(`Subscription ID: ${subscriptionId}`);
152
+
153
+ // Later, unsubscribe
154
+ client.unsubscribe(subscriptionId);
155
+ ```
156
+
157
+ ## Configuration
158
+
159
+ ```typescript
160
+ interface DubheGrpcClientConfig {
161
+ endpoint: string; // gRPC server endpoint
162
+ enableRetry?: boolean; // Enable automatic retry (default: true)
163
+ retryAttempts?: number; // Number of retry attempts (default: 3)
164
+ timeout?: number; // Request timeout in ms (default: 30000)
165
+ }
166
+ ```
167
+
168
+ ## Filter Operators
169
+
170
+ The client supports various filter operators:
171
+
172
+ ```typescript
173
+ import { FilterOperator } from '@0xobelisk/grpc-client';
174
+
175
+ // Available operators:
176
+ FilterOperator.EQUALS;
177
+ FilterOperator.NOT_EQUALS;
178
+ FilterOperator.GREATER_THAN;
179
+ FilterOperator.GREATER_THAN_EQUAL;
180
+ FilterOperator.LESS_THAN;
181
+ FilterOperator.LESS_THAN_EQUAL;
182
+ FilterOperator.LIKE;
183
+ FilterOperator.NOT_LIKE;
184
+ FilterOperator.IN;
185
+ FilterOperator.NOT_IN;
186
+ FilterOperator.IS_NULL;
187
+ FilterOperator.IS_NOT_NULL;
188
+ FilterOperator.BETWEEN;
189
+ FilterOperator.NOT_BETWEEN;
190
+ ```
191
+
192
+ ## Utility Functions
193
+
194
+ ### GrpcUtils
195
+
196
+ ```typescript
197
+ import { GrpcUtils } from '@0xobelisk/grpc-client';
198
+
199
+ // Extract field from data
200
+ const value = GrpcUtils.extractField(data, 'fieldName');
201
+
202
+ // Convert protobuf struct to object
203
+ const obj = GrpcUtils.structToObject(struct);
204
+
205
+ // Check if error is gRPC error
206
+ if (GrpcUtils.isGrpcError(error, 404)) {
207
+ console.log('Not found error');
208
+ }
209
+
210
+ // Format error for display
211
+ const message = GrpcUtils.formatGrpcError(error);
212
+ ```
213
+
214
+ ### Data Processing Utilities
215
+
216
+ ```typescript
217
+ import { DataUtils, QueryUtils, ValidationUtils } from '@0xobelisk/grpc-client';
218
+
219
+ // Build filters easily
220
+ const filters = [
221
+ QueryUtils.equals('status', 'active'),
222
+ QueryUtils.in('role', ['admin', 'user']),
223
+ QueryUtils.like('name', '%john%'),
224
+ QueryUtils.between('age', 18, 65),
225
+ QueryUtils.isNotNull('email')
226
+ ];
227
+
228
+ // Data manipulation
229
+ const flattened = DataUtils.flatten(nestedObject);
230
+ const merged = DataUtils.deepMerge(obj1, obj2);
231
+ const picked = DataUtils.pick(object, ['field1', 'field2']);
232
+
233
+ // Validation
234
+ const isValid = ValidationUtils.isValidTableName('users');
235
+ const isValidField = ValidationUtils.isValidFieldName('user.name');
236
+ ```
237
+
238
+ ## Error Handling
239
+
240
+ ```typescript
241
+ import { ErrorUtils } from '@0xobelisk/grpc-client';
242
+
243
+ try {
244
+ const response = await client.query('users');
245
+ } catch (error) {
246
+ if (ErrorUtils.isTimeoutError(error)) {
247
+ console.log('Request timed out');
248
+ } else if (ErrorUtils.isConnectionError(error)) {
249
+ console.log('Connection failed');
250
+ } else {
251
+ console.log('Other error:', ErrorUtils.formatError(error));
252
+ }
253
+ }
254
+ ```
255
+
256
+ ## Connection Management
257
+
258
+ ```typescript
259
+ // Check connection status
260
+ console.log('Status:', client.getStatus()); // 'connected', 'connecting', 'disconnected', 'error'
261
+
262
+ // Check if connected
263
+ if (client.isConnected()) {
264
+ console.log('Client is ready');
265
+ }
266
+
267
+ // Get active subscriptions
268
+ console.log('Active subscriptions:', client.getActiveSubscriptionCount());
269
+ console.log('Subscription IDs:', client.getActiveSubscriptionIds());
270
+
271
+ // Disconnect
272
+ client.disconnect();
273
+ ```
274
+
275
+ ## Complete Example
276
+
277
+ ```typescript
278
+ import {
279
+ createDubheGrpcClient,
280
+ FilterOperator,
281
+ SortDirection,
282
+ GrpcUtils
283
+ } from '@0xobelisk/grpc-client';
284
+
285
+ async function example() {
286
+ // Create and connect client
287
+ const client = createDubheGrpcClient({
288
+ endpoint: '127.0.0.1:8080',
289
+ timeout: 10000
290
+ });
291
+
292
+ await client.connect();
293
+
294
+ try {
295
+ // Query data
296
+ const users = await client.query('users', {
297
+ where: { status: 'active' },
298
+ orderBy: [{ field: 'created_at', direction: 'desc' }],
299
+ pageSize: 10,
300
+ includeTotalCount: true
301
+ });
302
+
303
+ console.log(`Found ${users.totalCount} users`);
304
+ console.log('Users:', users.data);
305
+
306
+ // Subscribe to updates
307
+ const subscriptionId = client.subscribeTable(['users'], {
308
+ onUpdate: (change) => {
309
+ console.log('User updated:', change.data);
310
+ },
311
+ onError: (error) => {
312
+ console.error('Subscription error:', GrpcUtils.formatGrpcError(error));
313
+ }
314
+ });
315
+
316
+ // Cleanup on exit
317
+ process.on('SIGINT', () => {
318
+ client.unsubscribe(subscriptionId);
319
+ client.disconnect();
320
+ process.exit(0);
321
+ });
322
+ } catch (error) {
323
+ console.error('Query failed:', GrpcUtils.formatGrpcError(error));
324
+ }
325
+ }
326
+
327
+ example();
328
+ ```
329
+
330
+ ## Advanced Types
331
+
332
+ For advanced usage, you can access the raw protobuf types:
333
+
334
+ ```typescript
335
+ import {
336
+ ProtoDubheGrpcClient,
337
+ ProtoQueryRequest,
338
+ ProtoQueryResponse
339
+ } from '@0xobelisk/grpc-client';
340
+
341
+ // Direct access to protobuf client if needed
342
+ const protoClient = new ProtoDubheGrpcClient(transport);
343
+ ```
344
+
345
+ ## Development
346
+
347
+ ### Generate Protobuf Types
348
+
349
+ ```bash
350
+ npm run generate
351
+ ```
352
+
353
+ This command will:
354
+
355
+ 1. Clean existing proto files
356
+ 2. Generate new TypeScript types from `.proto` files
357
+ 3. Format the generated code
358
+
359
+ ### Build
360
+
361
+ ```bash
362
+ npm run build
363
+ ```
364
+
365
+ ### Lint
366
+
367
+ ```bash
368
+ npm run lint
369
+ npm run lint:fix
370
+ ```
371
+
372
+ ## Migration from v1.x
373
+
374
+ The v2.x version introduces several breaking changes:
375
+
376
+ 1. **Removed EventEmitter**: Client no longer extends EventEmitter for simpler API
377
+ 2. **Updated Transport**: Now uses `@protobuf-ts/grpcweb-transport` instead of `@grpc/grpc-js`
378
+ 3. **Type-safe**: Full TypeScript support with generated protobuf types
379
+ 4. **Simplified API**: Cleaner method signatures and better error handling
380
+
381
+ ### Before (v1.x)
382
+
383
+ ```typescript
384
+ client.on('connect', () => console.log('Connected'));
385
+ client.on('error', (error) => console.error(error));
386
+ ```
387
+
388
+ ### After (v2.x)
389
+
390
+ ```typescript
391
+ // Connection status is handled through method calls
392
+ await client.connect();
393
+ if (client.isConnected()) {
394
+ console.log('Connected');
395
+ }
396
+
397
+ // Error handling through try-catch
398
+ try {
399
+ await client.query('table');
400
+ } catch (error) {
401
+ console.error(error);
402
+ }
403
+ ```
404
+
405
+ ## License
406
+
407
+ Apache-2.0
@@ -0,0 +1,6 @@
1
+ import type { GrpcWebOptions } from '@protobuf-ts/grpcweb-transport';
2
+ import { DubheGrpcClient as ProtoDubheGrpcClient } from './proto/dubhe_grpc.client';
3
+ export declare class DubheGrpcClient {
4
+ dubheGrpcClient: ProtoDubheGrpcClient;
5
+ constructor(options: GrpcWebOptions);
6
+ }
@@ -0,0 +1,5 @@
1
+ export * from './types';
2
+ export { DubheGrpcClient as ProtoDubheGrpcClient } from './proto/dubhe_grpc.client';
3
+ export { FilterOperator, SortDirection } from './proto/dubhe_grpc';
4
+ export type { QueryRequest, QueryResponse, SubscribeRequest, TableChange, FilterCondition, FilterValue, SortSpecification, PaginationRequest, PaginationResponse } from './proto/dubhe_grpc';
5
+ export { DubheGrpcClient } from './client';