feat(sub2api): add host adapter client and tests
This commit is contained in:
295
internal/host/sub2api/client.go
Normal file
295
internal/host/sub2api/client.go
Normal file
@@ -0,0 +1,295 @@
|
||||
package sub2api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type HostAdapter interface {
|
||||
GetHostVersion(ctx context.Context) (string, error)
|
||||
ProbeCapabilities(ctx context.Context) (HostCapabilities, error)
|
||||
CreateGroup(ctx context.Context, req CreateGroupRequest) (GroupRef, error)
|
||||
CreateChannel(ctx context.Context, req CreateChannelRequest) (ChannelRef, error)
|
||||
CreatePlan(ctx context.Context, req CreatePlanRequest) (PlanRef, error)
|
||||
CreateAccount(ctx context.Context, req CreateAccountRequest) (AccountRef, error)
|
||||
BatchCreateAccounts(ctx context.Context, req BatchCreateAccountsRequest) ([]AccountRef, error)
|
||||
TestAccount(ctx context.Context, accountID string) (ProbeResult, error)
|
||||
GetAccountModels(ctx context.Context, accountID string) ([]AccountModel, error)
|
||||
AssignSubscription(ctx context.Context, req AssignSubscriptionRequest) (SubscriptionRef, error)
|
||||
}
|
||||
|
||||
type HostCapabilities struct {
|
||||
Groups bool `json:"groups"`
|
||||
Channels bool `json:"channels"`
|
||||
Plans bool `json:"plans"`
|
||||
Accounts bool `json:"accounts"`
|
||||
AccountTest bool `json:"account_test"`
|
||||
AccountModels bool `json:"account_models"`
|
||||
Subscriptions bool `json:"subscriptions"`
|
||||
}
|
||||
|
||||
type CreateGroupRequest struct {
|
||||
Name string `json:"name"`
|
||||
RateMultiplier float64 `json:"rate_multiplier"`
|
||||
}
|
||||
|
||||
type GroupRef struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type CreateChannelRequest struct {
|
||||
Name string `json:"name"`
|
||||
GroupIDs []string `json:"group_ids"`
|
||||
}
|
||||
|
||||
type ChannelRef struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type CreatePlanRequest struct {
|
||||
GroupID string `json:"group_id"`
|
||||
Name string `json:"name"`
|
||||
Price float64 `json:"price"`
|
||||
ValidityDays int `json:"validity_days"`
|
||||
ValidityUnit string `json:"validity_unit"`
|
||||
}
|
||||
|
||||
type PlanRef struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type CreateAccountRequest struct {
|
||||
Name string `json:"name"`
|
||||
Platform string `json:"platform"`
|
||||
Type string `json:"type"`
|
||||
Credentials map[string]any `json:"credentials"`
|
||||
GroupIDs []string `json:"group_ids"`
|
||||
}
|
||||
|
||||
type BatchCreateAccountsRequest struct {
|
||||
Accounts []CreateAccountRequest `json:"accounts"`
|
||||
}
|
||||
|
||||
type AccountRef struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Platform string `json:"platform,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
}
|
||||
|
||||
type ProbeResult struct {
|
||||
OK bool `json:"ok"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
type AccountModel struct {
|
||||
ID string `json:"id"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type AssignSubscriptionRequest struct {
|
||||
UserID string `json:"user_id"`
|
||||
GroupID string `json:"group_id"`
|
||||
DurationDays int `json:"duration_days,omitempty"`
|
||||
}
|
||||
|
||||
type SubscriptionRef struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
baseURL *url.URL
|
||||
httpClient *http.Client
|
||||
apiKey string
|
||||
bearerToken string
|
||||
}
|
||||
|
||||
type Option func(*Client)
|
||||
|
||||
func WithHTTPClient(httpClient *http.Client) Option {
|
||||
return func(client *Client) {
|
||||
client.httpClient = httpClient
|
||||
}
|
||||
}
|
||||
|
||||
func WithAPIKey(apiKey string) Option {
|
||||
return func(client *Client) {
|
||||
client.apiKey = strings.TrimSpace(apiKey)
|
||||
}
|
||||
}
|
||||
|
||||
func WithBearerToken(token string) Option {
|
||||
return func(client *Client) {
|
||||
client.bearerToken = strings.TrimSpace(token)
|
||||
}
|
||||
}
|
||||
|
||||
func NewClient(baseURL string, opts ...Option) (*Client, error) {
|
||||
parsedURL, err := url.Parse(strings.TrimSpace(baseURL))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse base url: %w", err)
|
||||
}
|
||||
|
||||
if parsedURL.Scheme == "" || parsedURL.Host == "" {
|
||||
return nil, fmt.Errorf("base url must include scheme and host")
|
||||
}
|
||||
|
||||
client := &Client{
|
||||
baseURL: parsedURL,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 15 * time.Second,
|
||||
},
|
||||
}
|
||||
for _, opt := range opts {
|
||||
if opt != nil {
|
||||
opt(client)
|
||||
}
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
type HTTPError struct {
|
||||
Method string
|
||||
Path string
|
||||
StatusCode int
|
||||
Body string
|
||||
}
|
||||
|
||||
func (e *HTTPError) Error() string {
|
||||
return fmt.Sprintf("sub2api %s %s returned %d: %s", e.Method, e.Path, e.StatusCode, strings.TrimSpace(e.Body))
|
||||
}
|
||||
|
||||
func (c *Client) GetHostVersion(ctx context.Context) (string, error) {
|
||||
statusCode, _, body, err := c.perform(ctx, http.MethodGet, "/api/v1/admin/system/version", nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if statusCode < http.StatusOK || statusCode >= http.StatusMultipleChoices {
|
||||
return "", newHTTPError(http.MethodGet, "/api/v1/admin/system/version", statusCode, body)
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if err := decodeEnvelopeObject(body, &payload); err != nil {
|
||||
return "", fmt.Errorf("decode host version: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(payload.Version) == "" {
|
||||
return "", fmt.Errorf("decode host version: missing data.version")
|
||||
}
|
||||
|
||||
return payload.Version, nil
|
||||
}
|
||||
|
||||
func (c *Client) perform(ctx context.Context, method, path string, requestBody any) (int, http.Header, []byte, error) {
|
||||
var bodyReader io.Reader
|
||||
if requestBody != nil {
|
||||
payload, err := json.Marshal(requestBody)
|
||||
if err != nil {
|
||||
return 0, nil, nil, fmt.Errorf("marshal %s %s request: %w", method, path, err)
|
||||
}
|
||||
bodyReader = bytes.NewReader(payload)
|
||||
}
|
||||
|
||||
requestURL := c.resolvePath(path)
|
||||
req, err := http.NewRequestWithContext(ctx, method, requestURL, bodyReader)
|
||||
if err != nil {
|
||||
return 0, nil, nil, fmt.Errorf("build %s %s request: %w", method, path, err)
|
||||
}
|
||||
if requestBody != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("Accept", "application/json, text/event-stream")
|
||||
c.applyAuth(req)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, nil, fmt.Errorf("perform %s %s request: %w", method, path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return 0, nil, nil, fmt.Errorf("read %s %s response: %w", method, path, err)
|
||||
}
|
||||
|
||||
return resp.StatusCode, resp.Header.Clone(), body, nil
|
||||
}
|
||||
|
||||
func (c *Client) postJSON(ctx context.Context, path string, requestBody any, dest any) error {
|
||||
statusCode, _, body, err := c.perform(ctx, http.MethodPost, path, requestBody)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if statusCode < http.StatusOK || statusCode >= http.StatusMultipleChoices {
|
||||
return newHTTPError(http.MethodPost, path, statusCode, body)
|
||||
}
|
||||
if dest == nil {
|
||||
return nil
|
||||
}
|
||||
if err := decodeEnvelopeObject(body, dest); err != nil {
|
||||
return fmt.Errorf("decode %s response: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) getJSON(ctx context.Context, path string, dest any) error {
|
||||
statusCode, _, body, err := c.perform(ctx, http.MethodGet, path, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if statusCode < http.StatusOK || statusCode >= http.StatusMultipleChoices {
|
||||
return newHTTPError(http.MethodGet, path, statusCode, body)
|
||||
}
|
||||
if err := decodeEnvelopeObject(body, dest); err != nil {
|
||||
return fmt.Errorf("decode %s response: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) resolvePath(path string) string {
|
||||
base := strings.TrimRight(c.baseURL.String(), "/")
|
||||
return base + "/" + strings.TrimLeft(path, "/")
|
||||
}
|
||||
|
||||
func (c *Client) applyAuth(req *http.Request) {
|
||||
if c.apiKey != "" {
|
||||
req.Header.Set("x-api-key", c.apiKey)
|
||||
return
|
||||
}
|
||||
if c.bearerToken != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.bearerToken)
|
||||
}
|
||||
}
|
||||
|
||||
func newHTTPError(method, path string, statusCode int, body []byte) *HTTPError {
|
||||
return &HTTPError{
|
||||
Method: method,
|
||||
Path: path,
|
||||
StatusCode: statusCode,
|
||||
Body: string(body),
|
||||
}
|
||||
}
|
||||
|
||||
func decodeEnvelopeObject(body []byte, dest any) error {
|
||||
var envelope struct {
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &envelope); err == nil && len(bytes.TrimSpace(envelope.Data)) > 0 && string(bytes.TrimSpace(envelope.Data)) != "null" {
|
||||
return json.Unmarshal(envelope.Data, dest)
|
||||
}
|
||||
return json.Unmarshal(body, dest)
|
||||
}
|
||||
Reference in New Issue
Block a user