XU XUv0.16.0

#github.com/xulang-org/packages/grpc

import: grpc #github.com/xulang-org/packages/grpc

counts: 20 functions, 8 methods, 5 types, 20 constants, 0 method sets

gRPC & HTTP/2 High-Performance RPC Driver for Xu Implements HTTP/2 frame framing, HPACK headers, Protobuf serialization, and Unary RPC connection pooling.

github.com/xulang-org/packages · 1.17.2 · Install and use

Examples · API declarations

Examples

These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.

46_standalone_grpc/main.xu

Required SDK: Xu 0.8.3 · Complete project · Download source

XuLocal SDK example
@main

grpc #github.com/xulang-org/packages/grpc
#errors
#strings

fn verify_protobuf_encoding() {
    println("--- 1. Testing Protocol Buffers & gRPC Message Framing ---")

    // 1. Varint test
    v1 := grpc.encode_varint(300)
    decoded_v1 := grpc.decode_varint(&v1, 0)
    if decoded_v1 == 300 {
        println("   [PASS] Varint encode/decode matched: 300")
    } else {
        println("   [FAIL] Varint mismatch: " + str(decoded_v1))
    }

    // 2. Protobuf String & Int fields
    f_str := grpc.encode_string_field(1, "hello grpc")
    f_int := grpc.encode_int_field(2, 42)
    proto_msg := f_str + f_int
    println("   [PASS] Protobuf serialized message length: " + str(proto_msg.len) + " bytes")

    // 3. gRPC 5-byte Framing
    grpc_frame := grpc.build_grpc_message(proto_msg + "")
    if grpc_frame.len == proto_msg.len + 5 {
        println("   [PASS] gRPC 5-byte header prefixed successfully (total: " + str(grpc_frame.len) + " bytes)")
    } else {
        println("   [FAIL] gRPC frame length mismatch")
    }

    parsed_payload := grpc.parse_grpc_message(grpc_frame + "")
    if parsed_payload == proto_msg {
        println("   [PASS] gRPC payload parsed & unpacked cleanly.")
    } else {
        println("   [FAIL] Unpacked payload mismatch!")
    }

    // 4. Protobuf Field Extraction
    extracted_str := grpc.get_string_field(parsed_payload + "", 1)
    extracted_int := grpc.get_int_field(parsed_payload + "", 2)
    if extracted_str == "hello grpc" && extracted_int == 42 {
        println("   [PASS] Protobuf field extraction: str='" + extracted_str + "', int=" + str(extracted_int))
    } else {
        println("   [FAIL] Protobuf field extraction mismatch")
    }
}

fn verify_grpc_pool() {
    println("\n--- 2. Testing gRPC Connection Pool ---")
    $p := grpc.open_pool("127.0.0.1:9000", 5)

    // 1. Connection Reuse
    fd1 := p.get_conn()
    println("   Borrow 1 fd: " + str(fd1))
    p.put_conn(fd1)

    fd2 := p.get_conn()
    println("   Borrow 2 (after return) fd: " + str(fd2))
    if fd1 == fd2 {
        println("   [PASS] Connection reused successfully (fd " + str(fd1) + " == " + str(fd2) + ")")
    } else {
        println("   [WARN] Different fd allocated: " + str(fd1) + " vs " + str(fd2))
    }

    // 2. Multi-connection concurrent borrow
    fd3 := p.get_conn()
    println("   Borrow 3 (concurrently) fd: " + str(fd3))
    if fd2 != fd3 {
        println("   [PASS] Concurrently allocated distinct fds (" + str(fd2) + " != " + str(fd3) + ")")
    } else {
        println("   [FAIL] Expected distinct fds for concurrent connections!")
    }
    p.put_conn(fd2)
    p.put_conn(fd3)

    p.close()
    println("   [PASS] gRPC Pool closed cleanly.")
}

