fraiseql-wire 2.2.1

Streaming JSON query engine for Postgres 17
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
#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
#![allow(clippy::cast_possible_truncation)] // Reason: test buffer protocol encoding
#![allow(clippy::cast_possible_wrap)] // Reason: test data values within positive range

//! Wire Protocol Robustness Tests
//!
//! Tests for PostgreSQL wire protocol message decoding:
//! - Malformed message handling (invalid tags, truncation, overflow)
//! - Error field parsing (severity, SQLSTATE, position, hint, detail)
//! - Backend message decoding (`ReadyForQuery`, `CommandComplete`, `DataRow`, etc.)
//! - Edge cases (empty results, large payloads, invalid UTF-8)

use bytes::{BufMut, BytesMut};
use fraiseql_wire::protocol::decode::decode_message;
use fraiseql_wire::protocol::message::BackendMessage;
use std::io;

// ============================================================================
// Malformed Message Handling
// ============================================================================

#[test]
fn test_decode_malformed_message_tag() {
    let mut buf = BytesMut::from(&[b'!', 0, 0, 0, 4][..]);
    let result = decode_message(&mut buf);
    assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
}

#[test]
fn test_decode_truncated_message() {
    // Only 3 bytes when minimum is 5
    let mut buf = BytesMut::from(&[b'Z', 0, 0][..]);
    let result = decode_message(&mut buf);
    assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
}

#[test]
fn test_decode_length_field_overflow() {
    // Length field claims ~4GB but only 10 bytes present
    let mut buf = BytesMut::from(&[b'T', 0x7F, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0][..]);
    let result = decode_message(&mut buf);
    assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
}

#[test]
fn test_decode_length_too_small() {
    // Length < 4 is invalid (length includes itself but not the tag)
    let mut buf = BytesMut::from(&[b'Z', 0, 0, 0, 3, b'I'][..]);
    let result = decode_message(&mut buf);
    assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidData);
}

#[test]
fn test_decode_zero_length_message() {
    // Length = 0 is invalid
    let mut buf = BytesMut::from(&[b'Z', 0, 0, 0, 0][..]);
    let result = decode_message(&mut buf);
    assert!(
        result.is_err(),
        "expected Err for zero-length message, got: {result:?}"
    );
}

#[test]
fn test_decode_empty_buffer() {
    let mut buf = BytesMut::new();
    let result = decode_message(&mut buf);
    assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
}

#[test]
fn test_decode_invalid_utf8_in_error_response() {
    let mut buf = BytesMut::new();
    buf.put_u8(b'E');
    // Build error response body: severity + invalid UTF-8 message + terminator
    let body: Vec<u8> = vec![
        b'S', 0xFF, 0xFE, 0x00, // severity with invalid UTF-8 + null
        b'M', b't', b'e', b's', b't', 0x00, // message "test" + null
        0x00, // terminator
    ];
    let len = (body.len() + 4) as i32;
    buf.put_i32(len);
    buf.extend_from_slice(&body);

    let result = decode_message(&mut buf);
    // Should succeed with lossy UTF-8 conversion (not panic)
    let (msg, _) =
        result.unwrap_or_else(|e| panic!("expected Ok for lossy UTF-8 error response: {e}"));
    if let BackendMessage::ErrorResponse(fields) = msg {
        assert!(fields.severity.is_some());
        assert_eq!(fields.message.as_deref(), Some("test"));
    } else {
        panic!("Expected ErrorResponse");
    }
}

// ============================================================================
// Partial & Incomplete Messages
// ============================================================================

#[test]
fn test_partial_message_buffering() {
    // Header present but body incomplete: ReadyForQuery needs 1 byte of body
    let mut buf = BytesMut::from(&[b'Z', 0, 0, 0, 5][..]); // says 5 bytes but no status byte
    let result = decode_message(&mut buf);
    assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);

    // Now append the status byte — should succeed
    buf.put_u8(b'I');
    let result = decode_message(&mut buf);
    result.unwrap_or_else(|e| panic!("expected Ok after appending status byte: {e}"));
}

