New:Microsoft Teams Notifications Are Now Available in Socket.Learn more →
Get Started

@galaxy-stack/orbit-microservices-grpc

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@galaxy-stack/orbit-microservices-grpc

gRPC transport for Orbit microservices

latest
Source
npmnpm
Version
0.1.9
Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

@galaxy-stack/orbit-microservices-grpc

npm version docs

Part of the Orbit framework — a NestJS-style backend framework for Bun.

Installation

bun add @galaxy-stack/orbit-microservices-grpc

@galaxy-stack/orbit-microservices-grpc

Status: ✅ Full Implementation - Complete gRPC over HTTP/2 với node:http2

Mô tả

gRPC transport implementation cho Orbit microservices sử dụng HTTP/2 qua node:http2 module.

Tính năng

  • Full HTTP/2 support qua node:http2
  • gRPC message framing (length-prefixed)
  • JSON serialization (protobuf support planned)
  • Unary RPC pattern
  • TLS/SSL support với certificates
  • Insecure mode cho development
  • gRPC status codes và trailers
  • Metadata extraction từ headers
  • Request timeout handling
  • Graceful shutdown

Cài đặt

bun add @galaxy-stack/orbit-microservices-grpc

Sử dụng

gRPC Server

import { BunFactory } from '@galaxy-stack/orbit-core';
import '@galaxy-stack/orbit-microservices-grpc';

// Insecure mode (development)
const app = await BunFactory.createMicroservice(AppModule, {
  transport: 'GRPC',
  options: {
    host: '0.0.0.0',
    port: 50051,
    package: 'myservice',
    insecure: true,
  },
});

await app.listen();
// [GrpcServer] Listening on h2c://0.0.0.0:50051

// Secure mode (production)
const secureApp = await BunFactory.createMicroservice(AppModule, {
  transport: 'GRPC',
  options: {
    host: '0.0.0.0',
    port: 50051,
    package: 'myservice',
    insecure: false,
    credentials: {
      key: './certs/server.key',
      cert: './certs/server.crt',
      ca: './certs/ca.crt', // optional
    },
  },
});

gRPC Client

import { MicroservicesModule } from '@galaxy-stack/orbit-microservices';
import '@galaxy-stack/orbit-microservices-grpc';

@Module({
  imports: [
    MicroservicesModule.register({
      name: 'GRPC_SERVICE',
      transport: 'GRPC',
      options: {
        host: 'localhost',
        port: 50051,
        package: 'myservice',
        insecure: true,
      },
    }),
  ],
})
class ClientModule {}

Message Handlers

import { Controller, GrpcMethod } from '@galaxy-stack/orbit-microservices';

interface GetUserRequest {
  id: number;
}

interface User {
  id: number;
  name: string;
  email: string;
}

@Controller()
class UserController {
  @GrpcMethod('UserService', 'GetUser')
  getUser(data: GetUserRequest, metadata?: Record<string, string>): User {
    return { 
      id: data.id, 
      name: 'John Doe',
      email: 'john@example.com',
    };
  }

  @GrpcMethod('UserService', 'CreateUser')
  createUser(data: { name: string; email: string }): User {
    return { 
      id: Date.now(), 
      name: data.name,
      email: data.email,
    };
  }
}

Client Usage

@Injectable()
class UserService {
  constructor(
    @Inject('GRPC_SERVICE') private client: ClientProxy
  ) {}

  async getUser(id: number): Promise<User> {
    return this.client.send('UserService/GetUser', { id });
  }

  async createUser(name: string, email: string): Promise<User> {
    return this.client.send('UserService/CreateUser', { name, email });
  }
}

Options

GrpcServerOptions

