warden

package
v1.4.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

README

Warden SDK

📖 Multi-language Documentation: For documentation in other languages, please refer to docs directory

Warden SDK is a Go client library for interacting with the Warden API. It provides simple and easy-to-use interfaces for fetching user lists, querying individual user information, checking if users are in the allow list, and supports caching for improved performance.

Features

  • 🚀 Simple and Easy: Provides clean API interfaces
  • ⚡ High Performance: Built-in cache support (GetUsers), direct queries (GetUserByIdentifier) reduce API calls
  • 🔒 Secure: Supports API Key authentication, error handling doesn't leak sensitive information
  • 📦 Flexible: Configurable timeout, cache TTL, etc.
  • 🔌 Extensible: Supports custom logger implementations
  • 🎯 Smart Fallback: CheckUserInList supports automatic fallback to mail when phone is not found

Installation

go get github.com/soulteary/warden/pkg/warden

Quick Start

Basic Usage
package main

import (
    "context"
    "fmt"
    "time"
    
    "github.com/soulteary/warden/pkg/warden"
)

func main() {
    // Create client options
    opts := warden.DefaultOptions().
        WithBaseURL("http://localhost:8081").
        WithAPIKey("your-api-key").
        WithTimeout(10 * time.Second).
        WithCacheTTL(5 * time.Minute)
    
    // Create client
    client, err := warden.NewClient(opts)
    if err != nil {
        panic(err)
    }
    
    // Get user list
    ctx := context.Background()
    users, err := client.GetUsers(ctx)
    if err != nil {
        panic(err)
    }
    
    // Check if user is in the list (can provide phone, mail, or both)
    exists := client.CheckUserInList(ctx, "13800138000", "user@example.com")
    if exists {
        println("User is in the allow list and active")
    }
    
    // Can also use only phone or mail
    existsByPhone := client.CheckUserInList(ctx, "13800138000", "")
    existsByMail := client.CheckUserInList(ctx, "", "user@example.com")
    
    // Get user details
    user, err := client.GetUserByIdentifier(ctx, "13800138000", "", "")
    if err != nil {
        panic(err)
    }
    fmt.Printf("User: %s, Status: %s\n", user.UserID, user.Status)
}
Using Custom Logger

The SDK supports custom logger implementations. For example, using logrus:

import (
    "github.com/sirupsen/logrus"
    "github.com/soulteary/warden/pkg/warden"
)

func main() {
    logger := logrus.StandardLogger()
    
    opts := warden.DefaultOptions().
        WithBaseURL("http://localhost:8081").
        WithLogger(warden.NewLogrusAdapter(logger))
    
    client, err := warden.NewClient(opts)
    // ...
}
Paginated Query
// Get paginated user list
resp, err := client.GetUsersPaginated(ctx, 1, 10) // Page 1, 10 items per page
if err != nil {
    panic(err)
}

fmt.Printf("Total users: %d\n", resp.Pagination.Total)
fmt.Printf("Total pages: %d\n", resp.Pagination.TotalPages)
for _, user := range resp.Data {
    fmt.Printf("UserID: %s, Phone: %s, Mail: %s, Status: %s\n", 
        user.UserID, user.Phone, user.Mail, user.Status)
}
Get Single User Information
// Get user information by phone
user, err := client.GetUserByIdentifier(ctx, "13800138000", "", "")
if err != nil {
    if sdkErr, ok := err.(*warden.Error); ok && sdkErr.Code == warden.ErrCodeNotFound {
        println("User not found")
    } else {
        panic(err)
    }
} else {
    fmt.Printf("UserID: %s, Phone: %s, Mail: %s, Status: %s\n", 
        user.UserID, user.Phone, user.Mail, user.Status)
    if user.IsActive() {
        println("User is active")
    }
}

// Get user information by email
user, err = client.GetUserByIdentifier(ctx, "", "user@example.com", "")

// Get user information by user ID
user, err = client.GetUserByIdentifier(ctx, "", "", "user123")
Clear Cache
// Clear client cache manually
client.ClearCache()

// Or use the alias
client.InvalidateCache()
Custom HTTP Transport
import "net/http"

