Skip to content

geniustechspace/api-contracts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

17 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Enterprise API Contracts

License: BSD-3-Clause Buf Rust

Enterprise-Grade gRPC API Contracts with Multi-Language Client Generation

Single Source of Truth for GeniusTechSpace Platform

Features β€’ Quick Start β€’ Architecture β€’ Documentation β€’ Contributing


🎯 Overview

This repository is the single source of truth for all API contracts across the GeniusTechSpace platform. It provides:

  • Protocol Buffer Definitions: Complete API specifications using proto3
  • Multi-Language Clients: Auto-generated clients for Rust, Go, Python, TypeScript, and Java
  • Enterprise Features: Multitenancy, compliance, audit logging, and security
  • Developer Experience: Strong typing, validation, comprehensive documentation
  • CI/CD Integration: Automated testing, breaking change detection, and publishing

🎯 Primary Language: Rust

This project prioritizes Rust for high-performance, type-safe service development while supporting multiple languages for diverse use cases.


✨ Features

Core Capabilities

  • 🏒 Enterprise Multitenancy - Tenant/Organization/Workspace isolation
  • πŸ” Security First - TLS, authentication, authorization, encryption
  • πŸ“Š Comprehensive Audit Logging - Compliance-ready audit trails
  • 🌍 Data Residency - Geographic data storage controls
  • ⚑ High Performance - gRPC binary protocol, streaming support
  • πŸ”„ Backward Compatibility - Breaking change detection
  • πŸ“ Self-Documenting - Auto-generated documentation
  • βœ… Input Validation - Request/response validation rules

Compliance & Standards

  • GDPR - General Data Protection Regulation
  • HIPAA - Health Insurance Portability and Accountability Act
  • SOC 2 - Service Organization Control 2
  • PCI DSS - Payment Card Industry Data Security Standard
  • ISO 27001 - Information Security Management

πŸš€ Quick Start

Prerequisites

  • Buf >= 1.28.0 (required)
  • Rust >= 1.75 (primary language)
  • Go >= 1.21 (optional)
  • Python >= 3.8 (optional)
  • Node.js >= 18 (optional)
  • Java >= 17 (optional)

Installation

# Clone the repository
git clone https://github.com/geniustechspace/api-contracts.git
cd api-contracts

# Install dependencies
make install

# Set up enterprise structure
make setup

# Generate clients
make generate

# Build Rust client (primary)
make build-rust

Verify Installation

# Check setup
make help

# Lint proto files
make lint

# Run tests
make test

πŸ“ Repository Structure

api-contracts/
β”œβ”€β”€ proto/                              # Protocol Buffer definitions
β”‚   β”œβ”€β”€ core/v1/                        # Core infrastructure types
β”‚   β”‚   β”œβ”€β”€ tenant.proto               # Multitenancy primitives βœ…
β”‚   β”‚   β”œβ”€β”€ context.proto              # Request/response context
β”‚   β”‚   β”œβ”€β”€ errors.proto               # Standard error handling
β”‚   β”‚   β”œβ”€β”€ audit.proto                # Audit logging
β”‚   β”‚   β”œβ”€β”€ metadata.proto             # Standard metadata
β”‚   β”‚   β”œβ”€β”€ health.proto               # Health checks
β”‚   β”‚   β”œβ”€β”€ pagination.proto           # Pagination patterns
β”‚   β”‚   └── types.proto                # Common data types (email, phone, address)
β”‚   β”œβ”€β”€ idp/v1/                        # Identity Provider
β”‚   β”‚   β”œβ”€β”€ auth/                      # Authentication
β”‚   β”‚   β”œβ”€β”€ user/                      # User management
β”‚   β”‚   β”œβ”€β”€ organization/              # Organization management
β”‚   β”‚   β”œβ”€β”€ role/                      # RBAC
β”‚   β”‚   β”œβ”€β”€ permission/                # Permissions
β”‚   β”‚   └── session/                   # Session management
β”‚   └── services/                      # Business services
β”œβ”€β”€ clients/                           # Generated clients
β”‚   β”œβ”€β”€ rust/                          # Rust (PRIMARY)
β”‚   β”œβ”€β”€ go/                            # Go
β”‚   β”œβ”€β”€ python/                        # Python
β”‚   β”œβ”€β”€ typescript/                    # TypeScript/JavaScript
β”‚   └── java/                          # Java
β”œβ”€β”€ docs/                              # Documentation
β”‚   β”œβ”€β”€ api/                           # Generated API docs
β”‚   β”œβ”€β”€ standards/                     # Design standards
β”‚   β”œβ”€β”€ compliance/                    # Compliance guides
β”‚   β”œβ”€β”€ architecture/                  # Architecture docs
β”‚   └── guides/                        # How-to guides
β”œβ”€β”€ scripts/                           # Automation scripts
β”œβ”€β”€ tests/                             # Integration tests
β”œβ”€β”€ buf.yaml                           # Buf configuration
β”œβ”€β”€ buf.gen.yaml                       # Code generation config
β”œβ”€β”€ Makefile                           # Build automation
└── README.md                          # This file

