surrealdb-ffi-codec

A codec implementation pattern for high‑efficiency FFI data exchange between SurrealDB Embedded and Go/Swift/other languages, eliminating JSON by using FlatBuffers + MessagePack. Used for Rust FFI layer construction, SurrealDB query result conversion, and binary serialization.

16 stars

Best use case

surrealdb-ffi-codec is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

A codec implementation pattern for high‑efficiency FFI data exchange between SurrealDB Embedded and Go/Swift/other languages, eliminating JSON by using FlatBuffers + MessagePack. Used for Rust FFI layer construction, SurrealDB query result conversion, and binary serialization.

Teams using surrealdb-ffi-codec should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/surrealdb-ffi-codec/SKILL.md --create-dirs "https://raw.githubusercontent.com/diegosouzapw/awesome-omni-skill/main/skills/development/surrealdb-ffi-codec/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/surrealdb-ffi-codec/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How surrealdb-ffi-codec Compares

Feature / Agentsurrealdb-ffi-codecStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

A codec implementation pattern for high‑efficiency FFI data exchange between SurrealDB Embedded and Go/Swift/other languages, eliminating JSON by using FlatBuffers + MessagePack. Used for Rust FFI layer construction, SurrealDB query result conversion, and binary serialization.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# SurrealDB FFI Codec

## Overview

An efficient binary codec pattern for accessing SurrealDB Embedded from other languages (Go, Swift, Kotlin, etc.) via FFI.

**Core principle**: eliminate JSON and optimize with a two‑layer structure:
- **FlatBuffers**: fixed schema (error codes, status, operation types)
- **MessagePack**: dynamic schema (query results, parameters)

## When to Use

- Embedding SurrealDB in Rust and accessing it from other languages via FFI
- Eliminating JSON parse/serialize overhead
- Handling dynamic query results while preserving type safety
- Requiring zero‑copy access through FlatBuffers

## When NOT to Use

- HTTP/WebSocket client implementations (use official SurrealDB SDKs)
- Server-side API development without FFI requirements
- Simple single-language Rust projects (use surrealdb crate directly)
- MCP server implementations (this skill provides templates, not runtime)

**Important**: This skill provides implementation **templates and guidelines only**, not executable binaries or runtime libraries.

## Examples

**User request**: "Create an FFI layer to access SurrealDB from Go"

→ Generate Rust library with:
- FlatBuffers schemas from `resources/schemas/`
- Codec implementation from `resources/codec/`
- C ABI wrapper from `resources/ffi/`
- Go client code following `docs/integration_guide.md`

**User request**: "Convert SurrealDB query results to MessagePack"

→ Implement converter using `resources/codec/converter.rs.template` with proper TypeHints handling.

## Conversion Flow

See `docs/design_principle.md` for detailed architecture. Summary:

```
sql::Value → rmpv::Value → [u8] bytes (in FlatBuffers payload)
```

## Type Mapping

See `docs/conversion_table.md` for the complete type conversion reference.

Key points:
- `sql::Number::Decimal` → `f64` (precision loss beyond 15-17 digits)
- `sql::Datetime` → RFC3339 string (remove `d'...'` wrapper)
- `sql::Thing` → ID-only string (remove table prefix and brackets)

## Instructions

### Project Layout

Generate the following structure:

```
rust_lib/
├── Cargo.toml
├── schemas/
│   ├── request.fbs
│   └── response.fbs
└── src/
    ├── lib.rs
    ├── codec/
    │   ├── mod.rs
    │   ├── converter.rs
    │   ├── msgpack.rs
    │   └── generated/
    └── ffi/
        ├── mod.rs
        ├── wrapper.rs
        └── error_codes.rs
```

### Implementation

1. **FlatBuffers schemas** - Use `resources/schemas/*.fbs.template`, replace `{{NAMESPACE}}`
2. **Codec** - Use `resources/codec/*.rs.template` for type conversion
3. **FFI wrapper** - Use `resources/ffi/*.rs.template` for C ABI exports

### FlatBuffers Code Generation

```bash
flatc --rust -o src/codec/generated schemas/request.fbs schemas/response.fbs
```

### Dependencies

```toml
[dependencies]
surrealdb = { version = "2.x", features = ["kv-mem"] }  # or kv-rocksdb
flatbuffers = "24.x"
rmp-serde = "1.x"
rmpv = "1.x"
chrono = { version = "0.4", features = ["serde"] }
thiserror = "2.x"
log = "0.4"
```

## Guidelines

### Using TypeHints

Convert string parameters from clients into native SurrealDB types:

```rust
// Formats: "field_name" or "datetime:field_name" or "record:table:field"
let hints = TypeHints::parse(&[
    "created_at".to_string(),
    "record:user:owner_id".to_string(),
]);
let surreal_value = to_surreal_value_with_type_hints(msgpack_value, &hints);
```

### Decimal Precision Loss

`sql::Number::Decimal` is converted to f64, so precision beyond 15–17 digits is lost. If exact precision is required, treat it as a string.

### Thing ID Cleanup

SurrealDB 2.x wraps Thing IDs in angle brackets. Remove them during conversion:

```rust
// "user:⟨uuid-here⟩" -> "uuid-here"
let clean_id = id.trim_matches(|c| c == '\u{27E8}' || c == '\u{27E9}');
```