#[test]
fn test_large_data_row() {
    // 1MB DataRow with 1 field containing 1MB of data
    let field_size: usize = 1_000_000;
    let mut buf = BytesMut::new();
    buf.put_u8(b'D'); // DataRow tag

    // Body: 2 bytes field count + 4 bytes field length + field data
    let body_len = 2 + 4 + field_size;
    buf.put_i32((body_len + 4) as i32); // length includes self
    buf.put_i16(1); // 1 field
    buf.put_i32(field_size as i32); // field length
    buf.extend_from_slice(&vec![b'x'; field_size]); // field data

    let (msg, consumed) =
        decode_message(&mut buf).unwrap_or_else(|e| panic!("expected Ok for 1MB DataRow: {e}"));
    if let BackendMessage::DataRow(fields) = msg {
        assert_eq!(fields.len(), 1);
        assert_eq!(fields[0].as_ref().unwrap().len(), field_size);
        assert_eq!(consumed, 1 + 4 + body_len);
    } else {
        panic!("Expected DataRow");
    }
}

// ============================================================================
// Error Response Field Parsing
// ============================================================================

#[test]
fn test_error_sqlstate_parsing() {
    let mut buf = BytesMut::new();
    buf.put_u8(b'E');
    let body: Vec<u8> = vec![
        b'S', b'E', b'R', b'R', b'O', b'R', 0, // severity "ERROR"
        b'C', b'2', b'3', b'5', b'0', b'5', 0, // SQLSTATE "23505"
        b'M', b'u', b'n', b'i', b'q', b'u', b'e', 0, // message "unique"
        0, // terminator
    ];
    let len = (body.len() + 4) as i32;
    buf.put_i32(len);
    buf.extend_from_slice(&body);

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::ErrorResponse(fields) = msg {
        assert_eq!(fields.code.as_deref(), Some("23505"));
        assert_eq!(fields.severity.as_deref(), Some("ERROR"));
        assert_eq!(fields.message.as_deref(), Some("unique"));
    } else {
        panic!("Expected ErrorResponse");
    }
}

#[test]
fn test_error_position_marker() {
    let mut buf = BytesMut::new();
    buf.put_u8(b'E');
    let body: Vec<u8> = vec![
        b'M', b'e', b'r', b'r', 0, // message "err"
        b'P', b'9', 0, // position "9"
        0, // terminator
    ];
    let len = (body.len() + 4) as i32;
    buf.put_i32(len);
    buf.extend_from_slice(&body);

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::ErrorResponse(fields) = msg {
        assert_eq!(fields.position.as_deref(), Some("9"));
    } else {
        panic!("Expected ErrorResponse");
    }
}

#[test]
fn test_error_hint_field() {
    let hint_text = b"Did you mean FROM?";
    let mut buf = BytesMut::new();
    buf.put_u8(b'E');
    let mut body = vec![b'M', b'e', 0]; // message "e"
    body.push(b'H'); // hint field
    body.extend_from_slice(hint_text);
    body.push(0); // null terminator
    body.push(0); // terminator
    let len = (body.len() + 4) as i32;
    buf.put_i32(len);
    buf.extend_from_slice(&body);

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::ErrorResponse(fields) = msg {
        assert_eq!(fields.hint.as_deref(), Some("Did you mean FROM?"));
    } else {
        panic!("Expected ErrorResponse");
    }
}

#[test]
fn test_error_detail_field() {
    let detail_text = b"Key (id)=(5) already exists.";
    let mut buf = BytesMut::new();
    buf.put_u8(b'E');
    let mut body = vec![b'M', b'e', 0]; // message "e"
    body.push(b'D'); // detail field
    body.extend_from_slice(detail_text);
    body.push(0); // null terminator
    body.push(0); // terminator
    let len = (body.len() + 4) as i32;
    buf.put_i32(len);
    buf.extend_from_slice(&body);

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::ErrorResponse(fields) = msg {
        assert_eq!(
            fields.detail.as_deref(),
            Some("Key (id)=(5) already exists.")
        );
    } else {
        panic!("Expected ErrorResponse");
    }
}