// Create custom transport
customTransport := &http.Transport{
    MaxIdleConns: 100,
    IdleConnTimeout: 90 * time.Second,
}

opts := warden.DefaultOptions().
    WithBaseURL("http://localhost:8081").
    WithTransport(customTransport)

client, err := warden.NewClient(opts)
Retry Configuration
// Configure retry options
retryOpts := warden.DefaultRetryOptions()
retryOpts.MaxRetries = 3
retryOpts.RetryDelay = 100 * time.Millisecond
retryOpts.MaxRetryDelay = 5 * time.Second
retryOpts.BackoffMultiplier = 2.0

opts := warden.DefaultOptions().
    WithBaseURL("http://localhost:8081").
    WithRetry(retryOpts)

client, err := warden.NewClient(opts)
Event-Driven Cache Invalidation
// Create channel for cache invalidation events
invalidationCh := make(chan struct{}, 1)

opts := warden.DefaultOptions().
    WithBaseURL("http://localhost:8081").
    WithCacheInvalidationChannel(invalidationCh)

client, err := warden.NewClient(opts)
if err != nil {
    panic(err)
}
defer client.Close() // Important: close to stop background listener

// Later, trigger cache invalidation from external event
invalidationCh <- struct{}{}

// Cache will be automatically cleared when signal is received

API Reference

Options

The Options struct is used to configure the client:

  • BaseURL: Warden service address (required)
  • APIKey: API Key (optional)
  • Timeout: HTTP request timeout (default 10 seconds)
  • CacheTTL: Cache TTL (default 5 minutes)
  • Logger: Logger interface (optional, defaults to NoOpLogger)
  • Transport: Custom HTTP transport (optional)
  • Retry: Retry configuration (optional, defaults to no retry)
  • CacheInvalidationChannel: Channel for event-driven cache invalidation (optional)
Client Methods
NewClient(opts *Options) (*Client, error)

Creates a new Warden client.

GetUsers(ctx context.Context) ([]AllowListUser, error)

Gets all user list. If cache is valid, returns cached data directly.

GetUsersPaginated(ctx context.Context, page, pageSize int) (*PaginatedResponse, error)

Gets paginated user list.

  • page: Page number (starts from 1)
  • pageSize: Page size

Returns PaginatedResponse, containing:

  • Data: User list
  • Pagination: Pagination information (page number, page size, total, total pages)

Note: This method does not use cache, each call fetches the latest data from the API.

GetUserByIdentifier(ctx context.Context, phone, mail, userID string) (*AllowListUser, error)

Gets a single user information by identifier.

  • phone: User phone number (optional, but must provide one of phone, mail, or userID)
  • mail: User email (optional)
  • userID: User unique identifier (optional)

Important: Must provide exactly one identifier among phone, mail, or userID.

Returns *AllowListUser and error. If user does not exist, returns ErrCodeNotFound error.

Note: This method does not use cache, each call fetches the latest data from the API.

CheckUserInList(ctx context.Context, phone, mail string) bool

Checks if a user is in the allow list.

  • phone: User phone number (optional)
  • mail: User email (optional)

Returns true if the user exists (matched by phone or email), false otherwise.

Behavior:

  • If both phone and mail are provided, phone takes priority
  • If phone lookup fails (returns NotFound error) and mail is not empty, automatically falls back to mail lookup
  • If phone lookup succeeds but user status is not active, does not fall back to mail (user already found)
  • If phone lookup fails and error is not NotFound (e.g., network error), does not fall back to mail
  • Input is automatically normalized: phone is trimmed, mail is trimmed and converted to lowercase
  • This method uses GetUserByIdentifier for lookup, more efficient than iterating through user list
  • Only users with status "active" will return true
ClearCache()

Clears the internal client cache.

InvalidateCache()

Alias for ClearCache() for consistency with event-driven invalidation.

Close()

Stops background goroutines (e.g., cache invalidation listener) and releases resources. Should be called when the client is no longer needed.

Type Definitions

