Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Plugin SDK Reference

Complete type reference for the aeordb-plugin-sdk crate. This covers every public struct, enum, trait, and method available to plugin authors.

Macros

aeordb_parser!(fn_name)

Generates WASM exports for a parser plugin. Your function must have the signature:

#![allow(unused)]
fn main() {
fn fn_name(input: ParserInput) -> Result<serde_json::Value, String>
}

Generated exports:

  • handle(ptr: i32, len: i32) -> i64 – deserializes the parser envelope, calls your function, returns packed pointer+length to the serialized response

aeordb_query_plugin!(fn_name)

Generates WASM exports for a query plugin. Your function must have the signature:

#![allow(unused)]
fn main() {
fn fn_name(ctx: PluginContext, request: PluginRequest) -> Result<PluginResponse, PluginError>
}

Generated exports:

  • alloc(size: i32) -> i32 – allocates guest memory for the host to write request data
  • handle(ptr: i32, len: i32) -> i64 – deserializes the request, creates a PluginContext, calls your function, returns packed pointer+length to the serialized response

Prelude

Import everything you need with:

#![allow(unused)]
fn main() {
use aeordb_plugin_sdk::prelude::*;
}

This re-exports: PluginError, PluginRequest, PluginResponse, json, ParserInput, FileMeta, PluginContext, FileData, DirEntry, FileMetadata, ExtractRequest, ExtractedText, QueryResult, AggregateResult, SortDirection.


PluginRequest

Request passed to a query plugin when it is invoked.

FieldTypeDescription
argumentsVec<u8>Raw argument bytes (e.g., the HTTP request body forwarded to the plugin)
metadataHashMap<String, String>Key-value metadata about the invocation context

Common metadata keys:

KeyDescription
function_nameThe function name from the invoke URL

PluginResponse

Response returned by a plugin after handling a request.

FieldTypeDescription
status_codeu16HTTP-style status code
bodyVec<u8>Raw response body bytes
content_typeOption<String>MIME content type of the body
headersHashMap<String, String>Additional response headers

Builder Methods

PluginResponse::json(status_code: u16, body: &T) -> Result<Self, serde_json::Error>

Serializes body (any Serialize type) to JSON. Sets content_type to "application/json".

#![allow(unused)]
fn main() {
PluginResponse::json(200, &serde_json::json!({"ok": true}))
}

PluginResponse::text(status_code: u16, body: impl Into<String>) -> Self

Creates a plain text response. Sets content_type to "text/plain".

#![allow(unused)]
fn main() {
PluginResponse::text(200, "Hello, world!")
}

PluginResponse::error(status_code: u16, message: impl Into<String>) -> Self

Creates a JSON error response: {"error": "<message>"}. Sets content_type to "application/json".

#![allow(unused)]
fn main() {
PluginResponse::error(404, "not found")
}

PluginError

Error enum for the plugin system.

VariantDescription
NotFound(String)The plugin could not be found
ExecutionFailed(String)The plugin failed during execution
SerializationFailed(String)Request or response could not be serialized/deserialized
ResourceLimitExceeded(String)Plugin exceeded memory, fuel, or other resource limits
InvalidModule(String)An invalid or corrupt WASM module was provided
Internal(String)A generic internal error

All variants carry a String message. PluginError implements Display, Debug, and Error.


json

The SDK re-exports serde_json directly and also provides aeordb_plugin_sdk::json helpers for common plugin request parsing, serialization, and recursive value merging.

Types and macros re-exported from serde_json:

ItemDescription
json!Build a JSON value inline
ValueDynamic JSON value
MapJSON object map
NumberJSON number

Helper functions:

FunctionSignatureDescription
parse_bytes<T: DeserializeOwned>(&[u8]) -> Result<T, PluginError>Parse raw JSON bytes into a typed value
parse_str<T: DeserializeOwned>(&str) -> Result<T, PluginError>Parse a JSON string into a typed value
parse_request<T: DeserializeOwned>(&PluginRequest) -> Result<T, PluginError>Parse PluginRequest.arguments into a typed value
to_value<T: Serialize>(&T) -> Result<Value, PluginError>Serialize into serde_json::Value
to_bytes<T: Serialize>(&T) -> Result<Vec<u8>, PluginError>Serialize into compact JSON bytes
to_string<T: Serialize>(&T) -> Result<String, PluginError>Serialize into a compact JSON string
merge_into(&mut Value, Value)Recursively merge one JSON value into another
merged(Value, Value) -> ValueReturn a merged copy
merge_all(Value, impl IntoIterator<Item = Value>) -> ValueApply overlays left to right

