bloom-filter-driver 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,25 +1,41 @@
1
1
  # Bloom Filter Driver (TypeScript / Node.js HTTP Client)
2
2
 
3
- **BloomFilterDriver** thư viện client (SDK) nhỏ gọn được viết bằng TypeScript, đóng vai trò cầu nối giao tiếp giữa các ứng dụng Node.js/TypeScript (như `BloomFilterApplication`) máy chủ xử dữ liệu Bloom Filter (`BloomFilterProcess`) thông qua giao thức HTTP REST.
3
+ **BloomFilterDriver** is a lightweight client library (SDK) written in TypeScript, acting as a communication bridge between Node.js/TypeScript applications (such as `BloomFilterApplication`) and the Bloom Filter processing server (`BloomFilterProcess`) via the HTTP REST protocol.
4
4
 
5
- Thư viện được thiết kế độc lập, tuân thủ nguyên tắc kiến trúc sạch (Clean Architecture) với các lớp phân tách ràng, hỗ trợ đầy đủ kiểu dữ liệu TypeScript (Type Safety), chế kiểm tra tính hợp lệ dữ liệu (Validation) chặt chẽ và khả năng quản lý vòng đời request (Timeout & Cancellation) thông qua `AbortSignal`.
5
+ The library is architected independently, adhering to Clean Architecture principles with clear layer separation. It provides full TypeScript type safety, robust data validation mechanisms, and request lifecycle management (Timeout & Cancellation) via `AbortSignal`.
6
6
 
7
7
  ---
8
8
 
9
- ## 📦 Cài đặt
9
+ ## Prerequisites
10
10
 
11
- Bạn thể cài đặt thư viện thông qua các công cụ quản gói thông dụng:
11
+ Since **BloomFilterDriver** acts as an HTTP REST client SDK, you must ensure that the **BloomFilterProcess** server is running and ready to accept connections before making any API calls from your application.
12
+
13
+ You can pull and run the official Docker image of the processing server from Docker Hub:
14
+
15
+ ```bash
16
+ # Pull the latest image from Docker Hub
17
+ docker pull hongphucle1010/bloom-filter-process:latest
18
+
19
+ # Run the container on port 8080 (or your custom baseUrl port)
20
+ docker run -d -p 8080:8080 --name bloom-filter-process hongphucle1010/bloom-filter-process:latest
21
+ ```
22
+
23
+ ---
24
+
25
+ ## Installation
26
+
27
+ You can install the library using common package managers:
12
28
 
13
29
  ```bash
14
30
  npm install bloom-filter-driver
15
- # hoặc
31
+ # or
16
32
  yarn add bloom-filter-driver
17
- # hoặc
33
+ # or
18
34
  pnpm add bloom-filter-driver
19
35
  ```
20
36
 
21
- > **Lưu ý khi phát triển cục bộ (Local Development):**
22
- > Nếu bạn đang làm việc trực tiếp trong repository chứa mã nguồn của driver, hãy cài đặt các gói phụ thuộc biên dịch nguồn trước khi sử dụng hoặc liên kết (link) tới ứng dụng:
37
+ > **Note for Local Development:**
38
+ > If you are working directly within the driver repository, make sure to install dependencies and build the source code before using or linking it to your application:
23
39
  > ```bash
24
40
  > npm install
25
41
  > npm run build
@@ -27,25 +43,25 @@ pnpm add bloom-filter-driver
27
43
 
28
44
  ---
29
45
 
30
- ## 🚀 Khởi tạo & Cấu hình Driver
46
+ ## Initialization & Configuration
31
47
 
32
- Để sử dụng, bạn cần khởi tạo một đối tượng `BloomFilterDriver` với cấu hình `BloomDriverConfig`.
48
+ To use the library, you need to instantiate a `BloomFilterDriver` object with a `BloomDriverConfig`.
33
49
 
34
50
  ```typescript
35
51
  import { BloomFilterDriver } from 'bloom-filter-driver';
36
52
 
