feat: establish Orbit models, migrations and development baseline
This commit is contained in:
80
sdk/go/client.go
Normal file
80
sdk/go/client.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package orbit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Options currently configures bootstrap health calls. Task, Worker and workflow
|
||||
// clients will be added alongside their corresponding server endpoints.
|
||||
type Options struct{ HTTPClient *http.Client }
|
||||
type Client struct {
|
||||
baseURL string
|
||||
http *http.Client
|
||||
}
|
||||
type Health struct {
|
||||
Status string `json:"status"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
}
|
||||
|
||||
// HTTPError exposes the status code without including sensitive response bodies.
|
||||
type HTTPError struct{ StatusCode int }
|
||||
|
||||
func (e *HTTPError) Error() string { return fmt.Sprintf("orbit returned HTTP %d", e.StatusCode) }
|
||||
|
||||
func NewClient(baseURL string, opts Options) (*Client, error) {
|
||||
u, err := url.Parse(baseURL)
|
||||
if err != nil || u == nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, errors.New("Orbit base URL must be absolute HTTP(S), without credentials, query or fragment")
|
||||
}
|
||||
client := opts.HTTPClient
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 10 * time.Second}
|
||||
}
|
||||
clone := *client
|
||||
// Do not silently forward requests to another origin through redirects.
|
||||
clone.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
return &Client{baseURL: strings.TrimRight(u.String(), "/"), http: &clone}, nil
|
||||
}
|
||||
func (c *Client) Liveness(ctx context.Context) (Health, error) { return c.health(ctx, "/health/live") }
|
||||
func (c *Client) Readiness(ctx context.Context) (Health, error) {
|
||||
return c.health(ctx, "/health/ready")
|
||||
}
|
||||
func (c *Client) health(ctx context.Context, path string) (Health, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
|
||||
if err != nil {
|
||||
return Health{}, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
response, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return Health{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return Health{}, &HTTPError{StatusCode: response.StatusCode}
|
||||
}
|
||||
const maxBody = 16 << 10
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxBody+1))
|
||||
if err != nil {
|
||||
return Health{}, err
|
||||
}
|
||||
if len(body) > maxBody {
|
||||
return Health{}, errors.New("Orbit health response exceeds limit")
|
||||
}
|
||||
var health Health
|
||||
if err := json.Unmarshal(body, &health); err != nil {
|
||||
return Health{}, fmt.Errorf("decode Orbit health response: %w", err)
|
||||
}
|
||||
if health.Status == "" {
|
||||
return Health{}, errors.New("Orbit health response is missing status")
|
||||
}
|
||||
return health, nil
|
||||
}
|
||||
70
sdk/go/client_test.go
Normal file
70
sdk/go/client_test.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package orbit_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
orbit "git.yuntuo.hk/k2safe/orbit/sdk/go"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHealthContract(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" || r.Header.Get("Accept") != "application/json" {
|
||||
t.Error("incorrect request")
|
||||
}
|
||||
if r.URL.Path == "/health/live" {
|
||||
_, _ = w.Write([]byte(`{"status":"alive"}`))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
_, _ = w.Write([]byte(`{"secret":"must not appear in error"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := orbit.NewClient(server.URL, orbit.Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
live, err := client.Liveness(context.Background())
|
||||
if err != nil || live.Status != "alive" {
|
||||
t.Fatalf("%+v %v", live, err)
|
||||
}
|
||||
_, err = client.Readiness(context.Background())
|
||||
var status *orbit.HTTPError
|
||||
if !errors.As(err, &status) || status.StatusCode != 503 || strings.Contains(err.Error(), "secret") {
|
||||
t.Fatalf("unsafe status error: %v", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := client.Liveness(ctx); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("context ignored: %v", err)
|
||||
}
|
||||
}
|
||||
func TestRejectsUnsafeURLsRedirectsAndOversizedResponses(t *testing.T) {
|
||||
for _, url := range []string{"", "file:///tmp/x", "http://user:pass@example.org", "http://example.org?token=x"} {
|
||||
if _, err := orbit.NewClient(url, orbit.Options{}); err == nil {
|
||||
t.Fatalf("accepted %q", url)
|
||||
}
|
||||
}
|
||||
for _, scenario := range []string{"redirect", "oversize"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if scenario == "redirect" {
|
||||
http.Redirect(w, r, "/other", http.StatusFound)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(strings.Repeat("x", 17000)))
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := orbit.NewClient(server.URL, orbit.Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.Liveness(context.Background()); err == nil {
|
||||
t.Fatal("accepted unsafe response")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
4
sdk/go/doc.go
Normal file
4
sdk/go/doc.go
Normal file
@@ -0,0 +1,4 @@
|
||||
// Package orbit is the standalone Go SDK for Orbit. This foundation release
|
||||
// implements health calls; task, Worker and workflow APIs are planned next.
|
||||
// The SDK does not import server models, migrations or storage dependencies.
|
||||
package orbit
|
||||
33
sdk/go/examples/health/main.go
Normal file
33
sdk/go/examples/health/main.go
Normal file
@@ -0,0 +1,33 @@
|
||||
// Run against a started bootstrap server: ORBIT_URL=http://127.0.0.1:8080 go run ./examples/health
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
orbit "git.yuntuo.hk/k2safe/orbit/sdk/go"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
address := os.Getenv("ORBIT_URL")
|
||||
if address == "" {
|
||||
address = "http://127.0.0.1:8080"
|
||||
}
|
||||
client, err := orbit.NewClient(address, orbit.Options{})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
live, err := client.Liveness(ctx)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ready, err := client.Readiness(ctx)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Printf("liveness=%s readiness=%s scope=%s\n", live.Status, ready.Status, ready.Scope)
|
||||
}
|
||||
3
sdk/go/go.mod
Normal file
3
sdk/go/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module git.yuntuo.hk/k2safe/orbit/sdk/go
|
||||
|
||||
go 1.27.1
|
||||
Reference in New Issue
Block a user