interface GrpcServerOptions {
  host?: string;                    // Default: '0.0.0.0'
  port?: number;                    // Default: 50051
  package?: string;                 // Package name (default: 'orbit')
  insecure?: boolean;               // Use h2c (HTTP/2 cleartext) (default: true)
  credentials?: {
    key: string | Buffer;           // Private key path or buffer
    cert: string | Buffer;          // Certificate path or buffer
    ca?: string | Buffer;           // CA certificate (optional)
  };
  protoPath?: string | string[];    // Proto file paths (future use)
  protoLoader?: {
    keepCase?: boolean;
    longs?: 'String' | 'Number';
    enums?: 'String' | 'Number';
    defaults?: boolean;
    oneofs?: boolean;
    includeDirs?: string[];
  };
  maxSendMessageLength?: number;    // Default: 4MB
  maxReceiveMessageLength?: number; // Default: 4MB
}

GrpcClientOptions

interface GrpcClientOptions extends GrpcServerOptions {
  requestTimeout?: number;          // Default: 30000ms
  keepalive?: {
    time?: number;
    timeout?: number;
    permitWithoutCalls?: boolean;
  };
}

Pattern Format

gRPC patterns support:

  • String: "UserService/GetUser"
  • Object: { service: 'UserService', method: 'GetUser' }

Path Mapping

Path được xây dựng theo gRPC format:

/{package}.{service}/{method}

Ví dụ: /myservice.UserService/GetUser

Message Framing

gRPC sử dụng length-prefixed framing:

┌────────────────┬────────────────┬────────────────────────┐
│ Compressed (1B)│ Length (4B BE) │ Message (N bytes)      │
└────────────────┴────────────────┴────────────────────────┘

gRPC Status Codes

CodeNameDescription
0OKSuccess
1CANCELLEDOperation cancelled
2UNKNOWNUnknown error
3INVALID_ARGUMENTInvalid argument
4DEADLINE_EXCEEDEDTimeout
5NOT_FOUNDNot found
6ALREADY_EXISTSAlready exists
7PERMISSION_DENIEDPermission denied
8RESOURCE_EXHAUSTEDResource exhausted
9FAILED_PRECONDITIONFailed precondition
10ABORTEDAborted
11OUT_OF_RANGEOut of range
12UNIMPLEMENTEDNot implemented
13INTERNALInternal error
14UNAVAILABLEService unavailable
15DATA_LOSSData loss
16UNAUTHENTICATEDUnauthenticated

Metadata

Headers với prefix grpc- và x- được extract thành metadata:

@GrpcMethod('UserService', 'GetUser')
getUser(data: GetUserRequest, metadata?: Record<string, string>): User {
  console.log('Auth token:', metadata?.['x-auth-token']);
  return { id: data.id, name: 'John' };
}

Error Handling

@GrpcMethod('UserService', 'GetUser')
getUser(data: { id: number }) {
  const user = this.userRepo.find(data.id);
  if (!user) {
    throw new Error('User not found');
  }
  return user;
}

// Client side
try {
  const user = await client.send('UserService/GetUser', { id: 999 });
} catch (error) {
  console.error(error.message); // 'User not found'
}

HTTP/2 Features

Full HTTP/2 support qua node:http2:

  • Multiplexing - multiple requests trên single connection
  • Header compression (HPACK)
  • Stream prioritization
  • Flow control
  • Trailers cho gRPC status

Insecure vs Secure Mode

ModeProtocolUse Case
insecure: trueh2c (HTTP/2 cleartext)Development, internal services
insecure: falseh2 (HTTP/2 over TLS)Production, public APIs

Architecture

┌─────────────────────────────────────────────────────────┐
│                    Application                          │
├─────────────────────────────────────────────────────────┤
│      GrpcServer          │         GrpcClient          │
├─────────────────────────────────────────────────────────┤
│              gRPC Message Framing                       │
├─────────────────────────────────────────────────────────┤
│              node:http2 (HTTP/2)                        │
└─────────────────────────────────────────────────────────┘

Roadmap

  • Protobuf serialization (currently JSON)
  • Bidirectional streaming
  • gRPC reflection
  • Load balancing
  • Health checking protocol

FAQs

Package last updated on 26 Sep 2026

Related posts