37
53
  const driver = new BloomFilterDriver({
38
- baseUrl: 'http://localhost:8080', // Địa chỉ gốc của máy chủ BloomFilterProcess
39
- timeoutMs: 5000, // (Tùy chọn) Thời gian chờ tối đa cho mỗi request (mặc định: 5000ms)
40
- // fetchImpl: customFetch // (Tùy chọn) Hàm fetch tùy chỉnh (hữu ích khi viết mock/unit test)
54
+ baseUrl: 'http://localhost:8080', // Base URL of the BloomFilterProcess server
55
+ timeoutMs: 5000, // (Optional) Maximum waiting time per request (default: 5000ms)
56
+ // fetchImpl: customFetch // (Optional) Custom fetch implementation (useful for mocking/unit testing)
41
57
  });
42
58
  ```
43
59
 
44
- ### Quản vòng đời Request (Timeout & Cancellation)
60
+ ### Request Lifecycle Management (Timeout & Cancellation)
45
61
 
46
- Tất cả các phương thức API trong driver đều hỗ trợ tham số tùy chọn `options?: { signal?: AbortSignal }`. Điều này cho phép bạn:
47
- - Tự động hủy các request vượt quá thời gian `timeoutMs` đã cấu hình.
48
- - Chủ động hủy request từ bên ngoài thông qua `AbortController`.
62
+ All API methods in the driver support an optional `options?: { signal?: AbortSignal }` parameter. This allows you to:
63
+ - Automatically cancel requests that exceed the configured `timeoutMs`.
64
+ - Manually cancel requests from the outside using an `AbortController`.
49
65
 
50
66
  ```typescript
51
67
  const controller = new AbortController();
@@ -56,74 +72,74 @@ try {
56
72
  { signal: controller.signal }
57
73
  );
58
74
  } catch (error) {
59
- // Xử lý khi request bị hủy hoặc lỗi
75
+ // Handle request cancellation or errors
60
76
  }
61
77
 
62
- // Khi muốn chủ động hủy request đang thực thi:
78
+ // To manually cancel an ongoing request:
63
79
  controller.abort();
64
80
  ```
65
81
 
66
82
  ---
67
83
 
68
- ## 🏗️ Kiến trúc & Thiết kế
84
+ ## Architecture & Design
69
85
 
70
- Driver được phân chia thành các module chuyên biệt nhằm đảm bảo tính dễ bảo trì và mở rộng:
86
+ The driver is divided into specialized modules to ensure maintainability and scalability:
71
87
 
72
88
  ```
73
89
  ┌─────────────────────────────────────────────────────────┐
74
- │ BloomFilterDriver │ (Lớp Facade tổng quan)
90
+ │ BloomFilterDriver │ (Main Facade Layer)
75
91
  └────────────┬───────────────────────────────┬────────────┘
76
92
  │ │
77
93
  ▼ ▼
78
94
  ┌─────────────────────────┐ ┌─────────────────────────┐
79
- │ BloomApiClient │ │ RangeApiClient │ (Lớp Client nghiệp vụ)
95
+ │ BloomApiClient │ │ RangeApiClient │ (Business Client Layer)
80
96
  └────────────┬────────────┘ └────────────┬────────────┘
81
97
  │ │
82
98
  └───────────────┬───────────────┘
83
99
 
84
100
 
85
101
  ┌─────────────────────────────────────────────────────────┐
86
- │ HttpClient │ (Lớp xử lý HTTP & Timeout)
102
+ │ HttpClient │ (HTTP & Timeout Handling)
87
103
  └────────────────────────────┬────────────────────────────┘
88
104
 
89
105
 
90
106
  ┌─────────────────────────────────────────────────────────┐
91
- │ DriverValidator │ (Lớp kiểm tra dữ liệu)
107
+ │ DriverValidator │ (Input Validation Layer)
92
108
  └─────────────────────────────────────────────────────────┘
