vldb-lancedb 0.1.5

A Rust gRPC, library, and FFI gateway for LanceDB vector data with JSON and Arrow IPC support.
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
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

use tonic::{Request, Response, Status};
use vldb_lancedb::engine::{LanceDbEngine, LanceDbEngineError, LanceDbEngineErrorKind};
use vldb_lancedb::types::{
    LanceDbColumnDef, LanceDbColumnType, LanceDbCreateTableInput, LanceDbDeleteInput,
    LanceDbDropTableInput, LanceDbInputFormat, LanceDbOutputFormat, LanceDbSearchInput,
    LanceDbUpsertInput,
};

use crate::logging::{LoggingConfig, ServiceLogger};
use crate::pb::lance_db_service_server::LanceDbService;
use crate::pb::{
    ColumnDef, ColumnType, CreateTableRequest, CreateTableResponse, DeleteRequest, DeleteResponse,
    DropTableRequest, DropTableResponse, InputFormat, OutputFormat, SearchRequest, SearchResponse,
    UpsertRequest, UpsertResponse,
};

/// gRPC 服务配置,仅保留传输层需要的控制项。
/// gRPC service configuration keeping only transport-layer control settings.
pub struct ServiceConfig {
    pub request_timeout: Option<Duration>,
}

/// gRPC 服务实现,负责日志、超时与 protobuf/engine 之间的映射。
/// gRPC service implementation responsible for logging, timeouts, and protobuf-to-engine mapping.
#[derive(Clone)]
pub struct LanceDbGrpcService {
    state: Arc<ServiceState>,
}

/// 服务内部状态。
/// Internal service state.
struct ServiceState {
    engine: LanceDbEngine,
    logger: Arc<ServiceLogger>,
    config: ServiceConfig,
}

/// 请求日志上下文。
/// Request logging context.
#[derive(Clone, Debug)]
struct RequestLogContext {
    request_id: u64,
    operation: &'static str,
    remote_addr: String,
    summary: String,
    started_at: Instant,
    logger: Arc<ServiceLogger>,
    request_log_enabled: bool,
    slow_request_log_enabled: bool,
    slow_request_threshold: Duration,
    include_request_details_in_slow_log: bool,
}

impl LanceDbGrpcService {
    /// 使用已经构造好的引擎创建 gRPC 服务实例。
    /// Create the gRPC service instance from an already constructed engine.
    pub fn from_engine(
        engine: LanceDbEngine,
        logger: Arc<ServiceLogger>,
        config: ServiceConfig,
    ) -> Self {
        Self {
            state: Arc::new(ServiceState {
                engine,
                logger,
                config,
            }),
        }
    }

    /// 用可选超时包装 Future。
    /// Wrap a future with an optional timeout.
    async fn with_timeout<R>(
        &self,
        future: impl std::future::Future<Output = R>,
    ) -> Result<R, Status> {
        match &self.state.config.request_timeout {
            Some(timeout) => tokio::time::timeout(*timeout, future).await.map_err(|_| {
                Status::deadline_exceeded(format!("request timeout after {:?}", *timeout))
            }),
            None => Ok(future.await),
        }
    }
}

static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1);

#[tonic::async_trait]
impl LanceDbService for LanceDbGrpcService {
    async fn create_table(
        &self,
        request: Request<CreateTableRequest>,
    ) -> Result<Response<CreateTableResponse>, Status> {
        let context = build_request_context(
            &self.state.logger,
            "create_table",
            request.remote_addr(),
            format!(
                "table={} columns={} overwrite_if_exists={}",
                request.get_ref().table_name.trim(),
                request.get_ref().columns.len(),
                request.get_ref().overwrite_if_exists,
            ),
        );
        log_request_started(&context);
        let req = request.into_inner();

        let input = LanceDbCreateTableInput {
            table_name: req.table_name,
            columns: req.columns.iter().map(map_column_def).collect(),
            overwrite_if_exists: req.overwrite_if_exists,
        };

        match self
            .with_timeout(self.state.engine.create_table(input))
            .await?
        {
            Ok(result) => {
                log_request_succeeded(&context, result.message.as_str());
                Ok(Response::new(CreateTableResponse {
                    success: true,
                    message: result.message,
                }))
            }
            Err(error) => {
                let status = map_engine_error(error);
                log_request_failed(&context, &status);
                Err(status)
            }
        }
    }