#[test]
fn test_multi_field_error_response() {
    let mut buf = BytesMut::new();
    buf.put_u8(b'E');
    let body: Vec<u8> = vec![
        b'S', b'E', b'R', b'R', b'O', b'R', 0, // severity
        b'C', b'4', b'2', b'P', b'0', b'1', 0, // SQLSTATE
        b'M', b'r', b'e', b'l', b'a', b't', b'i', b'o', b'n', 0, // message
        b'P', b'1', b'5', 0, // position
        b'D', b'd', b'e', b't', 0, // detail
        b'H', b'h', b'n', b't', 0, // hint
        0, // terminator
    ];
    let len = (body.len() + 4) as i32;
    buf.put_i32(len);
    buf.extend_from_slice(&body);

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::ErrorResponse(fields) = msg {
        assert_eq!(fields.severity.as_deref(), Some("ERROR"));
        assert_eq!(fields.code.as_deref(), Some("42P01"));
        assert_eq!(fields.message.as_deref(), Some("relation"));
        assert_eq!(fields.position.as_deref(), Some("15"));
        assert_eq!(fields.detail.as_deref(), Some("det"));
        assert_eq!(fields.hint.as_deref(), Some("hnt"));
    } else {
        panic!("Expected ErrorResponse");
    }
}

// ============================================================================
// Backend Message Decoding
// ============================================================================

#[test]
fn test_notice_response_handling() {
    let mut buf = BytesMut::new();
    buf.put_u8(b'N'); // Notice (not Error)
    let body: Vec<u8> = vec![
        b'S', b'W', b'A', b'R', b'N', b'I', b'N', b'G', 0, // severity "WARNING"
        b'M', b'c', b'o', b'l', 0, // message "col"
        0, // terminator
    ];
    let len = (body.len() + 4) as i32;
    buf.put_i32(len);
    buf.extend_from_slice(&body);

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::NoticeResponse(fields) = msg {
        assert_eq!(fields.severity.as_deref(), Some("WARNING"));
        assert_eq!(fields.message.as_deref(), Some("col"));
    } else {
        panic!("Expected NoticeResponse, not ErrorResponse");
    }
}

#[test]
fn test_parameter_status_updates() {
    let mut buf = BytesMut::new();
    buf.put_u8(b'S'); // ParameterStatus
    let body: Vec<u8> = vec![
        b'c', b'l', b'i', b'e', b'n', b't', b'_', b'e', b'n', b'c', b'o', b'd', b'i', b'n', b'g',
        0, // name "client_encoding"
        b'U', b'T', b'F', b'8', 0, // value "UTF8"
    ];
    let len = (body.len() + 4) as i32;
    buf.put_i32(len);
    buf.extend_from_slice(&body);

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::ParameterStatus { name, value } = msg {
        assert_eq!(name, "client_encoding");
        assert_eq!(value, "UTF8");
    } else {
        panic!("Expected ParameterStatus");
    }
}

#[test]
fn test_backend_key_data_storage() {
    let mut buf = BytesMut::new();
    buf.put_u8(b'K'); // BackendKeyData
    buf.put_i32(12); // length: 4 (self) + 4 (pid) + 4 (key)
    buf.put_i32(12345); // process_id
    buf.put_i32(0x7FFF_ABCD); // secret_key

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::BackendKeyData {
        process_id,
        secret_key,
    } = msg
    {
        assert_eq!(process_id, 12345);
        assert_eq!(secret_key, 0x7FFF_ABCD);
    } else {
        panic!("Expected BackendKeyData");
    }
}

#[test]
fn test_command_complete_parsing() {
    for (tag, expected) in [
        ("SELECT 5", "SELECT 5"),
        ("INSERT 0 1", "INSERT 0 1"),
        ("UPDATE 10", "UPDATE 10"),
        ("DELETE 3", "DELETE 3"),
    ] {
        let mut buf = BytesMut::new();
        buf.put_u8(b'C'); // CommandComplete
        let body_len = tag.len() + 1; // tag + null terminator
        buf.put_i32((body_len + 4) as i32);
        buf.extend_from_slice(tag.as_bytes());
        buf.put_u8(0); // null terminator

        let (msg, _) = decode_message(&mut buf).unwrap();
        if let BackendMessage::CommandComplete(parsed_tag) = msg {
            assert_eq!(parsed_tag, expected);
        } else {
            panic!("Expected CommandComplete for tag '{tag}'");
        }
    }
}