πŸ—οΈ Architecture

Multitenancy Model

Tenant (Required)
  └── Organization (Optional)
      └── Workspace (Optional)

Every request MUST include tenant context:

gRPC Metadata:

x-tenant-id: tenant-123
x-organization-id: org-456
x-workspace-id: workspace-789

HTTP Headers:

X-Tenant-ID: tenant-123
X-Organization-ID: org-456
X-Workspace-ID: workspace-789

Request Flow

Client β†’ API Gateway β†’ Service β†’ Database
         ↓
      Metadata:
      - x-tenant-id (required)
      - x-request-id (required)
      - x-correlation-id (for tracing)
      - x-user-id (if authenticated)
      - Authorization: Bearer <token>

Error Handling

All services return standardized errors:

message ErrorResponse {
  string code = 1;                    // Application error code
  string message = 2;                 // Human-readable message
  ErrorCategory category = 3;          // Classification
  ErrorSeverity severity = 4;          // Severity level
  repeated FieldViolation fields = 5;  // Field-level errors
  RetryInfo retry_info = 6;           // Retry guidance
}

πŸ“ Usage Examples

Rust (Primary Language)

use geniustechspace_api_contracts::idp::auth::v1::*;
use tonic::Request;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to auth service
    let mut client = AuthServiceClient::connect("http://[::1]:50051").await?;
    
    // Create request with tenant context
    let mut request = Request::new(SignInRequest {
        tenant_id: "tenant-123".into(),
        email: "user@example.com".into(),
        password: "secure-password".into(),
    });
    
    // Add metadata
    request.metadata_mut().insert(
        "x-request-id",
        "req-123".parse().unwrap()
    );
    
    // Make request
    let response = client.sign_in(request).await?;
    let token = response.into_inner().access_token;
    
    println!("βœ… Authenticated: {}", token);
    
    Ok(())
}

Go

package main

import (
    "context"
    "log"
    
    "google.golang.org/grpc"
    authv1 "github.com/geniustechspace/api-contracts/gen/go/idp/v1/auth"
)

func main() {
    conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
    if err != nil {
        log.Fatalf("Failed to connect: %v", err)
    }
    defer conn.Close()
    
    client := authv1.NewAuthServiceClient(conn)
    
    resp, err := client.SignIn(context.Background(), &authv1.SignInRequest{
        TenantId: "tenant-123",
        Email:    "user@example.com",
        Password: "secure-password",
    })
    
    if err != nil {
        log.Fatalf("SignIn failed: %v", err)
    }
    
    log.Printf("βœ… Authenticated: %s", resp.AccessToken)
}

Python

import grpc
from proto.idp.v1.auth import auth_service_pb2, auth_service_pb2_grpc

# Connect to service
channel = grpc.insecure_channel('localhost:50051')
stub = auth_service_pb2_grpc.AuthServiceStub(channel)

# Make request
request = auth_service_pb2.SignInRequest(
    tenant_id="tenant-123",
    email="user@example.com",
    password="secure-password"
)

response = stub.SignIn(request)
print(f"βœ… Authenticated: {response.access_token}")

TypeScript

import * as grpc from '@grpc/grpc-js';
import { AuthServiceClient } from '@geniustechspace/api-contracts/idp/v1/auth';

const client = new AuthServiceClient(
  'localhost:50051',
  grpc.credentials.createInsecure()
);

client.signIn({
  tenantId: 'tenant-123',
  email: 'user@example.com',
  password: 'secure-password'
}, (err, response) => {
  if (err) {
    console.error('❌ Error:', err);
    return;
  }
  console.log('βœ… Authenticated:', response.accessToken);
});

πŸ› οΈ Development

Adding a New Service

Quick Start (Interactive)

Use the interactive service generator for fast setup:

make add-service

This will prompt you for:

  • Service name (e.g., user-management, billing)
  • Service description
  • API version (default: v1)
  • Main entity name

The tool automatically:

  • Creates directory structure (proto/<service-name>/v1/)
  • Generates proto files from templates
  • Sets up README documentation
  • Includes multitenancy, validation, and error handling
  • Integrates with existing build scripts

Manual Setup

Alternatively, create services manually:

  1. Create proto directory:

    mkdir -p proto/services/myservice/v1
  2. Define service (proto/services/myservice/v1/service.proto):

    syntax = "proto3";
    
    package geniustechspace.services.myservice.v1;
    
    import "core/v1/tenant.proto";
    import "core/v1/errors.proto";
    import "google/api/annotations.proto";
    import "validate/validate.proto";
    
    option rust_package = "geniustechspace::services::myservice::v1";
    
    // MyService provides example functionality.
    service MyService {
      // GetResource retrieves a resource by ID.
      rpc GetResource(GetResourceRequest) returns (GetResourceResponse) {
        option (google.api.http) = {
          get: "/v1/resources/{id}"
        };
      }
    }
    
    // GetResourceRequest requests a resource by ID.
    message GetResourceRequest {
      // Resource identifier.
      string id = 1 [(validate.rules).string.uuid = true];
    }
    
    // GetResourceResponse returns the requested resource.
    message GetResourceResponse {
      // Resource identifier.
      string id = 1;
      
      // Resource name.
      string name = 2;
    }
  3. Generate clients:

    make generate
  4. Build and test:

    make build
    make test