    async fn vector_upsert(
        &self,
        request: Request<UpsertRequest>,
    ) -> Result<Response<UpsertResponse>, Status> {
        let context = build_request_context(
            &self.state.logger,
            "vector_upsert",
            request.remote_addr(),
            format!(
                "table={} key_columns={} input_format={:?} payload_bytes={}",
                request.get_ref().table_name.trim(),
                request.get_ref().key_columns.len(),
                request.get_ref().input_format(),
                request.get_ref().data.len(),
            ),
        );
        log_request_started(&context);
        let req = request.into_inner();
        let input_format = map_input_format(req.input_format());

        let input = LanceDbUpsertInput {
            table_name: req.table_name,
            input_format,
            data: req.data,
            key_columns: req.key_columns,
        };

        match self
            .with_timeout(self.state.engine.vector_upsert(input))
            .await?
        {
            Ok(result) => {
                log_request_succeeded(&context, result.message.as_str());
                Ok(Response::new(UpsertResponse {
                    success: true,
                    message: result.message,
                    version: result.version,
                    input_rows: result.input_rows,
                    inserted_rows: result.inserted_rows,
                    updated_rows: result.updated_rows,
                    deleted_rows: result.deleted_rows,
                }))
            }
            Err(error) => {
                let status = map_engine_error(error);
                log_request_failed(&context, &status);
                Err(status)
            }
        }
    }

    async fn vector_search(
        &self,
        request: Request<SearchRequest>,
    ) -> Result<Response<SearchResponse>, Status> {
        let context = build_request_context(
            &self.state.logger,
            "vector_search",
            request.remote_addr(),
            format!(
                "table={} vector_dim={} limit={} output_format={:?} filter=\"{}\"",
                request.get_ref().table_name.trim(),
                request.get_ref().vector.len(),
                request.get_ref().limit,
                request.get_ref().output_format(),
                preview_text(
                    request.get_ref().filter.trim(),
                    self.state.logger.config().request_preview_chars
                ),
            ),
        );
        log_request_started(&context);
        let req = request.into_inner();
        let output_format = map_output_format(req.output_format());

        let input = LanceDbSearchInput {
            table_name: req.table_name,
            vector: req.vector,
            limit: req.limit,
            filter: req.filter,
            vector_column: req.vector_column,
            output_format,
        };

        match self
            .with_timeout(self.state.engine.vector_search(input))
            .await?
        {
            Ok(result) => {
                log_request_succeeded(
                    &context,
                    format!(
                        "{} rows encoded as {}",
                        result.rows,
                        result.format.as_wire_name()
                    ),
                );
                Ok(Response::new(SearchResponse {
                    success: true,
                    message: result.message,
                    format: result.format.as_wire_name().to_string(),
                    rows: result.rows,
                    data: result.data,
                }))
            }
            Err(error) => {
                let status = map_engine_error(error);
                log_request_failed(&context, &status);
                Err(status)
            }
        }
    }

    async fn delete(
        &self,
        request: Request<DeleteRequest>,
    ) -> Result<Response<DeleteResponse>, Status> {
        let context = build_request_context(
            &self.state.logger,
            "delete",
            request.remote_addr(),
            format!(
                "table={} condition=\"{}\"",
                request.get_ref().table_name.trim(),
                preview_text(
                    request.get_ref().condition.trim(),
                    self.state.logger.config().request_preview_chars
                ),
            ),
        );
        log_request_started(&context);
        let req = request.into_inner();

        let input = LanceDbDeleteInput {
            table_name: req.table_name,
            condition: req.condition,
        };

        match self.with_timeout(self.state.engine.delete(input)).await? {
            Ok(result) => {
                log_request_succeeded(&context, format!("deleted_rows={}", result.deleted_rows));
                Ok(Response::new(DeleteResponse {
                    success: true,
                    message: result.message,
                    version: result.version,
                    deleted_rows: result.deleted_rows,
                }))
            }
            Err(error) => {
                let status = map_engine_error(error);
                log_request_failed(&context, &status);
                Err(status)
            }
        }
    }