93
109
  ```
94
110
 
95
- - **`BloomFilterDriver`**: Lớp giao diện chính (Facade) tổng hợp toàn bộ các phương thức thao tác với Bloom Filter RangeLH.
96
- - **`BloomApiClient`**: Quản các endpoint liên quan đến cấu trúc Bloom Filter (`/bloom/*`).
97
- - **`RangeApiClient`**: Quản các endpoint liên quan đến cấu trúc phân cấp/chỉ mục dải RangeLH (`/rangelh/*`).
98
- - **`HttpClient`**: Đóng gói hàm `fetch`, xử nối chuỗi URL, thiết lập HTTP headers, quản `AbortController` chuẩn hóa lỗi HTTP.
99
- - **`DriverValidator`**: Kiểm tra tính hợp lệ của dữ liệu đầu vào (tên bộ lọc, dải giá trị, xác suất, tham số cấu hình) trước khi gửi request tới máy chủ.
111
+ - **`BloomFilterDriver`**: The main Facade layer aggregating all methods for interacting with Bloom Filters and RangeLH.
112
+ - **`BloomApiClient`**: Manages endpoints related to Bloom Filter structures (`/bloom/*`).
113
+ - **`RangeApiClient`**: Manages endpoints related to RangeLH hierarchical index structures (`/rangelh/*`).
114
+ - **`HttpClient`**: Encapsulates `fetch`, handles URL construction, sets HTTP headers, manages `AbortController`, and standardizes HTTP errors.
115
+ - **`DriverValidator`**: Validates input data (filter names, ranges, probabilities, configuration parameters) before sending requests to the server.
100
116
 
101
117
  ---
102
118
 
103
- ## 📚 Tài liệu API Tham khảo (API Reference)
119
+ ## 📚 API Reference
104
120
 
105
121
  ---
106
122
 
107
123
  ### 1. Bloom Filter API (`BloomApiClient`)
108
124
 
109
- Các API chuyên biệt dành cho bộ lọc Bloom thông thường (Standard Bloom Filter) bộ lọc Bloom có đếm (Counting Bloom Filter).
125
+ Specialized APIs for Standard Bloom Filters and Counting Bloom Filters.
110
126
 
111
127
  #### `createBloom(payload: BloomCreatePayload, options?: DriverRequestOptions): Promise<void>`
112
- Khởi tạo cấu hình một bộ lọc Bloom mới trên máy chủ trước khi sử dụng.
128
+ Initializes and configures a new Bloom filter on the server before use.
113
129
 
114
130
  ```typescript
115
131
  await driver.createBloom({
116
- bfName: 'users-bf', // Tên định danh của bộ lọc
117
- expectedValues: 100000, // Số lượng phần tử dự kiến thêm vào
118
- bloomType: 'standard', // 'standard' | 'counting' (mặc định: 'standard')
119
- falsePositiveProbability: 0.01, // (Tùy chọn) Xác suất dương tính giả mong muốn ( dụ: 1%)
120
- counterBits: 4 // (Tùy chọn) Số bit cho mỗi bộ đếm (chỉ dùng khi bloomType 'counting', từ 1-8)
132
+ bfName: 'users-bf', // Identifier of the bloom filter
133
+ expectedValues: 100000, // Expected number of elements to be added
134
+ bloomType: 'standard', // 'standard' | 'counting' (default: 'standard')
135
+ falsePositiveProbability: 0.01, // (Optional) Desired false positive probability (e.g., 1%)
136
+ counterBits: 4 // (Optional) Number of bits per counter (only used when bloomType is 'counting', from 1-8)
121
137
  });
122
138
  ```
123
- > *Lưu ý:* Thư viện cung cấp hàm alias `configureBloom` tương đương với `createBloom` nhằm mục đích tương thích ngược. Khuyến nghị sử dụng `createBloom` cho các dự án mới.
139
+ > *Note:* The library provides an alias function `configureBloom` equivalent to `createBloom` for backward compatibility. Using `createBloom` is recommended for new projects.
124
140
 
125
141
  #### `add(payload: BloomDataPayload, options?: DriverRequestOptions): Promise<void>`
126
- Thêm một phần tử (chuỗi dữ liệu) vào bộ lọc Bloom.
142
+ Adds an element (string data) to the Bloom filter.
127
143
 
128
144
  ```typescript
129
145
  await driver.add({
@@ -133,7 +149,7 @@ await driver.add({
133
149
  ```
134
150
 
135
151
  #### `mightContain(payload: BloomDataPayload, options?: DriverRequestOptions): Promise<boolean>`
136
- Kiểm tra xem một phần tử ** thể** tồn tại trong bộ lọc Bloom hay không.
152
+ Checks whether an element **might** exist in the Bloom filter.
137
153
 
138
154
  ```typescript
139
155
  const isPresent = await driver.mightContain({
@@ -142,14 +158,14 @@ const isPresent = await driver.mightContain({
142
158
  });
143
159
 
144
160
  if (isPresent) {
145
- console.log('Phần tử THỂ tồn tại ( rủi ro dương tính giả theo xác suất đã cấu hình).');
161
+ console.log('Element MIGHT exist (subject to the configured false positive probability).');
146
162
  } else {
147
- console.log('Phần tử CHẮC CHẮN KHÔNG tồn tại trong bộ lọc.');
163
+ console.log('Element DEFINITELY DOES NOT exist in the filter.');
148
164
  }
149
165
  ```
150
166
 
151
167
  #### `remove(payload: BloomDataPayload, options?: DriverRequestOptions): Promise<void>`
152
- Xóa một phần tử khỏi bộ lọc Bloom. (Yêu cầu bộ lọc phải được khởi tạo với `bloomType: 'counting'`).
168
+ Removes an element from the Bloom filter. (Requires the filter to be initialized with `bloomType: 'counting'`).
153
169
 
154
170
  ```typescript
155
171
  await driver.remove({
@@ -159,45 +175,45 @@ await driver.remove({
159
175
  ```
160
176
 
161
177
  #### `benchLoadSequentialKeys(payload: BloomBenchSequentialPayload, options?: DriverRequestOptions): Promise<void>`
162
- API hỗ trợ nạp dữ liệu giả lập hàng loạt (bulk insert) trực tiếp trên máy chủ với hiệu năng cao (chỉ tốn 1 lần gọi HTTP 1 lần lưu trữ/persist). Thường dùng cho mục đích benchmark hoặc khởi tạo dữ liệu mẫu.
178
+ API supporting high-performance bulk insertion of simulated sequential keys directly on the server (requiring only 1 HTTP call and 1 persistence operation). Typically used for benchmarking or generating sample data.
163
179
 
164
180
  ```typescript
165
181
  await driver.benchLoadSequentialKeys({
166
182
  bfName: 'users-bf',
167
- from: 1, // (Tùy chọn) Chỉ số bắt đầu (mặc định: 1)
168
- to: 100000, // Chỉ số kết thúc
169
- keyWidth: 10 // (Tùy chọn) Độ rộng chuỗi số được đệm zero (zero-padding, mặc định: 10)
183
+ from: 1, // (Optional) Starting index (default: 1)
184
+ to: 100000, // Ending index
185
+ keyWidth: 10 // (Optional) Width of zero-padded numeric string (default: 10)
170
186
  });
171
- // Máy chủ sẽ tự động nạp các key dạng: "k-0000000001", "k-0000000002", ..., "k-0000100000"
187
+ // The server will automatically load keys such as: "k-0000000001", "k-0000000002", ..., "k-0000100000"
172
188
  ```
173
189
 
174
190
  ---
175
191
 
176
192
  ### 2. RangeLH API (`RangeApiClient`)
177
193
 
178
- RangeLH (Range Linear Hashing) cấu trúc chỉ mục nâng cao phân bổ theo `key`, hỗ trợ tối ưu hóa các truy vấn điểm (point query), truy vấn khoảng (range query) tổng hợp dữ liệu (aggregation).
194
+ RangeLH (Range Linear Hashing) is an advanced key-distributed index structure supporting optimized point queries, range queries, and aggregations.
179
195
 
180
196
  #### `createRange(payload: RangeCreatePayload, options?: DriverRequestOptions): Promise<void>`
181
- Khởi tạo cấu trúc chỉ mục RangeLH với các tham số tinh chỉnh chuyên sâu.
197
+ Initializes the RangeLH index structure with advanced tuning parameters.
182
198
 
183
199
  ```typescript
184
200
  await driver.createRange({
185
201
  bfName: 'orders-range',
186
202
  config: {
187
- masterInitNumBucket: 2, // Số lượng bucket khởi tạo ban đầu cho Master Index
188
- masterSplitPolicy: 0.5, // Tỷ lệ/Chính sách tách bucket (split policy)
189
- expectedNItems: 1000000, // Tổng số lượng phần tử dự kiến
190
- fpProbBloomRF: 0.01, // Xác suất dương tính giả cho các Bloom Filter con
191
- deltaBloomRF: 10, // Tham số dải delta cho bộ lọc
192
- keyLength: 20, // Độ dài cố định của chuỗi key (từ 1-64)
193
- maxBytesString: 8, // Số byte tối đa cho phần chuỗi giá trị (từ 1-8)
194
- floatScale: 100 // Tỷ lệ nhân (scale) cho dữ liệu số thực
203
+ masterInitNumBucket: 2, // Initial number of buckets for Master Index
204
+ masterSplitPolicy: 0.5, // Bucket split policy/ratio
205
+ expectedNItems: 1000000, // Total expected number of elements
206
+ fpProbBloomRF: 0.01, // False positive probability for child Bloom Filters
207
+ deltaBloomRF: 10, // Delta range parameter for the filter
208
+ keyLength: 20, // Fixed length of the key string (from 1-64)
209
+ maxBytesString: 8, // Maximum bytes for the string value portion (from 1-8)
210
+ floatScale: 100 // Scaling factor for floating-point data
195
211
  }
196
212
  });
197
213
  ```
198
214
 
199
- #### `addRange(payload: RangePayload, options?: Driver: RequestOptions): Promise<void>`
200
- Thêm một cặp định danh/khóa (key) đơn lẻ vào chỉ mục RangeLH.
215
+ #### `addRange(payload: RangePayload, options?: DriverRequestOptions): Promise<void>`
216
+ Adds a single key/identifier pair to the RangeLH index.
201
217
 
202
218
  ```typescript
203
219
  await driver.addRange({
@@ -207,7 +223,7 @@ await driver.addRange({
207
223
  ```
208
224
 
209
225
  #### `addRangeBulk(payload: RangeBulkAddPayload, options?: DriverRequestOptions): Promise<void>`
210
- Thêm nhiều khóa cùng lúc (bulk insert) vào chỉ mục RangeLH, giúp tiết kiệm băng thông và giảm thiểu độ trễ mạng.
226
+ Adds multiple keys simultaneously (bulk insert) to the RangeLH index, conserving bandwidth and minimizing network latency.
211
227
 
212
228
  ```typescript
213
229
  await driver.addRangeBulk({
@@ -221,7 +237,7 @@ await driver.addRangeBulk({
221
237
  ```
222
238
 
223
239
  #### `removeRange(payload: RangePayload, options?: DriverRequestOptions): Promise<void>`
224
- Xóa một khóa khỏi chỉ mục RangeLH.
240
+ Removes a key from the RangeLH index.
225
241
 
226
242
  ```typescript
227
243
  await driver.removeRange({
@@ -231,18 +247,18 @@ await driver.removeRange({
231
247
  ```
232
248
 
233
249
  #### `pointQuery(payload: PointQueryPayload, options?: DriverRequestOptions): Promise<string[]>`
234
- Truy vấn điểm để lấy ra danh sách các khóa khớp chính xác.
250
+ Performs a point query to retrieve a list of exactly matching keys.
235
251
 
236
252
  ```typescript
237
253
  const results = await driver.pointQuery({
238
254
  bfName: 'orders-range',
239
255
  key: '2026-05-17T12:00:00Z'
240
256
  });
241
- // results: string[] (Danh sách các giá trị/khóa tìm thấy)
257
+ // results: string[] (List of matching keys/values found)
242
258
  ```
243
259
 
244
260
  #### `rangeQuery(payload: RangeQueryPayload, options?: DriverRequestOptions): Promise<string[]>`
245
- Truy vấn khoảng để lấy ra danh sách các khóa nằm trong dải từ `from` đến `to`.
261
+ Performs a range query to retrieve a list of keys falling within the range from `from` to `to`.
246
262
 
247
263
  ```typescript
248
264
  const results = await driver.rangeQuery({
@@ -250,27 +266,27 @@ const results = await driver.rangeQuery({
250
266
  from: '2026-05-01T00:00:00Z',
251
267
  to: '2026-05-31T23:59:59Z'
252
268
  });
253
- // results: string[] (Danh sách các khóa thuộc khoảng thời gian/dải truy vấn)
269
+ // results: string[] (List of keys within the specified query range/timeframe)
254
270
  ```
255
271
 
256
272
  #### `aggregate(payload: RangeAggregatePayload, options?: DriverRequestOptions): Promise<number>`
257
- Thực hiện truy vấn tổng hợp (aggregation) dữ liệu trên một dải khóa cụ thể.
273
+ Performs data aggregation over a specific key range.
258
274
 
259
275
  ```typescript
260
276
  const totalOrders = await driver.aggregate({
261
277
  bfName: 'orders-range',
262
278
  from: '2026-05-01T00:00:00Z',
263
279
  to: '2026-05-31T23:59:59Z',
264
- op: 'count' // Các phép toán hỗ trợ: 'sum' | 'avg' | 'min' | 'max' | 'count'
280
+ op: 'count' // Supported operations: 'sum' | 'avg' | 'min' | 'max' | 'count'
265
281
  });
266
- console.log(`Tổng số đơn hàng trong tháng 5: ${totalOrders}`);
282
+ console.log(`Total orders in May: ${totalOrders}`);
267
283
  ```
268
284
 
269
285
  ---
270
286
 
271
- ## ⚠️ Xử lý lỗi (Error Handling)
287
+ ## ⚠️ Error Handling
272
288
 
273
- Tất cả các lỗi phát sinh từ driver (bao gồm lỗi kiểm tra dữ liệu đầu vào, lỗi mạng, lỗi timeout hoặc lỗi nghiệp vụ từ phía máy chủ) đều được ném ra dưới dạng đối tượng `BloomDriverError`.
289
+ All errors originating from the driver (including input validation errors, network errors, timeouts, or server-side business errors) are thrown as `BloomDriverError` objects.
274
290
 
275
291
  ```typescript
276
292
  import { BloomFilterDriver, BloomDriverError } from 'bloom-filter-driver';
@@ -279,20 +295,20 @@ const driver = new BloomFilterDriver({ baseUrl: 'http://localhost:8080' });
279
295
 
280
296
  async function execute() {
281
297
  try {
282
- // Thử gửi dữ liệu không hợp lệ (chuỗi rỗng)
298
+ // Attempt to send invalid data (empty string)
283
299
  await driver.add({ bfName: 'users-bf', data: '' });
284
300
  } catch (error) {
285
301
  if (error instanceof BloomDriverError) {
286
- console.error('[BloomDriverError] Thông báo lỗi:', error.message);
302
+ console.error('[BloomDriverError] Error message:', error.message);
287
303
 
288
304
  if (error.status) {
289
- console.error(' trạng thái HTTP:', error.status);
305
+ console.error('HTTP status code:', error.status);
290
306
  }
291
307
  if (error.responseBody) {
292
- console.error('Nội dung phản hồi từ máy chủ:', error.responseBody);
308
+ console.error('Server response body:', error.responseBody);
293
309
  }
294
310
  } else {
295
- console.error('[Lỗi không xác định]:', error);
311
+ console.error('[Unknown error]:', error);
296
312
  }
297
313
  }
298
314
  }
@@ -300,22 +316,22 @@ async function execute() {
300
316
 
301
317
  ---
302
318
 
303
- ## 🛠️ Build & Publish (Dành cho nhà phát triển)
319
+ ## 🛠️ Build & Publish (For Developers)
304
320
 
305
- Các lệnh thao tác chính khi tham gia phát triển gói thư viện `bloom-filter-driver`:
321
+ Main commands for developing the `bloom-filter-driver` package:
306
322
 
307
- - **Kiểm tra lỗi cú pháp và định dạng (Lint & Format):**
323
+ - **Linting & Formatting:**
308
324
  ```bash
309
325
  npm run lint
310
326
  ```
311
327
 
312
- - **Biên dịch nguồn TypeScript sang JavaScript (thư mục `dist`):**
328
+ - **Compile TypeScript source code to JavaScript (`dist` directory):**
313
329
  ```bash
314
330
  npm run build
315
331
  ```
316
332
 
317
- - **Đóng gói phát hành lên NPM registry:**
333
+ - **Package and publish to NPM registry:**
318
334
  ```bash
319
335
  npm publish
320
336
  ```
321
- *(Lưu ý: Script `prepublishOnly` trong `package.json` sẽ tự động kích hoạt tiến trình `build` trước khi publish để đảm bảo nguồn phát hành luôn mới nhất).*
337
+ *(Note: The `prepublishOnly` script in `package.json` automatically triggers the `build` process before publishing to ensure the published code is always up to date).*
@@ -11,6 +11,8 @@ export declare class DriverValidator {
11
11
  parseNumericValue(body: string): number;
12
12
  positiveNumberInZeroOne(value: number, fieldName: string): number;
13
13
  keysArray(values: string[]): string[];
14
+ uint64Key(value: number, fieldName: string): number;
15
+ uint64KeysArray(values: number[]): number[];
14
16
  rangeConfig(config: RangeConfigPayload): RangeConfigPayload;
15
17
  integerInRange(value: number, fieldName: string, min: number, max: number): number;
16
18
  }
@@ -74,6 +74,18 @@ class DriverValidator {
74
74
  }
75
75
  return values.map((value, index) => this.nonEmpty(value, `keys[${index}]`));
76
76
  }
77
+ uint64Key(value, fieldName) {
78
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {
79
+ throw new errors_1.BloomDriverError(`"${fieldName}" must be a non-negative integer`);
80
+ }
81
+ return value;
82
+ }
83
+ uint64KeysArray(values) {
84
+ if (!Array.isArray(values) || values.length === 0) {
85
+ throw new errors_1.BloomDriverError('"keys" must be a non-empty array');
86
+ }
87
+ return values.map((value, index) => this.uint64Key(value, `keys[${index}]`));
88
+ }
77
89
  rangeConfig(config) {
78
90
  return {
79
91
  masterInitNumBucket: this.positiveInt(config.masterInitNumBucket, 'masterInitNumBucket'),
@@ -23,43 +23,51 @@ class RangeApiClient {
23
23
  }, options);
24
24
  }
25
25
  async addRange(payload, options) {
26
- await this.http.post('/rangelh/add', {
26
+ const requestBody = {
27
27
  bfName: this.validator.bfName(payload.bfName),
28
- key: this.validator.nonEmpty(payload.key, 'key')
29
- }, options);
28
+ key: this.validator.uint64Key(payload.key, 'key')
29
+ };
30
+ if (payload.data !== undefined) {
31
+ requestBody.data = this.validator.nonEmpty(payload.data, 'data');
32
+ }
33
+ await this.http.post('/rangelh/add', requestBody, options);
30
34
  }
31
35
  async addRangeBulk(payload, options) {
32
- await this.http.post('/rangelh/add-bulk', {
36
+ const requestBody = {
33
37
  bfName: this.validator.bfName(payload.bfName),
34
- keys: this.validator.keysArray(payload.keys)
35
- }, options);
38
+ keys: this.validator.uint64KeysArray(payload.keys)
39
+ };
40
+ if (payload.data !== undefined) {
41
+ requestBody.data = this.validator.keysArray(payload.data);
42
+ }
43
+ await this.http.post('/rangelh/add-bulk', requestBody, options);
36
44
  }
37
45
  async removeRange(payload, options) {
38
46
  await this.http.post('/rangelh/remove', {
39
47
  bfName: this.validator.bfName(payload.bfName),
40
- key: this.validator.nonEmpty(payload.key, 'key')
48
+ key: this.validator.uint64Key(payload.key, 'key')
41
49
  }, options);
42
50
  }
43
51
  async pointQuery(payload, options) {
44
52
  const response = await this.http.get('/rangelh/point-query', {
45
53
  bfName: this.validator.bfName(payload.bfName),
46
- key: this.validator.nonEmpty(payload.key, 'key')
54
+ key: this.validator.uint64Key(payload.key, 'key').toString()
47
55
  }, options);
48
56
  return this.validator.parseStringList(response);
49
57
  }
50
58
  async rangeQuery(payload, options) {
51
59
  const response = await this.http.get('/rangelh/range-query', {
52
60
  bfName: this.validator.bfName(payload.bfName),
53
- from: this.validator.nonEmpty(payload.from, 'from'),
54
- to: this.validator.nonEmpty(payload.to, 'to')
61
+ from: this.validator.uint64Key(payload.from, 'from').toString(),
62
+ to: this.validator.uint64Key(payload.to, 'to').toString()
55
63
  }, options);
56
64
  return this.validator.parseStringList(response);
57
65
  }
58
66
  async aggregate(payload, options) {
59
67
  const response = await this.http.get('/rangelh/aggregate', {
60
68
  bfName: this.validator.bfName(payload.bfName),
61
- from: this.validator.nonEmpty(payload.from, 'from'),
62
- to: this.validator.nonEmpty(payload.to, 'to'),
69
+ from: this.validator.uint64Key(payload.from, 'from').toString(),
70
+ to: this.validator.uint64Key(payload.to, 'to').toString(),
63
71
  op: this.validator.aggregateOp(payload.op)
64
72
  }, options);
65
73
  return this.validator.parseNumericValue(response);
package/dist/types.d.ts CHANGED
@@ -27,7 +27,8 @@ export interface BloomBenchSequentialPayload {
27
27
  }
28
28
  export interface RangePayload {
29
29
  bfName: string;
30
- key: string;
30
+ key: number;
31
+ data?: string;
31
32
  }
32
33
  export interface RangeConfigPayload {
33
34
  masterInitNumBucket: number;
@@ -45,22 +46,23 @@ export interface RangeCreatePayload {
45
46
  }
46
47
  export interface RangeBulkAddPayload {
47
48
  bfName: string;
48
- keys: string[];
49
+ keys: number[];
50
+ data?: string[];
49
51
  }
50
52
  export interface PointQueryPayload {
51
53
  bfName: string;
52
- key: string;
54
+ key: number;
53
55
  }
54
56
  export interface RangeQueryPayload {
55
57
  bfName: string;
56
- from: string;
57
- to: string;
58
+ from: number;
59
+ to: number;
58
60
  }
59
61
  export type RangeAggregateOp = 'sum' | 'avg' | 'min' | 'max' | 'count';
60
62
  export interface RangeAggregatePayload {
61
63
  bfName: string;
62
- from: string;
63
- to: string;
64
+ from: number;
65
+ to: number;
64
66
  op: RangeAggregateOp;
65
67
  }
66
68
  export interface DriverRequestOptions {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bloom-filter-driver",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "HTTP driver for BloomFilterProcess",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",