v_queue 0.2.9

simple file based queue
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# API Reference

Complete HTTP API documentation for V-Queue server.

**Important Note**: The v-queue-server provides a **consumer-only HTTP API**. There are no HTTP endpoints for producing/pushing messages. To produce messages, you must use the v_queue library directly in your Rust application or via JNI bindings for Java.

## Base URL

```
http://localhost:9093/api/v1
```

## Authentication

Most endpoints require HTTP Basic Authentication (when `auth_enabled = true`).

```bash
curl -u username:password http://localhost:9093/api/v1/queues
```

Or with Authorization header:

```bash
curl -H "Authorization: Basic <base64_credentials>" http://localhost:9093/api/v1/queues
```

## Endpoints

### Health Check

#### GET /health

Check server health status.

**Authentication**: Not required

**Response**:
```json
{
  "status": "ok",
  "version": "0.1.0"
}
```

**Status Codes**:
- `200 OK` - Server is healthy

**Example**:
```bash
curl http://localhost:9093/health
```

---

### List Queues

#### GET /api/v1/queues

List all available queues.

**Authentication**: Required

**Response**:
```json
{
  "queues": ["events", "logs", "metrics"]
}
```

**Status Codes**:
- `200 OK` - Success
- `401 Unauthorized` - Authentication failed

**Example**:
```bash
curl -u admin:password http://localhost:9093/api/v1/queues
```

---

### Get Queue Information

#### GET /api/v1/queues/{queue}

Get detailed information about a specific queue.

**Authentication**: Required

**Path Parameters**:
- `queue` (string) - Queue name

**Response**:
```json
{
  "name": "events",
  "id": 0,
  "count_pushed": 42,
  "is_ready": true
}
```

**Response Fields**:
- `name` - Queue name
- `id` - Current active partition ID
- `count_pushed` - Number of messages in current partition
- `is_ready` - Queue operational status

**Status Codes**:
- `200 OK` - Success
- `401 Unauthorized` - Authentication failed
- `404 Not Found` - Queue doesn't exist
- `500 Internal Server Error` - Server error

**Example**:
```bash
curl -u admin:password http://localhost:9093/api/v1/queues/events
```

---

### List Consumers

#### GET /api/v1/queues/{queue}/consumers

List all consumers for a specific queue.

**Authentication**: Required

**Path Parameters**:
- `queue` (string) - Queue name

**Response**:
```json
{
  "consumers": ["consumer1", "consumer2", "web-app"]
}
```

**Status Codes**:
- `200 OK` - Success
- `401 Unauthorized` - Authentication failed
- `404 Not Found` - Queue doesn't exist

**Example**:
```bash
curl -u admin:password http://localhost:9093/api/v1/queues/events/consumers
```

---

### Consume Messages

#### GET /api/v1/queues/{queue}/consumers/{consumer}/messages

Retrieve messages from a queue for a specific consumer.

**Authentication**: Required