    async fn drop_table(
        &self,
        request: Request<DropTableRequest>,
    ) -> Result<Response<DropTableResponse>, Status> {
        let context = build_request_context(
            &self.state.logger,
            "drop_table",
            request.remote_addr(),
            format!("table={}", request.get_ref().table_name.trim()),
        );
        log_request_started(&context);
        let req = request.into_inner();

        let input = LanceDbDropTableInput {
            table_name: req.table_name,
        };

        match self
            .with_timeout(self.state.engine.drop_table(input))
            .await?
        {
            Ok(result) => {
                log_request_succeeded(&context, result.message.as_str());
                Ok(Response::new(DropTableResponse {
                    success: true,
                    message: result.message,
                }))
            }
            Err(error) => {
                let status = map_engine_error(error);
                log_request_failed(&context, &status);
                Err(status)
            }
        }
    }
}

/// 将 protobuf 列定义映射到库层列定义。
/// Map a protobuf column definition into the library-layer column definition.
fn map_column_def(column: &ColumnDef) -> LanceDbColumnDef {
    LanceDbColumnDef {
        name: column.name.clone(),
        column_type: map_column_type(column.column_type()),
        vector_dim: column.vector_dim,
        nullable: column.nullable,
    }
}

/// 将 protobuf 列类型映射到库层列类型。
/// Map a protobuf column type into the library-layer column type.
fn map_column_type(column_type: ColumnType) -> LanceDbColumnType {
    match column_type {
        ColumnType::String => LanceDbColumnType::String,
        ColumnType::Int64 => LanceDbColumnType::Int64,
        ColumnType::Float64 => LanceDbColumnType::Float64,
        ColumnType::Bool => LanceDbColumnType::Bool,
        ColumnType::VectorFloat32 => LanceDbColumnType::VectorFloat32,
        ColumnType::Float32 => LanceDbColumnType::Float32,
        ColumnType::Uint64 => LanceDbColumnType::Uint64,
        ColumnType::Int32 => LanceDbColumnType::Int32,
        ColumnType::Uint32 => LanceDbColumnType::Uint32,
        ColumnType::Unspecified => LanceDbColumnType::Unspecified,
    }
}

/// 将 protobuf 输入格式映射到库层输入格式。
/// Map a protobuf input format into the library-layer input format.
fn map_input_format(input_format: InputFormat) -> LanceDbInputFormat {
    match input_format {
        InputFormat::JsonRows => LanceDbInputFormat::JsonRows,
        InputFormat::ArrowIpc => LanceDbInputFormat::ArrowIpc,
        InputFormat::Unspecified => LanceDbInputFormat::Unspecified,
    }
}

/// 将 protobuf 输出格式映射到库层输出格式。
/// Map a protobuf output format into the library-layer output format.
fn map_output_format(output_format: OutputFormat) -> LanceDbOutputFormat {
    match output_format {
        OutputFormat::JsonRows => LanceDbOutputFormat::JsonRows,
        OutputFormat::ArrowIpc => LanceDbOutputFormat::ArrowIpc,
        OutputFormat::Unspecified => LanceDbOutputFormat::Unspecified,
    }
}

/// 将引擎错误映射为 gRPC Status。
/// Map an engine error into a gRPC status.
fn map_engine_error(error: LanceDbEngineError) -> Status {
    match error.kind {
        LanceDbEngineErrorKind::InvalidArgument => Status::invalid_argument(error.message),
        LanceDbEngineErrorKind::Internal => Status::internal(error.message),
    }
}