AllowListUser
type AllowListUser struct {
    Phone  string   `json:"phone"`   // User phone number
    Mail   string   `json:"mail"`    // User email address
    UserID string   `json:"user_id"` // User unique identifier (optional, auto-generated if not provided)
    Status string   `json:"status"`  // User status (e.g., "active", "inactive", "suspended")
    Scope  []string `json:"scope"`   // User permission scope (optional)
    Role   string   `json:"role"`    // User role (optional)
}

Methods:

  • IsActive() bool: Checks if user status is "active"
  • IsValid() bool: Checks if user status is valid (currently only supports "active")
PaginatedResponse
type PaginatedResponse struct {
    Data       []AllowListUser `json:"data"`
    Pagination PaginationInfo  `json:"pagination"`
}

type PaginationInfo struct {
    Page       int `json:"page"`        // Current page number (starts from 1)
    PageSize   int `json:"page_size"`   // Page size
    Total      int `json:"total"`       // Total number of records
    TotalPages int `json:"total_pages"` // Total number of pages
}

Error Handling

The SDK uses custom error types with error codes and detailed information:

if err != nil {
    if sdkErr, ok := err.(*warden.Error); ok {
        switch sdkErr.Code {
        case warden.ErrCodeUnauthorized:
            // Handle authentication error
        case warden.ErrCodeRequestFailed:
            // Handle request failure
        // ...
        }
    }
}
Error Codes
  • ErrCodeInvalidConfig: Invalid configuration
  • ErrCodeRequestFailed: Request failed
  • ErrCodeInvalidResponse: Invalid response format
  • ErrCodeUnauthorized: Unauthorized
  • ErrCodeNotFound: Not found
  • ErrCodeServerError: Server error

RetryOptions

The RetryOptions struct configures retry behavior:

  • MaxRetries: Maximum number of retries (default 0, no retry)
  • RetryDelay: Initial delay between retries (default 100ms)
  • MaxRetryDelay: Maximum delay between retries (default 5s)
  • BackoffMultiplier: Multiplier for exponential backoff (default 2.0)
  • RetryableStatusCodes: HTTP status codes that trigger retry (default: 5xx)

Note: Network errors are always retryable. Client errors (4xx) are never retried.

Best Practices

  1. Reuse Client: Create the client once and reuse it throughout the application lifecycle
  2. Set Cache TTL Appropriately: Set appropriate cache time based on data update frequency
  3. Use Context: Pass context to support cancellation and timeout control
  4. Error Handling: Always check and handle errors
  5. Logging: Use appropriate logger implementation in production environments
  6. Close Client: Call Close() when the client is no longer needed to stop background goroutines
  7. Configure Retry: Enable retry for production environments to handle transient failures
  8. Custom Transport: Use custom transport for advanced scenarios (TLS, proxy, connection pooling, etc.)

Examples

For complete examples, please refer to the example directory.

License

MIT License

Documentation

Overview

Package warden provides a client SDK for interacting with Warden API.

Index

Constants

View Source
const (
	ErrCodeInvalidConfig   = "INVALID_CONFIG"
	ErrCodeRequestFailed   = "REQUEST_FAILED"
	ErrCodeInvalidResponse = "INVALID_RESPONSE"
	ErrCodeUnauthorized    = "UNAUTHORIZED"
	ErrCodeNotFound        = "NOT_FOUND"
	ErrCodeServerError     = "SERVER_ERROR"
)

Predefined error codes

View Source
const DefaultMaxResponseBytes int64 = 8 << 20

DefaultMaxResponseBytes is the default cap on response body size (8 MiB).

Variables

View Source
var ErrResponseTooLarge = errors.New("warden: response exceeds size limit")

ErrResponseTooLarge is returned when a response exceeds MaxResponseBytes.

Functions

This section is empty.

Types

type AllowListUser

type AllowListUser struct {
	Phone          string   `json:"phone"`                     // User phone number
	Mail           string   `json:"mail"`                      // User email address
	UserID         string   `json:"user_id"`                   // User unique identifier (optional, auto-generated if not provided)
	Status         string   `json:"status"`                    // User status (e.g., "active", "inactive", "suspended")
	Scope          []string `json:"scope"`                     // User permission scope (optional)
	Role           string   `json:"role"`                      // User role (optional)
	Name           string   `json:"name,omitempty"`            // User display name (optional)
	DingtalkUserID string   `json:"dingtalk_userid,omitempty"` // DingTalk user ID for work notification (optional)
}