πŸ’‘ Tip: For a complete service template with validation, multitenancy, and CRUD operations, use make add-service instead. See templates/README.md for details.

Code Quality

# Lint proto files
make lint

# Format proto files
make format

# Check for breaking changes
make breaking

# Run all checks
make check

πŸ“š Documentation

Generated Documentation

Standards & Guides

Key Documents


πŸ”’ Security

Best Practices

  • TLS Required: All connections must use TLS 1.3+
  • Token Validation: JWT tokens validated on every request
  • Rate Limiting: Per-tenant rate limits enforced
  • Audit Logging: All security events logged
  • Encryption: Data encrypted at rest and in transit

Reporting Vulnerabilities

Email security concerns to: security@geniustechspace.com


🀝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Development Workflow

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Add/modify proto files
  4. Generate clients (make generate)
  5. Run tests (make test)
  6. Commit changes (git commit -m 'Add amazing feature')
  7. Push to branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

Code Review

All changes require:

  • βœ… Passing CI checks
  • βœ… No breaking changes (or properly versioned)
  • βœ… Complete documentation
  • βœ… Code review approval

πŸ“‹ Compliance

This project supports the following compliance frameworks:

Framework Status Documentation
GDPR βœ… Supported docs/compliance/gdpr.md
HIPAA βœ… Supported docs/compliance/hipaa.md
SOC 2 βœ… Supported docs/compliance/soc2.md
PCI DSS βœ… Supported docs/compliance/pci-dss.md

πŸ”„ Versioning

We use a dual versioning strategy that combines directory-based API versioning with Buf's module versioning:

  • Proto API Versioning: Directory-based (v1/, v2/, etc.) for API evolution

    • Enables multiple API versions to coexist
    • Allows smooth client migration without breaking changes
    • Industry standard (used by Google, Kubernetes, etc.)
  • Module Versioning: Semantic versioning (SemVer) via Buf for releases

    • Tags: Format v<major>.<minor>.<patch> (e.g., v1.0.0)
    • Breaking changes in API require new directory (v2) AND new major version (v2.0.0)
    • Buf tracks module dependencies and ensures reproducible builds

Why both? They solve different problems:

  • Directory versioning = API contract evolution (runtime coexistence)
  • Buf versioning = Module release management (dependency tracking)

See Versioning Strategy for detailed explanation.


πŸ“¦ Client Packages

This project uses a modular, multi-package architecture where each API module is independently installable. See MULTI_PACKAGE_ARCHITECTURE.md for details.

Rust (Primary)

[dependencies]
# Install only what you need
geniustechspace-core = "0.1.0"
geniustechspace-idp = "0.1.0"
geniustechspace-notification = "0.1.0"

Go

# Install only what you need
go get github.com/geniustechspace/api-contracts/gen/go/core
go get github.com/geniustechspace/api-contracts/gen/go/idp
go get github.com/geniustechspace/api-contracts/gen/go/notification

Python

# Install only what you need
pip install geniustechspace-core
pip install geniustechspace-idp
pip install geniustechspace-notification

TypeScript

# Install only what you need
npm install @geniustechspace/core
npm install @geniustechspace/idp
npm install @geniustechspace/notification

Java

<dependencies>
  <!-- Install only what you need -->
  <dependency>
    <groupId>com.geniustechspace</groupId>
    <artifactId>api-contracts-core</artifactId>
    <version>0.1.0</version>
  </dependency>
  <dependency>
    <groupId>com.geniustechspace</groupId>
    <artifactId>api-contracts-idp</artifactId>
    <version>0.1.0</version>
  </dependency>
  <dependency>
    <groupId>com.geniustechspace</groupId>
    <artifactId>api-contracts-notification</artifactId>
    <version>0.1.0</version>
  </dependency>
</dependencies>

🎯 Roadmap

  • Core infrastructure types (tenant, context, errors)
  • Multi-language client generation
  • Rust as primary language
  • Complete IDP service definitions
  • Common business types
  • Service templates and generators
  • Advanced streaming patterns
  • GraphQL gateway support
  • Automated SDK publishing

πŸ“Š Performance

Targets

  • Latency: p95 < 100ms, p99 < 500ms
  • Throughput: 10,000+ RPS per service
  • Availability: 99.95% uptime SLA
  • Scalability: Horizontal scaling supported

Benchmarks

Run benchmarks:

cd clients/rust
cargo bench

πŸ“ž Support


πŸ“„ License

This project is licensed under the BSD-3-Clause License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • Buf - Protocol Buffer tooling
  • gRPC - High-performance RPC framework
  • Tonic - Rust gRPC implementation
  • Prost - Rust Protocol Buffer implementation

Built with ❀️ by GeniusTechSpace

⭐ Star us on GitHub β€” it helps!

Website β€’ Blog β€’ Twitter

About

API Contracts Mono-Repo

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors