Compare commits

..
13 Commits
Author SHA1 Message Date
XingfenD 998a47193d Merge branch 'feat/verbose-debug' into master 2026-07-30 01:04:48 +08:00
XingfenD 38d5b3f338 fix: unwrap nested Data field in server Get response 2026-07-29 00:54:28 +08:00
XingfenD 317dc9c4e5 fix: correct rainyunServer JSON field names to match actual API (PascalCase) 2026-07-29 00:39:28 +08:00
XingfenD e6e9ad01e1 refactor: remove --debug flag, keep --verbose/-v only 2026-07-29 00:04:16 +08:00
XingfenD 468262305e feat: wire --verbose/--debug flags with runtime info 2026-07-28 23:59:05 +08:00
XingfenD 9faf881efa feat: HTTP debug logging in client.do() 2026-07-28 23:57:24 +08:00
XingfenD b7085af9d3 feat: add Debug field to ProviderConfig 2026-07-28 23:55:50 +08:00
XingfenD 86ced3e4bb docs: verbose/debug implementation plan 2026-07-28 23:53:44 +08:00
XingfenD 72bbb4c8a0 docs: verbose/debug mode design spec 2026-07-28 23:52:23 +08:00
NightStar 93cea77bba Merge branch 'refactor/extract-model-package' 2026-07-28 19:34:24 +08:00
NightStar bbba314127 refactor: extract domain models from provider into internal/model
- Move Server/Domain/DNSRecord/Bucket/StorageInstance/CDNInstance/Order/Error structs to internal/model/
- Provider interfaces now reference model.* types
- Rainyun provider implementations import model package for data types
- CLI commands updated to use model.DNSRecord directly