#[test]
fn test_empty_result_set_messages() {
    // Simulate empty result: RowDescription(0 fields) + CommandComplete("SELECT 0") + ReadyForQuery

    // 1. RowDescription with 0 fields
    let mut buf = BytesMut::new();
    buf.put_u8(b'T');
    buf.put_i32(6); // length: 4 (self) + 2 (field count)
    buf.put_i16(0); // 0 fields

    let (msg, _) = decode_message(&mut buf).unwrap();
    assert!(matches!(msg, BackendMessage::RowDescription(ref fields) if fields.is_empty()));

    // 2. CommandComplete "SELECT 0"
    let tag = b"SELECT 0\0";
    buf = BytesMut::new();
    buf.put_u8(b'C');
    buf.put_i32((tag.len() + 4) as i32);
    buf.extend_from_slice(tag);

    let (msg, _) = decode_message(&mut buf).unwrap();
    assert!(matches!(msg, BackendMessage::CommandComplete(ref t) if t == "SELECT 0"));

    // 3. ReadyForQuery 'I' (idle)
    buf = BytesMut::new();
    buf.put_u8(b'Z');
    buf.put_i32(5);
    buf.put_u8(b'I');

    let (msg, _) = decode_message(&mut buf).unwrap();
    assert!(matches!(
        msg,
        BackendMessage::ReadyForQuery { status: b'I' }
    ));
}

#[test]
fn test_ready_for_query_status() {
    for (status_byte, label) in [(b'I', "idle"), (b'T', "in transaction"), (b'E', "failed")] {
        let mut buf = BytesMut::new();
        buf.put_u8(b'Z');
        buf.put_i32(5);
        buf.put_u8(status_byte);

        let (msg, _) = decode_message(&mut buf).unwrap();
        if let BackendMessage::ReadyForQuery { status } = msg {
            assert_eq!(status, status_byte, "Status mismatch for {label}");
        } else {
            panic!("Expected ReadyForQuery for {label}");
        }
    }
}

#[test]
fn test_data_row_with_null_field() {
    let mut buf = BytesMut::new();
    buf.put_u8(b'D');
    // 2 fields: one NULL (-1), one "hello"
    let mut body = BytesMut::new();
    body.put_i16(2); // 2 fields
    body.put_i32(-1); // NULL field
    body.put_i32(5); // 5 bytes
    body.extend_from_slice(b"hello");

    buf.put_i32((body.len() + 4) as i32);
    buf.extend_from_slice(&body);

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::DataRow(fields) = msg {
        assert_eq!(fields.len(), 2);
        assert!(fields[0].is_none(), "First field should be NULL");
        assert_eq!(fields[1].as_ref().unwrap().as_ref(), b"hello");
    } else {
        panic!("Expected DataRow");
    }
}

#[test]
fn test_row_description_parsing() {
    let mut buf = BytesMut::new();
    buf.put_u8(b'T');

    let mut body = BytesMut::new();
    body.put_i16(1); // 1 field
                     // Field: name "id" + null + 18 bytes of descriptor
    body.extend_from_slice(b"id\0");
    body.put_i32(0); // table_oid
    body.put_i16(0); // column_attr
    body.put_i32(23); // type_oid (int4 = 23)
    body.put_i16(4); // type_size
    body.put_i32(-1); // type_modifier
    body.put_i16(0); // format_code (text)

    buf.put_i32((body.len() + 4) as i32);
    buf.extend_from_slice(&body);

    let (msg, _) = decode_message(&mut buf).unwrap();
    if let BackendMessage::RowDescription(fields) = msg {
        assert_eq!(fields.len(), 1);
        assert_eq!(fields[0].name, "id");
        assert_eq!(fields[0].type_oid, 23);
        assert_eq!(fields[0].type_size, 4);
    } else {
        panic!("Expected RowDescription");
    }
}