AllowListUser represents a user in the allow list.

func (*AllowListUser) IsActive added in v0.3.0

func (u *AllowListUser) IsActive() bool

IsActive checks if the user status is active.

Returns true if the user status is "active", false otherwise. This method is used to verify if a user is allowed to access the system.

func (*AllowListUser) IsValid added in v0.3.0

func (u *AllowListUser) IsValid() bool

IsValid checks if the user has a valid status for authentication.

Returns true if the user status is one of the valid statuses (currently only "active"). This method can be extended in the future to support other valid statuses if needed.

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache provides thread-safe caching for user list.

func NewCache

func NewCache(ttl time.Duration) *Cache

NewCache creates a new cache instance with the specified TTL.

func (*Cache) Clear

func (c *Cache) Clear()

Clear clears the cache.

func (*Cache) Get

func (c *Cache) Get() []AllowListUser

Get returns the cached user list if it's still valid, nil otherwise.

func (*Cache) Set

func (c *Cache) Set(users []AllowListUser)

Set stores the user list in cache with expiration.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the Warden API client.

func NewClient

func NewClient(opts *Options) (*Client, error)

NewClient creates a new Warden API client with the provided options.

func (*Client) CheckUserInList

func (c *Client) CheckUserInList(ctx context.Context, phone, mail string) bool

CheckUserInList checks if a user (by phone or mail) is in the allow list and has active status. Returns false if the user is not found, has inactive/suspended status, or if there's an error. This method uses GetUserByIdentifier for better performance and includes status validation. If both phone and mail are provided, phone takes priority. If phone lookup fails with NotFound error, it will fall back to mail lookup.

func (*Client) ClearCache

func (c *Client) ClearCache()

ClearCache clears the internal cache.

func (*Client) Close added in v0.4.0

func (c *Client) Close()

Close stops the cache invalidation listener and releases resources. This should be called when the client is no longer needed.

func (*Client) GetUserByIdentifier

func (c *Client) GetUserByIdentifier(ctx context.Context, phone, mail, userID string) (*AllowListUser, error)

GetUserByIdentifier fetches a single user by phone, mail, or user_id. Only one identifier should be provided.

func (*Client) GetUsers

func (c *Client) GetUsers(ctx context.Context) ([]AllowListUser, error)

GetUsers fetches the user list from Warden API. If pagination parameters are not provided, returns all users.

func (*Client) GetUsersPaginated

func (c *Client) GetUsersPaginated(ctx context.Context, page, pageSize int) (*PaginatedResponse, error)

GetUsersPaginated fetches a paginated user list from Warden API.

func (*Client) InvalidateCache added in v0.4.0

func (c *Client) InvalidateCache()

InvalidateCache is an alias for ClearCache for consistency with event-driven invalidation.

type Clock added in v0.14.0

type Clock interface {
	Now() time.Time
}

Clock abstracts time for deterministic testing of signature timestamps.

type Error

type Error struct {
	Code    string // Error code
	Message string // Error message
	Err     error  // Original error (if any)
}

Error represents an error that occurred in the SDK.

func NewError

func NewError(code, message string, err error) *Error

NewError creates a new SDK error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Logger

type Logger interface {
	Debug(msg string)
	Debugf(format string, args ...interface{})
	Info(msg string)
	Infof(format string, args ...interface{})
	Warn(msg string)
	Warnf(format string, args ...interface{})
	Error(msg string)
	Errorf(format string, args ...interface{})
}

Logger defines the interface for logging operations. This allows the SDK to work with different logging libraries (e.g., logger-kit, zerolog, standard log). Use NewLoggerKitAdapter for logger-kit.

type LoggerKitAdapter added in v0.9.0

type LoggerKitAdapter struct {
	// contains filtered or unexported fields
}