fn verify_grpc_unary_call() {
    println("\n--- 3. Testing gRPC Unary RPC Call ---")
    $p := grpc.open_pool("127.0.0.1:9000", 5)

    // DummyUnary accepts an empty or arbitrary message and echoes dummy response
    req_body := grpc.encode_string_field(1, "Xu Language gRPC test")
    resp := p.call_unary("/grpcbin.GRPCBin/DummyUnary", req_body) >>> (err) {
        println("   [FAIL] gRPC call failed: " + err.msg())
        p.close()
        <<
    }

    println("   [PASS] gRPC Unary RPC Call (DummyUnary) succeeded!")
    println("   Response payload length: " + str(resp.payload.len) + " bytes")
    println("   Status: " + str(resp.status))

    // Call SayHello on hello.HelloService
    hello_req := grpc.encode_string_field(1, "Antigravity")
    hello_resp := p.call_unary("/hello.HelloService/SayHello", hello_req) >>> (err) {
        println("   [FAIL] SayHello failed: " + err.msg())
        p.close()
        <<
    }
    reply_msg := grpc.get_string_field(hello_resp.payload + "", 1)
    if reply_msg == "hello Antigravity" {
        println("   [PASS] gRPC Unary RPC Call (SayHello) succeeded!")
        println("   [PASS] Echoed reply matched exactly: '" + reply_msg + "'")
    } else {
        println("   [FAIL] Echoed reply unexpected: '" + reply_msg + "'")
    }

    p.close()
}

fn main() {
    println("=== Xu gRPC & HTTP/2 Native Driver Verification ===\n")
    verify_protobuf_encoding()
    verify_grpc_pool()
    verify_grpc_unary_call()
    println("\n[GRPC VERIFICATION 100% COMPLETED]")
}

API declarations

struct Response

XuAPI
pub struct Response {
    pub status int
    pub message string
    pub payload string
}

Purpose

Grpc Server response payload containing status, headers, and body.

Public fields

status int
field (int)
message string
field (string)
payload string
field (string)

struct GrpcClient

XuAPI
pub struct GrpcClient {
    pub host string
    pub port int
    pub secure bool
}

Purpose

Grpc Client session maintaining connection and operations.

Public fields

host string
host
port int
port
secure bool
field (bool)

new_client

XuAPI
pub fn new_client(endpoint string) GrpcClient

Purpose

Construct client.

Parameters

endpoint string
endpoint (string)

Returns

GrpcClient — a value of this type

(GrpcClient) read_h2_frame

XuAPI
pub fn (c GrpcClient) read_h2_frame(fd int) H2Frame

Purpose

Operation on GrpcClient: read h2 frame. Throws on failure; handle the error or propagate it to the caller.

Parameters

c GrpcClient
The GrpcClient instance used by this call (value receiver).
fd int
file descriptor (int)

Returns

H2Frame — a value of this type

(GrpcClient) connect

XuAPI
pub fn (c GrpcClient) connect() int

Purpose

Establish network connection to the target server endpoint. Throws on failure; handle the error or propagate it to the caller.

Parameters

c GrpcClient
The GrpcClient instance used by this call (value receiver).

Returns

int — a value of this type

(GrpcClient) call_unary

XuAPI
pub fn (c GrpcClient) call_unary(path string, req_bytes string) Response

Purpose

Executes an Unary RPC Call over HTTP/2 with gRPC framing Throws on failure; handle the error or propagate it to the caller.

Parameters

c GrpcClient
The GrpcClient instance used by this call (value receiver).
path string
filesystem path (string)
req_bytes string
req_bytes (string)

Returns

Response — a value of this type

(GrpcClient) call_unary_on_fd

XuAPI
pub fn (c GrpcClient) call_unary_on_fd(fd int, path string, req_bytes string, stream_id int) Response

Purpose

Operation on GrpcClient: call unary on fd. Throws on failure; handle the error or propagate it to the caller.

Parameters

c GrpcClient
The GrpcClient instance used by this call (value receiver).
fd int
file descriptor (int)
path string
filesystem path (string)
req_bytes string
req_bytes (string)
stream_id int
stream_id (int)

Returns

Response — a value of this type

const H2_CLIENT_PREFACE

XuAPI
pub const H2_CLIENT_PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"

Purpose

Constant H2_CLIENT_PREFACE, defining protocol or algorithm parameters.

const FRAME_DATA

XuAPI
pub const FRAME_DATA = 0

Purpose

HTTP/2 Frame Types

const FRAME_HEADERS

XuAPI
pub const FRAME_HEADERS = 1

Purpose

Constant FRAME_HEADERS, defining protocol or algorithm parameters.

const FRAME_PRIORITY

XuAPI
pub const FRAME_PRIORITY = 2

Purpose

Constant FRAME_PRIORITY, defining protocol or algorithm parameters.

const FRAME_RST_STREAM

XuAPI
pub const FRAME_RST_STREAM = 3

Purpose

Constant FRAME_RST_STREAM, defining protocol or algorithm parameters.

const FRAME_SETTINGS

XuAPI
pub const FRAME_SETTINGS = 4

Purpose

