docs: Add Ruby SDK README with comprehensive API documentation and implement modular architecture with HTTParty integration

- Add README.md with installation instructions, architecture overview, and API examples for all SDK modules
- Refactor TelecomSDK::Client to use modular API clients (SubscriberAPI, UsageAPI, PaymentAPI, RatingPlanAPI, SystemAPI, GraphQLAPI)
- Add AuthProvider class with API key and JWT token support (generate_jwt_token, validate_jwt_token methods)
- Add HTTPClient base class with retry
This commit is contained in:
nutcas3
2026-04-25 04:57:00 +03:00
parent d846c304a4
commit ea20dfb302
10 changed files with 637 additions and 194 deletions
+111
View File
@@ -0,0 +1,111 @@
require "openssl"
require "base64"
require "json"
module TelecomSDK
# Authentication provider for the Telecom SDK
class AuthProvider
attr_reader :api_key, :jwt_secret, :token_cache, :token_expiry
def initialize(api_key: nil, jwt_secret: nil)
@api_key = api_key
@jwt_secret = jwt_secret
@token_cache = nil
@token_expiry = nil
end
# Get authentication headers for API requests
def get_headers
headers = {
"Content-Type" => "application/json",
"User-Agent" => "Telecom-Ruby-SDK/1.0.0"
}
headers["X-API-Key"] = @api_key if @api_key
if @token_cache && token_valid?
headers["Authorization"] = "Bearer #{@token_cache}"
end
headers
end
# Generate a JWT token for authentication
def generate_jwt_token(user_id, expiry_hours = 24, additional_claims = {})
raise AuthenticationError, "JWT secret not configured" unless @jwt_secret
now = Time.now.to_i
exp = now + (expiry_hours * 3600)
claims = {
"sub" => user_id,
"exp" => exp,
"iat" => now
}.merge(additional_claims)
header = { "alg" => "HS256", "typ" => "JWT" }
encoded_header = base64_url_encode(header)
encoded_payload = base64_url_encode(claims)
signature = sign("#{encoded_header}.#{encoded_payload}")
@token_cache = "#{encoded_header}.#{encoded_payload}.#{signature}"
@token_expiry = exp
@token_cache
end
# Validate a JWT token
def validate_jwt_token(token)
raise AuthenticationError, "JWT secret not configured" unless @jwt_secret
parts = token.split(".")
raise AuthenticationError, "Invalid token format" if parts.size != 3
encoded_header, encoded_payload, signature = parts
expected_signature = sign("#{encoded_header}.#{encoded_payload}")
raise AuthenticationError, "Invalid token signature" unless signature == expected_signature
payload_bytes = base64_url_decode(encoded_payload)
raise AuthenticationError, "Failed to decode payload" unless payload_bytes
payload = JSON.parse(payload_bytes)
if payload["exp"] && payload["exp"] < Time.now.to_i
raise AuthenticationError, "Token has expired"
end
payload
end
# Clear the cached JWT token
def clear_token_cache
@token_cache = nil
@token_expiry = nil
end
private
def token_valid?
@token_cache && @token_expiry && Time.now.to_i < @token_expiry
end
def base64_url_encode(data)
json = data.to_json
Base64.urlsafe_encode64(json).gsub("=", "")
end
def base64_url_decode(data)
# Add padding if needed
padded_data = data + "=" * (4 - data.length % 4)
Base64.urlsafe_decode64(padded_data)
end
def sign(data)
hmac = OpenSSL::HMAC.new(@jwt_secret, OpenSSL::Digest::SHA256.new)
hmac.update(data)
Base64.urlsafe_encode64(hmac.digest).gsub("=", "")
end
end
end
+14
View File
@@ -0,0 +1,14 @@
module TelecomSDK
# API for GraphQL queries
class GraphQLAPI
def initialize(client)
@client = client
end
def execute(query, variables = nil)
request = { query: query }
request[:variables] = variables if variables
@client.post("/graphql", request)
end
end
end
+81
View File
@@ -0,0 +1,81 @@
require "httparty"
module TelecomSDK
# HTTP client for making API requests
class HTTPClient
include HTTParty
def initialize(base_url, auth_provider, timeout: 30, max_retries: 3, retry_delay: 1, enable_logging: false)
@base_url = base_url
@auth_provider = auth_provider
@timeout = timeout
@max_retries = max_retries
@retry_delay = retry_delay
@enable_logging = enable_logging
end
def get(path, params = {})
request("GET", path, nil, params)
end
def post(path, body = nil)
request("POST", path, body, nil)
end
def put(path, body = nil)
request("PUT", path, body, nil)
end
def delete(path)
request("DELETE", path, nil, nil)
end
private
def request(method, path, body, params)
url = "#{@base_url}#{path}"
headers = @auth_provider.get_headers
options = {
timeout: @timeout,
headers: headers
}
options[:query] = params if params
options[:body] = body.to_json if body
last_error = nil
(0..@max_retries).each do |attempt|
begin
response = HTTParty.send(method.downcase, url, options)
handle_response_errors(response)
return response.parsed_response
rescue StandardError => e
last_error = e
if attempt < @max_retries
sleep(@retry_delay * (2 ** attempt))
end
end
end
raise last_error || NetworkError, "Request failed after #{@max_retries} retries"
end
def handle_response_errors(response)
case response.code
when 401
raise AuthenticationError, "Authentication failed"
when 429
raise RateLimitError, "Rate limit exceeded"
when 400..499
raise APIError, "API error: #{response.parsed_response}"
when 500..599
raise ServerError, "Server error: #{response.code}"
end
end
def close
# HTTParty doesn't need explicit cleanup
end
end
end
+23
View File
@@ -0,0 +1,23 @@
module TelecomSDK
# API for payment management
class PaymentAPI
def initialize(client)
@client = client
end
def create_transaction(request)
@client.post("/v1/payments/transactions", request)
end
def get_transaction(transaction_id)
@client.get("/v1/payments/transactions/#{transaction_id}")
end
def list_transactions(subscriber_id: nil, status: nil, page: 1, page_size: 50)
params = { page: page, page_size: page_size }
params[:subscriber_id] = subscriber_id if subscriber_id
params[:status] = status if status
@client.get("/v1/payments/transactions", params)
end
end
end
@@ -0,0 +1,16 @@
module TelecomSDK
# API for rating plan management
class RatingPlanAPI
def initialize(client)
@client = client
end
def list
@client.get("/v1/rating-plans")
end
def get(plan_id)
@client.get("/v1/rating-plans/#{plan_id}")
end
end
end
@@ -0,0 +1,38 @@
module TelecomSDK
# API for subscriber management
class SubscriberAPI
def initialize(client)
@client = client
end
def get(id)
@client.get("/v1/subscribers/#{id}")
end
def list(page: 1, page_size: 50, status: nil)
params = { page: page, page_size: page_size }
params[:status] = status if status
@client.get("/v1/subscribers", params)
end
def create(request)
@client.post("/v1/subscribers", request)
end
def update(id, request)
@client.put("/v1/subscribers/#{id}", request)
end
def delete(id)
@client.delete("/v1/subscribers/#{id}")
end
def suspend(id)
@client.post("/v1/subscribers/#{id}/suspend")
end
def activate(id)
@client.post("/v1/subscribers/#{id}/activate")
end
end
end
+16
View File
@@ -0,0 +1,16 @@
module TelecomSDK
# API for system management
class SystemAPI
def initialize(client)
@client = client
end
def get_stats
@client.get("/v1/system/stats")
end
def get_health
@client.get("/v1/health")
end
end
end
+29
View File
@@ -0,0 +1,29 @@
module TelecomSDK
# API for usage management
class UsageAPI
def initialize(client)
@client = client
end
def get_stats(subscriber_id, start_date, end_date)
params = {
start_date: start_date.iso8601,
end_date: end_date.iso8601
}
@client.get("/v1/subscribers/#{subscriber_id}/usage", params)
end
def list_events(subscriber_id: nil, usage_type: nil, start_date: nil, end_date: nil, page: 1, page_size: 50)
params = { page: page, page_size: page_size }
params[:subscriber_id] = subscriber_id if subscriber_id
params[:usage_type] = usage_type if usage_type
params[:start_date] = start_date.iso8601 if start_date
params[:end_date] = end_date.iso8601 if end_date
@client.get("/v1/usage/events", params)
end
def get_realtime(subscriber_id)
@client.get("/v1/subscribers/#{subscriber_id}/realtime")
end
end
end