Merge semantics are recursive for object/object branches. Arrays, scalars, and null replace the existing value. This is not JSON Merge Patch; null is preserved as a value and does not delete a key.

#![allow(unused)]
fn main() {
use aeordb_plugin_sdk::prelude::*;
use serde::Deserialize;

#[derive(Deserialize)]
struct Args {
    file: String,
    options: json::Value,
}

let args: Args = json::parse_request(&request)?;
let options = json::merged(
    json::json!({"max_bytes": 65536, "format": {"pretty": false}}),
    args.options,
);
}

PluginContext

Guest-side handle for calling AeorDB host functions from WASM. Created automatically by aeordb_query_plugin! and passed to the handler.

On non-WASM targets (native compilation), all methods return PluginError::ExecutionFailed – this allows IDE support and unit testing of plugin logic without a WASM runtime.

File Operations

read_file(&self, path: &str) -> Result<FileData, PluginError>

Read a file at the given path. Returns the decoded file bytes, content type, and size.

extract_file(&self, path: &str, request: ExtractRequest) -> Result<ExtractedText, PluginError>

Extract a UTF-8 text slice without buffering the full file through the plugin boundary.

Supported modes:

ModeRange semantics
linesstart and end are 1-based inclusive line numbers
charsstart is 0-based inclusive and end is exclusive

Line extraction treats \r\n as one line break while preserving the original line ending in the returned text. Lone \n and lone \r also count as line breaks.

#![allow(unused)]
fn main() {
let lines = ctx.extract_file("/docs/readme.md", ExtractRequest::lines(10, 20))?;
let chars = ctx.extract_file("/docs/readme.md", ExtractRequest::chars(0, 500))?;
}

ExtractRequest.max_bytes can cap the returned text size. The host enforces an absolute upper bound and sets ExtractedText.truncated when output is cut at the cap.

write_file(&self, path: &str, data: &[u8], content_type: &str) -> Result<(), PluginError>

Write (create or overwrite) a file. Data is base64-encoded on the wire automatically.

delete_file(&self, path: &str) -> Result<(), PluginError>

Delete a file at the given path.

file_metadata(&self, path: &str) -> Result<FileMetadata, PluginError>

Retrieve metadata for a file without reading its contents.

list_directory(&self, path: &str) -> Result<Vec<DirEntry>, PluginError>

List directory entries at the given path.

Query and Aggregation

query(&self, path: &str) -> QueryBuilder

Start building a query against files at the given path. See QueryBuilder.

aggregate(&self, path: &str) -> AggregateBuilder

Start building an aggregation against files at the given path. See AggregateBuilder.


FileData

Raw file data returned by read_file.

FieldTypeDescription
dataVec<u8>Decoded file bytes
content_typeStringMIME content type
sizeu64File size in bytes

DirEntry

A single directory entry returned by list_directory.

FieldTypeDescription
nameStringEntry name (file or directory name, not the full path)
entry_typeString"file" or "directory"
sizeu64Size in bytes (0 for directories, defaults to 0 if absent)

FileMetadata

Metadata about a stored file.

FieldTypeDescription
pathStringFull storage path
sizeu64File size in bytes
content_typeOption<String>MIME content type (if known)
created_ati64Creation timestamp (ms since epoch)
updated_ati64Last update timestamp (ms since epoch)

ParserInput

Input to a parser function.

FieldTypeDescription
dataVec<u8>Raw file bytes (base64-decoded from the wire envelope)
metaFileMetaFile metadata

FileMeta

Metadata about the file being parsed (available inside parser plugins).

FieldTypeDescription
filenameStringFile name only (e.g., "report.pdf")
pathStringFull storage path (e.g., "/docs/reports/report.pdf")
content_typeStringMIME type
sizeu64Raw file size in bytes
hashStringHex-encoded content hash (may be empty)
hash_algorithmStringHash algorithm (e.g., "blake3_256", may be empty)
created_ati64Creation timestamp (ms since epoch, default 0)
updated_ati64Last update timestamp (ms since epoch, default 0)

QueryBuilder

Fluent builder for constructing AeorDB queries. Obtained via PluginContext::query(path) or QueryBuilder::new(path).

Field Conditions

Start with .field("name") to get a FieldQueryBuilder, then chain one operator:

Equality