Constant FRAME_SETTINGS, defining protocol or algorithm parameters.

const FRAME_PUSH_PROMISE

XuAPI
pub const FRAME_PUSH_PROMISE = 5

Purpose

Constant FRAME_PUSH_PROMISE, defining protocol or algorithm parameters.

const FRAME_PING

XuAPI
pub const FRAME_PING = 6

Purpose

Constant FRAME_PING, defining protocol or algorithm parameters.

const FRAME_GOAWAY

XuAPI
pub const FRAME_GOAWAY = 7

Purpose

Constant FRAME_GOAWAY, defining protocol or algorithm parameters.

const FRAME_WINDOW_UPDATE

XuAPI
pub const FRAME_WINDOW_UPDATE = 8

Purpose

Constant FRAME_WINDOW_UPDATE, defining protocol or algorithm parameters.

const FRAME_CONTINUATION

XuAPI
pub const FRAME_CONTINUATION = 9

Purpose

Constant FRAME_CONTINUATION, defining protocol or algorithm parameters.

const FLAG_ACK

XuAPI
pub const FLAG_ACK = 1

Purpose

HTTP/2 Flags

const FLAG_END_STREAM

XuAPI
pub const FLAG_END_STREAM = 1

Purpose

Constant FLAG_END_STREAM, defining protocol or algorithm parameters.

const FLAG_END_HEADERS

XuAPI
pub const FLAG_END_HEADERS = 4

Purpose

Constant FLAG_END_HEADERS, defining protocol or algorithm parameters.

const FLAG_PADDED

XuAPI
pub const FLAG_PADDED = 8

Purpose

Constant FLAG_PADDED, defining protocol or algorithm parameters.

const FLAG_PRIORITY

XuAPI
pub const FLAG_PRIORITY = 32

Purpose

Constant FLAG_PRIORITY, defining protocol or algorithm parameters.

struct H2Frame

XuAPI
pub struct H2Frame {
    pub length int
    pub frame_type int
    pub flags int
    pub stream_id int
    pub payload string
}

Purpose

Grpc Protocol data frame encapsulation.

Public fields

length int
field (int)
frame_type int
field (int)
flags int
field (int)
stream_id int
field (int)
payload string
field (string)

encode_h2_header

XuAPI
pub fn encode_h2_header(len int, frame_type int, flags int, stream_id int) string

Purpose

Encode h2 header data.

Parameters

len int
len (int)
frame_type int
frame_type (int)
flags int
flags (int)
stream_id int
stream_id (int)

Returns

string — result string

build_settings_frame

XuAPI
pub fn build_settings_frame(ack bool) string

Purpose

Build settings frame.

Parameters

ack bool
ack (bool)

Returns

string — result string

build_data_frame

XuAPI
pub fn build_data_frame(stream_id int, data string, end_stream bool) string

Purpose

Build data frame.

Parameters

stream_id int
stream_id (int)
data string
data (string)
end_stream bool
end_stream (bool)

Returns

string — result string

build_grpc_hpack_headers

XuAPI
pub fn build_grpc_hpack_headers(path string) string

Purpose

Builds HPACK block for gRPC request method: POST (Index 3 -> 0x83) scheme: http (Index 6 -> 0x86) path: path content-type: application/grpc te: trailers

Parameters

path string
filesystem path (string)

Returns

string — result string

build_grpc_headers_for_host_scheme

XuAPI
pub fn build_grpc_headers_for_host_scheme(path string, authority string, scheme string) string

Purpose

Build grpc headers for host scheme.

Parameters

path string
filesystem path (string)
authority string
authority (string)
scheme string
scheme (string)

Returns

string — result string

build_headers_frame

XuAPI
pub fn build_headers_frame(stream_id int, path string, end_stream bool) string

Purpose

Build headers frame.

Parameters

stream_id int
stream_id (int)
path string
filesystem path (string)
end_stream bool
end_stream (bool)

Returns

string — result string

struct Pool

XuAPI
pub struct Pool {
    pub client GrpcClient
    pub idle chan int
    pub max_idle int
}

Purpose

Grpc Connection pool manager scheduling reusable socket connections.

Public fields

client GrpcClient
field (GrpcClient)
idle chan int
field (channel; type chan int)
max_idle int
field (int)

new_pool

XuAPI
pub fn new_pool(endpoint string, max_idle int) Pool

Purpose

Construct pool.

Parameters

