From ff4aa1b64ef5e86fe3527b08c9e5786b9fd9f36d Mon Sep 17 00:00:00 2001 From: AS213905 Engineering Date: Fri, 14 Aug 2026 11:06:03 +0000 Subject: [PATCH] Initial AS213905 SDK release --- .gitignore | 9 + LICENSE | 21 + README.md | 67 ++ docs/index.html | 30 + docs/package-lock.json | 28 + docs/package.json | 4 + docs/swagger-initializer.js | 13 + go/README.md | 13 + go/as213905/client.go | 258 +++++++ go/as213905/client_test.go | 44 ++ go/as213905/models.go | 111 +++ go/examples/quickstart/main.go | 19 + go/go.mod | 3 + javascript/README.md | 14 + javascript/package.json | 14 + javascript/src/index.d.ts | 34 + javascript/src/index.js | 49 ++ javascript/test/client.test.js | 13 + openapi/openapi.yaml | 611 +++++++++++++++ python/README.md | 13 + python/pyproject.toml | 20 + python/src/as213905/__init__.py | 4 + python/src/as213905/client.py | 99 +++ python/tests/test_client.py | 28 + rust/Cargo.lock | 1277 +++++++++++++++++++++++++++++++ rust/Cargo.toml | 17 + rust/README.md | 10 + rust/examples/quickstart.rs | 12 + rust/src/lib.rs | 478 ++++++++++++ 29 files changed, 3313 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 docs/index.html create mode 100644 docs/package-lock.json create mode 100644 docs/package.json create mode 100644 docs/swagger-initializer.js create mode 100644 go/README.md create mode 100644 go/as213905/client.go create mode 100644 go/as213905/client_test.go create mode 100644 go/as213905/models.go create mode 100644 go/examples/quickstart/main.go create mode 100644 go/go.mod create mode 100644 javascript/README.md create mode 100644 javascript/package.json create mode 100644 javascript/src/index.d.ts create mode 100644 javascript/src/index.js create mode 100644 javascript/test/client.test.js create mode 100644 openapi/openapi.yaml create mode 100644 python/README.md create mode 100644 python/pyproject.toml create mode 100644 python/src/as213905/__init__.py create mode 100644 python/src/as213905/client.py create mode 100644 python/tests/test_client.py create mode 100644 rust/Cargo.lock create mode 100644 rust/Cargo.toml create mode 100644 rust/README.md create mode 100644 rust/examples/quickstart.rs create mode 100644 rust/src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ce347d5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.DS_Store +.env +target/ +dist/ +node_modules/ +__pycache__/ +.pytest_cache/ +*.egg-info/ +coverage/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c560308 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 AS213905 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0121718 --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# AS213905 SDK + +Official API clients and the OpenAPI contract for the AS213905 customer API. + +The clients cover organisations, invoices, services, VM metrics and power +actions, transit traffic, tunnels, and RFC 8805 geofeeds. API keys are created +in **Panel → Settings → API keys** and are always scoped to one organisation. + +## Packages + +| Language | Package | Install | +| --- | --- | --- | +| Go | `as213905` | `go get git.datacoria.com/Phylex/as213905-sdk/go` | +| Rust | `as213905-sdk` | Git dependency shown in `rust/README.md` | +| Python | `as213905` | `pip install "as213905 @ git+https://git.datacoria.com/Phylex/as213905-sdk.git#subdirectory=python"` | +| JavaScript | `@as213905/sdk` | `npm install git+https://git.datacoria.com/Phylex/as213905-sdk.git#javascript` | + +All clients use `https://as213905.com` by default and accept a different base +URL for tests. Never put an API key in a query string or commit it to source. + +## Quick start + +```go +client := as213905.New(os.Getenv("AS213905_API_KEY")) +traffic, err := client.Traffic(ctx, &as213905.TrafficQuery{Days: 7}) +``` + +```rust +let client = as213905_sdk::Client::new(std::env::var("AS213905_API_KEY")?); +let traffic = client.traffic(Some(7), None, None).await?; +``` + +```python +client = AS213905(os.environ["AS213905_API_KEY"]) +traffic = client.traffic(days=7) +``` + +```js +const client = new AS213905({apiKey: process.env.AS213905_API_KEY}); +const traffic = await client.traffic({days: 7}); +``` + +Geofeed methods additionally take the organisation UUID because the geofeed +service also supports administrator sessions. An API key can only use its own +organisation UUID and needs `geofeeds:read` or `geofeeds:write`. + +## API contract + +- [`openapi/openapi.yaml`](openapi/openapi.yaml) is the source of truth. +- Interactive reference: +- Machine-readable production contract: + +## Development + +Each language directory is independently buildable and tested. See its README +for language-specific commands. Behaviour shared by every client: + +- bearer authentication in the `Authorization` header; +- stable `APIError`/`Error` values containing HTTP status, API error code and + response message; +- request timeouts; +- no automatic retries for mutation requests; +- typed request and response models for the documented operations. + +## License + +MIT. See [LICENSE](LICENSE). diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..225dd78 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,30 @@ + + + + + + + AS213905 API reference + + + + +
+ + + + + diff --git a/docs/package-lock.json b/docs/package-lock.json new file mode 100644 index 0000000..5deb961 --- /dev/null +++ b/docs/package-lock.json @@ -0,0 +1,28 @@ +{ + "name": "docs", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "swagger-ui-dist": "5.27.1" + } + }, + "node_modules/@scarf/scarf": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz", + "integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==", + "hasInstallScript": true, + "license": "Apache-2.0" + }, + "node_modules/swagger-ui-dist": { + "version": "5.27.1", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.27.1.tgz", + "integrity": "sha512-oGtpYO3lnoaqyGtlJalvryl7TwzgRuxpOVWqEHx8af0YXI+Kt+4jMpLdgMtMcmWmuQ0QTCHLKExwrBFMSxvAUA==", + "license": "Apache-2.0", + "dependencies": { + "@scarf/scarf": "=1.4.0" + } + } + } +} diff --git a/docs/package.json b/docs/package.json new file mode 100644 index 0000000..3fe7758 --- /dev/null +++ b/docs/package.json @@ -0,0 +1,4 @@ +{ + "private": true, + "dependencies": {"swagger-ui-dist": "5.27.1"} +} diff --git a/docs/swagger-initializer.js b/docs/swagger-initializer.js new file mode 100644 index 0000000..bbce495 --- /dev/null +++ b/docs/swagger-initializer.js @@ -0,0 +1,13 @@ +window.addEventListener('load', () => { + window.ui = SwaggerUIBundle({ + url: '/api/v1/openapi.json', + dom_id: '#swagger-ui', + deepLinking: true, + displayRequestDuration: true, + filter: true, + persistAuthorization: false, + tryItOutEnabled: false, + presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset], + layout: 'StandaloneLayout', + }); +}); diff --git a/go/README.md b/go/README.md new file mode 100644 index 0000000..2b0bc78 --- /dev/null +++ b/go/README.md @@ -0,0 +1,13 @@ +# Go SDK + +```bash +go get git.datacoria.com/Phylex/as213905-sdk/go +``` + +```go +client := as213905.New(os.Getenv("AS213905_API_KEY")) +org, err := client.Organization(context.Background()) +``` + +The client is safe for concurrent use. Use `NewWithOptions` to supply a custom +base URL, HTTP client or user agent. diff --git a/go/as213905/client.go b/go/as213905/client.go new file mode 100644 index 0000000..e56322c --- /dev/null +++ b/go/as213905/client.go @@ -0,0 +1,258 @@ +package as213905 + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +const defaultBaseURL = "https://as213905.com" + +type Options struct { + BaseURL string + HTTPClient *http.Client + UserAgent string +} + +type Client struct { + apiKey string + base *url.URL + http *http.Client + userAgent string +} + +type APIError struct { + Status int + Code string `json:"error"` + Message string `json:"message"` + RequiredScope string `json:"required_scope"` + RetryAfter int `json:"retry_after"` +} + +func (e *APIError) Error() string { + if e.Message != "" { + return fmt.Sprintf("as213905: %s (%d): %s", e.Code, e.Status, e.Message) + } + return fmt.Sprintf("as213905: %s (%d)", e.Code, e.Status) +} + +func New(apiKey string) *Client { + c, err := NewWithOptions(apiKey, Options{}) + if err != nil { + panic(err) + } + return c +} + +func NewWithOptions(apiKey string, opts Options) (*Client, error) { + if strings.TrimSpace(apiKey) == "" { + return nil, errors.New("as213905: api key is required") + } + base := opts.BaseURL + if base == "" { + base = defaultBaseURL + } + u, err := url.Parse(strings.TrimRight(base, "/")) + if err != nil || u.Scheme == "" || u.Host == "" { + return nil, errors.New("as213905: invalid base URL") + } + hc := opts.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + ua := opts.UserAgent + if ua == "" { + ua = "as213905-go/1.1.0" + } + return &Client{apiKey: apiKey, base: u, http: hc, userAgent: ua}, nil +} + +func (c *Client) do(ctx context.Context, method, path, organizationID string, body, out any) error { + var reader io.Reader + if body != nil { + payload, err := json.Marshal(body) + if err != nil { + return err + } + reader = bytes.NewReader(payload) + } + rel, err := url.Parse(path) + if err != nil { + return err + } + u := c.base.ResolveReference(rel) + req, err := http.NewRequestWithContext(ctx, method, u.String(), reader) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+c.apiKey) + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", c.userAgent) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if organizationID != "" { + req.Header.Set("X-Organization-ID", organizationID) + } + res, err := c.http.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + data, err := io.ReadAll(io.LimitReader(res.Body, 4<<20)) + if err != nil { + return err + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + e := &APIError{Status: res.StatusCode, Code: "http_error"} + _ = json.Unmarshal(data, e) + if e.Code == "" { + e.Code = "http_error" + } + if e.RetryAfter == 0 { + e.RetryAfter, _ = strconv.Atoi(res.Header.Get("Retry-After")) + } + return e + } + if out == nil || len(data) == 0 { + return nil + } + if err := json.Unmarshal(data, out); err != nil { + return fmt.Errorf("as213905: decode response: %w", err) + } + return nil +} + +func withTrafficQuery(path string, q *TrafficQuery) string { + if q == nil { + return path + } + v := url.Values{} + if q.Days > 0 { + v.Set("days", strconv.Itoa(q.Days)) + } + if q.From != "" { + v.Set("from", q.From) + } + if q.To != "" { + v.Set("to", q.To) + } + if len(v) > 0 { + return path + "?" + v.Encode() + } + return path +} + +func (c *Client) Organization(ctx context.Context) (Organization, error) { + var r struct { + Organization Organization `json:"organization"` + } + err := c.do(ctx, http.MethodGet, "/api/v1/organization", "", nil, &r) + return r.Organization, err +} +func (c *Client) Invoices(ctx context.Context) ([]Invoice, error) { + var r struct { + Invoices []Invoice `json:"invoices"` + } + err := c.do(ctx, http.MethodGet, "/api/v1/invoices", "", nil, &r) + return r.Invoices, err +} +func (c *Client) Services(ctx context.Context) ([]Service, error) { + var r struct { + Services []Service `json:"services"` + } + err := c.do(ctx, http.MethodGet, "/api/v1/services", "", nil, &r) + return r.Services, err +} +func (c *Client) Service(ctx context.Context, id string) (Service, error) { + var r struct { + Service Service `json:"service"` + } + err := c.do(ctx, http.MethodGet, "/api/v1/services/"+url.PathEscape(id), "", nil, &r) + return r.Service, err +} +func (c *Client) ServiceMetrics(ctx context.Context, id, target, metricRange string) (MetricSeries, error) { + q := url.Values{} + if target != "" { + q.Set("target", target) + } + if metricRange != "" { + q.Set("range", metricRange) + } + path := "/api/v1/services/" + url.PathEscape(id) + "/metrics" + if len(q) > 0 { + path += "?" + q.Encode() + } + var r MetricSeries + err := c.do(ctx, http.MethodGet, path, "", nil, &r) + return r, err +} +func (c *Client) PowerService(ctx context.Context, id, action string) error { + return c.do(ctx, http.MethodPost, "/api/v1/services/"+url.PathEscape(id)+"/power", "", map[string]string{"action": action}, nil) +} +func (c *Client) Traffic(ctx context.Context, q *TrafficQuery) (Traffic, error) { + var r Traffic + err := c.do(ctx, http.MethodGet, withTrafficQuery("/api/v1/traffic", q), "", nil, &r) + return r, err +} +func (c *Client) Tunnels(ctx context.Context) ([]Tunnel, error) { + var r struct { + Tunnels []Tunnel `json:"tunnels"` + } + err := c.do(ctx, http.MethodGet, "/api/v1/tunnels", "", nil, &r) + return r.Tunnels, err +} +func (c *Client) CreateTunnel(ctx context.Context, input CreateTunnelRequest) (Tunnel, error) { + var r struct { + Tunnel Tunnel `json:"tunnel"` + } + err := c.do(ctx, http.MethodPost, "/api/v1/tunnels", "", input, &r) + return r.Tunnel, err +} +func (c *Client) DeleteTunnel(ctx context.Context, id string) error { + return c.do(ctx, http.MethodDelete, "/api/v1/tunnels/"+url.PathEscape(id), "", nil, nil) +} +func (c *Client) TunnelTraffic(ctx context.Context, id string, q *TrafficQuery) (Traffic, error) { + var r Traffic + err := c.do(ctx, http.MethodGet, withTrafficQuery("/api/v1/tunnels/"+url.PathEscape(id)+"/traffic", q), "", nil, &r) + return r, err +} +func (c *Client) Geofeeds(ctx context.Context, org string) (GeofeedList, error) { + var r GeofeedList + err := c.do(ctx, http.MethodGet, "/api/v1/geofeeds", org, nil, &r) + return r, err +} +func (c *Client) CreateGeofeed(ctx context.Context, org, name string) (GeofeedList, error) { + var r GeofeedList + err := c.do(ctx, http.MethodPost, "/api/v1/geofeeds", org, map[string]string{"name": name}, &r) + return r, err +} +func (c *Client) Geofeed(ctx context.Context, org, id string) (Geofeed, error) { + var r struct { + Geofeed Geofeed `json:"geofeed"` + } + err := c.do(ctx, http.MethodGet, "/api/v1/geofeeds/"+url.PathEscape(id), org, nil, &r) + return r.Geofeed, err +} +func (c *Client) RenameGeofeed(ctx context.Context, org, id, name string) error { + return c.do(ctx, http.MethodPatch, "/api/v1/geofeeds/"+url.PathEscape(id), org, map[string]string{"name": name}, nil) +} +func (c *Client) DeleteGeofeed(ctx context.Context, org, id string) error { + return c.do(ctx, http.MethodDelete, "/api/v1/geofeeds/"+url.PathEscape(id), org, nil, nil) +} +func (c *Client) ReplaceGeofeedRecords(ctx context.Context, org, id string, records []GeofeedRecord) error { + return c.do(ctx, http.MethodPut, "/api/v1/geofeeds/"+url.PathEscape(id)+"/records", org, map[string]any{"records": records}, nil) +} +func (c *Client) RotateGeofeedURL(ctx context.Context, org, id string) (GeofeedList, error) { + var r GeofeedList + err := c.do(ctx, http.MethodPost, "/api/v1/geofeeds/"+url.PathEscape(id)+"/rotate", org, nil, &r) + return r, err +} diff --git a/go/as213905/client_test.go b/go/as213905/client_test.go new file mode 100644 index 0000000..5d5ad62 --- /dev/null +++ b/go/as213905/client_test.go @@ -0,0 +1,44 @@ +package as213905 + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +func TestOrganizationAndHeaders(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Authorization"); got != "Bearer secret" { + t.Errorf("authorization = %q", got) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"organization":{"id":"o","asn":213905,"name":"ISPLABS","status":"active","commit_kbps":50000}}`)) + })) + defer s.Close() + c, err := NewWithOptions("secret", Options{BaseURL: s.URL}) + if err != nil { + t.Fatal(err) + } + org, err := c.Organization(context.Background()) + if err != nil { + t.Fatal(err) + } + if org.ASN != 213905 { + t.Fatalf("asn = %d", org.ASN) + } +} + +func TestAPIError(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(403) + _, _ = w.Write([]byte(`{"error":"scope_required","message":"need traffic:read"}`)) + })) + defer s.Close() + c, _ := NewWithOptions("secret", Options{BaseURL: s.URL}) + _, err := c.Traffic(context.Background(), nil) + e, ok := err.(*APIError) + if !ok || e.Code != "scope_required" || e.Status != 403 { + t.Fatalf("error = %#v", err) + } +} diff --git a/go/as213905/models.go b/go/as213905/models.go new file mode 100644 index 0000000..da1e969 --- /dev/null +++ b/go/as213905/models.go @@ -0,0 +1,111 @@ +package as213905 + +import "time" + +type Organization struct { + ID string `json:"id"` + ASN int64 `json:"asn"` + Name string `json:"name"` + Status string `json:"status"` + CommitKbps int64 `json:"commit_kbps"` +} + +type Invoice struct { + ID string `json:"id"` + Number string `json:"number"` + Status string `json:"status"` + Currency string `json:"currency"` + TotalCents int64 `json:"total_cents"` + PeriodFrom *string `json:"period_from,omitempty"` + PeriodTo *string `json:"period_to,omitempty"` + IssuedAt *time.Time `json:"issued_at,omitempty"` + DueAt *time.Time `json:"due_at,omitempty"` +} + +type Service struct { + ID string `json:"id"` + Kind string `json:"kind"` + Label string `json:"label"` + Status string `json:"status"` + MonthlyCents int64 `json:"monthly_cents"` + NextDueOn *string `json:"next_due_on,omitempty"` + Controllable bool `json:"controllable,omitempty"` + Location string `json:"location,omitempty"` + Configuration map[string]any `json:"configuration,omitempty"` +} + +type MetricPoint struct { + Time time.Time `json:"t"` + Value *float64 `json:"v,omitempty"` +} + +type MetricSeries struct { + Metric string `json:"metric"` + Target string `json:"target"` + Range string `json:"range"` + Points []MetricPoint `json:"points"` +} + +type Period struct { + From time.Time `json:"from"` + To time.Time `json:"to"` + Label string `json:"label"` +} + +type Traffic struct { + P95Kbps int64 `json:"p95_kbps"` + CommitKbps int64 `json:"commit_kbps,omitempty"` + OverCommit bool `json:"over_commit,omitempty"` + TotalBytes int64 `json:"total_bytes"` + TotalGB float64 `json:"total_gb"` + Period Period `json:"period"` +} + +type Tunnel struct { + ID string `json:"id"` + Status string `json:"status"` + Label string `json:"label,omitempty"` + Location string `json:"location"` + PeerEndpoint string `json:"peer_endpoint"` + IfName string `json:"ifname,omitempty"` + InnerV4 string `json:"inner_v4,omitempty"` + InnerV6 string `json:"inner_v6,omitempty"` + Announce bool `json:"announce,omitempty"` +} + +type TrafficQuery struct { + Days int + From string + To string +} + +type CreateTunnelRequest struct { + PeerEndpoint string `json:"peer_endpoint"` + Location string `json:"location"` + Label string `json:"label,omitempty"` + Announce bool `json:"announce,omitempty"` +} + +type Geofeed struct { + ID string `json:"id"` + Name string `json:"name"` + Slug string `json:"slug"` + RecordCount int `json:"record_count"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + Records []GeofeedRecord `json:"records,omitempty"` +} + +type GeofeedRecord struct { + ID string `json:"id,omitempty"` + Prefix string `json:"prefix"` + CountryCode string `json:"country_code"` + RegionCode string `json:"region_code,omitempty"` + City string `json:"city,omitempty"` + PostalCode string `json:"postal_code,omitempty"` +} + +type GeofeedList struct { + Geofeeds []Geofeed `json:"geofeeds"` + Limit int `json:"limit"` +} diff --git a/go/examples/quickstart/main.go b/go/examples/quickstart/main.go new file mode 100644 index 0000000..08fd00a --- /dev/null +++ b/go/examples/quickstart/main.go @@ -0,0 +1,19 @@ +package main + +import ( + "context" + "fmt" + "log" + "os" + + as213905 "git.datacoria.com/Phylex/as213905-sdk/go/as213905" +) + +func main() { + client := as213905.New(os.Getenv("AS213905_API_KEY")) + traffic, err := client.Traffic(context.Background(), &as213905.TrafficQuery{Days: 7}) + if err != nil { + log.Fatal(err) + } + fmt.Printf("p95: %d kbit/s, volume: %.2f GB\n", traffic.P95Kbps, traffic.TotalGB) +} diff --git a/go/go.mod b/go/go.mod new file mode 100644 index 0000000..e591dc4 --- /dev/null +++ b/go/go.mod @@ -0,0 +1,3 @@ +module git.datacoria.com/Phylex/as213905-sdk/go + +go 1.22 diff --git a/javascript/README.md b/javascript/README.md new file mode 100644 index 0000000..4fa3645 --- /dev/null +++ b/javascript/README.md @@ -0,0 +1,14 @@ +# JavaScript / TypeScript SDK + +```bash +npm install git+https://git.datacoria.com/Phylex/as213905-sdk.git#javascript +``` + +```js +import {AS213905} from '@as213905/sdk'; +const client = new AS213905({apiKey: process.env.AS213905_API_KEY}); +console.log(await client.traffic({days: 7})); +``` + +The package has no dependencies, works in Node 18+ and modern browsers, and +ships TypeScript declarations. diff --git a/javascript/package.json b/javascript/package.json new file mode 100644 index 0000000..50c9a78 --- /dev/null +++ b/javascript/package.json @@ -0,0 +1,14 @@ +{ + "name": "@as213905/sdk", + "version": "1.1.0", + "description": "Official AS213905 customer API client", + "type": "module", + "main": "./src/index.js", + "types": "./src/index.d.ts", + "exports": {".": {"types": "./src/index.d.ts", "import": "./src/index.js"}}, + "files": ["src", "README.md"], + "scripts": {"test": "node --test", "check": "node --check src/index.js"}, + "engines": {"node": ">=18"}, + "license": "MIT", + "repository": {"type": "git", "url": "https://git.datacoria.com/Phylex/as213905-sdk.git", "directory": "javascript"} +} diff --git a/javascript/src/index.d.ts b/javascript/src/index.d.ts new file mode 100644 index 0000000..0b4d437 --- /dev/null +++ b/javascript/src/index.d.ts @@ -0,0 +1,34 @@ +export interface ClientOptions { apiKey: string; baseUrl?: string; timeout?: number; fetch?: typeof fetch } +export interface RequestOptions { signal?: AbortSignal } +export interface Organization { id: string; asn: number; name: string; status: string; commit_kbps: number } +export interface Invoice { id: string; number: string; status: string; currency: string; total_cents: number; period_from?: string|null; period_to?: string|null; issued_at?: string|null; due_at?: string|null } +export interface Service { id: string; kind: string; label: string; status: string; monthly_cents: number; next_due_on?: string|null; controllable?: boolean; location?: string; configuration?: Record } +export interface Period { from: string; to: string; label: string } +export interface Traffic { p95_kbps: number; commit_kbps?: number; over_commit?: boolean; total_bytes: number; total_gb: number; period: Period } +export interface Tunnel { id: string; status: string; label?: string; location: string; peer_endpoint: string; ifname?: string; inner_v4?: string; inner_v6?: string; announce?: boolean } +export interface CreateTunnel { peer_endpoint: string; location: string; label?: string; announce?: boolean } +export interface GeofeedRecord { id?: string; prefix: string; country_code: string; region_code?: string; city?: string; postal_code?: string } +export interface Geofeed { id: string; name: string; slug: string; record_count: number; created_at: string; updated_at: string; records?: GeofeedRecord[] } +export interface GeofeedList { geofeeds: Geofeed[]; limit: number } +export class APIError extends Error { status: number; code: string; requiredScope?: string; retryAfter?: number } +export class AS213905 { + constructor(options: ClientOptions); + organization(options?: RequestOptions): Promise; + invoices(options?: RequestOptions): Promise; + services(options?: RequestOptions): Promise; + service(id: string, options?: RequestOptions): Promise; + serviceMetrics(id: string, options?: RequestOptions & {target?: string; range?: string}): Promise<{metric:string;target:string;range:string;points:Array<{t:string;v?:number}>}>; + powerService(id: string, action: 'start'|'stop'|'restart', options?: RequestOptions): Promise<{status:string;action:string}>; + traffic(options?: RequestOptions & {days?:number;from?:string;to?:string}): Promise; + tunnels(options?: RequestOptions): Promise; + createTunnel(input: CreateTunnel, options?: RequestOptions): Promise; + deleteTunnel(id: string, options?: RequestOptions): Promise; + tunnelTraffic(id:string, options?:RequestOptions & {days?:number;from?:string;to?:string}):Promise; + geofeeds(organizationId:string,options?:RequestOptions):Promise; + createGeofeed(organizationId:string,name:string,options?:RequestOptions):Promise; + geofeed(organizationId:string,id:string,options?:RequestOptions):Promise; + renameGeofeed(organizationId:string,id:string,name:string,options?:RequestOptions):Promise; + deleteGeofeed(organizationId:string,id:string,options?:RequestOptions):Promise; + replaceGeofeedRecords(organizationId:string,id:string,records:GeofeedRecord[],options?:RequestOptions):Promise; + rotateGeofeedUrl(organizationId:string,id:string,options?:RequestOptions):Promise; +} diff --git a/javascript/src/index.js b/javascript/src/index.js new file mode 100644 index 0000000..ae426c4 --- /dev/null +++ b/javascript/src/index.js @@ -0,0 +1,49 @@ +export class APIError extends Error { + constructor(status, code, message = '', details = {}) { + super(`AS213905 API error ${status} (${code})${message ? `: ${message}` : ''}`); + this.name = 'APIError'; this.status = status; this.code = code; + this.requiredScope = details.required_scope; this.retryAfter = details.retry_after; + } +} + +export class AS213905 { + constructor({apiKey, baseUrl = 'https://as213905.com', timeout = 30000, fetch: fetchImpl = globalThis.fetch} = {}) { + if (!apiKey) throw new TypeError('apiKey is required'); + if (typeof fetchImpl !== 'function') throw new TypeError('fetch implementation is required'); + this.apiKey = apiKey; this.baseUrl = baseUrl.replace(/\/$/, ''); this.timeout = timeout; this.fetch = fetchImpl; + } + async request(method, path, {body, organizationId, signal} = {}) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(new Error('request timed out')), this.timeout); + if (signal) signal.addEventListener('abort', () => controller.abort(signal.reason), {once: true}); + try { + const response = await this.fetch(this.baseUrl + path, { + method, signal: controller.signal, + headers: {Authorization: `Bearer ${this.apiKey}`, Accept: 'application/json', ...(body === undefined ? {} : {'Content-Type': 'application/json'}), ...(organizationId ? {'X-Organization-ID': organizationId} : {})}, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const value = await response.json().catch(() => ({})); + if (!response.ok) throw new APIError(response.status, value.error || 'http_error', value.message || '', {...value, retry_after: value.retry_after || Number(response.headers.get('Retry-After')) || undefined}); + return value; + } finally { clearTimeout(timer); } + } + static query(values) { const q = new URLSearchParams(Object.entries(values).filter(([,v]) => v !== undefined && v !== null)); return q.size ? `?${q}` : ''; } + organization(options) { return this.request('GET', '/api/v1/organization', options).then(v => v.organization); } + invoices(options) { return this.request('GET', '/api/v1/invoices', options).then(v => v.invoices); } + services(options) { return this.request('GET', '/api/v1/services', options).then(v => v.services); } + service(id, options) { return this.request('GET', `/api/v1/services/${encodeURIComponent(id)}`, options).then(v => v.service); } + serviceMetrics(id, {target, range, ...options} = {}) { return this.request('GET', `/api/v1/services/${encodeURIComponent(id)}/metrics${AS213905.query({target, range})}`, options); } + powerService(id, action, options = {}) { return this.request('POST', `/api/v1/services/${encodeURIComponent(id)}/power`, {...options, body: {action}}); } + traffic({days, from, to, ...options} = {}) { return this.request('GET', `/api/v1/traffic${AS213905.query({days, from, to})}`, options); } + tunnels(options) { return this.request('GET', '/api/v1/tunnels', options).then(v => v.tunnels); } + createTunnel(input, options = {}) { return this.request('POST', '/api/v1/tunnels', {...options, body: input}).then(v => v.tunnel); } + deleteTunnel(id, options) { return this.request('DELETE', `/api/v1/tunnels/${encodeURIComponent(id)}`, options); } + tunnelTraffic(id, {days, from, to, ...options} = {}) { return this.request('GET', `/api/v1/tunnels/${encodeURIComponent(id)}/traffic${AS213905.query({days, from, to})}`, options); } + geofeeds(organizationId, options = {}) { return this.request('GET', '/api/v1/geofeeds', {...options, organizationId}); } + createGeofeed(organizationId, name, options = {}) { return this.request('POST', '/api/v1/geofeeds', {...options, organizationId, body: {name}}); } + geofeed(organizationId, id, options = {}) { return this.request('GET', `/api/v1/geofeeds/${encodeURIComponent(id)}`, {...options, organizationId}).then(v => v.geofeed); } + renameGeofeed(organizationId, id, name, options = {}) { return this.request('PATCH', `/api/v1/geofeeds/${encodeURIComponent(id)}`, {...options, organizationId, body: {name}}); } + deleteGeofeed(organizationId, id, options = {}) { return this.request('DELETE', `/api/v1/geofeeds/${encodeURIComponent(id)}`, {...options, organizationId}); } + replaceGeofeedRecords(organizationId, id, records, options = {}) { return this.request('PUT', `/api/v1/geofeeds/${encodeURIComponent(id)}/records`, {...options, organizationId, body: {records}}); } + rotateGeofeedUrl(organizationId, id, options = {}) { return this.request('POST', `/api/v1/geofeeds/${encodeURIComponent(id)}/rotate`, {...options, organizationId}); } +} diff --git a/javascript/test/client.test.js b/javascript/test/client.test.js new file mode 100644 index 0000000..bbaec54 --- /dev/null +++ b/javascript/test/client.test.js @@ -0,0 +1,13 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {AS213905, APIError} from '../src/index.js'; + +test('sets bearer authentication and parses organization', async () => { + const client = new AS213905({apiKey:'secret',fetch:async (url,init)=>{assert.equal(init.headers.Authorization,'Bearer secret');return new Response(JSON.stringify({organization:{asn:213905}}),{status:200,headers:{'content-type':'application/json'}})}}); + assert.equal((await client.organization()).asn,213905); +}); + +test('throws a structured APIError', async () => { + const client = new AS213905({apiKey:'secret',fetch:async()=>new Response(JSON.stringify({error:'scope_required',message:'need traffic:read'}),{status:403})}); + await assert.rejects(client.traffic(),error=>error instanceof APIError&&error.status===403&&error.code==='scope_required'); +}); diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml new file mode 100644 index 0000000..078b153 --- /dev/null +++ b/openapi/openapi.yaml @@ -0,0 +1,611 @@ +openapi: 3.1.0 +info: + title: AS213905 API + version: 1.1.0 + description: | + Customer automation API for organisations, invoices, services, traffic, + tunnels and RFC 8805 geofeeds. Create a scoped key in Panel → Settings. + contact: + name: AS213905 NOC + email: noc@as213905.com + url: https://as213905.com/docs/api + license: + name: Proprietary API; SDKs licensed under MIT + url: https://git.datacoria.com/Phylex/as213905-sdk/src/branch/main/LICENSE +servers: + - url: https://as213905.com +tags: + - name: Organisation + description: The organisation bound to the API key. + - name: Invoices + description: Billing documents and payment state. + - name: Services + description: Customer services, BGP VM metrics and power actions. + - name: Traffic + description: Organisation and per-tunnel traffic accounting. + - name: Tunnels + description: Transit tunnel inventory and lifecycle. + - name: Geofeeds + description: RFC 8805 public geofeed management. +security: + - apiKey: [] +paths: + /api/v1/organization: + get: + tags: [Organisation] + summary: Get the API key's organisation + operationId: getOrganization + x-required-scope: organizations:read + responses: + '200': + description: Organisation + content: + application/json: + schema: {$ref: '#/components/schemas/OrganizationResponse'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + /api/v1/invoices: + get: + tags: [Invoices] + summary: List invoices, newest first + operationId: listInvoices + x-required-scope: invoices:read + responses: + '200': + description: Invoice list + content: + application/json: + schema: + type: object + required: [invoices] + properties: + invoices: {type: array, items: {$ref: '#/components/schemas/Invoice'}} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + /api/v1/services: + get: + tags: [Services] + summary: List services + operationId: listServices + x-required-scope: services:read + responses: + '200': + description: Service list + content: + application/json: + schema: + type: object + required: [services] + properties: + services: {type: array, items: {$ref: '#/components/schemas/Service'}} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + /api/v1/services/{id}: + parameters: + - {$ref: '#/components/parameters/ResourceId'} + get: + tags: [Services] + summary: Get one service + operationId: getService + x-required-scope: services:read + responses: + '200': + description: Service + content: + application/json: + schema: + type: object + required: [service] + properties: + service: {$ref: '#/components/schemas/Service'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} + /api/v1/services/{id}/metrics: + parameters: + - {$ref: '#/components/parameters/ResourceId'} + get: + tags: [Services] + summary: Read a BGP VM metric series + operationId: getServiceMetrics + x-required-scope: services:read + parameters: + - name: target + in: query + schema: + type: string + enum: [cpu_load, mem_usage_percent, net_rx, net_tx, iops, df.root.used] + default: cpu_load + - name: range + in: query + schema: {type: string, enum: [1h, 6h, 24h, 7d], default: 24h} + responses: + '200': + description: Metric series + content: + application/json: + schema: {$ref: '#/components/schemas/MetricSeries'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} + /api/v1/services/{id}/power: + parameters: + - {$ref: '#/components/parameters/ResourceId'} + post: + tags: [Services] + summary: Start, stop or restart a BGP VM + operationId: powerService + x-required-scope: services:write + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [action] + properties: + action: {type: string, enum: [start, stop, restart]} + responses: + '202': + description: Command accepted + content: + application/json: + schema: + type: object + required: [status, action] + properties: + status: {type: string, const: accepted} + action: {type: string, enum: [start, stop, restart]} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} + '429': {$ref: '#/components/responses/RateLimited'} + /api/v1/traffic: + get: + tags: [Traffic] + summary: Get organisation transit usage + operationId: getTraffic + x-required-scope: traffic:read + parameters: + - {$ref: '#/components/parameters/Days'} + - {$ref: '#/components/parameters/From'} + - {$ref: '#/components/parameters/To'} + responses: + '200': + description: Traffic summary + content: + application/json: + schema: {$ref: '#/components/schemas/Traffic'} + '400': {$ref: '#/components/responses/BadRequest'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + /api/v1/tunnels: + get: + tags: [Tunnels] + summary: List tunnels + operationId: listTunnels + x-required-scope: tunnels:read + responses: + '200': + description: Tunnel list + content: + application/json: + schema: + type: object + required: [tunnels] + properties: + tunnels: {type: array, items: {$ref: '#/components/schemas/Tunnel'}} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + post: + tags: [Tunnels] + summary: Request a transit tunnel + operationId: createTunnel + x-required-scope: tunnels:write + requestBody: + required: true + content: + application/json: + schema: {$ref: '#/components/schemas/CreateTunnelRequest'} + responses: + '202': + description: Tunnel recorded for provisioning + content: + application/json: + schema: + type: object + required: [tunnel] + properties: + tunnel: {$ref: '#/components/schemas/Tunnel'} + '400': {$ref: '#/components/responses/BadRequest'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + /api/v1/tunnels/{id}: + parameters: + - {$ref: '#/components/parameters/ResourceId'} + delete: + tags: [Tunnels] + summary: Remove a tunnel asynchronously + operationId: deleteTunnel + x-required-scope: tunnels:write + responses: + '202': + description: Removal accepted + content: + application/json: + schema: {$ref: '#/components/schemas/StatusResponse'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} + /api/v1/tunnels/{id}/traffic: + parameters: + - {$ref: '#/components/parameters/ResourceId'} + get: + tags: [Traffic, Tunnels] + summary: Get one tunnel's usage + operationId: getTunnelTraffic + x-required-scope: traffic:read + parameters: + - {$ref: '#/components/parameters/Days'} + - {$ref: '#/components/parameters/From'} + - {$ref: '#/components/parameters/To'} + responses: + '200': + description: Tunnel traffic + content: + application/json: + schema: {$ref: '#/components/schemas/TunnelTraffic'} + '400': {$ref: '#/components/responses/BadRequest'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} + /api/v1/geofeeds: + parameters: + - {$ref: '#/components/parameters/OrganizationId'} + get: + tags: [Geofeeds] + summary: List geofeeds + operationId: listGeofeeds + x-required-scope: geofeeds:read + responses: + '200': + description: Geofeed list + content: + application/json: + schema: {$ref: '#/components/schemas/GeofeedList'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + post: + tags: [Geofeeds] + summary: Create a geofeed (maximum two per organisation) + operationId: createGeofeed + x-required-scope: geofeeds:write + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name] + properties: + name: {type: string, minLength: 1, maxLength: 100} + responses: + '201': + description: Created + content: + application/json: + schema: {$ref: '#/components/schemas/GeofeedList'} + '400': {$ref: '#/components/responses/BadRequest'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '409': {$ref: '#/components/responses/Conflict'} + /api/v1/geofeeds/{id}: + parameters: + - {$ref: '#/components/parameters/OrganizationId'} + - {$ref: '#/components/parameters/ResourceId'} + get: + tags: [Geofeeds] + summary: Get a geofeed and its records + operationId: getGeofeed + x-required-scope: geofeeds:read + responses: + '200': + description: Geofeed + content: + application/json: + schema: + type: object + required: [geofeed] + properties: + geofeed: {$ref: '#/components/schemas/GeofeedWithRecords'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} + patch: + tags: [Geofeeds] + summary: Rename a geofeed + operationId: updateGeofeed + x-required-scope: geofeeds:write + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name] + properties: + name: {type: string, minLength: 1, maxLength: 100} + responses: + '200': + description: Updated + content: + application/json: + schema: {$ref: '#/components/schemas/StatusResponse'} + '400': {$ref: '#/components/responses/BadRequest'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} + delete: + tags: [Geofeeds] + summary: Delete a geofeed + operationId: deleteGeofeed + x-required-scope: geofeeds:write + responses: + '200': + description: Deleted + content: + application/json: + schema: {$ref: '#/components/schemas/StatusResponse'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} + /api/v1/geofeeds/{id}/records: + parameters: + - {$ref: '#/components/parameters/OrganizationId'} + - {$ref: '#/components/parameters/ResourceId'} + put: + tags: [Geofeeds] + summary: Atomically replace all RFC 8805 records + operationId: replaceGeofeedRecords + x-required-scope: geofeeds:write + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [records] + properties: + records: + type: array + maxItems: 1000 + items: {$ref: '#/components/schemas/GeofeedRecordInput'} + responses: + '200': + description: Saved + content: + application/json: + schema: {$ref: '#/components/schemas/StatusResponse'} + '400': {$ref: '#/components/responses/BadRequest'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} + /api/v1/geofeeds/{id}/rotate: + parameters: + - {$ref: '#/components/parameters/OrganizationId'} + - {$ref: '#/components/parameters/ResourceId'} + post: + tags: [Geofeeds] + summary: Rotate the unguessable public CSV URL + operationId: rotateGeofeedUrl + x-required-scope: geofeeds:write + responses: + '200': + description: Rotated + content: + application/json: + schema: {$ref: '#/components/schemas/GeofeedList'} + '401': {$ref: '#/components/responses/Unauthenticated'} + '403': {$ref: '#/components/responses/Forbidden'} + '404': {$ref: '#/components/responses/NotFound'} +components: + securitySchemes: + apiKey: + type: http + scheme: bearer + bearerFormat: as213905_… + description: API key from Panel → Settings. Query-string keys are rejected. + parameters: + ResourceId: + name: id + in: path + required: true + schema: {type: string, format: uuid} + OrganizationId: + name: X-Organization-ID + in: header + required: true + description: Organisation UUID. An API key can only address its own organisation. + schema: {type: string, format: uuid} + Days: + name: days + in: query + description: Last N days; mutually exclusive with from/to. + schema: {type: integer, minimum: 1, maximum: 366} + From: + name: from + in: query + schema: {type: string, format: date} + To: + name: to + in: query + description: Inclusive whole-day end. + schema: {type: string, format: date} + responses: + BadRequest: + description: Invalid request + content: {application/json: {schema: {$ref: '#/components/schemas/APIError'}}} + Unauthenticated: + description: Missing, malformed, expired, revoked or unknown API key + content: {application/json: {schema: {$ref: '#/components/schemas/APIError'}}} + Forbidden: + description: Missing scope or disallowed source address + content: {application/json: {schema: {$ref: '#/components/schemas/APIError'}}} + NotFound: + description: Resource not found + content: {application/json: {schema: {$ref: '#/components/schemas/APIError'}}} + Conflict: + description: Resource limit or state conflict + content: {application/json: {schema: {$ref: '#/components/schemas/APIError'}}} + RateLimited: + description: Rate limit exceeded + headers: + Retry-After: {schema: {type: integer}} + content: {application/json: {schema: {$ref: '#/components/schemas/APIError'}}} + schemas: + APIError: + type: object + required: [error] + properties: + error: {type: string, examples: [scope_required]} + message: {type: string} + required_scope: {type: string} + retry_after: {type: integer} + StatusResponse: + type: object + required: [status] + properties: {status: {type: string}} + OrganizationResponse: + type: object + required: [organization] + properties: {organization: {$ref: '#/components/schemas/Organization'}} + Organization: + type: object + required: [id, asn, name, status, commit_kbps] + properties: + id: {type: string, format: uuid} + asn: {type: integer, minimum: 1, maximum: 4294967295} + name: {type: string} + status: {type: string} + commit_kbps: {type: integer, format: int64} + Invoice: + type: object + required: [id, number, status, currency, total_cents] + properties: + id: {type: string, format: uuid} + number: {type: string} + status: {type: string, enum: [draft, issued, paid, overdue, cancelled]} + currency: {type: string, minLength: 3, maxLength: 3} + total_cents: {type: integer, format: int64} + period_from: {type: [string, 'null'], format: date} + period_to: {type: [string, 'null'], format: date} + issued_at: {type: [string, 'null'], format: date-time} + due_at: {type: [string, 'null'], format: date-time} + Service: + type: object + required: [id, kind, label, status, monthly_cents] + properties: + id: {type: string, format: uuid} + kind: {type: string} + label: {type: string} + status: {type: string, enum: [awaiting_payment, provisioning, active, suspended, terminating, terminated]} + monthly_cents: {type: integer, format: int64} + next_due_on: {type: [string, 'null'], format: date} + controllable: {type: boolean} + location: {type: string} + configuration: {type: object, additionalProperties: true} + MetricPoint: + type: object + required: [t] + properties: + t: {type: string, format: date-time} + v: {type: number} + MetricSeries: + type: object + required: [metric, target, range, points] + properties: + metric: {type: string} + target: {type: string} + range: {type: string} + points: {type: array, items: {$ref: '#/components/schemas/MetricPoint'}} + Period: + type: object + required: [from, to, label] + properties: + from: {type: string, format: date-time} + to: {type: string, format: date-time} + label: {type: string} + Traffic: + type: object + required: [p95_kbps, total_bytes, total_gb, period] + properties: + p95_kbps: {type: integer, format: int64} + commit_kbps: {type: integer, format: int64} + over_commit: {type: boolean} + total_bytes: {type: integer, format: int64} + total_gb: {type: number} + period: {$ref: '#/components/schemas/Period'} + Tunnel: + type: object + required: [id, status, location, peer_endpoint] + properties: + id: {type: string, format: uuid} + status: {type: string, enum: [provisioning, configuring, awaiting_peer, active, error, suspended, removed]} + label: {type: string} + location: {type: string, examples: [fra]} + peer_endpoint: {type: string, format: ip} + ifname: {type: string} + inner_v4: {type: string} + inner_v6: {type: string} + announce: {type: boolean} + CreateTunnelRequest: + type: object + required: [peer_endpoint, location] + properties: + peer_endpoint: {type: string, format: ip} + location: {type: string, examples: [fra]} + label: {type: string, maxLength: 100} + announce: {type: boolean, default: false} + TunnelTraffic: + allOf: + - {$ref: '#/components/schemas/Traffic'} + - type: object + required: [tunnel] + properties: {tunnel: {$ref: '#/components/schemas/Tunnel'}} + Geofeed: + type: object + required: [id, name, slug, record_count, created_at, updated_at] + properties: + id: {type: string, format: uuid} + name: {type: string} + slug: {type: string} + record_count: {type: integer, minimum: 0} + created_at: {type: string, format: date-time} + updated_at: {type: string, format: date-time} + GeofeedRecordInput: + type: object + required: [prefix, country_code] + properties: + prefix: {type: string, examples: [203.0.113.0/24]} + country_code: {type: string, pattern: '^[A-Z]{2}$', examples: [DE]} + region_code: {type: string, maxLength: 128, examples: [DE-HE]} + city: {type: string, maxLength: 128, examples: [Frankfurt am Main]} + postal_code: {type: string, maxLength: 128} + GeofeedRecord: + allOf: + - {$ref: '#/components/schemas/GeofeedRecordInput'} + - type: object + properties: {id: {type: string, format: uuid}} + GeofeedWithRecords: + allOf: + - {$ref: '#/components/schemas/Geofeed'} + - type: object + required: [records] + properties: + records: {type: array, items: {$ref: '#/components/schemas/GeofeedRecord'}} + GeofeedList: + type: object + required: [geofeeds, limit] + properties: + geofeeds: {type: array, items: {$ref: '#/components/schemas/Geofeed'}} + limit: {type: integer, const: 2} diff --git a/python/README.md b/python/README.md new file mode 100644 index 0000000..6abf8dc --- /dev/null +++ b/python/README.md @@ -0,0 +1,13 @@ +# Python SDK + +```bash +pip install "as213905 @ git+https://git.datacoria.com/Phylex/as213905-sdk.git#subdirectory=python" +``` + +```python +from as213905 import AS213905 +client = AS213905("as213905_…") +print(client.traffic(days=7)) +``` + +The package has no runtime dependencies and uses the Python standard library. diff --git a/python/pyproject.toml b/python/pyproject.toml new file mode 100644 index 0000000..aa05ecd --- /dev/null +++ b/python/pyproject.toml @@ -0,0 +1,20 @@ +[build-system] +requires = ["hatchling>=1.24"] +build-backend = "hatchling.build" + +[project] +name = "as213905" +version = "1.1.0" +description = "Official AS213905 customer API client" +readme = "README.md" +requires-python = ">=3.9" +license = {text = "MIT"} +authors = [{name = "AS213905", email = "noc@as213905.com"}] +keywords = ["as213905", "bgp", "transit", "geofeed"] + +[project.urls] +Documentation = "https://as213905.com/docs/api/reference" +Repository = "https://git.datacoria.com/Phylex/as213905-sdk" + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/python/src/as213905/__init__.py b/python/src/as213905/__init__.py new file mode 100644 index 0000000..f83b918 --- /dev/null +++ b/python/src/as213905/__init__.py @@ -0,0 +1,4 @@ +from .client import AS213905, APIError + +__all__ = ["AS213905", "APIError"] +__version__ = "1.1.0" diff --git a/python/src/as213905/client.py b/python/src/as213905/client.py new file mode 100644 index 0000000..17c6540 --- /dev/null +++ b/python/src/as213905/client.py @@ -0,0 +1,99 @@ +"""Typed, dependency-free AS213905 API client.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from typing import Any, Iterable, Mapping, Optional +from urllib.error import HTTPError, URLError +from urllib.parse import quote, urlencode +from urllib.request import Request, urlopen + + +@dataclass +class APIError(Exception): + status: int + code: str + message: str = "" + required_scope: Optional[str] = None + retry_after: Optional[int] = None + + def __str__(self) -> str: + detail = f": {self.message}" if self.message else "" + return f"AS213905 API error {self.status} ({self.code}){detail}" + + +class AS213905: + def __init__(self, api_key: str, *, base_url: str = "https://as213905.com", timeout: float = 30.0) -> None: + if not api_key.strip(): + raise ValueError("api_key is required") + self.api_key = api_key + self.base_url = base_url.rstrip("/") + self.timeout = timeout + + def _request(self, method: str, path: str, *, organization_id: Optional[str] = None, body: Any = None) -> Any: + payload = None if body is None else json.dumps(body).encode() + headers = {"Authorization": f"Bearer {self.api_key}", "Accept": "application/json", "User-Agent": "as213905-python/1.1.0"} + if payload is not None: + headers["Content-Type"] = "application/json" + if organization_id: + headers["X-Organization-ID"] = organization_id + request = Request(self.base_url + path, data=payload, headers=headers, method=method) + try: + with urlopen(request, timeout=self.timeout) as response: + raw = response.read() + except HTTPError as exc: + try: + value = json.loads(exc.read()) + except (ValueError, UnicodeDecodeError): + value = {} + retry = value.get("retry_after") or exc.headers.get("Retry-After") + raise APIError(exc.code, value.get("error", "http_error"), value.get("message", ""), value.get("required_scope"), int(retry) if retry else None) from None + except URLError as exc: + raise APIError(0, "network_error", str(exc.reason)) from exc + return json.loads(raw) if raw else None + + @staticmethod + def _traffic_query(days: Optional[int], from_date: Optional[str], to_date: Optional[str]) -> str: + query = {key: value for key, value in (("days", days), ("from", from_date), ("to", to_date)) if value is not None} + return "?" + urlencode(query) if query else "" + + def organization(self) -> Mapping[str, Any]: + return self._request("GET", "/api/v1/organization")["organization"] + def invoices(self) -> list[Mapping[str, Any]]: + return self._request("GET", "/api/v1/invoices")["invoices"] + def services(self) -> list[Mapping[str, Any]]: + return self._request("GET", "/api/v1/services")["services"] + def service(self, service_id: str) -> Mapping[str, Any]: + return self._request("GET", f"/api/v1/services/{quote(service_id, safe='')}" )["service"] + def service_metrics(self, service_id: str, *, target: Optional[str] = None, range: Optional[str] = None) -> Mapping[str, Any]: + query = urlencode({k: v for k, v in (("target", target), ("range", range)) if v is not None}) + return self._request("GET", f"/api/v1/services/{quote(service_id, safe='')}/metrics" + ("?" + query if query else "")) + def power_service(self, service_id: str, action: str) -> Mapping[str, Any]: + return self._request("POST", f"/api/v1/services/{quote(service_id, safe='')}/power", body={"action": action}) + def traffic(self, *, days: Optional[int] = None, from_date: Optional[str] = None, to_date: Optional[str] = None) -> Mapping[str, Any]: + return self._request("GET", "/api/v1/traffic" + self._traffic_query(days, from_date, to_date)) + def tunnels(self) -> list[Mapping[str, Any]]: + return self._request("GET", "/api/v1/tunnels")["tunnels"] + def create_tunnel(self, peer_endpoint: str, location: str, *, label: Optional[str] = None, announce: bool = False) -> Mapping[str, Any]: + body = {"peer_endpoint": peer_endpoint, "location": location, "announce": announce} + if label is not None: body["label"] = label + return self._request("POST", "/api/v1/tunnels", body=body)["tunnel"] + def delete_tunnel(self, tunnel_id: str) -> None: + self._request("DELETE", f"/api/v1/tunnels/{quote(tunnel_id, safe='')}") + def tunnel_traffic(self, tunnel_id: str, *, days: Optional[int] = None, from_date: Optional[str] = None, to_date: Optional[str] = None) -> Mapping[str, Any]: + return self._request("GET", f"/api/v1/tunnels/{quote(tunnel_id, safe='')}/traffic" + self._traffic_query(days, from_date, to_date)) + def geofeeds(self, organization_id: str) -> Mapping[str, Any]: + return self._request("GET", "/api/v1/geofeeds", organization_id=organization_id) + def create_geofeed(self, organization_id: str, name: str) -> Mapping[str, Any]: + return self._request("POST", "/api/v1/geofeeds", organization_id=organization_id, body={"name": name}) + def geofeed(self, organization_id: str, geofeed_id: str) -> Mapping[str, Any]: + return self._request("GET", f"/api/v1/geofeeds/{quote(geofeed_id, safe='')}", organization_id=organization_id)["geofeed"] + def rename_geofeed(self, organization_id: str, geofeed_id: str, name: str) -> None: + self._request("PATCH", f"/api/v1/geofeeds/{quote(geofeed_id, safe='')}", organization_id=organization_id, body={"name": name}) + def delete_geofeed(self, organization_id: str, geofeed_id: str) -> None: + self._request("DELETE", f"/api/v1/geofeeds/{quote(geofeed_id, safe='')}", organization_id=organization_id) + def replace_geofeed_records(self, organization_id: str, geofeed_id: str, records: Iterable[Mapping[str, Any]]) -> None: + self._request("PUT", f"/api/v1/geofeeds/{quote(geofeed_id, safe='')}/records", organization_id=organization_id, body={"records": list(records)}) + def rotate_geofeed_url(self, organization_id: str, geofeed_id: str) -> Mapping[str, Any]: + return self._request("POST", f"/api/v1/geofeeds/{quote(geofeed_id, safe='')}/rotate", organization_id=organization_id) diff --git a/python/tests/test_client.py b/python/tests/test_client.py new file mode 100644 index 0000000..876ea6d --- /dev/null +++ b/python/tests/test_client.py @@ -0,0 +1,28 @@ +import io +import json +import unittest +from unittest.mock import patch + +from as213905 import AS213905, APIError + + +class Response(io.BytesIO): + def __enter__(self): return self + def __exit__(self, *args): return False + + +class ClientTests(unittest.TestCase): + def test_organization_sets_bearer_header(self): + def open_(request, timeout): + self.assertEqual(request.get_header("Authorization"), "Bearer secret") + return Response(json.dumps({"organization": {"asn": 213905}}).encode()) + with patch("as213905.client.urlopen", open_): + self.assertEqual(AS213905("secret").organization()["asn"], 213905) + + def test_traffic_query(self): + client = AS213905("secret") + self.assertEqual(client._traffic_query(7, None, None), "?days=7") + + +if __name__ == "__main__": + unittest.main() diff --git a/rust/Cargo.lock b/rust/Cargo.lock new file mode 100644 index 0000000..a275b91 --- /dev/null +++ b/rust/Cargo.lock @@ -0,0 +1,1277 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "as213905-sdk" +version = "1.1.0" +dependencies = [ + "reqwest", + "serde", + "serde_json", + "serde_urlencoded", + "thiserror", + "tokio", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92a7ed671a6aad807a8651a2e1782a6598fda9ce5185dd8158549e95a91c6428" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0527518605e68109d875e248ea259b6758801cf165e4b2c2733ae3b51f12535a" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94b5c6b5976d66c1d703c4fd17d3f5e43c8cedaacf604961b171adc7130896d8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47402523226a02bfe5230160dc3ccc089aa6f6f19e7fcbb4e6f824bbb1b4aa62" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/rust/Cargo.toml b/rust/Cargo.toml new file mode 100644 index 0000000..ac899f6 --- /dev/null +++ b/rust/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "as213905-sdk" +version = "1.1.0" +edition = "2021" +license = "MIT" +description = "Official AS213905 customer API client" +repository = "https://git.datacoria.com/Phylex/as213905-sdk" + +[dependencies] +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +serde_urlencoded = "0.7" +thiserror = "2" + +[dev-dependencies] +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } diff --git a/rust/README.md b/rust/README.md new file mode 100644 index 0000000..de6dba9 --- /dev/null +++ b/rust/README.md @@ -0,0 +1,10 @@ +# Rust SDK + +```toml +[dependencies] +as213905-sdk = { git = "https://git.datacoria.com/Phylex/as213905-sdk.git" } +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +``` + +The async client uses `reqwest` with rustls and exposes typed models for every +documented operation. diff --git a/rust/examples/quickstart.rs b/rust/examples/quickstart.rs new file mode 100644 index 0000000..a088807 --- /dev/null +++ b/rust/examples/quickstart.rs @@ -0,0 +1,12 @@ +use as213905_sdk::Client; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let client = Client::new(std::env::var("AS213905_API_KEY")?); + let traffic = client.traffic(Some(7), None, None).await?; + println!( + "p95: {} kbit/s, volume: {:.2} GB", + traffic.p95_kbps, traffic.total_gb + ); + Ok(()) +} diff --git a/rust/src/lib.rs b/rust/src/lib.rs new file mode 100644 index 0000000..473f2bf --- /dev/null +++ b/rust/src/lib.rs @@ -0,0 +1,478 @@ +use reqwest::{Method, StatusCode}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use std::time::Duration; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("AS213905 API error {status}: {code}: {message}")] + Api { + status: StatusCode, + code: String, + message: String, + required_scope: Option, + }, + #[error("HTTP client error: {0}")] + Http(#[from] reqwest::Error), + #[error("invalid base URL: {0}")] + InvalidBaseUrl(String), +} + +#[derive(Clone)] +pub struct Client { + api_key: String, + base_url: String, + http: reqwest::Client, +} + +impl Client { + pub fn new(api_key: impl Into) -> Self { + Self::with_base_url(api_key, "https://as213905.com").expect("built-in URL is valid") + } + pub fn with_base_url( + api_key: impl Into, + base_url: impl AsRef, + ) -> Result { + let parsed = reqwest::Url::parse(base_url.as_ref()) + .map_err(|e| Error::InvalidBaseUrl(e.to_string()))?; + let http = reqwest::Client::builder() + .timeout(Duration::from_secs(30)) + .user_agent("as213905-rust/1.1.0") + .build()?; + Ok(Self { + api_key: api_key.into(), + base_url: parsed.as_str().trim_end_matches('/').to_owned(), + http, + }) + } + async fn request( + &self, + method: Method, + path: &str, + org: Option<&str>, + body: Option<&B>, + ) -> Result { + let mut request = self + .http + .request(method, format!("{}{}", self.base_url, path)) + .bearer_auth(&self.api_key) + .header("Accept", "application/json"); + if let Some(value) = org { + request = request.header("X-Organization-ID", value); + } + if let Some(value) = body { + request = request.json(value); + } + let response = request.send().await?; + let status = response.status(); + if !status.is_success() { + let value: APIErrorBody = response.json().await.unwrap_or_default(); + return Err(Error::Api { + status, + code: value.error.unwrap_or_else(|| "http_error".into()), + message: value.message.unwrap_or_default(), + required_scope: value.required_scope, + }); + } + Ok(response.json().await?) + } + async fn empty( + &self, + method: Method, + path: &str, + org: Option<&str>, + body: Option<&B>, + ) -> Result<(), Error> { + let _: serde_json::Value = self.request(method, path, org, body).await?; + Ok(()) + } + pub async fn organization(&self) -> Result { + Ok(self + .request::( + Method::GET, + "/api/v1/organization", + None, + None, + ) + .await? + .organization) + } + pub async fn invoices(&self) -> Result, Error> { + Ok(self + .request::(Method::GET, "/api/v1/invoices", None, None) + .await? + .invoices) + } + pub async fn services(&self) -> Result, Error> { + Ok(self + .request::(Method::GET, "/api/v1/services", None, None) + .await? + .services) + } + pub async fn service(&self, id: &str) -> Result { + Ok(self + .request::( + Method::GET, + &format!("/api/v1/services/{id}"), + None, + None, + ) + .await? + .service) + } + pub async fn service_metrics( + &self, + id: &str, + target: Option<&str>, + range: Option<&str>, + ) -> Result { + let mut q = vec![]; + if let Some(v) = target { + q.push(("target", v)) + }; + if let Some(v) = range { + q.push(("range", v)) + }; + let s = serde_urlencoded::to_string(q).unwrap_or_default(); + self.request::( + Method::GET, + &format!( + "/api/v1/services/{id}/metrics{}{}", + if s.is_empty() { "" } else { "?" }, + s + ), + None, + None, + ) + .await + } + pub async fn power_service( + &self, + id: &str, + action: PowerAction, + ) -> Result { + self.request( + Method::POST, + &format!("/api/v1/services/{id}/power"), + None, + Some(&PowerRequest { action }), + ) + .await + } + pub async fn traffic( + &self, + days: Option, + from: Option<&str>, + to: Option<&str>, + ) -> Result { + self.request::( + Method::GET, + &traffic_path("/api/v1/traffic", days, from, to), + None, + None, + ) + .await + } + pub async fn tunnels(&self) -> Result, Error> { + Ok(self + .request::(Method::GET, "/api/v1/tunnels", None, None) + .await? + .tunnels) + } + pub async fn create_tunnel(&self, input: &CreateTunnel) -> Result { + Ok(self + .request::( + Method::POST, + "/api/v1/tunnels", + None, + Some(input), + ) + .await? + .tunnel) + } + pub async fn delete_tunnel(&self, id: &str) -> Result<(), Error> { + self.empty::( + Method::DELETE, + &format!("/api/v1/tunnels/{id}"), + None, + None, + ) + .await + } + pub async fn tunnel_traffic( + &self, + id: &str, + days: Option, + from: Option<&str>, + to: Option<&str>, + ) -> Result { + self.request::( + Method::GET, + &traffic_path(&format!("/api/v1/tunnels/{id}/traffic"), days, from, to), + None, + None, + ) + .await + } + pub async fn geofeeds(&self, org: &str) -> Result { + self.request::( + Method::GET, + "/api/v1/geofeeds", + Some(org), + None, + ) + .await + } + pub async fn create_geofeed(&self, org: &str, name: &str) -> Result { + self.request( + Method::POST, + "/api/v1/geofeeds", + Some(org), + Some(&NameRequest { name }), + ) + .await + } + pub async fn geofeed(&self, org: &str, id: &str) -> Result { + Ok(self + .request::( + Method::GET, + &format!("/api/v1/geofeeds/{id}"), + Some(org), + None, + ) + .await? + .geofeed) + } + pub async fn rename_geofeed(&self, org: &str, id: &str, name: &str) -> Result<(), Error> { + self.empty( + Method::PATCH, + &format!("/api/v1/geofeeds/{id}"), + Some(org), + Some(&NameRequest { name }), + ) + .await + } + pub async fn delete_geofeed(&self, org: &str, id: &str) -> Result<(), Error> { + self.empty::( + Method::DELETE, + &format!("/api/v1/geofeeds/{id}"), + Some(org), + None, + ) + .await + } + pub async fn replace_geofeed_records( + &self, + org: &str, + id: &str, + records: &[GeofeedRecord], + ) -> Result<(), Error> { + self.empty( + Method::PUT, + &format!("/api/v1/geofeeds/{id}/records"), + Some(org), + Some(&RecordsRequest { records }), + ) + .await + } + pub async fn rotate_geofeed_url(&self, org: &str, id: &str) -> Result { + self.request::( + Method::POST, + &format!("/api/v1/geofeeds/{id}/rotate"), + Some(org), + None, + ) + .await + } +} + +fn traffic_path(base: &str, days: Option, from: Option<&str>, to: Option<&str>) -> String { + let mut q = vec![]; + if let Some(v) = days { + q.push(("days", v.to_string())) + }; + if let Some(v) = from { + q.push(("from", v.to_owned())) + }; + if let Some(v) = to { + q.push(("to", v.to_owned())) + }; + let s = serde_urlencoded::to_string(q).unwrap_or_default(); + format!("{base}{}{}", if s.is_empty() { "" } else { "?" }, s) +} +#[derive(Default, Deserialize)] +struct APIErrorBody { + error: Option, + message: Option, + required_scope: Option, +} +#[derive(Deserialize)] +struct OrganizationResponse { + organization: Organization, +} +#[derive(Deserialize)] +struct InvoiceList { + invoices: Vec, +} +#[derive(Deserialize)] +struct ServiceList { + services: Vec, +} +#[derive(Deserialize)] +struct ServiceResponse { + service: Service, +} +#[derive(Deserialize)] +struct TunnelList { + tunnels: Vec, +} +#[derive(Deserialize)] +struct TunnelResponse { + tunnel: Tunnel, +} +#[derive(Deserialize)] +struct GeofeedResponse { + geofeed: Geofeed, +} +#[derive(Serialize)] +struct PowerRequest { + action: PowerAction, +} +#[derive(Serialize)] +struct NameRequest<'a> { + name: &'a str, +} +#[derive(Serialize)] +struct RecordsRequest<'a> { + records: &'a [GeofeedRecord], +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Organization { + pub id: String, + pub asn: u32, + pub name: String, + pub status: String, + pub commit_kbps: i64, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Invoice { + pub id: String, + pub number: String, + pub status: String, + pub currency: String, + pub total_cents: i64, + pub period_from: Option, + pub period_to: Option, + pub issued_at: Option, + pub due_at: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Service { + pub id: String, + pub kind: String, + pub label: String, + pub status: String, + pub monthly_cents: i64, + pub next_due_on: Option, + #[serde(default)] + pub controllable: bool, + pub location: Option, + pub configuration: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MetricPoint { + pub t: String, + pub v: Option, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MetricSeries { + pub metric: String, + pub target: String, + pub range: String, + pub points: Vec, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Period { + pub from: String, + pub to: String, + pub label: String, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Traffic { + pub p95_kbps: i64, + #[serde(default)] + pub commit_kbps: i64, + #[serde(default)] + pub over_commit: bool, + pub total_bytes: i64, + pub total_gb: f64, + pub period: Period, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Tunnel { + pub id: String, + pub status: String, + pub label: Option, + pub location: String, + pub peer_endpoint: String, + pub ifname: Option, + pub inner_v4: Option, + pub inner_v6: Option, + #[serde(default)] + pub announce: bool, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TunnelTraffic { + #[serde(flatten)] + pub traffic: Traffic, + pub tunnel: Tunnel, +} +#[derive(Debug, Clone, Serialize)] +pub struct CreateTunnel { + pub peer_endpoint: String, + pub location: String, + pub label: Option, + pub announce: Option, +} +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum PowerAction { + Start, + Stop, + Restart, +} +#[derive(Debug, Clone, Deserialize)] +pub struct StatusAction { + pub status: String, + pub action: PowerAction, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GeofeedRecord { + #[serde(default, skip_serializing_if = "String::is_empty")] + pub id: String, + pub prefix: String, + pub country_code: String, + #[serde(default)] + pub region_code: String, + #[serde(default)] + pub city: String, + #[serde(default)] + pub postal_code: String, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Geofeed { + pub id: String, + pub name: String, + pub slug: String, + #[serde(default)] + pub record_count: u32, + pub created_at: String, + pub updated_at: String, + #[serde(default)] + pub records: Vec, +} +#[derive(Debug, Clone, Deserialize)] +pub struct GeofeedList { + pub geofeeds: Vec, + pub limit: u8, +}