MethodSignatureDescription
eq(value: &[u8]) -> QueryBuilderExact match on raw bytes
eq_u64(value: u64) -> QueryBuilderExact match on u64
eq_i64(value: i64) -> QueryBuilderExact match on i64
eq_f64(value: f64) -> QueryBuilderExact match on f64
eq_str(value: &str) -> QueryBuilderExact match on string
eq_bool(value: bool) -> QueryBuilderExact match on boolean

Greater Than

MethodSignatureDescription
gt(value: &[u8]) -> QueryBuilderGreater than on raw bytes
gt_u64(value: u64) -> QueryBuilderGreater than on u64
gt_str(value: &str) -> QueryBuilderGreater than on string
gt_f64(value: f64) -> QueryBuilderGreater than on f64

Less Than

MethodSignatureDescription
lt(value: &[u8]) -> QueryBuilderLess than on raw bytes
lt_u64(value: u64) -> QueryBuilderLess than on u64
lt_str(value: &str) -> QueryBuilderLess than on string
lt_f64(value: f64) -> QueryBuilderLess than on f64

Range

MethodSignatureDescription
between(min: &[u8], max: &[u8]) -> QueryBuilderInclusive range on raw bytes
between_u64(min: u64, max: u64) -> QueryBuilderInclusive range on u64
between_str(min: &str, max: &str) -> QueryBuilderInclusive range on strings

Set Membership

MethodSignatureDescription
in_values(values: &[&[u8]]) -> QueryBuilderMatch any of the given byte values
in_u64(values: &[u64]) -> QueryBuilderMatch any of the given u64 values
in_str(values: &[&str]) -> QueryBuilderMatch any of the given strings
MethodSignatureDescription
contains(text: &str) -> QueryBuilderSubstring / trigram contains search
similar(text: &str, threshold: f64) -> QueryBuilderTrigram similarity search (0.0–1.0)
phonetic(text: &str) -> QueryBuilderSoundex/Metaphone phonetic search
fuzzy(text: &str) -> QueryBuilderLevenshtein distance fuzzy search
match_query(text: &str) -> QueryBuilderFull-text match query

Boolean Combinators

MethodSignatureDescription
and(build_fn: FnOnce(QueryBuilder) -> QueryBuilder) -> SelfAND group via closure
or(build_fn: FnOnce(QueryBuilder) -> QueryBuilder) -> SelfOR group via closure
not(build_fn: FnOnce(QueryBuilder) -> QueryBuilder) -> SelfNegate a condition via closure

Sorting and Pagination

MethodSignatureDescription
sort(field: impl Into<String>, direction: SortDirection) -> SelfAdd a sort field
limit(count: usize) -> SelfLimit result count
offset(count: usize) -> SelfSkip the first N results

Execution

MethodSignatureDescription
execute(self) -> Result<Vec<QueryResult>, PluginError>Execute the query via host FFI
to_json(&self) -> serde_json::ValueSerialize builder state to JSON (for inspection/debugging)

QueryResult

A single query result returned by the host.

FieldTypeDescription
pathStringPath of the matching file
scoref64Relevance score (higher is better, default 0.0)
matched_byVec<String>Names of the indexes/operations that matched (default empty)

SortDirection

Sort direction for query results.

VariantDescription
AscAscending order
DescDescending order

AggregateBuilder

Fluent builder for constructing AeorDB aggregation queries. Obtained via PluginContext::aggregate(path) or AggregateBuilder::new(path).

Aggregation Operations

MethodSignatureDescription
count(self) -> SelfRequest a count aggregation
sum(field: impl Into<String>) -> SelfRequest a sum on a field
avg(field: impl Into<String>) -> SelfRequest an average on a field
min_val(field: impl Into<String>) -> SelfRequest a minimum value on a field
max_val(field: impl Into<String>) -> SelfRequest a maximum value on a field

Grouping and Filtering

MethodSignatureDescription
group_by(field: impl Into<String>) -> SelfGroup results by a field
filter(build_fn: FnOnce(QueryBuilder) -> QueryBuilder) -> SelfAdd a where condition via closure
limit(count: usize) -> SelfLimit the number of groups returned

Execution

MethodSignatureDescription
execute(self) -> Result<AggregateResult, PluginError>Execute the aggregation via host FFI
to_json(&self) -> serde_json::ValueSerialize builder state to JSON

AggregateResult

Aggregation result returned by the host.

FieldTypeDescription
groupsVec<serde_json::Value>Per-group aggregation results (default empty)
total_countOption<u64>Total count if count was requested without group_by

See Also