### Error Handling

- status_code = 0: success
- status_code = -1: Rust panic (fatal)
- status_code > 0: application error

All FFI functions must wrap logic with `std::panic::catch_unwind` to prevent panics from crossing the FFI boundary.

### Async Runtime Management

FFI functions are synchronous but SurrealDB SDK is async. Use `OnceLock` for global runtime singleton. See `docs/integration_guide.md` for the complete pattern.

### Applying RecordFieldHint

FlatBuffers `record_fields: [RecordFieldHint]` should be mapped into `TypeHints.record_fields`.

```
record_fields = [
  { field: "owner_id", table_name: "user" }
]
```

The above is equivalent to `record:user:owner_id`. Ensure client hints and Rust `TypeHints` are consistent.

### FFI Input Safety

- If `request_ptr` is null or `request_len == 0`, return `InvalidRequest` immediately.
- FFI callers must always invoke `free_response_buffer` and avoid double‑free.

### Error Payload Format

Use a structured MessagePack payload on error:

```
{ "code": i32, "message": String, "details": Option<String> }
```

Clients should ignore unknown fields for forward compatibility.

Related Skills

surrealdb

16
from diegosouzapw/awesome-omni-skill

Expert SurrealDB 3 architect and developer skill. SurrealQL mastery, multi-model data modeling (document, graph, vector, time-series, geospatial), schema design, security, deployment, performance tuning, SDK integration (JS, Python, Go, Rust), Surrealism WASM extensions, and full ecosystem (Surrealist, Surreal-Sync, SurrealFS). Universal skill for 30+ AI agents.

bgo

10
from diegosouzapw/awesome-omni-skill

Automates the complete Blender build-go workflow, from building and packaging your extension/add-on to removing old versions, installing, enabling, and launching Blender for quick testing and iteration.

Coding & Development

swift-human-guidelines

16
from diegosouzapw/awesome-omni-skill

Comprehensive Swift 6 and SwiftUI development guidelines for building iOS 26, iOS 18, iPadOS, macOS, watchOS, visionOS, and tvOS applications. Covers Foundation Models API, BGContinuedProcessingTask, Call Translation API, Liquid Glass design system, data-race safety, typed throws, synchronization primitives, SwiftUI/UIKit interoperability, zoom transitions, and document-based apps. Use when building new Apple platform apps, implementing Apple Intelligence features, optimizing performance with Swift 6 concurrency, following Apple Human Interface Guidelines, creating cross-platform applications, or working with iOS 26/18 APIs. Triggers on Swift code, SwiftUI views, Xcode projects, app architecture, background processing, translation features, Foundation Models, synchronization, actors, Sendable types, or modern Apple platform development.

swift-conventions

16
from diegosouzapw/awesome-omni-skill

Swift coding conventions and best practices for modern Swift development. Use when writing, reviewing, or refactoring Swift code to ensure consistency with naming conventions, access control, async/await patterns, and SwiftUI/framework best practices.

swift-concurrency

16
from diegosouzapw/awesome-omni-skill

Expert guidance on Swift Concurrency best practices, patterns, and implementation. Use when developers mention: (1) Swift Concurrency, async/await, actors, or tasks, (2) "use Swift Concurrency" or "modern concurrency patterns", (3) migrating to Swift 6, (4) data races or thread safety issues, (5) refactoring closures to async/await, (6) @MainActor, Sendable, or actor isolation, (7) concurrent code architecture or performance optimization, (8) concurrency-related linter warnings (SwiftLint or similar; e.g. async_without_await, Sendable/actor isolation/MainActor lint).

swedish-medications

16
from diegosouzapw/awesome-omni-skill

Look up Swedish medication information from FASS (Farmaceutiska Specialiteter i Sverige). Use when users ask about medications, drugs, läkemedel, dosages, side effects (biverkningar), interactions, or need to understand prescriptions in Sweden. Covers all medications approved for use in Sweden.

swe-programming-elixir-phoenix

16
from diegosouzapw/awesome-omni-skill

Phoenix Framework coding standards from authoritative docs/explanation/software-engineering/platform-web/tools/elixir-phoenix/ documentation

sw-tech-stack-planner

16
from diegosouzapw/awesome-omni-skill

Use when user wants a tech stack recommendation, technology choices, docker-compose setup, or architecture decisions for a software project – reads vision.md, user-stories.md, use-cases.md and generates requirements/tech-stack.yaml silently.

sveltekit

16
from diegosouzapw/awesome-omni-skill

Expert guidance for building modern, performant web applications with SvelteKit.

sveltekit-latest

16
from diegosouzapw/awesome-omni-skill

Quick-reference for SvelteKit + Svelte 5 development (Feb 2026)

svelte-remote-functions

16
from diegosouzapw/awesome-omni-skill

Guide for SvelteKit Remote Functions. Use this skill by default for all SvelteKit projects doing type-safe client-server communication with query (data fetching), form (progressive enhancement), command (imperative actions), or data invalidation/refresh patterns.

superpowers-writing-skills

16
from diegosouzapw/awesome-omni-skill

Use when creating new skills, editing existing skills, or verifying skills work before deployment