/// 构建请求日志上下文。
/// Build the request logging context.
fn build_request_context(
    logger: &Arc<ServiceLogger>,
    operation: &'static str,
    remote_addr: Option<std::net::SocketAddr>,
    summary: String,
) -> RequestLogContext {
    let logging: &LoggingConfig = logger.config();
    RequestLogContext {
        request_id: NEXT_REQUEST_ID.fetch_add(1, Ordering::Relaxed),
        operation,
        remote_addr: remote_addr
            .map(|addr| addr.to_string())
            .unwrap_or_else(|| "unknown".to_string()),
        summary,
        started_at: Instant::now(),
        logger: Arc::clone(logger),
        request_log_enabled: logging.request_log_enabled,
        slow_request_log_enabled: logging.slow_request_log_enabled,
        slow_request_threshold: Duration::from_millis(logging.slow_request_threshold_ms),
        include_request_details_in_slow_log: logging.include_request_details_in_slow_log,
    }
}

/// 记录请求开始日志。
/// Record the request-start log.
fn log_request_started(context: &RequestLogContext) {
    if !context.request_log_enabled {
        return;
    }

    context.logger.log(
        "start",
        format!(
            "request_id={} op={} remote={} summary={}",
            context.request_id, context.operation, context.remote_addr, context.summary
        ),
    );
}

/// 记录请求成功日志。
/// Record the request-success log.
fn log_request_succeeded(context: &RequestLogContext, detail: impl AsRef<str>) {
    let elapsed = context.started_at.elapsed();
    if context.request_log_enabled {
        context.logger.log(
            "ok",
            format!(
                "request_id={} op={} elapsed_ms={} remote={} detail={} summary={}",
                context.request_id,
                context.operation,
                elapsed.as_millis(),
                context.remote_addr,
                detail.as_ref(),
                context.summary,
            ),
        );
    }
    maybe_log_slow_request(context, elapsed, "completed", detail.as_ref());
}

/// 记录请求失败日志。
/// Record the request-failure log.
fn log_request_failed(context: &RequestLogContext, status: &Status) {
    let elapsed = context.started_at.elapsed();
    context.logger.log(
        "error",
        format!(
            "request_id={} op={} elapsed_ms={} remote={} code={:?} message={} summary={}",
            context.request_id,
            context.operation,
            elapsed.as_millis(),
            context.remote_addr,
            status.code(),
            status.message(),
            context.summary,
        ),
    );
    maybe_log_slow_request(context, elapsed, "failed", status.message());
}

/// 根据阈值记录慢请求日志。
/// Record the slow-request log when the threshold is exceeded.
fn maybe_log_slow_request(
    context: &RequestLogContext,
    elapsed: Duration,
    final_state: &str,
    detail: &str,
) {
    if !context.slow_request_log_enabled || elapsed < context.slow_request_threshold {
        return;
    }

    let summary = if context.include_request_details_in_slow_log {
        context.summary.as_str()
    } else {
        context.operation
    };

    context.logger.log(
        "slow_request",
        format!(
            "request_id={} op={} elapsed_ms={} threshold_ms={} remote={} state={} detail={} summary={}",
            context.request_id,
            context.operation,
            elapsed.as_millis(),
            context.slow_request_threshold.as_millis(),
            context.remote_addr,
            final_state,
            detail,
            summary,
        ),
    );
}

/// 预览文本,压缩空白并按字符截断。
/// Preview text by compacting whitespace and truncating by character count.
fn preview_text(value: &str, max_chars: usize) -> String {
    let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
    if normalized.is_empty() {
        return "<empty>".to_string();
    }

    let mut preview = String::new();
    for (index, ch) in normalized.chars().enumerate() {
        if index >= max_chars {
            preview.push_str("...");
            return preview;
        }
        preview.push(ch);
    }

    preview
}

#[cfg(test)]
mod tests {
    use super::preview_text;

    #[test]
    fn preview_text_compacts_whitespace_and_truncates() {
        let preview = preview_text("table = demo\nfilter = id   > 1", 160);
        assert_eq!(preview, "table = demo filter = id > 1");

        let preview = preview_text(&format!("prefix {}", "x".repeat(300)), 24);
        assert!(preview.ends_with("..."));
        assert!(preview.len() >= 24);
    }

    #[test]
    fn preview_text_marks_empty_input() {
        assert_eq!(preview_text(" \n\t ", 64), "<empty>");
    }
}