Separates pure data structures from service contract interfaces,
following hexagonal architecture: models (entities) live independently
from ports (provider interfaces) and adapters (rainyun/* implementations).
2026-07-28 19:31:22 +08:00
NightStar ccc9f27130 Merge branch 'docs/clean-agents-webui' 2026-07-28 19:16:00 +08:00
NightStar 2c13f4c5d9 docs: remove webui-related rules from AGENTS.md
The cross-domain guard and release branch naming patterns referenced
cmd/webui/ which doesn't exist in this repo — they were copied from
another project template.
2026-07-28 19:14:52 +08:00
20 changed files with 574 additions and 146 deletions
+1 -2
View File
@@ -3,6 +3,5 @@
## Safety Rules
- **Branch safety**: If the current branch is NOT a dev branch (name does NOT contain `feat`, `refactor`, `docs`, `fix`), do NOT commit directly — warn the user first.
- **Commit SOP**: Before every `git commit`, run `git branch --show-current`. If the branch is not a dev branch, ask the user for a branch name, create it, and commit there.
- **Branch naming**: Dev branches must contain `feat`, `refactor`, `docs`, or `fix`. Release branches follow `release/[webui|core]-[fix|refactor]/<branch_name>` (e.g. `release/webui-refactor/glassmorphism-theme`).
- **Cross-domain guard**: If `cmd/webui/` does NOT exist, warn before modifying `cmd/webui/` files (they belong in the other repo). If `cmd/webui/` exists, warn before modifying `internal/` files (they belong in the core repo).
- **Branch naming**: Dev branches must contain `feat`, `refactor`, `docs`, or `fix`.
- **CHANGELOG**: Core changes → `docs/CHANGELOG.md` only. Higher versions on TOP, lower versions below.
+2 -1
View File
@@ -3,6 +3,7 @@ package domain
import (
"fmt"
"git.yoresee.cc/nightstar/ry/internal/model"
"git.yoresee.cc/nightstar/ry/internal/output"
"git.yoresee.cc/nightstar/ry/internal/provider"
@@ -66,7 +67,7 @@ func Cmd(prov *provider.Provider, out **output.Printer) *cobra.Command {
value, _ := cmd.Flags().GetString("value")
ttl, _ := cmd.Flags().GetInt("ttl")
return svc.DNSAdd(cmd.Context(), args[0],
provider.DNSRecord{Type: recType, Name: name, Value: value, TTL: ttl})
model.DNSRecord{Type: recType, Name: name, Value: value, TTL: ttl})
},
}
+8 -2
View File
@@ -26,7 +26,7 @@ var (
flagProvider string
flagOutput string
flagRaw bool
flagDebug bool
flagVerbose bool
)
var rootCmd = &cobra.Command{
@@ -67,6 +67,7 @@ Use "ry [command] --help" for more information about a command.`,
AccessKeyID: pc.AccessKeyID,
AccessKeySecret: pc.AccessKeySecret,
Endpoint: pc.Endpoint,
Debug: flagVerbose,
})
if err != nil {
return err
@@ -80,6 +81,11 @@ Use "ry [command] --help" for more information about a command.`,
outputFormat = "raw"
}
out = output.New(outputFormat, os.Stdout)
if flagVerbose {
fmt.Fprintf(os.Stderr, "[debug] provider: %s\n", providerName)
fmt.Fprintf(os.Stderr, "[debug] config: %s\n", cfgPath)
fmt.Fprintf(os.Stderr, "[debug] output: %s\n", outputFormat)
}
return nil
},
}
@@ -89,7 +95,7 @@ func init() {
rootCmd.PersistentFlags().StringVarP(&flagProvider, "provider", "p", "", "Cloud provider to use")
rootCmd.PersistentFlags().StringVarP(&flagOutput, "output", "o", "", "Output format: table, json, yaml, raw")
rootCmd.PersistentFlags().BoolVar(&flagRaw, "raw", false, "Output raw API response")
rootCmd.PersistentFlags().BoolVar(&flagDebug, "debug", false, "Enable debug output")
rootCmd.PersistentFlags().BoolVarP(&flagVerbose, "verbose", "v", false, "Enable verbose output")
completionCmd := &cobra.Command{
Use: "completion [bash|zsh|fish]",
+316
View File
@@ -0,0 +1,316 @@
# Verbose/Debug Mode Implementation Plan
> **For agentic workers:** Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Wire up `--debug`/`--verbose` flags to print HTTP request details and runtime info to stderr.
**Architecture:** Add `Debug bool` to `ProviderConfig`, pass it through to the HTTP client. Client's `do()` method logs request/response when debug is on. Root command prints runtime info in `PersistentPreRunE`.
**Tech Stack:** Go, cobra, net/http
## Global Constraints
- All debug output goes to `os.Stderr`
- `--verbose` is an alias for `--debug` (both set `flagDebug`)
- Debug prefix: `[debug]`
- Existing tests must pass after each task
---
### Task 1: Add Debug field to ProviderConfig
**Files:**
- Modify: `internal/provider/provider.go`
**Interfaces:**
- Produces: `ProviderConfig.Debug bool` — consumed by Task 3 and Task 4
- [ ] **Step 1: Add Debug field**
```go
// internal/provider/provider.go — add to ProviderConfig
type ProviderConfig struct {
APIKey string
AccessKeyID string
AccessKeySecret string
Endpoint string
Debug bool
}
```
- [ ] **Step 2: Verify build**
Run: `go build ./...`
Expected: PASS (field addition is backward-compatible)
- [ ] **Step 3: Commit**
```bash
git add internal/provider/provider.go
git commit -m "feat: add Debug field to ProviderConfig"
```
---
### Task 2: Update client to accept and use debug flag
**Files:**
- Modify: `internal/provider/rainyun/client.go`
- Modify: `internal/provider/rainyun/client_test.go` — update `newClient` calls
- Modify: `internal/provider/rainyun/server_test.go` — update `newClient` calls
**Interfaces:**
- Consumes: `debug bool` parameter
- Produces: `newClient(endpoint, apiKey string, debug bool) *client`
- Produces: stderr debug output with `[debug]` prefix
- [ ] **Step 1: Update client struct and newClient**
```go
// internal/provider/rainyun/client.go
type client struct {
httpClient *http.Client
baseURL string
apiKey string
debug bool
}
func newClient(endpoint, apiKey string, debug bool) *client {
if endpoint == "" {
endpoint = defaultEndpoint
}
return &client{
httpClient: &http.Client{Timeout: 30 * time.Second},
baseURL: endpoint,
apiKey: apiKey,
debug: debug,
}
}
```
- [ ] **Step 2: Add debug logging to do()**
Add to top of `client.go` imports: `"os"`, `"time"` (time already imported).
In `do()`, after building the URL and before creating the request, add:
```go
if c.debug {
fmt.Fprintf(os.Stderr, "[debug] > %s %s\n", method, u)
if body != nil {
fmt.Fprintf(os.Stderr, "[debug] %s\n", bodyReader.(*bytes.Reader). // wrong
}
}
```
Actually, the body bytes are already in `b` at that point. Better approach — log after marshaling:
```go
func (c *client) do(ctx context.Context, method, path string, body, result any, query map[string]string) error {
u := c.baseURL + path
if len(query) > 0 {
params := url.Values{}
for k, v := range query {
params.Set(k, v)
}
u += "?" + params.Encode()
}
var bodyReader io.Reader
var bodyBytes []byte
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal request: %w", err)
}
bodyBytes = b
bodyReader = bytes.NewReader(b)
}
if c.debug {
fmt.Fprintf(os.Stderr, "[debug] > %s %s\n", method, u)
if bodyBytes != nil {
fmt.Fprintf(os.Stderr, "[debug] %s\n", bodyBytes)
}
}
req, err := http.NewRequestWithContext(ctx, method, u, bodyReader)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
req.Header.Set("X-Api-Key", c.apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
start := time.Now()
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read response: %w", err)
}
if c.debug {
fmt.Fprintf(os.Stderr, "[debug] < %d %s %s\n", resp.StatusCode, http.StatusText(resp.StatusCode), time.Since(start).Round(time.Millisecond))
fmt.Fprintf(os.Stderr, "[debug] %s\n", respBody)
}
// ... rest unchanged
```
- [ ] **Step 3: Update test calls to newClient**
In `client_test.go`, change all `newClient(srv.URL, "sk-test")` to `newClient(srv.URL, "sk-test", false)`.
In `server_test.go`, change all `newClient(srv.URL, "sk-test")` to `newClient(srv.URL, "sk-test", false)`.
- [ ] **Step 4: Run tests**
Run: `go test ./internal/provider/rainyun/...`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add internal/provider/rainyun/
git commit -m "feat: HTTP debug logging in client.do()"
```
---
### Task 3: Pass debug flag from provider to client
**Files:**
- Modify: `internal/provider/rainyun/rainyun.go`
**Interfaces:**
- Consumes: `ProviderConfig.Debug` (from Task 1)
- Consumes: `newClient(endpoint, apiKey string, debug bool)` (from Task 2)
- [ ] **Step 1: Update New()**
```go
func New(cfg provider.ProviderConfig) (provider.Provider, error) {
c := newClient(cfg.Endpoint, cfg.APIKey, cfg.Debug)
// ... rest unchanged
}
```
- [ ] **Step 2: Run tests**
Run: `go test ./internal/provider/rainyun/...`
Expected: PASS
- [ ] **Step 3: Commit**
```bash
git add internal/provider/rainyun/rainyun.go
git commit -m "feat: pass Debug flag from config to client"
```
---
### Task 4: Wire --verbose alias and runtime info in root
**Files:**
- Modify: `cmd/cli/root.go`
**Interfaces:**
- Consumes: `flagDebug` (existing, now wired)
- Consumes: `ProviderConfig.Debug` (from Task 1)
- [ ] **Step 1: Add --verbose alias**
In `init()`, add after the `--debug` flag registration:
```go
rootCmd.PersistentFlags().BoolVarP(&flagDebug, "verbose", "v", false, "Enable verbose/debug output")
```
Note: cobra doesn't support two flags binding to the same var directly. Instead, use `MarkHidden` or just register `--verbose` as the primary and `--debug` as hidden alias. Simplest approach:
```go
rootCmd.PersistentFlags().BoolVarP(&flagDebug, "verbose", "v", false, "Enable verbose/debug output (same as --debug)")
rootCmd.PersistentFlags().BoolVar(&flagDebug, "debug", false, "Enable debug output (same as --verbose)")
```
- [ ] **Step 2: Wire flagDebug into ProviderConfig**
In `PersistentPreRunE`, after creating `pc`:
```go
prov, err = provider.New(providerName, provider.ProviderConfig{
APIKey: pc.APIKey,
AccessKeyID: pc.AccessKeyID,
AccessKeySecret: pc.AccessKeySecret,
Endpoint: pc.Endpoint,
Debug: flagDebug,
})
```
- [ ] **Step 3: Print runtime info when debug**
At the end of `PersistentPreRunE`, after creating `out`:
```go
if flagDebug {
fmt.Fprintf(os.Stderr, "[debug] provider: %s\n", providerName)
fmt.Fprintf(os.Stderr, "[debug] config: %s\n", cfgPath)
fmt.Fprintf(os.Stderr, "[debug] output: %s\n", outputFormat)
}
```
- [ ] **Step 4: Run full test suite**
Run: `go test ./...`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add cmd/cli/root.go
git commit -m "feat: wire --verbose/--debug flags with runtime info"
```
---
### Task 5: Manual verification
- [ ] **Step 1: Build and test verbose output**
```bash
go build -o ry ./cmd/cli/
./ry --verbose server list 2>&1 | head -20
```
Expected stderr output:
```
[debug] provider: rainyun
[debug] config: /path/to/config.json
[debug] output: table
[debug] > GET /product/rcs/?Page=1&PageSize=999&PerPage=999
[debug] < 200 OK 123ms
[debug] {"code":200,"data":{...}}
```
- [ ] **Step 2: Verify --debug works too**
```bash
./ry --debug server list 2>&1 | head -5
```
Expected: same `[debug]` output
- [ ] **Step 3: Verify no debug output without flag**
```bash
./ry server list 2>/dev/null
```
Expected: clean table output, no debug lines
@@ -0,0 +1,70 @@
# Verbose/Debug Mode Design
**Date:** 2026-07-28
**Status:** Approved
## Goal
Wire up the existing `--debug` flag (currently unused) and add `--verbose` as an alias. When enabled, print detailed runtime and HTTP request information to stderr.
## Scope
4 files modified, 0 new files.
## Changes
### 1. `internal/provider/provider.go` — ProviderConfig
Add `Debug bool` field to `ProviderConfig`:
```go
type ProviderConfig struct {
APIKey string
AccessKeyID string
AccessKeySecret string
Endpoint string
Debug bool
}
```
### 2. `cmd/cli/root.go` — Flag + Runtime Info
- Register `--verbose` as alias for `--debug` (both set `flagDebug`)
- In `PersistentPreRunE`, when debug is on, print to stderr:
- Provider name
- Config file path
- Output format
### 3. `internal/provider/rainyun/client.go` — HTTP Logging
- Add `debug bool` field to `client` struct
- Update `newClient(endpoint, apiKey string, debug bool)` signature
- In `do()`, when `c.debug` is true, print to `os.Stderr`:
- Request: `> METHOD /path` + request body (if any)
- Response: `< StatusCode StatusText Duration` + response body
### 4. `internal/provider/rainyun/rainyun.go` — Pass Debug
- `New()` passes `cfg.Debug` to `newClient()`
## Output Format
All debug output goes to **stderr** to avoid polluting stdout data pipeline.
```
[debug] provider: rainyun
[debug] config: /Users/user/.config/ry/config.json
[debug] output: table
[debug] > GET /api/v2/servers
[debug] < 200 OK 123ms
[debug] {"code":200,"data":[...]}
```
## Files
| File | Change |
|------|--------|
| `internal/provider/provider.go` | Add `Debug` to `ProviderConfig` |
| `cmd/cli/root.go` | Wire `--verbose`, print runtime info |
| `internal/provider/rainyun/client.go` | HTTP request/response logging |
| `internal/provider/rainyun/rainyun.go` | Pass `cfg.Debug` to client |
+12
View File
@@ -0,0 +1,12 @@
package model
import "time"
type Order struct {
ID string `json:"id" table:"ID"`
Product string `json:"product" table:"PRODUCT"`
Amount float64 `json:"amount" table:"AMOUNT"`
Status string `json:"status" table:"STATUS"`
Created time.Time `json:"created" table:"CREATED"`
Raw any `json:"-"`
}
+8
View File
@@ -0,0 +1,8 @@
package model
type CDNInstance struct {
ID string `json:"id" table:"ID"`
Domain string `json:"domain" table:"DOMAIN"`
Status string `json:"status" table:"STATUS"`
Raw any `json:"-"`
}
+19
View File
@@ -0,0 +1,19 @@
package model
import "time"
type Domain struct {
ID string `json:"id" table:"ID"`
Name string `json:"name" table:"DOMAIN"`
Status string `json:"status" table:"STATUS"`
ExpireAt time.Time `json:"expires" table:"EXPIRES"`
Raw any `json:"-"`
}
type DNSRecord struct {
ID string `json:"id" table:"ID"`
Type string `json:"type" table:"TYPE"`
Name string `json:"name" table:"NAME"`
Value string `json:"value" table:"VALUE"`
TTL int `json:"ttl" table:"TTL"`
}
+18
View File
@@ -0,0 +1,18 @@
package model
import "fmt"
type Error struct {
Code int
Message string
Detail string
Raw []byte
}
func (e *Error) Error() string {
return e.Message
}
func (e *Error) Debug() string {
return fmt.Sprintf("%s\n%s", e.Detail, string(e.Raw))
}
+17
View File
@@ -0,0 +1,17 @@
package model
import "time"
type Server struct {
ID string `json:"id" table:"ID"`
Name string `json:"name" table:"NAME"`
Status string `json:"status" table:"STATUS"`
IP string `json:"ip" table:"IP"`
CPU int `json:"cpu" table:"CPU"`
Memory int `json:"memory" table:"MEM"`
Disk int `json:"disk" table:"DISK"`
OS string `json:"os" table:"OS"`
Region string `json:"region" table:"REGION"`
ExpireAt time.Time `json:"expires" table:"EXPIRES"`
Raw any `json:"-"`
}
+14
View File
@@ -0,0 +1,14 @@
package model
type StorageInstance struct {
ID string `json:"id" table:"ID"`
Name string `json:"name" table:"NAME"`
Status string `json:"status" table:"STATUS"`
Raw any `json:"-"`
}
type Bucket struct {
ID string `json:"id" table:"ID"`
Name string `json:"name" table:"NAME"`
Region string `json:"region" table:"REGION"`
}
+12 -85
View File
@@ -2,8 +2,8 @@ package provider
import (
"context"
"fmt"
"time"
"git.yoresee.cc/nightstar/ry/internal/model"
)
type ProviderConfig struct {
@@ -11,6 +11,7 @@ type ProviderConfig struct {
AccessKeyID string
AccessKeySecret string
Endpoint string
Debug bool
}
type Provider interface {
@@ -25,8 +26,8 @@ type Provider interface {
}
type ServerService interface {
List(ctx context.Context) ([]Server, error)
Get(ctx context.Context, id string) (*Server, error)
List(ctx context.Context) ([]model.Server, error)
Get(ctx context.Context, id string) (*model.Server, error)
Start(ctx context.Context, id string) error
Stop(ctx context.Context, id string) error
Reboot(ctx context.Context, id string) error
@@ -37,96 +38,22 @@ type ServerService interface {
}
type DomainService interface {
List(ctx context.Context) ([]Domain, error)
DNSList(ctx context.Context, domain string) ([]DNSRecord, error)
DNSAdd(ctx context.Context, domain string, record DNSRecord) error
List(ctx context.Context) ([]model.Domain, error)
DNSList(ctx context.Context, domain string) ([]model.DNSRecord, error)
DNSAdd(ctx context.Context, domain string, record model.DNSRecord) error
DNSDelete(ctx context.Context, domain string, recordID string) error
}
type StorageService interface {
List(ctx context.Context) ([]StorageInstance, error)
BucketList(ctx context.Context, instanceID string) ([]Bucket, error)
List(ctx context.Context) ([]model.StorageInstance, error)
BucketList(ctx context.Context, instanceID string) ([]model.Bucket, error)
BucketCreate(ctx context.Context, instanceID, name string) error
}
type CDNService interface {
List(ctx context.Context) ([]CDNInstance, error)
List(ctx context.Context) ([]model.CDNInstance, error)
}
type BillingService interface {
Orders(ctx context.Context) ([]Order, error)
}
type Server struct {
ID string `json:"id" table:"ID"`
Name string `json:"name" table:"NAME"`
Status string `json:"status" table:"STATUS"`
IP string `json:"ip" table:"IP"`
CPU int `json:"cpu" table:"CPU"`
Memory int `json:"memory" table:"MEM"`
Disk int `json:"disk" table:"DISK"`
OS string `json:"os" table:"OS"`
Region string `json:"region" table:"REGION"`
ExpireAt time.Time `json:"expires" table:"EXPIRES"`
Raw any `json:"-"`
}
type Domain struct {
ID string `json:"id" table:"ID"`
Name string `json:"name" table:"DOMAIN"`
Status string `json:"status" table:"STATUS"`
ExpireAt time.Time `json:"expires" table:"EXPIRES"`
Raw any `json:"-"`
}
type DNSRecord struct {
ID string `json:"id" table:"ID"`
Type string `json:"type" table:"TYPE"`
Name string `json:"name" table:"NAME"`
Value string `json:"value" table:"VALUE"`
TTL int `json:"ttl" table:"TTL"`
}
type StorageInstance struct {
ID string `json:"id" table:"ID"`
Name string `json:"name" table:"NAME"`
Status string `json:"status" table:"STATUS"`
Raw any `json:"-"`
}
type Bucket struct {
ID string `json:"id" table:"ID"`
Name string `json:"name" table:"NAME"`
Region string `json:"region" table:"REGION"`
}
type CDNInstance struct {
ID string `json:"id" table:"ID"`
Domain string `json:"domain" table:"DOMAIN"`
Status string `json:"status" table:"STATUS"`
Raw any `json:"-"`
}
type Order struct {
ID string `json:"id" table:"ID"`
Product string `json:"product" table:"PRODUCT"`
Amount float64 `json:"amount" table:"AMOUNT"`
Status string `json:"status" table:"STATUS"`
Created time.Time `json:"created" table:"CREATED"`
Raw any `json:"-"`
}
type Error struct {
Code int
Message string
Detail string
Raw []byte
}
func (e *Error) Error() string {
return e.Message
}
func (e *Error) Debug() string {
return fmt.Sprintf("%s\n%s", e.Detail, string(e.Raw))
Orders(ctx context.Context) ([]model.Order, error)
}
+4 -4
View File
@@ -5,14 +5,14 @@ import (
"fmt"
"time"
"git.yoresee.cc/nightstar/ry/internal/provider"
"git.yoresee.cc/nightstar/ry/internal/model"
)
type BillingService struct {
client *client
}
func (b *BillingService) Orders(ctx context.Context) ([]provider.Order, error) {
func (b *BillingService) Orders(ctx context.Context) ([]model.Order, error) {
type rainyunOrder struct {
ID int `json:"id"`
ProductName string `json:"product_name"`
@@ -24,10 +24,10 @@ func (b *BillingService) Orders(ctx context.Context) ([]provider.Order, error) {
if err := b.client.getList(ctx, "/expense/orders/list", &raw); err != nil {
return nil, err
}
orders := make([]provider.Order, len(raw))
orders := make([]model.Order, len(raw))
for i, r := range raw {
t, _ := time.Parse("2006-01-02 15:04:05", r.CreateDate)
orders[i] = provider.Order{
orders[i] = model.Order{
ID: fmt.Sprintf("%d", r.ID),
Product: r.ProductName,
Amount: r.Amount,
+19 -1
View File
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"net/url"
"os"
"time"
)
@@ -17,9 +18,10 @@ type client struct {
httpClient *http.Client
baseURL string
apiKey string
debug bool
}
func newClient(endpoint, apiKey string) *client {
func newClient(endpoint, apiKey string, debug bool) *client {
if endpoint == "" {
endpoint = defaultEndpoint
}
@@ -27,6 +29,7 @@ func newClient(endpoint, apiKey string) *client {
httpClient: &http.Client{Timeout: 30 * time.Second},
baseURL: endpoint,
apiKey: apiKey,
debug: debug,
}
}
@@ -85,14 +88,23 @@ func (c *client) do(ctx context.Context, method, path string, body, result any,
}
var bodyReader io.Reader
var bodyBytes []byte
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal request: %w", err)
}
bodyBytes = b
bodyReader = bytes.NewReader(b)
}
if c.debug {
fmt.Fprintf(os.Stderr, "[debug] > %s %s\n", method, u)
if bodyBytes != nil {
fmt.Fprintf(os.Stderr, "[debug] %s\n", bodyBytes)
}
}
req, err := http.NewRequestWithContext(ctx, method, u, bodyReader)
if err != nil {
return fmt.Errorf("create request: %w", err)
@@ -101,6 +113,7 @@ func (c *client) do(ctx context.Context, method, path string, body, result any,
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
start := time.Now()
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
@@ -112,6 +125,11 @@ func (c *client) do(ctx context.Context, method, path string, body, result any,
return fmt.Errorf("read response: %w", err)
}
if c.debug {
fmt.Fprintf(os.Stderr, "[debug] < %d %s %s\n", resp.StatusCode, http.StatusText(resp.StatusCode), time.Since(start).Round(time.Millisecond))
fmt.Fprintf(os.Stderr, "[debug] %s\n", respBody)
}
var apiResp apiResponse
if err := json.Unmarshal(respBody, &apiResp); err == nil {
// Rainyun uses code:200 and code:0 both as success indicators
+2 -2
View File
@@ -16,7 +16,7 @@ func TestClientAuthHeader(t *testing.T) {
}))
defer srv.Close()
c := newClient(srv.URL, "sk-test")
c := newClient(srv.URL, "sk-test", false)
var result struct {
ID int `json:"id"`
Name string `json:"name"`
@@ -40,7 +40,7 @@ func TestClientAPIError(t *testing.T) {
}))
defer srv.Close()
c := newClient(srv.URL, "sk-test")
c := newClient(srv.URL, "sk-test", false)
var result any
err := c.get(context.Background(), "/error", &result)
if err == nil {
+8 -8
View File
@@ -4,7 +4,7 @@ import (
"context"
"fmt"
"git.yoresee.cc/nightstar/ry/internal/provider"
"git.yoresee.cc/nightstar/ry/internal/model"
)
type DomainService struct {
@@ -18,14 +18,14 @@ type rainyunDomain struct {
ExpireDate string `json:"expire_date"`
}
func (d *DomainService) List(ctx context.Context) ([]provider.Domain, error) {
func (d *DomainService) List(ctx context.Context) ([]model.Domain, error) {
var raw []rainyunDomain
if err := d.client.getList(ctx, "/product/domain/", &raw); err != nil {
return nil, err
}
domains := make([]provider.Domain, len(raw))
domains := make([]model.Domain, len(raw))
for i, r := range raw {
domains[i] = provider.Domain{
domains[i] = model.Domain{
ID: fmt.Sprintf("%d", r.ID),
Name: r.DomainName,
}
@@ -33,7 +33,7 @@ func (d *DomainService) List(ctx context.Context) ([]provider.Domain, error) {
return domains, nil
}
func (d *DomainService) DNSList(ctx context.Context, domain string) ([]provider.DNSRecord, error) {
func (d *DomainService) DNSList(ctx context.Context, domain string) ([]model.DNSRecord, error) {
type rainyunDNSRecord struct {
ID int `json:"id"`
RecordType string `json:"record_type"`
@@ -46,9 +46,9 @@ func (d *DomainService) DNSList(ctx context.Context, domain string) ([]provider.
if err := d.client.get(ctx, path, &raw); err != nil {
return nil, err
}
records := make([]provider.DNSRecord, len(raw))
records := make([]model.DNSRecord, len(raw))
for i, r := range raw {
records[i] = provider.DNSRecord{
records[i] = model.DNSRecord{
ID: fmt.Sprintf("%d", r.ID),
Type: r.RecordType,
Name: r.Host,
@@ -59,7 +59,7 @@ func (d *DomainService) DNSList(ctx context.Context, domain string) ([]provider.
return records, nil
}
func (d *DomainService) DNSAdd(ctx context.Context, domain string, record provider.DNSRecord) error {
func (d *DomainService) DNSAdd(ctx context.Context, domain string, record model.DNSRecord) error {
body := map[string]any{
"record_type": record.Type,
"host": record.Name,
+1 -1
View File
@@ -21,7 +21,7 @@ type Rainyun struct {
// New creates a Rainyun provider from config.
func New(cfg provider.ProviderConfig) (provider.Provider, error) {
c := newClient(cfg.Endpoint, cfg.APIKey)
c := newClient(cfg.Endpoint, cfg.APIKey, cfg.Debug)
r := &Rainyun{client: c}
r.server = &ServerService{client: c}
r.domain = &DomainService{client: c}
+23 -21
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"time"
"git.yoresee.cc/nightstar/ry/internal/provider"
"git.yoresee.cc/nightstar/ry/internal/model"
)
// ServerService implements provider.ServerService for 雨云.
@@ -16,36 +16,38 @@ type ServerService struct {
// rainyunServer mirrors the Rainyun RCS API JSON fields (PascalCase).
type rainyunServer struct {
ID int `json:"ID"`
Name string `json:"name"`
HostName string `json:"HostName"`
Status string `json:"status"`
IP string `json:"ip"`
VCPU int `json:"vcpu"`
MainIPv4 string `json:"MainIPv4"`
CPU int `json:"CPU"`
Memory int `json:"memory"`
Disk int `json:"disk"`
OS string `json:"os"`
Region string `json:"zone_name"`
ExpireDate int64 `json:"ExpDate"` // Unix timestamp
OsName string `json:"OsName"`
Zone string `json:"Zone"`
ExpireDate int64 `json:"ExpDate"`
}
func (s *ServerService) List(ctx context.Context) ([]provider.Server, error) {
func (s *ServerService) List(ctx context.Context) ([]model.Server, error) {
var raw []rainyunServer
if err := s.client.getList(ctx, "/product/rcs/", &raw); err != nil {
return nil, err
}
servers := make([]provider.Server, len(raw))
servers := make([]model.Server, len(raw))
for i, r := range raw {
servers[i] = toServer(r)
}
return servers, nil
}
func (s *ServerService) Get(ctx context.Context, id string) (*provider.Server, error) {
var raw rainyunServer
func (s *ServerService) Get(ctx context.Context, id string) (*model.Server, error) {
var resp struct {
Data rainyunServer `json:"Data"`
}
path := fmt.Sprintf("/product/rcs/%s/", id)
if err := s.client.get(ctx, path, &raw); err != nil {
if err := s.client.get(ctx, path, &resp); err != nil {
return nil, err
}
sv := toServer(raw)
sv := toServer(resp.Data)
return &sv, nil
}
@@ -85,19 +87,19 @@ func (s *ServerService) Upgrade(ctx context.Context, id, plan string) error {
return s.client.post(ctx, fmt.Sprintf("/product/rcs/%s/upgrade", id), body, nil)
}
// toServer maps a rainyunServer to the provider.Server model.
func toServer(r rainyunServer) provider.Server {
// toServer maps a rainyunServer to the model.Server model.
func toServer(r rainyunServer) model.Server {
expire := time.Unix(r.ExpireDate, 0)
return provider.Server{
return model.Server{
ID: fmt.Sprintf("%d", r.ID),
Name: r.Name,
Name: r.HostName,
Status: r.Status,
IP: r.IP,
CPU: r.VCPU,
IP: r.MainIPv4,
CPU: r.CPU,
Memory: r.Memory,
Disk: r.Disk,
OS: r.OS,
Region: r.Region,
OS: r.OsName,
Region: r.Zone,
ExpireAt: expire,
Raw: r,
}
+13 -12
View File
@@ -18,15 +18,16 @@ func TestServerList(t *testing.T) {
"data": map[string]any{
"Records": []map[string]any{
{
"ID": 12001,
"name": "web-server",
"status": "running",
"ip": "1.2.3.4",
"vcpu": 2,
"memory": 4096,
"disk": 50,
"os": "Ubuntu 22.04",
"ExpDate": 1756656000,
"ID": 12001,
"HostName": "web-server",
"status": "running",
"MainIPv4": "1.2.3.4",
"CPU": 2,
"memory": 4096,
"disk": 50,
"OsName": "Ubuntu 22.04",
"Zone": "cn-sy1",
"ExpDate": 1756656000,
},
},
"TotalRecords": 1,
@@ -36,7 +37,7 @@ func TestServerList(t *testing.T) {
}))
defer srv.Close()
rain := &Rainyun{client: newClient(srv.URL, "sk-test")}
rain := &Rainyun{client: newClient(srv.URL, "sk-test", false)}
svc := rain.Server()
servers, err := svc.List(context.Background())
if err != nil {
@@ -66,7 +67,7 @@ func TestServerStart(t *testing.T) {
}))
defer srv.Close()
rain := &Rainyun{client: newClient(srv.URL, "sk-test")}
rain := &Rainyun{client: newClient(srv.URL, "sk-test", false)}
err := rain.Server().Start(context.Background(), "12001")
if err != nil {
t.Fatalf("Start() error: %v", err)
@@ -83,7 +84,7 @@ func TestServerVNC(t *testing.T) {
}))
defer srv.Close()
rain := &Rainyun{client: newClient(srv.URL, "sk-test")}
rain := &Rainyun{client: newClient(srv.URL, "sk-test", false)}
url, err := rain.Server().GetVNC(context.Background(), "12001")
if err != nil {
t.Fatalf("GetVNC() error: %v", err)
+7 -7
View File
@@ -4,14 +4,14 @@ import (
"context"
"fmt"
"git.yoresee.cc/nightstar/ry/internal/provider"
"git.yoresee.cc/nightstar/ry/internal/model"
)
type StorageService struct {
client *client
}
func (s *StorageService) List(ctx context.Context) ([]provider.StorageInstance, error) {
func (s *StorageService) List(ctx context.Context) ([]model.StorageInstance, error) {
var raw []struct {
ID int `json:"id"`
Name string `json:"name"`
@@ -20,9 +20,9 @@ func (s *StorageService) List(ctx context.Context) ([]provider.StorageInstance,
if err := s.client.getList(ctx, "/product/ros/instance", &raw); err != nil {
return nil, err
}
instances := make([]provider.StorageInstance, len(raw))
instances := make([]model.StorageInstance, len(raw))
for i, r := range raw {
instances[i] = provider.StorageInstance{
instances[i] = model.StorageInstance{
ID: fmt.Sprintf("%d", r.ID),
Name: r.Name,
Raw: r,
@@ -31,7 +31,7 @@ func (s *StorageService) List(ctx context.Context) ([]provider.StorageInstance,
return instances, nil
}
func (s *StorageService) BucketList(ctx context.Context, instanceID string) ([]provider.Bucket, error) {
func (s *StorageService) BucketList(ctx context.Context, instanceID string) ([]model.Bucket, error) {
type rainyunBucket struct {
ID int `json:"id"`
Name string `json:"name"`
@@ -42,9 +42,9 @@ func (s *StorageService) BucketList(ctx context.Context, instanceID string) ([]p
if err := s.client.get(ctx, path, &raw); err != nil {
return nil, err
}
buckets := make([]provider.Bucket, len(raw))
buckets := make([]model.Bucket, len(raw))
for i, r := range raw {
buckets[i] = provider.Bucket{
buckets[i] = model.Bucket{
ID: fmt.Sprintf("%d", r.ID),
Name: r.Name,
}