endpoint string
endpoint (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

open_pool

XuAPI
pub fn open_pool(endpoint string, max_idle int) Pool

Purpose

Open pool.

Parameters

endpoint string
endpoint (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

See usage example

(&Pool) get_conn

XuAPI
pub fn (p &Pool) get_conn() int

Purpose

Operation on &Pool: read conn.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

int — a value of this type

(&Pool) put_conn

XuAPI
pub fn (p &Pool) put_conn(fd int)

Purpose

Operation on &Pool: put connection.

Parameters

p &Pool
The Pool instance used by this call (borrow).
fd int
file descriptor (int)

Returns

This call does not return a value.

(&Pool) call_unary

XuAPI
pub fn (p &Pool) call_unary(path string, req_bytes string) Response

Purpose

Operation on &Pool: call unary. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).
path string
filesystem path (string)
req_bytes string
req_bytes (string)

Returns

Response — a value of this type

(&Pool) close

XuAPI
pub fn (p &Pool) close()

Purpose

Operation on &Pool: close the resource.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

This call does not return a value.

const WIRE_VARINT

XuAPI
pub const WIRE_VARINT = 0

Purpose

Protocol Buffers Wire Types

const WIRE_FIXED64

XuAPI
pub const WIRE_FIXED64 = 1

Purpose

Constant WIRE_FIXED64, defining protocol or algorithm parameters.

const WIRE_LENGTH_DELIMITED

XuAPI
pub const WIRE_LENGTH_DELIMITED = 2

Purpose

Constant WIRE_LENGTH_DELIMITED, defining protocol or algorithm parameters.

const WIRE_FIXED32

XuAPI
pub const WIRE_FIXED32 = 5

Purpose

Constant WIRE_FIXED32, defining protocol or algorithm parameters.

encode_varint

XuAPI
pub fn encode_varint(val int) string

Purpose

Encode varint data.

Parameters

val int
value (int)

Returns

string — result string

See usage example

struct VarintResult

XuAPI
pub struct VarintResult {
    pub value int
    pub bytes_read int
}

Purpose

Structure encapsulating value, bytes_read.

Public fields

value int
field (int)
bytes_read int
field (int)

decode_varint_full

XuAPI
pub fn decode_varint_full(buf &string, pos int) VarintResult

Purpose

Decode varint full data.

Parameters

buf &string
buffer (read-only borrow; caller keeps the original; type &string)
pos int
pos (int)

Returns

VarintResult — a value of this type

decode_varint

XuAPI
pub fn decode_varint(buf &string, pos int) int

Purpose

Decode varint data.

Parameters

buf &string
buffer (read-only borrow; caller keeps the original; type &string)
pos int
pos (int)

Returns

int — a value of this type

See usage example

encode_tag

XuAPI
pub fn encode_tag(field_num int, wire_type int) string

Purpose

Encode tag data.

Parameters

field_num int
field_num (int)
wire_type int
wire_type (int)

Returns

string — result string

encode_string_field

XuAPI
pub fn encode_string_field(field_num int, val string) string

Purpose

Encode string field data.

Parameters

field_num int
field_num (int)
val string
value (string)

Returns

string — result string

See usage example

encode_int_field

XuAPI
pub fn encode_int_field(field_num int, val int) string

Purpose

Encode int field data.

Parameters

field_num int
field_num (int)
val int
value (int)

Returns

string — result string

See usage example

build_grpc_message

XuAPI
pub fn build_grpc_message(payload string) string

Purpose

Packages Protobuf payload into a 5-byte prefixed gRPC frame [1 byte compressed flag] + [4 bytes big-endian length] + [payload]

Parameters

payload string
payload (string)

Returns

string — result string

See usage example

parse_grpc_message

XuAPI
pub fn parse_grpc_message(raw string) string

Purpose

Parses gRPC message frame and extracts raw protobuf payload

Parameters

raw string
raw (string)

Returns

string — result string

See usage example

decode_grpc_message

XuAPI
pub fn decode_grpc_message(raw string) string

Purpose

Decode grpc message data. Throws on failure; handle the error or propagate it to the caller.

Parameters

raw string
raw (string)

Returns

string — result string

get_string_field

XuAPI
pub fn get_string_field(payload string, target_field int) string

Purpose

Read string field.

Parameters

payload string
payload (string)
target_field int
target_field (int)

Returns

string — result string

See usage example

get_int_field

XuAPI
pub fn get_int_field(payload string, target_field int) int

Purpose

Read int field.

Parameters

payload string
payload (string)
target_field int
target_field (int)

Returns

int — a value of this type

See usage example