**Path Parameters**:
- `queue` (string) - Queue name
- `consumer` (string) - Consumer name (created automatically if doesn't exist)

**Query Parameters**:
- `timeout_ms` (integer, optional) - Long polling timeout in milliseconds (default: 1000)
  - `0` - Return immediately if no messages
  - `> 0` - Wait up to N milliseconds for messages
- `max_messages` (integer, optional) - Maximum messages to return (default: 1)
  - Range: 1-10000
  - Note: The `default_batch_size` config setting is not currently used for this parameter

**Response**:
```json
{
  "messages": [
    {
      "offset": 0,
      "msg_type": "string",
      "value": "Hello World"
    },
    {
      "offset": 42,
      "msg_type": "object",
      "value": {"event": "user_login", "user_id": 123}
    },
    {
      "offset": 98,
      "msg_type": "object",
      "value": "[Binary Data]",
      "raw_bytes": "SGVsbG8gV29ybGQ="
    }
  ]
}
```

**Response Fields**:

Message object:
- `offset` (integer) - Message offset in queue
- `msg_type` (string) - Message type: `"string"` or `"object"`
- `value` - Message content:
  - String messages: UTF-8 string
  - Object messages: JSON object or `"[Binary Data]"`
- `raw_bytes` (string, optional) - Base64-encoded raw bytes (for binary data)

**Status Codes**:
- `200 OK` - Success (may return empty array if no messages)
- `401 Unauthorized` - Authentication failed
- `404 Not Found` - Queue doesn't exist
- `500 Internal Server Error` - Server error

**Behavior**:

1. **First Request**: Consumer created with offset 0
2. **Subsequent Requests**: Reads from last position
3. **Offset NOT Updated**: Offset only updated by commit
4. **Re-reading**: Same messages returned until committed

**Examples**:

Consume immediately:
```bash
curl -u admin:password \
  "http://localhost:9093/api/v1/queues/events/consumers/my-app/messages"
```

With timeout (long polling):
```bash
curl -u admin:password \
  "http://localhost:9093/api/v1/queues/events/consumers/my-app/messages?timeout_ms=30000"
```

Limit messages:
```bash
curl -u admin:password \
  "http://localhost:9093/api/v1/queues/events/consumers/my-app/messages?max_messages=10"
```

Combined:
```bash
curl -u admin:password \
  "http://localhost:9093/api/v1/queues/events/consumers/my-app/messages?timeout_ms=5000&max_messages=100"
```

---

### Commit Consumer Position

#### POST /api/v1/queues/{queue}/consumers/{consumer}/commit

Commit the current consumer position, marking messages as processed.

**Authentication**: Required

**Path Parameters**:
- `queue` (string) - Queue name
- `consumer` (string) - Consumer name

**Request Body**: None required

**Response**: Empty body with HTTP status code only

**Status Codes**:
- `200 OK` - Successfully committed
- `401 Unauthorized` - Authentication failed
- `404 Not Found` - Queue or consumer doesn't exist
- `500 Internal Server Error` - Server error

**Behavior**:

1. Saves current read position to disk
2. Subsequent consume requests start from committed position
3. Prevents re-reading already processed messages

**Example**:
```bash
curl -X POST -u admin:password \
  http://localhost:9093/api/v1/queues/events/consumers/my-app/commit
```

---

## Message Types

### String Messages

Text messages stored as UTF-8 strings.

**Type**: `"string"`

**Example**:
```json
{
  "offset": 0,
  "msg_type": "string",
  "value": "Hello World"
}
```

### Object/Binary Messages

Structured data or binary content.

**Type**: `"object"`

**JSON Object**:
```json
{
  "offset": 42,
  "msg_type": "object",
  "value": {
    "event": "user_login",
    "timestamp": "2024-01-15T10:30:00Z"
  }
}
```

**Binary Data**:
```json
{
  "offset": 98,
  "msg_type": "object",
  "value": "[Binary Data]",
  "raw_bytes": "SGVsbG8gV29ybGQ="
}
```

## Consumer Workflow

Typical consumer workflow:

```
1. GET /messages?timeout_ms=30000  → Receive messages
2. Process messages                → Application logic
3. POST /commit                    → Mark as processed
4. Repeat from step 1
```

## Error Handling

### Error Response Format

```json
{
  "error": "Error description"
}
```

### Common Error Codes

#### 400 Bad Request

Invalid request parameters.

**Example**:
```json
{
  "error": "Invalid max_messages parameter"
}
```

#### 401 Unauthorized

Authentication required or invalid credentials.

**Example**:
```json
{
  "error": "Authentication required"
}
```

#### 404 Not Found

Queue or consumer doesn't exist.

**Example**:
```json
{
  "error": "Queue not found: unknown-queue"
}
```

#### 500 Internal Server Error

Server-side error.

**Example**:
```json
{
  "error": "Failed to open queue"
}
```

## Usage Examples

### Python

```python
import requests
from requests.auth import HTTPBasicAuth

BASE_URL = "http://localhost:9093/api/v1"
auth = HTTPBasicAuth("admin", "password")

# List queues
response = requests.get(f"{BASE_URL}/queues", auth=auth)
queues = response.json()["queues"]

# Consume messages
response = requests.get(
    f"{BASE_URL}/queues/events/consumers/my-app/messages",
    params={"timeout_ms": 30000, "max_messages": 100},
    auth=auth
)
messages = response.json()["messages"]

# Process messages
for msg in messages:
    print(f"Offset: {msg['offset']}, Value: {msg['value']}")

# Commit
requests.post(
    f"{BASE_URL}/queues/events/consumers/my-app/commit",
    auth=auth
)
```

### JavaScript (Node.js)

```javascript
const axios = require('axios');

const client = axios.create({
  baseURL: 'http://localhost:9093/api/v1',
  auth: {
    username: 'admin',
    password: 'password'
  }
});

async function consumeMessages() {
  // Consume with timeout
  const response = await client.get(
    '/queues/events/consumers/my-app/messages',
    {
      params: {
        timeout_ms: 30000,
        max_messages: 100
      }
    }
  );

  const messages = response.data.messages;

  // Process messages
  for (const msg of messages) {
    console.log(`Offset: ${msg.offset}, Value: ${msg.value}`);
  }

  // Commit
  await client.post('/queues/events/consumers/my-app/commit');
}

consumeMessages().catch(console.error);
```

### Rust

```rust
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct MessagesResponse {
    messages: Vec<Message>,
}

#[derive(Deserialize)]
struct Message {
    offset: u64,
    msg_type: String,
    value: serde_json::Value,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();

    // Consume messages
    let response = client
        .get("http://localhost:9093/api/v1/queues/events/consumers/my-app/messages")
        .basic_auth("admin", Some("password"))
        .query(&[("timeout_ms", "30000"), ("max_messages", "100")])
        .send()?
        .json::<MessagesResponse>()?;

    // Process messages
    for msg in response.messages {
        println!("Offset: {}, Value: {}", msg.offset, msg.value);
    }

    // Commit
    client
        .post("http://localhost:9093/api/v1/queues/events/consumers/my-app/commit")
        .basic_auth("admin", Some("password"))
        .send()?;

    Ok(())
}
```

### cURL

```bash
#!/bin/bash

BASE_URL="http://localhost:9093/api/v1"
AUTH="admin:password"

# Consume messages
MESSAGES=$(curl -s -u "$AUTH" \
  "$BASE_URL/queues/events/consumers/my-app/messages?timeout_ms=30000&max_messages=100")

echo "$MESSAGES" | jq '.messages[]'

# Commit
curl -s -X POST -u "$AUTH" \
  "$BASE_URL/queues/events/consumers/my-app/commit"
```

## Rate Limits

Currently, no rate limits are enforced. Consider implementing rate limiting at the reverse proxy level if needed.

## Best Practices

### Consumer Naming

Use descriptive, unique consumer names:

- ✅ Good: `analytics-service`, `email-processor`, `audit-logger`
- ❌ Bad: `consumer1`, `test`, `temp`

### Timeout Values

Choose appropriate timeouts:

- **Short-lived jobs**: `timeout_ms=5000` (5 seconds)
- **Background processing**: `timeout_ms=30000` (30 seconds)
- **Batch processing**: `timeout_ms=60000` (60 seconds)
- **Real-time**: `timeout_ms=0` (no waiting)

### Batch Sizes

Balance throughput and latency:

- **Low latency**: `max_messages=10`
- **Balanced**: `max_messages=100`
- **High throughput**: `max_messages=1000`

Note: Default is `max_messages=1`. Specify a higher value for better throughput.

### Error Handling

Always handle errors:

```python
try:
    response = requests.get(url, timeout=35)  # HTTP timeout > server timeout
    response.raise_for_status()
    messages = response.json()["messages"]
except requests.Timeout:
    print("Request timed out")
except requests.HTTPError as e:
    print(f"HTTP error: {e}")
except Exception as e:
    print(f"Error: {e}")
```

### Commit Strategy

**Option 1 - Commit After Each Batch**:
```python
messages = consume()
process(messages)
commit()  # Safe, but more commits
```

**Option 2 - Commit Periodically**:
```python
for i in range(10):
    messages = consume()
    process(messages)
commit()  # Fewer commits, risk of reprocessing
```

**Option 3 - Commit After Successful Processing**:
```python
try:
    messages = consume()
    process(messages)
    commit()  # Only commit if successful
except Exception:
    # Don't commit, will retry
    pass
```

## Next Steps

- [Authentication Guide]06-authentication.md
- [Client Examples]07-client-examples.md
- [Performance Tuning]08-performance.md