LoggerKitAdapter adapts logger-kit Logger to the SDK Logger interface.

func NewLoggerKitAdapter added in v0.9.0

func NewLoggerKitAdapter(l *loggerkit.Logger) *LoggerKitAdapter

NewLoggerKitAdapter creates a new LoggerKitAdapter.

func (*LoggerKitAdapter) Debug added in v0.9.0

func (l *LoggerKitAdapter) Debug(msg string)

Debug logs a debug message using logger-kit.

func (*LoggerKitAdapter) Debugf added in v0.9.0

func (l *LoggerKitAdapter) Debugf(format string, args ...interface{})

Debugf logs a formatted debug message using logger-kit.

func (*LoggerKitAdapter) Error added in v0.9.0

func (l *LoggerKitAdapter) Error(msg string)

Error logs an error message using logger-kit.

func (*LoggerKitAdapter) Errorf added in v0.9.0

func (l *LoggerKitAdapter) Errorf(format string, args ...interface{})

Errorf logs a formatted error message using logger-kit.

func (*LoggerKitAdapter) Info added in v0.9.0

func (l *LoggerKitAdapter) Info(msg string)

Info logs an info message using logger-kit.

func (*LoggerKitAdapter) Infof added in v0.9.0

func (l *LoggerKitAdapter) Infof(format string, args ...interface{})

Infof logs a formatted info message using logger-kit.

func (*LoggerKitAdapter) Warn added in v0.9.0

func (l *LoggerKitAdapter) Warn(msg string)

Warn logs a warning message using logger-kit.

func (*LoggerKitAdapter) Warnf added in v0.9.0

func (l *LoggerKitAdapter) Warnf(format string, args ...interface{})

Warnf logs a formatted warning message using logger-kit.

type NoOpLogger

type NoOpLogger struct{}

NoOpLogger is a no-op implementation of Logger that discards all log messages. This is used as the default logger when no logger is provided.

func (*NoOpLogger) Debug

func (n *NoOpLogger) Debug(msg string)

Debug discards debug messages.

func (*NoOpLogger) Debugf

func (n *NoOpLogger) Debugf(format string, args ...interface{})

Debugf discards formatted debug messages.

func (*NoOpLogger) Error

func (n *NoOpLogger) Error(msg string)

Error discards error messages.

func (*NoOpLogger) Errorf

func (n *NoOpLogger) Errorf(format string, args ...interface{})

Errorf discards formatted error messages.

func (*NoOpLogger) Info

func (n *NoOpLogger) Info(msg string)

Info discards info messages.

func (*NoOpLogger) Infof

func (n *NoOpLogger) Infof(format string, args ...interface{})

Infof discards formatted info messages.

func (*NoOpLogger) Warn

func (n *NoOpLogger) Warn(msg string)

Warn discards warning messages.

func (*NoOpLogger) Warnf

func (n *NoOpLogger) Warnf(format string, args ...interface{})

Warnf discards formatted warning messages.

type Options

type Options struct {
	BaseURL                  string          // Warden service address (required)
	APIKey                   string          // API Key (optional)
	Timeout                  time.Duration   // HTTP request timeout (default 10s)
	CacheTTL                 time.Duration   // Cache TTL (default 5 minutes)
	Logger                   Logger          // Logger interface (optional, defaults to NoOpLogger)
	Transport                *http.Transport // Custom HTTP transport (optional)
	Retry                    *RetryOptions   // Retry configuration (optional)
	CacheInvalidationChannel <-chan struct{} // Channel for event-driven cache invalidation (optional)

	// HMACKeyID and HMACSecret enable request signing (HMAC v2). When both are set,
	// every request is signed. The secret is never logged.
	HMACKeyID  string
	HMACSecret string
	// Clock overrides the time source used for signature timestamps (testing).
	Clock Clock
	// TLSConfig, when set, is applied to the HTTP transport (e.g. client certs, root
	// CAs). It takes precedence over Transport's own TLSClientConfig.
	TLSConfig *tls.Config
	// MaxResponseBytes bounds the response body read to defend against unbounded
	// payloads. Zero means use DefaultMaxResponseBytes; a negative value disables it.
	MaxResponseBytes int64
}

Options contains configuration options for the Warden SDK client.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns default options with sensible defaults.

func (*Options) Validate

func (o *Options) Validate() error

Validate validates the options and returns an error if invalid.

func (*Options) WithAPIKey

func (o *Options) WithAPIKey(key string) *Options

WithAPIKey sets the API key for authentication.

func (*Options) WithBaseURL

func (o *Options) WithBaseURL(url string) *Options

WithBaseURL sets the base URL for the Warden service.

func (*Options) WithCacheInvalidationChannel added in v0.4.0

func (o *Options) WithCacheInvalidationChannel(ch <-chan struct{}) *Options

WithCacheInvalidationChannel sets a channel for event-driven cache invalidation. When a signal is received on this channel, the cache will be automatically cleared.

func (*Options) WithCacheTTL

func (o *Options) WithCacheTTL(ttl time.Duration) *Options

WithCacheTTL sets the cache TTL.

func (*Options) WithClock added in v0.14.0

func (o *Options) WithClock(clock Clock) *Options

WithClock overrides the time source used for signature timestamps. Primarily useful for deterministic tests.

func (*Options) WithHMAC added in v0.14.0

func (o *Options) WithHMAC(keyID, secret string) *Options

WithHMAC enables HMAC v2 request signing with the given key id and secret. The secret is never logged. Passing two empty values disables signing; a partial key-id/secret pair is rejected by Validate.

func (*Options) WithLogger

func (o *Options) WithLogger(logger Logger) *Options

WithLogger sets the logger implementation.

func (*Options) WithMaxResponseBytes added in v0.14.0

func (o *Options) WithMaxResponseBytes(n int64) *Options

WithMaxResponseBytes bounds how many bytes of a response body will be read. Zero uses DefaultMaxResponseBytes; a negative value disables the limit.

func (*Options) WithRetry added in v0.4.0

func (o *Options) WithRetry(retry *RetryOptions) *Options

WithRetry sets the retry configuration.

func (*Options) WithTLSClientCert added in v0.14.0

func (o *Options) WithTLSClientCert(cert tls.Certificate) *Options

WithTLSClientCert configures mutual TLS by presenting the given client certificate. It preserves any existing TLSConfig fields.

func (*Options) WithTLSConfig added in v0.14.0

func (o *Options) WithTLSConfig(cfg *tls.Config) *Options

WithTLSConfig sets a custom *tls.Config (e.g. client certificates, root CAs) that will be applied to the HTTP transport.

func (*Options) WithTimeout

func (o *Options) WithTimeout(timeout time.Duration) *Options

WithTimeout sets the HTTP request timeout.

func (*Options) WithTransport added in v0.4.0

func (o *Options) WithTransport(transport *http.Transport) *Options

WithTransport sets a custom HTTP transport.

type PaginatedResponse

type PaginatedResponse struct {
	Data       []AllowListUser `json:"data"`
	Pagination PaginationInfo  `json:"pagination"`
}

PaginatedResponse represents a paginated response from the Warden API.

type PaginationInfo

type PaginationInfo struct {
	Page       int `json:"page"`        // Current page number (starts from 1)
	PageSize   int `json:"page_size"`   // Page size
	Total      int `json:"total"`       // Total number of records
	TotalPages int `json:"total_pages"` // Total number of pages
}

PaginationInfo contains pagination metadata.

type RetryOptions added in v0.4.0

type RetryOptions struct {
	RetryableStatusCodes []int         // HTTP status codes that should trigger retry (default: 5xx)
	MaxRetries           int           // Maximum number of retries (default 0, no retry)
	RetryDelay           time.Duration // Initial delay between retries (default 100ms)
	MaxRetryDelay        time.Duration // Maximum delay between retries (default 5s)
	BackoffMultiplier    float64       // Multiplier for exponential backoff (default 2.0)
}

RetryOptions contains configuration for request retry behavior.

func DefaultRetryOptions added in v0.4.0

func DefaultRetryOptions() *RetryOptions

DefaultRetryOptions returns default retry options with sensible defaults.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL