squarecloud

package module
v4.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Square Cloud Banner

sdk-api-go

The official Go SDK for the Square Cloud API.

Go Reference License
  • Zero runtime dependencies.
  • Runs on Go 1.22 or newer. Every method takes a context.Context, and a *Client is safe for concurrent use.
  • Covers all 69 operations of the Square Cloud API, checked against the pinned OpenAPI spec on every CI run.
  • Uploads and snapshot downloads stream without loading files into memory, and realtime logs and usage arrive through an iterator (Next).
  • One error type, *APIError, for every API, network and local failure.

Documentation · Releases · Migration guide

Installation

go get github.com/squarecloudofc/sdk-api-go/v4

The SDK needs Go 1.22 or newer.

API key

Create an API key at squarecloud.app/account/security. You can limit a key to some scopes, such as apps:read or apps:deploy, and to some applications or databases. A call outside those limits returns an *APIError with 403 MISSING_SCOPE or RESOURCE_NOT_ALLOWED, and listings return only the resources that the key can see.

Quick start

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/squarecloudofc/sdk-api-go/v4"
)

func main() {
	ctx := context.Background()
	c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))

	me, err := c.Account.Me(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Hi %s, you have %d apps\n", me.User.Name, len(me.Applications))
	if len(me.Applications) == 0 {
		return
	}

	appID := me.Applications[0].ID
	if err := c.Apps.Restart(ctx, appID); err != nil {
		log.Fatal(err)
	}
	logs, err := c.Apps.Logs(ctx, appID)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(logs)
}

Every method takes ctx first, then the ids. Create one *Client and share it, because it is safe for concurrent use. example_test.go has more examples.

Configuration

c := squarecloud.New(key,
	squarecloud.WithBaseURL(url),            // default squarecloud.DefaultBaseURL
	squarecloud.WithTimeout(30*time.Second), // default 30 seconds
	squarecloud.WithMaxRetries(2),           // default 2
	squarecloud.WithHTTPClient(hc),          // default &http.Client{}
	squarecloud.WithUserAgent("my-tool/1"),  // default "squarecloud-sdk-go/<Version>"
)
Option Default Notes
apiKey, the first argument of New required New cannot return an error. With an empty or whitespace-only key, every call except Service.Status fails with INVALID_API_KEY without sending anything.
WithBaseURL(u) DefaultBaseURL Sends the requests to a proxy or a test server instead of the Square Cloud API. A trailing / is removed.
WithTimeout(d) 30 seconds Applies only when ctx has no deadline. A value of 0 or less turns every time limit off, including the 2-minute minimum of long calls. See Retries, timeouts and rate limits.
WithMaxRetries(n) 2 A negative n counts as 0.
WithHTTPClient(hc) &http.Client{} nil keeps the default. Do not set hc.Timeout, because it would cut realtime streams and large downloads.
WithUserAgent(ua) squarecloud-sdk-go/<Version> Replaces the whole User-Agent header.

The SDK never logs. To trace requests, wrap the http.RoundTripper of the client you pass to WithHTTPClient.

API

Wherever a method takes an application id, you can pass the composite id "<appId>-<workspaceId>" instead. It acts on an application that another account shares with you through a workspace.

Group Methods
c.Account Me, Snapshots(scope)
c.Service Status (works without an API key)
c.AI Chat (OpenAI format, without streaming)
c.Apps Create(zip), Get, Delete, StatusAll(workspaceID), Status, StatusRaw, Start, Stop, Restart, Logs, Metrics(id, rng), Realtime, Domains, LoadBalancers, Commit(id, r, path, filename)
c.Apps.Deploys SetWebhook(id, accessToken), LinkGithubApp(id, repository, branch), UnlinkGithubApp, List, Current
c.Apps.Envs Get, Set(id, envs) (merge), Replace(id, envs), Delete(id, keys...)
c.Apps.Files List(id, path), Read(id, path) → []byte, Write(id, path, content), Move(id, path, to), Delete(id, path)
c.Apps.Snapshots List, Create, Restore(id, name, versionID), RestoreState
c.Apps.Network Analytics(id, start, end, filters), Errors(id, start, end, include4xx), Logs(id, start, end), Performance(id, start, end), DNS, SetDomain(id, domain), PurgeCache
c.Databases Create(DatabaseCreate), Get, Update(id, DatabaseUpdate), Delete, Start, Stop, Status, StatusRaw, Metrics(id, rng), StatusAll, Certificate, ResetCredentials(id, ResetPassword | ResetCertificate) → the new password, or ""
c.Databases.Snapshots List, Create, Restore(id, name, versionID), RestoreState
c.Workspaces Create(name), List, Get, Delete, Leave
c.Workspaces.Members Add(workspaceID, code, group), Update(workspaceID, memberID, group), Remove(workspaceID, memberID), InviteCode
c.Workspaces.Apps Add(workspaceID, appID), Remove(workspaceID, appID)
c DownloadSnapshot(ctx, url, w)
  • Types are structs whose fields follow the API's names, such as CreatedAt for created_at, so the API reference applies as it is. Fields that the API can send as null are pointers.
  • start and end are time.Time values, and the SDK sends them in UTC.
  • An id that is empty, . or .. fails with INVALID_ID before anything is sent, because it would reach a different operation.
  • Network.Analytics, Errors and Performance return nil when nothing was served in the period. An analytics provider is written as "NAME (ASN)", such as "GOOGLE (15169)", and the Provider filter takes that exact value. A filter that the API does not accept returns 400 INVALID_FILTER.
  • Metrics returns the newest point first. rng is "24h", the default that "" also gets, or "7d". With "7d", the Pro and Enterprise plans get hourly points with the hour's average and peaks (CPUMax, RAMMax) for applications of 512 MB or more. Other plans and smaller applications get the 24-hour answer without an error, so check the points instead of assuming 7 days. Any other rng returns 400 INVALID_PARAMETERS. Applications below 512 MB get a point every 10 minutes, where they used to get 400 METRICS_NOT_SUPPORTED.
  • Service.Status also lists the open Incidents and the Components that are not fully working. Its Status "unknown" means that the check could not run, not that the platform is down.

Usage

Uploads

Apps.Create and Apps.Commit take an io.Reader and stream it, so the file is never loaded into memory. A commit unpacks a .zip into path, where "" is the application's root directory, and writes any other file to path/<filename>. The file name is the filename argument, or else the name of the *os.File, or else app.zip for a create and commit.zip for a commit. A zip over 100 MB fails with FILE_TOO_LARGE. When its size is known, as for an *os.File, nothing is sent. Otherwise the upload stops as soon as it passes 100 MB. Uploads have no time limit, so cancel ctx to stop one.

f, err := os.Open("app.zip")
if err != nil {
	log.Fatal(err)
}
defer f.Close()
app, err := c.Apps.Create(ctx, f)
if err != nil {
	log.Fatal(err)
}

patch, err := os.Open("main.py")
if err != nil {
	log.Fatal(err)
}
defer patch.Close()
err = c.Apps.Commit(ctx, app.ID, patch, "src", "") // The file lands at src/main.py.

Files

data, err := c.Apps.Files.Read(ctx, appID, "/package.json")
err = c.Apps.Files.Write(ctx, appID, "/logo.png", pngBytes)
err = c.Apps.Files.Move(ctx, appID, "/logo.png", "/assets/logo.png")

Read and Write keep text and binary files intact, byte for byte, and empty content creates an empty file. Write fails with FILE_TOO_LARGE before sending content over 10 MB, so upload larger files with Apps.Commit. The API returns 400 WRITE_FAILED when it cannot write the file. Content over 1 MiB has no time limit, like an upload. Read returns 413 FILE_TOO_LARGE for a file over 10 MB, and 400 READ_FAILED for a file the server cannot read. List returns 404 FILE_NOT_FOUND for a missing directory and 403 BLOCKED_PATH for a protected one. Paths are at most 256 characters long.

Snapshots

Create returns Pending: true while the snapshot is still being taken, which is not an error. The snapshot then appears in List on its own, usually within 2 minutes. Poll List and do not call Create again, because Create allows one call every 3 minutes and each call counts against your plan's daily snapshot quota.

snap, err := c.Apps.Snapshots.Create(ctx, appID)
if err != nil {
	log.Fatal(err)
}
if !snap.Pending {
	out, err := os.Create("backup.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer out.Close()
	err = c.DownloadSnapshot(ctx, snap.URL, out) // Streamed to the file, never held in memory.
	if err != nil {
		log.Fatal(err)
	}
}

list, err := c.Apps.Snapshots.List(ctx, appID)
res, err := c.Apps.Snapshots.Restore(ctx, appID, list[0].Name, list[0].VersionID)
st := squarecloud.SnapshotRestoreState{State: "success"}
for res.Pending { // Still running. Follow it, and never call Restore again.
	time.Sleep(10 * time.Second)
	if st, err = c.Apps.Snapshots.RestoreState(ctx, appID); err != nil {
		log.Fatal(err)
	}
	res.Pending = st.State == "queued" || st.State == "running"
}
switch st.State {
case "success":
	fmt.Println("restored")
case "error":
	log.Fatal("restore failed: ", st.Code)
default: // "none" means that the result is no longer available.
	fmt.Println("restore result unknown")
}

Every listed Snapshot has a VersionID, which Restore takes, and a URL, a download link for DownloadSnapshot that is valid for 1 hour. Only Create can return an empty URL and Key, when the API key lacks the snapshots:read scope. Listings return 503 SNAPSHOTS_UNAVAILABLE while snapshot storage cannot answer, where they used to return an empty list. DownloadSnapshot never sends your API key with the download and never puts the link in its errors. It has no time limit, so cancel ctx to stop it.

A restore that takes longer than about 90 seconds keeps running after the call returns. Restore then returns Pending: true, which is not an error. RestoreState reports the last restore. Its state is queued or running while the restore runs, with the current Step, and then success or error, with a Code, for 1 hour after it ends. It is none when there was no recent restore. RestoreState allows 30 calls a minute, so poll it every few seconds.

A restore can fail with these errors:

  • 400 MISSING_PARAMETERS, INVALID_SNAPSHOT_ID or INVALID_VERSION_ID, and SNAPSHOT_DATABASE_MISMATCH for databases.
  • 404 APP_NOT_FOUND or DATABASE_NOT_FOUND, SNAPSHOT_NOT_FOUND, SNAPSHOT_RESTORE_FAILED, SNAPSHOT_CORRUPT, RESTORE_INTERRUPTED or CONTAINER_NOT_FOUND.
  • 409 RESTORE_IN_PROGRESS or SNAPSHOT_IN_PROGRESS, while another restore or a snapshot is running.
  • 413 PAYLOAD_TOO_LARGE.
  • 503 CLUSTER_MAINTENANCE_TRY_LATER, during maintenance.

Snapshot Create can also return 409 RESTORE_IN_PROGRESS and 503 CLUSTER_MAINTENANCE_TRY_LATER.

Realtime

s, err := c.Apps.Realtime(ctx, appID)
if err != nil {
	log.Fatal(err)
}
defer s.Close()
for {
	ev, err := s.Next()
	if err != nil {
		break // The error is io.EOF when the stream ends normally.
	}
	switch ev.Event {
	case "logs":
		fmt.Println(ev.Stream, ev.Line) // Stream is "stdout" or "stderr".
	case "status":
		fmt.Println(ev.Status.CPU) // Status is never nil and holds the full state.
	default: // A "system" or "error" event.
		fmt.Println(ev.Data) // A code such as REALTIME_DISCONNECTED.
	}
}

Every event has Event, Data, which is the text the server sent, and ID. When the stream cannot open, Realtime returns the error before any event, such as 429 REALTIME_MAX_CONNECTIONS. When the connection drops, or the server sends REALTIME_RECONNECT, the stream reopens by itself, up to 3 times in a row. A logs or status event resets that count. The API allows one open per application every 5 seconds, so each reopen waits until at least 5.5 seconds have passed since the previous one. When the reopens run out, Next returns NETWORK_ERROR. The client timeout applies only until the stream opens, and after that only ctx limits it. The loop ends when the server closes the stream after its 10-minute limit, after a REALTIME_DISCONNECTED event, or when you cancel ctx. You can have at most 5 streams open per account and 30 per application.

GitHub deploys

// Deploy from a GitHub webhook. SetWebhook returns the URL to add on GitHub,
// or "" after "@" removes the webhook.
url, err := c.Apps.Deploys.SetWebhook(ctx, appID, "ghp_xxx")

// Or deploy through the Square Cloud GitHub App.
repo, err := c.Apps.Deploys.LinkGithubApp(ctx, appID, "octocat/hello-world", "main")
fmt.Println(repo.ID, repo.FullName, repo.Branch)

cur, err := c.Apps.Deploys.Current(ctx, appID) // The zero value when nothing is set up.
err = c.Apps.Deploys.UnlinkGithubApp(ctx, appID)

Linking needs the apps:deploy scope and a GitHub account connected to Square Cloud, or it returns 403 GITHUB_NOT_CONNECTED. Your GitHub account must have the Square Cloud GitHub App installed on the repository, or the call returns 403 REPOSITORY_NOT_AVAILABLE. It must also be able to write to the repository, or the call returns 403 REPOSITORY_PERMISSION_REQUIRED. A 502 FAILED_TO_FETCH means that GitHub did not confirm the branch, and it is safe to try again. When another application, of any account, already deploys from the same repository and branch, the call returns 409 REPOSITORY_BRANCH_ALREADY_CONFIGURED. Its Message names that application only when it is yours. To link a different repository, unlink first, or the call returns 400 GIT_ALREADY_CONFIGURED. Unlinking without a link returns 400 GIT_NOT_CONFIGURED. Linking and unlinking share a limit of 3 calls a minute.

Errors

Every API, network and local failure is an *APIError with these fields:

  • Status, the HTTP status, or 0 when no response arrived.
  • Code, such as APP_NOT_FOUND.
  • Message, the server's explanation, or "" when it sent only a code.
  • Method and Path. Path never includes the query string.
  • The cause, which Unwrap() returns.

When you cancel ctx, errors.Is(err, context.Canceled) reports true. A few mistakes in the arguments return a plain error instead. They are a nil upload reader, a snapshot link or base URL that cannot be parsed, a value that encoding/json cannot encode, and an error from the io.Writer given to DownloadSnapshot.

_, err := c.Apps.Get(ctx, appID)
var apiErr *squarecloud.APIError
if errors.As(err, &apiErr) && apiErr.Code == squarecloud.CodeMissingScope {
	fmt.Println(apiErr.Message) // Names the scope that the key lacks.
}
  • When no response arrives, Status is 0 and Code is NETWORK_ERROR or TIMEOUT. Unwrap returns the original error.
  • Local checks send nothing and leave Status at 0. They return FILE_TOO_LARGE, INVALID_ID for an id that is empty, . or .., and INVALID_API_KEY for an empty key. Their Message says what to fix.
  • A response without a code, such as a proxy page or a failed snapshot download, gets UNKNOWN_ERROR with the message HTTP <status>. A successful response whose body is not JSON gets UNKNOWN_ERROR with the message Invalid JSON in HTTP <status> response.
  • An API key that is missing, unknown, revoked or expired gets 401 ACCESS_DENIED.
  • When Start, Stop or Restart cannot act, it returns 409 with a code and no message. The codes are CONTAINER_ALREADY_STARTED, CONTAINER_ALREADY_STOPPED, CONTAINER_TEMPORARILY_SUSPENDED for applications, CONTAINER_NOT_FOUND, CONTAINER_INSUFFICIENT_DISK_SPACE, CONTAINER_NETWORK_CONFLICT, ACTION_FAILED and RESTORE_IN_PROGRESS. The SDK returns an "already started" or "already stopped" answer as an error like any other, so treat it as success in your code when that is what you need.
  • RESTORE_IN_PROGRESS is 409 while a snapshot restore holds the application or database. Delete, start and stop of applications and databases, application restart, and snapshot Create and Restore can return it. On delete and on database start and stop it used to be 403. A concurrent write to environment variables returns 409 ENV_BUSY. The SDK retries none of them.
  • A successful response whose body reports an error fails too. A 202 is never an error. SNAPSHOT_PROCESSING becomes SnapshotCreated{Pending: true}, and SNAPSHOT_RESTORE_PROCESSING becomes SnapshotRestored{Pending: true}.
  • Every AI.Chat error follows the OpenAI format, including authentication errors, 429 and 503. Code is its lowercase code, such as access_denied, upgrade_required, rate_limit_exceeded, weekly_limit_reached, database_unavailable or server_overloaded, or its type when there is no code.
  • Error() returns squarecloud: <METHOD> <path>: HTTP <status> <CODE>: <message>. It leaves out HTTP <status> when the status is 0, and : <message> when the message is empty.
  • There is a Code* constant for every code that the API documents, checked against the spec in CI, and for the SDK's own codes. The API can add codes, so handle a code you do not know by its HTTP status.

Retries, timeouts and rate limits

  • Timeouts. WithTimeout, 30 seconds by default, applies only when ctx has no deadline, and one limit covers every attempt of a call. Calls that the API can hold open get at least 2 minutes. They are Start, Stop and Restart of applications and databases, Databases.Create, and snapshot Create and Restore. AI.Chat also gets at least 2 minutes. The AI answers within 90 seconds or returns 503 server_overloaded, which is safe to try again, but the SDK does not retry it. A longer timeout wins over the 2-minute minimum, and WithTimeout(0) turns every time limit off. Uploads, Files.Write over 1 MiB and DownloadSnapshot have no time limit, so cancel ctx to stop them. Realtime applies the timeout only until the stream opens.
  • Retries. The SDK repeats a call only when that is safe, up to WithMaxRetries times, 2 by default. It waits longer before each new attempt, starting below half a second and doubling up to 8 seconds, with some randomness. It repeats network errors on GET requests, including a response cut off midway, a realtime open, and a snapshot download that has not started. It repeats 503 UPLOAD_BUSY and ANALYTICS_BUSY on any request, because the API refused those before doing any work. It repeats 503 DATABASE_UNAVAILABLE only on GET requests, because on other methods the change may already have started. You can repeat an idempotent change yourself. An upload is repeated only when its reader can be read again, such as an *os.File. The SDK never repeats a timeout or a 429. It does not repeat 503 SNAPSHOTS_UNAVAILABLE, for which the API asks you to wait about 30 seconds, or 503 CLUSTER_MAINTENANCE_TRY_LATER, which lasts minutes. It does not repeat a 409 from a busy resource either, such as RESTORE_IN_PROGRESS, SNAPSHOT_IN_PROGRESS or ENV_BUSY. You decide when to try those again.
  • Rate limits. Every account has a limit of requests per minute, set by its plan (values). Going over it, or over the limit of a single operation, returns 429 RATE_LIMITED or KEEP_CALM. RATE_LIMITED can block the account, API key or IP address for 30 minutes. It also replaces RATE_LIMIT_EXCEEDED on the network calls and on Account.Snapshots. CodeRateLimit and CodeRateLimitExceeded remain, marked deprecated. The API does not say when to try again, which is why the SDK never retries a 429.

Development

gofmt -l . && go vet ./... && go run honnef.co/go/tools/cmd/staticcheck@v0.8.1 ./...
go test -race -count=1 ./...   # offline, against a local test server only

The offline suites (transport_test.go, streams_test.go, conformance_test.go) never reach the API. The live suite runs all 69 operations against the real API:

SQUARECLOUD_API_KEY=... go test -tags live -run TestLive -count=1 -timeout 30m .

Warning: the live suite creates and deletes real resources on the key's account. They are an application, a database and a workspace named sdk-live-go-<timestamp>. The suite is skipped without SQUARECLOUD_API_KEY and never runs in CI. It spaces its requests 2.1 seconds apart, so run the JS, Python and Go live suites one after another, never at the same time.

Contributing

Issues and pull requests are welcome at squarecloudofc/sdk-api-go.

License

MIT, see LICENSE.

Authors

Maintained by Square Cloud.

Contributors:

Documentation

Overview

Package squarecloud is the official Go SDK for the Square Cloud API.

Create a Client with your API key and call the API through its groups, such as Account, Apps, Databases and Workspaces:

ctx := context.Background()
c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))

me, err := c.Account.Me(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(me.User.Name, len(me.Applications))

Every method takes a context.Context first. Cancel it, or give it a deadline, to stop a call. A Client is safe for concurrent use, so create one and share it.

A failed call returns an *APIError. Use errors.As to read its HTTP status and error code.

Example
ctx := context.Background()
c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))

me, err := c.Account.Me(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(me.User.Name, me.User.Plan.Name, len(me.Applications))

// For an application shared with you through a workspace, use its
// composite id instead (see AppsAPI).
appID := "a1b2c3d4e5f60718293a4b5c6d7e8f90"
if err := c.Apps.Restart(ctx, appID); err != nil {
	var apiErr *squarecloud.APIError
	if errors.As(err, &apiErr) {
		log.Fatalf("%s (HTTP %d): %s", apiErr.Code, apiErr.Status, apiErr.Message)
	}
	log.Fatal(err)
}

Index

Examples

Constants

View Source
const (
	// Version is the version of this SDK. It is part of the default
	// User-Agent header.
	Version = "4.0.0"
	// DefaultBaseURL is the address of the Square Cloud API. Use
	// [WithBaseURL] to send requests somewhere else, such as a proxy or a
	// test server.
	DefaultBaseURL = "https://api.squarecloud.app/v2"
)
View Source
const (
	// CodeNetworkError means that no complete response arrived, for example
	// because the connection dropped. [APIError.Unwrap] returns the cause.
	CodeNetworkError = "NETWORK_ERROR"
	// CodeTimeout means that the context deadline or the client timeout
	// passed before the call finished. See [WithTimeout].
	CodeTimeout = "TIMEOUT"
	// CodeUnknown means that the response had no error code, such as an error
	// page from a proxy, or that a successful response was not valid JSON.
	CodeUnknown = "UNKNOWN_ERROR"
	// CodeInvalidAPIKey means that [New] got an empty API key, so the call
	// was not sent.
	CodeInvalidAPIKey = "INVALID_API_KEY"

	// CodeRateLimit is the former code of the account rate limit.
	//
	// Deprecated: The API sends [CodeRateLimited] instead.
	CodeRateLimit = "RATE_LIMIT"
	// CodeRateLimitExceeded is the former code of the rate limit on the
	// network calls and on [AccountAPI.Snapshots].
	//
	// Deprecated: The API sends [CodeRateLimited] instead.
	CodeRateLimitExceeded = "RATE_LIMIT_EXCEEDED"
	// CodeMetricsNotSupported was the answer to Metrics for applications with
	// less than 512 MB.
	//
	// Deprecated: The API no longer sends it. Applications with less than
	// 512 MB now get a metrics point every 10 minutes.
	CodeMetricsNotSupported = "METRICS_NOT_SUPPORTED"
)

Codes that the SDK sets itself. They come with Status 0, except CodeUnknown, which comes with the HTTP status of the response.

View Source
const (
	// CodeAccessDenied comes with 401 when the API key is missing, unknown,
	// revoked or expired.
	CodeAccessDenied = "ACCESS_DENIED"
	// CodeActionFailed comes with 409 when Start, Stop or Restart could not
	// complete the action.
	CodeActionFailed           = "ACTION_FAILED"
	CodeAIDailyLimitReached    = "AI_DAILY_LIMIT_REACHED"
	CodeAIMaxConcurrentStreams = "AI_MAX_CONCURRENT_STREAMS"
	CodeAINoPlanLimitReached   = "AI_NO_PLAN_LIMIT_REACHED"
	CodeAIUnavailable          = "AI_UNAVAILABLE"
	CodeAIWeeklyLimitReached   = "AI_WEEKLY_LIMIT_REACHED"
	// CodeAnalyticsBusy comes with 503 when the API refused a network call
	// before doing any work. The SDK retries it.
	CodeAnalyticsBusy                  = "ANALYTICS_BUSY"
	CodeApplicationsLimitReached       = "APPLICATIONS_LIMIT_REACHED"
	CodeAppAlreadyInWorkspace          = "APP_ALREADY_IN_WORKSPACE"
	CodeAppNotFound                    = "APP_NOT_FOUND"
	CodeBlockedPath                    = "BLOCKED_PATH"
	CodeBranchNotFound                 = "BRANCH_NOT_FOUND"
	CodeCannotEditOwner                = "CANNOT_EDIT_OWNER"
	CodeCannotInviteOwner              = "CANNOT_INVITE_OWNER"
	CodeCannotLeaveOwner               = "CANNOT_LEAVE_OWNER"
	CodeCannotSetSubdomain             = "CANNOT_SET_SUBDOMAIN"
	CodeClusterMaintenanceTryLater     = "CLUSTER_MAINTENANCE_TRY_LATER"
	CodeClusterSelectionFailed         = "CLUSTER_SELECTION_FAILED"
	CodeClusterTimeout                 = "CLUSTER_TIMEOUT"
	CodeClusterUnavailable             = "CLUSTER_UNAVAILABLE"
	CodeCommitFailed                   = "COMMIT_FAILED"
	CodeConflictingResources           = "CONFLICTING_RESOURCES"
	CodeContainerAlreadyStarted        = "CONTAINER_ALREADY_STARTED"
	CodeContainerAlreadyStopped        = "CONTAINER_ALREADY_STOPPED"
	CodeContainerInsufficientDiskSpace = "CONTAINER_INSUFFICIENT_DISK_SPACE"
	CodeContainerNetworkConflict       = "CONTAINER_NETWORK_CONFLICT"
	CodeContainerNotFound              = "CONTAINER_NOT_FOUND"
	CodeContainerTemporarilySuspended  = "CONTAINER_TEMPORARILY_SUSPENDED"
	CodeDailySnapshotsLimitReached     = "DAILY_SNAPSHOTS_LIMIT_REACHED"
	CodeDatabaseCreationFailed         = "DATABASE_CREATION_FAILED"
	CodeDatabaseNotFound               = "DATABASE_NOT_FOUND"
	CodeDatabaseNotRunning             = "DATABASE_NOT_RUNNING"
	// CodeDatabaseUnavailable comes with 503 when the API cannot serve the
	// request for a moment. The SDK retries it on GET requests only. See
	// [APIError].
	CodeDatabaseUnavailable = "DATABASE_UNAVAILABLE"
	CodeDeleteFailed        = "DELETE_FAILED"
	CodeDNSFailed           = "DNS_FAILED"
	CodeDomainAlreadyExists = "DOMAIN_ALREADY_EXISTS"
	CodeEmptyResponse       = "EMPTY_RESPONSE"
	// CodeEnvBusy comes with 409 when another write to the same environment
	// variables was in progress. The SDK does not retry it.
	CodeEnvBusy           = "ENV_BUSY"
	CodeEnvContentTooLong = "ENV_CONTENT_TOO_LONG"
	CodeEnvNameTooLong    = "ENV_NAME_TOO_LONG"
	// CodeFailedToFetch comes with 502 when GitHub did not confirm the branch
	// in [AppDeploysAPI.LinkGithubApp]. It is safe to try again.
	CodeFailedToFetch = "FAILED_TO_FETCH"
	CodeFileNotFound  = "FILE_NOT_FOUND"
	// CodeFileTooLarge comes with 413 from the API, or with Status 0 from the
	// SDK's own check, when an upload is over 100 MB or a file is over 10 MB.
	CodeFileTooLarge         = "FILE_TOO_LARGE"
	CodeGitAlreadyConfigured = "GIT_ALREADY_CONFIGURED"
	// CodeGitBranchDeleted is sent only in answers to GitHub push webhooks,
	// never to the calls of this SDK.
	CodeGitBranchDeleted = "GIT_BRANCH_DELETED"
	CodeGitNotConfigured = "GIT_NOT_CONFIGURED"
	// CodeGitRefNotSupported is sent only in answers to GitHub push webhooks,
	// never to the calls of this SDK.
	CodeGitRefNotSupported     = "GIT_REF_NOT_SUPPORTED"
	CodeGithubNotConnected     = "GITHUB_NOT_CONNECTED"
	CodeInsufficientMemory     = "INSUFFICIENT_MEMORY"
	CodeInternalServerError    = "INTERNAL_SERVER_ERROR"
	CodeInvalidAccessToken     = "INVALID_ACCESS_TOKEN"
	CodeInvalidAutorestart     = "INVALID_AUTORESTART"
	CodeInvalidBranchLength    = "INVALID_BRANCH_LENGTH"
	CodeInvalidCode            = "INVALID_CODE"
	CodeInvalidContent         = "INVALID_CONTENT"
	CodeInvalidContentType     = "INVALID_CONTENT_TYPE"
	CodeInvalidDatabaseType    = "INVALID_DATABASE_TYPE"
	CodeInvalidDatabaseVersion = "INVALID_DATABASE_VERSION"
	CodeInvalidDescription     = "INVALID_DESCRIPTION"
	CodeInvalidDisplayName     = "INVALID_DISPLAY_NAME"
	CodeInvalidDomain          = "INVALID_DOMAIN"
	CodeInvalidEncoding        = "INVALID_ENCODING"
	CodeInvalidEnvContent      = "INVALID_ENV_CONTENT"
	CodeInvalidFile            = "INVALID_FILE"
	CodeInvalidFilename        = "INVALID_FILENAME"
	CodeInvalidFilter          = "INVALID_FILTER"
	CodeInvalidGroup           = "INVALID_GROUP"
	// CodeInvalidID comes with 400 from the API for a malformed id. The SDK
	// also returns it with Status 0, without sending anything, when an id is
	// empty, "." or "..".
	CodeInvalidID         = "INVALID_ID"
	CodeInvalidInput      = "INVALID_INPUT"
	CodeInvalidJSONBody   = "INVALID_JSON_BODY"
	CodeInvalidMemory     = "INVALID_MEMORY"
	CodeInvalidName       = "INVALID_NAME"
	CodeInvalidParameters = "INVALID_PARAMETERS"
	CodeInvalidPath       = "INVALID_PATH"
	CodeInvalidResetType  = "INVALID_RESET_TYPE"
	CodeInvalidScope      = "INVALID_SCOPE"
	CodeInvalidSnapshotID = "INVALID_SNAPSHOT_ID"
	CodeInvalidSubdomain  = "INVALID_SUBDOMAIN"
	CodeInvalidTimeRange  = "INVALID_TIME_RANGE"
	CodeInvalidVersionID  = "INVALID_VERSION_ID"
	// CodeKeepCalm comes with 429 when one call is made too often. The SDK
	// never retries it.
	CodeKeepCalm                 = "KEEP_CALM"
	CodeLoadBalancerLimitReached = "LOAD_BALANCER_LIMIT_REACHED"
	CodeLogsUnavailable          = "LOGS_UNAVAILABLE"
	CodeMembersLimitReached      = "MEMBERS_LIMIT_REACHED"
	CodeMemberAlreadyAdded       = "MEMBER_ALREADY_ADDED"
	CodeMemberNotFound           = "MEMBER_NOT_FOUND"
	CodeMissingParameters        = "MISSING_PARAMETERS"
	CodeMissingRequiredFields    = "MISSING_REQUIRED_FIELDS"
	CodeMissingScope             = "MISSING_SCOPE"
	CodeNoCustomDomain           = "NO_CUSTOM_DOMAIN"
	CodeNoUpdateData             = "NO_UPDATE_DATA"
	CodePayloadTooLarge          = "PAYLOAD_TOO_LARGE"
	CodePermissionDenied         = "PERMISSION_DENIED"
	CodePurgeCacheFailed         = "PURGE_CACHE_FAILED"
	// CodeRateLimited comes with 429 when the account, API key or IP address
	// went over its rate limit, which can block it for about 30 minutes. It
	// also limits the network calls and [AccountAPI.Snapshots]. The SDK never
	// retries it.
	CodeRateLimited                       = "RATE_LIMITED"
	CodeReadFailed                        = "READ_FAILED"
	CodeRealtimeMaxConnections            = "REALTIME_MAX_CONNECTIONS"
	CodeRealtimeMaxConnectionsApp         = "REALTIME_MAX_CONNECTIONS_APP"
	CodeRenameFailed                      = "RENAME_FAILED"
	CodeRepositoryBranchAlreadyConfigured = "REPOSITORY_BRANCH_ALREADY_CONFIGURED"
	CodeRepositoryNotAvailable            = "REPOSITORY_NOT_AVAILABLE"
	CodeRepositoryNotFound                = "REPOSITORY_NOT_FOUND"
	// CodeRepositoryPermissionRequired comes with 403 when your GitHub
	// account cannot write to the repository.
	CodeRepositoryPermissionRequired = "REPOSITORY_PERMISSION_REQUIRED"
	CodeRequestAborted               = "REQUEST_ABORTED"
	CodeReservedDomain               = "RESERVED_DOMAIN"
	CodeResetFailed                  = "RESET_FAILED"
	CodeResourceNotAllowed           = "RESOURCE_NOT_ALLOWED"
	// CodeRestoreInProgress comes with 409 while a snapshot is being restored
	// into the application or database. The SDK does not retry it.
	CodeRestoreInProgress  = "RESTORE_IN_PROGRESS"
	CodeRestoreInterrupted = "RESTORE_INTERRUPTED"
	CodeRouteNotFound      = "ROUTE_NOT_FOUND"
	CodeSaveFailed         = "SAVE_FAILED"
	CodeScopeNotGrantable  = "SCOPE_NOT_GRANTABLE"
	// CodeSnapshotsUnavailable comes with 503 when snapshot storage cannot
	// answer a listing. The SDK does not retry it.
	CodeSnapshotsUnavailable     = "SNAPSHOTS_UNAVAILABLE"
	CodeSnapshotCorrupt          = "SNAPSHOT_CORRUPT"
	CodeSnapshotDatabaseMismatch = "SNAPSHOT_DATABASE_MISMATCH"
	CodeSnapshotFailed           = "SNAPSHOT_FAILED"
	// CodeSnapshotInProgress comes with 409 from Restore while a snapshot of
	// the same application or database is being taken.
	CodeSnapshotInProgress = "SNAPSHOT_IN_PROGRESS"
	CodeSnapshotNotFound   = "SNAPSHOT_NOT_FOUND"
	// CodeSnapshotProcessing is never returned as an error. The SDK reports it
	// as [SnapshotCreated.Pending].
	CodeSnapshotProcessing    = "SNAPSHOT_PROCESSING"
	CodeSnapshotRestoreFailed = "SNAPSHOT_RESTORE_FAILED"
	// CodeSnapshotRestoreProcessing is never returned as an error. The SDK
	// reports it as [SnapshotRestored.Pending].
	CodeSnapshotRestoreProcessing = "SNAPSHOT_RESTORE_PROCESSING"
	CodeStaticAppEnvNotSupported  = "STATIC_APP_ENV_NOT_SUPPORTED"
	CodeStorageUploadFailed       = "STORAGE_UPLOAD_FAILED"
	CodeTooManyEnvVars            = "TOO_MANY_ENV_VARS"
	CodeUnableToFetchAnalytics    = "UNABLE_TO_FETCH_ANALYTICS"
	CodeUnableToFetchErrors       = "UNABLE_TO_FETCH_ERRORS"
	CodeUnableToFetchPerformance  = "UNABLE_TO_FETCH_PERFORMANCE"
	CodeUpgradeRequired           = "UPGRADE_REQUIRED"
	CodeUploadAborted             = "UPLOAD_ABORTED"
	// CodeUploadBusy comes with 503 when the API refused an upload before
	// doing any work. The SDK retries it.
	CodeUploadBusy              = "UPLOAD_BUSY"
	CodeUploadFailed            = "UPLOAD_FAILED"
	CodeValidationFailed        = "VALIDATION_FAILED"
	CodeValidationTimeout       = "VALIDATION_TIMEOUT"
	CodeWorkspaceCreationFailed = "WORKSPACE_CREATION_FAILED"
	CodeWorkspaceLimitReached   = "WORKSPACE_LIMIT_REACHED"
	CodeWorkspaceNotFound       = "WORKSPACE_NOT_FOUND"
	CodeWriteFailed             = "WRITE_FAILED"
	// CodeWrongHost comes with 421, but never in answer to the calls of this
	// SDK. It is listed so that every documented code has a constant.
	CodeWrongHost = "WRONG_HOST"
)

Codes that the API sends, one for every error code its calls document. Compare APIError.Code with them. The API can add codes at any time, so handle a code you do not know by its HTTP status. Errors from AIAPI.Chat use lowercase OpenAI codes instead, such as "access_denied", "rate_limit_exceeded" and "server_overloaded", which Code holds as they are.

View Source
const (
	DeployPending    = "pending"    // The deploy is waiting to start.
	DeployClone      = "clone"      // The repository is being cloned.
	DeployCommit     = "commit"     // The changed files are being applied.
	DeployRestarting = "restarting" // The application is restarting.
	DeploySuccess    = "success"    // The deploy finished.
	DeployError      = "error"      // The deploy failed.
)

Values of DeployEvent.State, in the order a deploy goes through them. DeployError can replace any step after DeployPending.

Variables

This section is empty.

Functions

This section is empty.

Types

type AIAPI

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

AIAPI sends chat requests to the Square Cloud AI, which uses the OpenAI chat completions format. An OpenAI client library pointed at DefaultBaseURL + "/ai" works too.

func (AIAPI) Chat

func (a AIAPI) Chat(ctx context.Context, req ChatRequest) (ChatCompletion, error)

Chat sends the conversation in req and returns the model's reply. Streaming is not supported. It needs an API key with the ai:chat scope and a Standard plan or higher. Other plans get 403 upgrade_required.

The AI answers within 90 seconds, or returns 503 server_overloaded. That error is safe to try again, but the SDK does not retry it. Without a deadline on ctx, Chat waits at least 2 minutes. Errors from Chat use the OpenAI format, so their Code is lowercase, such as "rate_limit_exceeded". See APIError.

Example
ctx := context.Background()
c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))

res, err := c.AI.Chat(ctx, squarecloud.ChatRequest{
	Messages: []squarecloud.ChatMessage{{Role: "user", Content: "Say hi"}},
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(res.Choices[0].Message.Content)

type APIError

type APIError struct {
	// Status is the HTTP status of the response. It is 0 when no complete
	// response arrived or a local check stopped the call.
	Status int
	// Code is the error code, such as "APP_NOT_FOUND". Compare it with the
	// Code constants, such as [CodeAppNotFound].
	Code string
	// Message is the server's explanation of the error. It is "" when the
	// server sent only a code. When no response arrived, it is the text of
	// the cause.
	Message string
	// Method is the HTTP method of the request, such as "GET".
	Method string
	// Path is the URL path of the request, including the path of the base
	// URL. It never includes the query string, so a signed snapshot link
	// never appears in an error.
	Path string
	// contains filtered or unexported fields
}

APIError is the error a call returns when the API refuses the request, the network fails, or a local check stops the call before anything is sent. Use errors.As to read it:

var apiErr *squarecloud.APIError
if errors.As(err, &apiErr) && apiErr.Code == squarecloud.CodeMissingScope {
	fmt.Println(apiErr.Message)
}

Status is 0 when no complete response arrived. Code is then CodeNetworkError or CodeTimeout, and APIError.Unwrap returns the cause. Local checks also leave Status at 0. They return CodeInvalidID for an id that is empty, "." or "..", CodeFileTooLarge for content over the size limits, and CodeInvalidAPIKey for an empty API key.

A response without an error code gets CodeUnknown, with the server's message or "HTTP <status>" as Message. So does a successful response whose body is not valid JSON. A successful response whose body reports an error is returned as an error too, except a 202, which only means that the work is still running (see SnapshotCreated and SnapshotRestored). Errors from AIAPI.Chat follow the OpenAI format, so their Code is a lowercase OpenAI code such as "rate_limit_exceeded", or the error type when the code is missing. An API key that is unknown, revoked or expired gets 401 ACCESS_DENIED.

When you cancel the context, errors.Is(err, context.Canceled) reports true. When the context deadline or the client timeout passes first, Code is CodeTimeout.

The SDK repeats a call only when that is safe, up to the count set with WithMaxRetries, and waits longer before each new attempt, up to 8 seconds. It repeats network errors on GET requests. It repeats 503 UPLOAD_BUSY and ANALYTICS_BUSY on any request, because the API refused those before doing any work. It repeats 503 DATABASE_UNAVAILABLE only on GET requests, because on other methods the change may already have started. You can repeat an idempotent call yourself, such as AppEnvsAPI.Replace, AppFilesAPI.Write or a Delete. An upload is repeated only when its reader can be read again, such as an *os.File.

A 429 is never repeated. RATE_LIMITED can block the account, API key or IP address for about 30 minutes, and KEEP_CALM is the limit of a single operation. When Status is 429, wait before you try again.

Some mistakes in the arguments return a plain error instead of an APIError. They are a nil upload reader, a snapshot URL or base URL that cannot be parsed, a value that encoding/json cannot encode, and an error from the io.Writer passed to Client.DownloadSnapshot.

func (*APIError) Error

func (e *APIError) Error() string

Error formats the error as "squarecloud: <METHOD> <path>: HTTP <status> <CODE>: <message>". It leaves out the HTTP status when Status is 0, and the message when Message is empty.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the cause of the error, such as a network, decoding or context error. It returns nil when there is none.

type APILatency

type APILatency struct {
	RecentMs  float64 `json:"recent_ms"`
	DayMeanMs float64 `json:"day_mean_ms"`
	Elevated  bool    `json:"elevated"`
}

APILatency is the response time of a service's API in milliseconds. RecentMs is the latest measurement and DayMeanMs the average over the last day. Elevated is true when the latency is higher than usual.

type Account

type Account struct {
	User         User              `json:"user"`
	Applications []AppSummary      `json:"applications"`
	Databases    []DatabaseSummary `json:"databases"`
}

Account is what AccountAPI.Me returns: your user and the applications and databases you own. With an API key limited to some resources, the lists hold only those.

type AccountAPI

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

AccountAPI reads the account that owns the API key.

func (AccountAPI) Me

func (a AccountAPI) Me(ctx context.Context) (Account, error)

Me returns your user, plan and memory usage, with the applications and databases you own. With an API key limited to some resources, the lists hold only those.

func (AccountAPI) Snapshots

func (a AccountAPI) Snapshots(ctx context.Context, scope SnapshotScope) ([]Snapshot, error)

Snapshots returns the snapshots of all your applications, or of all your databases when scope is SnapshotScopeDatabases. Pass "" for applications. It returns 402 UPGRADE_REQUIRED when the account has no active paid plan, and 429 RATE_LIMITED after 3 calls in a minute. It returns 503 SNAPSHOTS_UNAVAILABLE while snapshot storage cannot answer, so try again in about 30 seconds.

type AnalyticsBucket

type AnalyticsBucket struct {
	Type     string    `json:"type"`
	Date     time.Time `json:"date"`
	Visits   int64     `json:"visits"`
	Requests int64     `json:"requests"`
	Bytes    int64     `json:"bytes"`
}

AnalyticsBucket is the traffic of one value of a breakdown, such as one country, in the 15-minute slot that starts at Date. Type is the value. Visits counts unique visitors and Bytes is what was served to them.

type AnalyticsFilters

type AnalyticsFilters struct {
	// Country is a two-letter country code, such as "BR".
	Country string
	IP      string
	// Path keeps the requests whose path starts with this value.
	Path string
	// Status is an HTTP status code, such as "404".
	Status   string
	OS       string
	Browser  string
	Protocol string
	Referer  string
	// Provider is a network provider written as in
	// [NetworkAnalytics.Providers], such as "GOOGLE (15169)".
	Provider    string
	ContentType string
	Bot         string
}

AnalyticsFilters narrows the results of AppNetworkAPI.Analytics. Leave a field "" to skip that filter. A value the API does not accept returns 400 INVALID_FILTER.

type AnalyticsTimeBucket

type AnalyticsTimeBucket struct {
	Date     time.Time `json:"date"`
	Visits   int64     `json:"visits"`
	Requests int64     `json:"requests"`
	Bytes    int64     `json:"bytes"`
	BytesIn  int64     `json:"bytes_in,omitempty"`
}

AnalyticsTimeBucket is the traffic of one 15-minute slot in NetworkAnalytics.Visits. Date is the start of the slot, Visits counts unique visitors, Bytes is what was served to them, and BytesIn is what was received from them, such as uploads.

type AnalyticsTotalBucket

type AnalyticsTotalBucket struct {
	Type     string `json:"type"`
	Visits   int64  `json:"visits"`
	Requests int64  `json:"requests"`
	Bytes    int64  `json:"bytes"`
}

AnalyticsTotalBucket is the traffic of one value of a breakdown over the whole period. Type is the value. Visits counts unique visitors and Bytes is what was served to them.

type App

type App struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Description is "" when the application has none.
	Description string `json:"desc,omitempty"`
	// Owner is the user id of the application's owner.
	Owner string `json:"owner"`
	// Cluster identifies where the application is hosted.
	Cluster string `json:"cluster"`
	// RAM is the memory allocated to the application, in MB.
	RAM int `json:"ram"`
	// Language is the application's language, such as "javascript",
	// "python" or "static".
	Language string `json:"language"`
	// Domain is the default hostname, such as "my-app.squareweb.app", or nil
	// when the application has none.
	Domain *string `json:"domain"`
	// Custom is the custom domain, or nil when none is set.
	Custom    *string   `json:"custom"`
	CreatedAt time.Time `json:"created_at"`
}

App is an application as AppsAPI.Get returns it.

type AppCreated

type AppCreated struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Description is "" when the application has none.
	Description string `json:"description,omitempty"`
	// Domain is the full default hostname, such as "my-app.squareweb.app", or
	// "" when the application has no subdomain.
	Domain string `json:"domain,omitempty"`
	// Cluster identifies where the application is hosted.
	Cluster string `json:"cluster,omitempty"`
	// RAM is the memory allocated to the application, in MB.
	RAM int `json:"ram"`
	// CPU is the CPU allocated to the application. It can be a fraction, such
	// as 0.5.
	CPU float64 `json:"cpu"`
	// Language is the application's language and its version.
	Language AppLanguage `json:"language"`
}

AppCreated is the application that AppsAPI.Create deployed.

type AppDeploysAPI

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

AppDeploysAPI sets up deploys from GitHub and lists an application's past deploys.

func (AppDeploysAPI) Current

func (d AppDeploysAPI) Current(ctx context.Context, appID string) (DeployCurrent, error)

Current returns the repository linked through the GitHub App and the deploy webhook URL. Each part is empty when that kind of deploy is not set up. See AppsAPI for workspace applications.

func (AppDeploysAPI) LinkGithubApp

func (d AppDeploysAPI) LinkGithubApp(ctx context.Context, appID, repository, branch string) (LinkedRepository, error)

LinkGithubApp links the application to a branch of a GitHub repository through the Square Cloud GitHub App, and returns the linked repository. After that, a push to the branch deploys the application. repository is written as "owner/name". See AppsAPI for workspace applications.

Linking and unlinking each need an API key with the apps:deploy scope, and they share a limit of 3 calls a minute. Your GitHub account must be connected to Square Cloud, or the call returns 403 GITHUB_NOT_CONNECTED. The account must have the GitHub App installed on the repository, or the call returns 403 REPOSITORY_NOT_AVAILABLE. It must also be able to write to the repository, or the call returns 403 REPOSITORY_PERMISSION_REQUIRED.

A 502 FAILED_TO_FETCH means that GitHub did not confirm the branch, and it is safe to try again. A 409 REPOSITORY_BRANCH_ALREADY_CONFIGURED means that another application, of any account, already deploys from that repository and branch. Its Message names that application only when it is yours. To link a different repository, call AppDeploysAPI.UnlinkGithubApp first, or the call returns 400 GIT_ALREADY_CONFIGURED.

func (AppDeploysAPI) List

func (d AppDeploysAPI) List(ctx context.Context, appID string) ([][]DeployEvent, error)

List returns the application's recent deploys. Each deploy is a list of DeployEvent values that goes from "pending" to "success" or "error". See AppsAPI for workspace applications.

func (AppDeploysAPI) SetWebhook

func (d AppDeploysAPI) SetWebhook(ctx context.Context, appID, accessToken string) (string, error)

SetWebhook turns on deploys from a GitHub webhook and returns the webhook URL to add to your repository on GitHub. accessToken is a GitHub personal access token, which starts with "ghp_" or "github_pat_". Pass "@" to remove the webhook, in which case the returned URL is "". Any other token returns 400 INVALID_ACCESS_TOKEN. See AppsAPI for workspace applications.

func (AppDeploysAPI) UnlinkGithubApp

func (d AppDeploysAPI) UnlinkGithubApp(ctx context.Context, appID string) error

UnlinkGithubApp removes the link that AppDeploysAPI.LinkGithubApp created. It returns 400 GIT_NOT_CONFIGURED when the application has no link. It needs the apps:deploy scope and shares the limit of 3 calls a minute with AppDeploysAPI.LinkGithubApp. See AppsAPI for workspace applications.

type AppDomain

type AppDomain struct {
	// AppID is the application that the hostname points to.
	AppID    string `json:"app_id"`
	Hostname string `json:"hostname"`
	// Type is "subdomain" for a default hostname or "custom" for a custom
	// domain.
	Type string `json:"type"`
}

AppDomain is one hostname in AppsAPI.Domains.

type AppEnvsAPI

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

AppEnvsAPI reads and changes an application's environment variables.

Every method returns the variables as they are after the call. With an API key that lacks the envs:read scope, Set returns only the variables you sent and Delete returns an empty set. An application can have at most 256 variables, and a write past that returns 400 TOO_MANY_ENV_VARS. When two writes to the same application happen at the same time, one of them fails with 409 ENV_BUSY. The SDK does not retry it, so try again yourself. Static applications have no environment variables, so every method returns 400 STATIC_APP_ENV_NOT_SUPPORTED for them.

func (AppEnvsAPI) Delete

func (e AppEnvsAPI) Delete(ctx context.Context, appID string, keys ...string) (EnvVars, error)

Delete removes the variables named in keys and returns the ones that remain. See AppsAPI for workspace applications.

func (AppEnvsAPI) Get

func (e AppEnvsAPI) Get(ctx context.Context, appID string) (EnvVars, error)

Get returns the application's environment variables. See AppsAPI for workspace applications.

func (AppEnvsAPI) Replace

func (e AppEnvsAPI) Replace(ctx context.Context, appID string, envs EnvVars) (EnvVars, error)

Replace replaces all of the application's variables with envs and returns the result. See AppsAPI for workspace applications.

func (AppEnvsAPI) Set

func (e AppEnvsAPI) Set(ctx context.Context, appID string, envs EnvVars) (EnvVars, error)

Set adds envs to the application's variables, replacing the value of any name that already exists, and returns all of them. See AppsAPI for workspace applications.

type AppFilesAPI

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

AppFilesAPI reads and writes an application's files. Paths start at the application's root directory, such as "/src/index.js", and are at most 256 characters long.

func (AppFilesAPI) Delete

func (f AppFilesAPI) Delete(ctx context.Context, appID, path string) error

Delete deletes the file at path. See AppsAPI for workspace applications.

func (AppFilesAPI) List

func (f AppFilesAPI) List(ctx context.Context, appID, path string) ([]FileEntry, error)

List returns the entries of the directory path, or of the root directory when path is "". A missing directory returns 404 FILE_NOT_FOUND, and a directory that the API protects returns 403 BLOCKED_PATH. See AppsAPI for workspace applications.

func (AppFilesAPI) Move

func (f AppFilesAPI) Move(ctx context.Context, appID, path, to string) error

Move moves or renames the file at path to the new path to. See AppsAPI for workspace applications.

func (AppFilesAPI) Read

func (f AppFilesAPI) Read(ctx context.Context, appID, path string) ([]byte, error)

Read returns the content of the file at path, byte for byte. A file over 10 MB returns 413 FILE_TOO_LARGE, a missing file returns 404 FILE_NOT_FOUND, and a file the server cannot read returns 400 READ_FAILED. See AppsAPI for workspace applications.

func (AppFilesAPI) Write

func (f AppFilesAPI) Write(ctx context.Context, appID, path string, content []byte) error

Write creates or replaces the file at path with content. Text and binary content arrive byte for byte, and empty content creates an empty file. See AppsAPI for workspace applications.

Content over 10 MB returns CodeFileTooLarge without sending anything. Upload larger files with AppsAPI.Commit instead. The API returns 400 WRITE_FAILED when it cannot write the file. Content over 1 MiB has no time limit, so only ctx stops it.

type AppLanguage

type AppLanguage struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

AppLanguage is the language of a new application and its version.

type AppNetworkAPI

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

AppNetworkAPI reports the traffic of a website and sets its custom domain. Its methods work only for websites.

Analytics, Errors, Logs and Performance cover the traffic from start to end. The API keeps 7 days of traffic, so start reaches back at most 7 days. Analytics, Errors and Performance return nil when nothing was served in that period. The four share a limit of 20 calls a minute for data that is not cached, and past it they return 429 RATE_LIMITED.

func (AppNetworkAPI) Analytics

func (n AppNetworkAPI) Analytics(ctx context.Context, appID string, start, end time.Time, f AnalyticsFilters) (*NetworkAnalytics, error)

Analytics returns the visits, requests and bandwidth of the application's domains, broken down by country, device, path and more. f narrows the results, and its zero value applies no filter. See AppsAPI for workspace applications.

func (AppNetworkAPI) DNS

func (n AppNetworkAPI) DNS(ctx context.Context, appID string) ([]DNSRecord, error)

DNS returns the records to create at your DNS provider for the custom domain, with the validation status of each. It returns 400 NO_CUSTOM_DOMAIN when the application has no custom domain. See AppsAPI for workspace applications.

func (AppNetworkAPI) Errors

func (n AppNetworkAPI) Errors(ctx context.Context, appID string, start, end time.Time, include4xx bool) (*NetworkErrors, error)

Errors returns the error responses served from the application's domains, by status, path and method and over time. It counts only 5xx responses, unless include4xx is true. See AppsAPI for workspace applications.

func (AppNetworkAPI) Logs

func (n AppNetworkAPI) Logs(ctx context.Context, appID string, start, end time.Time) ([]NetworkLog, error)

Logs returns one entry for each request served from the application's domains. It returns 403 UPGRADE_REQUIRED on plans other than Pro and Enterprise. See AppsAPI for workspace applications.

func (AppNetworkAPI) Performance

func (n AppNetworkAPI) Performance(ctx context.Context, appID string, start, end time.Time) (*NetworkPerformance, error)

Performance returns how fast the application's domains answered, as latency percentiles at the edge and at your application. It breaks them down over time, by country and by edge location, and lists the slowest paths. It returns 403 UPGRADE_REQUIRED on plans other than Pro and Enterprise. See AppsAPI for workspace applications.

func (AppNetworkAPI) PurgeCache

func (n AppNetworkAPI) PurgeCache(ctx context.Context, appID string) error

PurgeCache clears the responses cached at the edge for the application's domains. See AppsAPI for workspace applications.

func (AppNetworkAPI) SetDomain

func (n AppNetworkAPI) SetDomain(ctx context.Context, appID, domain string) error

SetDomain sets the application's custom domain to domain, replacing any previous one. Pass "@" to remove the custom domain. See AppsAPI for workspace applications.

It returns 403 UPGRADE_REQUIRED on plans other than Standard, Pro and Enterprise, and 400 RESERVED_DOMAIN for a Square Cloud domain. It returns 409 DOMAIN_ALREADY_EXISTS when another account uses the domain, and 403 LOAD_BALANCER_LIMIT_REACHED when the domain is already on as many of your applications as your plan allows.

type AppSummary

type AppSummary struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Description is "" when the application has none.
	Description string `json:"desc,omitempty"`
	// RAM is the memory allocated to the application, in MB.
	RAM int `json:"ram"`
	// Lang is the application's language, such as "javascript".
	Lang string `json:"lang"`
	// Cluster identifies where the application is hosted.
	Cluster string `json:"cluster"`
	// Domain is the default hostname, or nil when the application has none.
	Domain *string `json:"domain"`
	// Custom is the custom domain, or nil when none is set.
	Custom    *string   `json:"custom"`
	CreatedAt time.Time `json:"created_at"`
}

AppSummary is an application as Account lists it.

type AppsAPI

type AppsAPI struct {

	// Files reads and writes the application's files.
	Files AppFilesAPI
	// Envs reads and changes the application's environment variables.
	Envs AppEnvsAPI
	// Snapshots takes, lists and restores the application's snapshots.
	Snapshots SnapshotsAPI
	// Network reports a website's traffic and sets its custom domain.
	Network AppNetworkAPI
	// Deploys sets up deploys from GitHub and lists past deploys.
	Deploys AppDeploysAPI
	// contains filtered or unexported fields
}

AppsAPI deploys and controls applications. Its fields group the calls that work on one application's files, environment variables, snapshots, network and deploys.

Every application id that this group and its fields take is normally the application's own id. To act on an application that another account shares with you through a workspace, pass the composite id "<appId>-<workspaceId>" instead.

func (AppsAPI) Commit

func (a AppsAPI) Commit(ctx context.Context, appID string, r io.Reader, path, filename string) error

Commit uploads a file into an existing application. A .zip archive is unpacked into the directory path, and any other file is written to path/<filename>. Pass "" as path for the application's root directory. See AppsAPI for workspace applications.

The uploaded file is named filename. When filename is "", it takes the base name of an *os.File, or "commit.zip" for other readers. The upload streams like the one of AppsAPI.Create, with the same 100 MB limit and no time limit. The API returns 403 BLOCKED_PATH when a workspace Maintainer sends one of the application's restricted files, such as an .env file or the configuration file.

func (AppsAPI) Create

func (a AppsAPI) Create(ctx context.Context, zip io.Reader) (AppCreated, error)

Create deploys a new application from a zip archive and returns its id and settings. The zip can be at most 100 MB.

The zip is streamed as it is read and never held in memory. Pass an *os.File when you can. Its size is then known before the upload starts, its name becomes the name of the uploaded file, and the upload can be repeated after 503 UPLOAD_BUSY. A reader without a name is uploaded as "app.zip". A zip over 100 MB returns CodeFileTooLarge, before anything is sent when its size is known, or as soon as the stream passes 100 MB. An upload has no time limit, so cancel ctx to stop it. The API returns 400 INSUFFICIENT_MEMORY when your plan does not have enough free memory for the application.

Example
ctx := context.Background()
c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))

// The zip is streamed as it is uploaded, never loaded into memory.
f, err := os.Open("app.zip")
if err != nil {
	log.Fatal(err)
}
defer f.Close()
app, err := c.Apps.Create(ctx, f)
if err != nil {
	log.Fatal(err)
}
fmt.Println(app.ID, app.Language.Name)

// Commit a single file. A file that is not a zip lands at
// <path>/<filename>, so this one becomes src/index.js.
src, err := os.Open("index.js")
if err != nil {
	log.Fatal(err)
}
defer src.Close()
if err := c.Apps.Commit(ctx, app.ID, src, "src", ""); err != nil {
	log.Fatal(err)
}

// Deploy on every push to main through the Square Cloud GitHub App. The
// API key needs the apps:deploy scope.
repo, err := c.Apps.Deploys.LinkGithubApp(ctx, app.ID, "octocat/hello-world", "main")
if err != nil {
	log.Fatal(err)
}
fmt.Println(repo.FullName, repo.Branch)
if err := c.Apps.Deploys.UnlinkGithubApp(ctx, app.ID); err != nil {
	log.Fatal(err)
}

func (AppsAPI) Delete

func (a AppsAPI) Delete(ctx context.Context, appID string) error

Delete deletes the application. It returns 409 RESTORE_IN_PROGRESS while a snapshot is being restored, so try again when the restore ends. See AppsAPI for workspace applications.

func (AppsAPI) Domains

func (a AppsAPI) Domains(ctx context.Context) ([]AppDomain, error)

Domains returns every hostname of your applications, both the default subdomains and the custom domains. Custom domains come first.

func (AppsAPI) Get

func (a AppsAPI) Get(ctx context.Context, appID string) (App, error)

Get returns the application's name, language, memory, domains and owner. See AppsAPI for workspace applications.

func (AppsAPI) LoadBalancers

func (a AppsAPI) LoadBalancers(ctx context.Context) (LoadBalancers, error)

LoadBalancers groups your applications by custom domain. A domain that two or more applications serve is a load balancer, which spreads the traffic across them. The result also says how many applications your plan lets share one domain.

func (AppsAPI) Logs

func (a AppsAPI) Logs(ctx context.Context, appID string) (string, error)

Logs returns the application's most recent output, with standard output and standard error together in the order they were written. It returns "" when there is no output. Use AppsAPI.Realtime to follow the logs live. See AppsAPI for workspace applications.

func (AppsAPI) Metrics

func (a AppsAPI) Metrics(ctx context.Context, appID, rng string) ([]MetricPoint, error)

Metrics returns the application's CPU, memory, network and disk usage over time, newest point first. See AppsAPI for workspace applications.

rng selects the period. With "24h", the default that "" also gets, there is a point every 5 minutes, or every 10 minutes for applications with less than 512 MB. With "7d" there is a point every hour, where CPU and RAM are the hour's average and MetricPoint.CPUMax and MetricPoint.RAMMax its peaks. "7d" works on the Pro and Enterprise plans for applications with 512 MB or more. Other plans and smaller applications get the 24-hour answer without an error, so check the points you get instead of assuming 7 days. Any other rng returns 400 INVALID_PARAMETERS.

func (AppsAPI) Realtime

func (a AppsAPI) Realtime(ctx context.Context, appID string) (*Realtime, error)

Realtime opens a live stream of the application's logs and resource usage. See Realtime for how to read it, and AppsAPI for workspace applications.

When the stream cannot open, Realtime returns the error before any event. You can have at most 5 streams open per account and 30 per application. Past those limits it returns 429 REALTIME_MAX_CONNECTIONS or 429 REALTIME_MAX_CONNECTIONS_APP. The client timeout applies only until the stream opens. After that, only ctx limits it.

Example
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))

s, err := c.Apps.Realtime(ctx, "a1b2c3d4e5f60718293a4b5c6d7e8f90")
if err != nil {
	log.Fatal(err)
}
defer s.Close()
for {
	ev, err := s.Next()
	if err != nil {
		return // The error is io.EOF when the stream ends normally.
	}
	switch ev.Event {
	case "logs":
		fmt.Printf("[%s] %s\n", ev.Stream, ev.Line)
	case "status": // Status is never nil on a status event.
		fmt.Printf("cpu %.1f%% ram %.0f/%.0f MB\n", ev.Status.CPU, ev.Status.RAM[0], ev.Status.RAM[1])
	default: // A "system" or "error" event.
		fmt.Println(ev.Event, ev.Data)
	}
}

func (AppsAPI) Restart

func (a AppsAPI) Restart(ctx context.Context, appID string) error

Restart restarts the application. Its time limit and errors are the same as for AppsAPI.Start. See AppsAPI for workspace applications.

func (AppsAPI) Start

func (a AppsAPI) Start(ctx context.Context, appID string) error

Start starts the application. Without a deadline on ctx, it waits at least 2 minutes for the API to answer. See AppsAPI for workspace applications.

When the application cannot start, Start returns a 409 error with no message and one of these codes: CONTAINER_ALREADY_STARTED, CONTAINER_ALREADY_STOPPED, CONTAINER_TEMPORARILY_SUSPENDED, CONTAINER_NOT_FOUND, CONTAINER_INSUFFICIENT_DISK_SPACE, CONTAINER_NETWORK_CONFLICT, ACTION_FAILED, or RESTORE_IN_PROGRESS while a snapshot is being restored. The "already" codes mean that the application is already in the state you asked for. They are still returned as errors, so treat them as success when that is what your code needs.

func (AppsAPI) Status

func (a AppsAPI) Status(ctx context.Context, appID string) (RuntimeStats, error)

Status returns the application's current CPU, memory, network and storage usage as formatted strings such as "120.4MB". Use AppsAPI.StatusRaw for numbers. See AppsAPI for workspace applications.

func (AppsAPI) StatusAll

func (a AppsAPI) StatusAll(ctx context.Context, workspaceID string) ([]StatusListItem, error)

StatusAll reports whether each of your applications is running, with its CPU and memory usage. Pass a workspaceID to list the applications shared in that workspace instead, or "" for your own.

func (AppsAPI) StatusRaw

func (a AppsAPI) StatusRaw(ctx context.Context, appID string) (RuntimeStatsRaw, error)

StatusRaw returns the same usage as AppsAPI.Status as numbers: CPU in percent, memory in MB, and storage and network traffic in bytes. See AppsAPI for workspace applications.

func (AppsAPI) Stop

func (a AppsAPI) Stop(ctx context.Context, appID string) error

Stop stops the application. Its time limit and errors are the same as for AppsAPI.Start. See AppsAPI for workspace applications.

type ChatChoice

type ChatChoice struct {
	Index        int         `json:"index"`
	Message      ChatMessage `json:"message"`
	FinishReason string      `json:"finish_reason"`
}

ChatChoice is one reply in a ChatCompletion. FinishReason says why the model stopped, such as "stop".

type ChatCompletion

type ChatCompletion struct {
	ID     string `json:"id"`
	Object string `json:"object"`
	// Created is when the reply was made, in Unix seconds.
	Created int64        `json:"created"`
	Model   string       `json:"model"`
	Choices []ChatChoice `json:"choices"`
	Usage   ChatUsage    `json:"usage"`
}

ChatCompletion is the reply of AIAPI.Chat, in the OpenAI chat completions format.

type ChatMessage

type ChatMessage struct {
	// Role is "system", "user", "assistant" or "tool".
	Role string `json:"role"`
	// Content is the text of the message. It is always sent, even when it is
	// "", because the API requires it.
	Content string `json:"content"`
	// ToolCallID is the id of the tool call that a "tool" message answers.
	ToolCallID string `json:"tool_call_id,omitempty"`
	// ToolCalls holds the tool calls of an "assistant" message, as OpenAI
	// JSON objects.
	ToolCalls []json.RawMessage `json:"tool_calls,omitempty"`
}

ChatMessage is one message of a conversation.

type ChatRequest

type ChatRequest struct {
	// Model is ignored, because every request uses the "cubic" model.
	Model string `json:"model,omitempty"`
	// Messages is the conversation so far.
	Messages []ChatMessage `json:"messages"`
	// Tools lists the tools that the model can call, as OpenAI tool
	// definitions in JSON.
	Tools []json.RawMessage `json:"tools,omitempty"`
	// ToolChoice controls whether and which tool the model calls, as in the
	// OpenAI format.
	ToolChoice any `json:"tool_choice,omitempty"`
	// MaxTokens is the older name of MaxCompletionTokens. When both are set,
	// MaxCompletionTokens wins.
	MaxTokens int `json:"max_tokens,omitempty"`
	// MaxCompletionTokens limits the length of the reply. A value above your
	// plan's limit is lowered to it.
	MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
	// Temperature controls how varied the reply is. Leave it nil for the
	// default.
	Temperature *float64 `json:"temperature,omitempty"`
}

ChatRequest is the request of AIAPI.Chat, in the OpenAI chat completions format. Streaming is not supported.

type ChatUsage

type ChatUsage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

ChatUsage counts the tokens of a ChatCompletion.

type Client

type Client struct {
	// Account reads the account that owns the API key.
	Account AccountAPI
	// Service reports the status of the platform. It works without an API
	// key.
	Service ServiceAPI
	// AI sends chat requests to the Square Cloud AI.
	AI AIAPI
	// Apps deploys and controls applications.
	Apps AppsAPI
	// Databases creates and controls databases.
	Databases DatabasesAPI
	// Workspaces shares applications with other accounts.
	Workspaces WorkspacesAPI
	// contains filtered or unexported fields
}

Client sends requests to the Square Cloud API. Create it with New. Its fields group the calls by what they act on. A Client is safe for concurrent use.

func New

func New(apiKey string, opts ...Option) *Client

New returns a client that authenticates every call with apiKey.

New never fails. With an empty or whitespace-only key, every call except ServiceAPI.Status returns an *APIError with code CodeInvalidAPIKey and sends nothing.

func (*Client) DownloadSnapshot

func (c *Client) DownloadSnapshot(ctx context.Context, link string, w io.Writer) error

DownloadSnapshot writes the snapshot archive at link to w as it arrives, without holding it in memory. Pass the URL field of a Snapshot or a SnapshotCreated. Those links stop working 1 hour after they are issued.

Your API key is not sent with the download, and the link never appears in a returned error, because the link itself grants access to the archive. Only ctx limits how long the download takes. A network error before the download starts is retried like any GET. A failed download returns an *APIError, and an error from w is returned unchanged.

type DNSRecord

type DNSRecord struct {
	// Type is "txt" or "cname".
	Type  string `json:"type"`
	Name  string `json:"name"`
	Value string `json:"value"`
	// Status is the validation state, such as "pending" or "active".
	Status string `json:"status"`
	// Errors holds up to 3 messages that say why a record is not active yet.
	Errors []string `json:"errors,omitempty"`
	// Fallback is true on the one _acme-challenge CNAME record that can
	// replace every SSL TXT record. Create either that CNAME or the TXT
	// records, never both.
	Fallback bool `json:"fallback,omitempty"`
}

DNSRecord is one record to create at your DNS provider for a custom domain.

type Database

type Database struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Owner is the user id of the database's owner.
	Owner string `json:"owner"`
	// Cluster identifies where the database is hosted.
	Cluster string `json:"cluster"`
	// RAM is the memory allocated to the database, in MB.
	RAM  int          `json:"ram"`
	Type DatabaseType `json:"type"`
	// Port is the TCP port that the database listens on.
	Port      int       `json:"port"`
	CreatedAt time.Time `json:"created_at"`
}

Database is a database as DatabasesAPI.Get returns it.

type DatabaseCreate

type DatabaseCreate struct {
	Name string `json:"name"`
	// Memory is the memory to allocate, in MB. Redis needs at least 512 and
	// the other engines at least 1024.
	Memory int          `json:"memory"`
	Type   DatabaseType `json:"type"`
	// Version is the engine version. It can be a full version or a major or
	// minor version such as "8".
	Version string `json:"version"`
}

DatabaseCreate describes the database that DatabasesAPI.Create creates.

type DatabaseCreated

type DatabaseCreated struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Memory is the memory allocated to the database, in MB.
	Memory int `json:"memory"`
	// CPU is the CPU allocated to the database. It can be a fraction, such as
	// 0.5.
	CPU      float64      `json:"cpu"`
	Type     DatabaseType `json:"type"`
	Password string       `json:"password"`
	// Certificate is the TLS file, encoded in base64. It is a PEM file with
	// the private key followed by the certificate, or nil when the API could
	// not create it.
	Certificate *string `json:"certificate,omitempty"`
	// ConnectionURL is a ready-to-use connection string that includes the
	// password.
	ConnectionURL string `json:"connection_url"`
	// Cluster identifies where the database is hosted.
	Cluster string `json:"cluster"`
}

DatabaseCreated is the database that DatabasesAPI.Create created. Save Password, because the API returns it only once. ConnectionURL includes it. DatabasesAPI.Certificate returns the certificate again later.

type DatabaseReset

type DatabaseReset string

DatabaseReset selects what DatabasesAPI.ResetCredentials replaces.

const (
	ResetPassword    DatabaseReset = "password"
	ResetCertificate DatabaseReset = "certificate"
)

DatabaseReset values.

type DatabaseSummary

type DatabaseSummary struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// RAM is the memory allocated to the database, in MB.
	RAM  int          `json:"ram"`
	Type DatabaseType `json:"type"`
	// Cluster identifies where the database is hosted.
	Cluster   string    `json:"cluster"`
	CreatedAt time.Time `json:"created_at"`
}

DatabaseSummary is a database as Account lists it.

type DatabaseType

type DatabaseType string

DatabaseType is a database engine.

const (
	DatabaseMongo    DatabaseType = "mongo"    // MongoDB.
	DatabaseMySQL    DatabaseType = "mysql"    // MySQL.
	DatabaseRedis    DatabaseType = "redis"    // Redis.
	DatabasePostgres DatabaseType = "postgres" // PostgreSQL.
)

DatabaseType values.

type DatabaseUpdate

type DatabaseUpdate struct {
	Name string `json:"name,omitempty"`
	// RAM is the new memory, in MB.
	RAM int `json:"ram,omitempty"`
}

DatabaseUpdate holds the changes that DatabasesAPI.Update makes. A field left at its zero value does not change, but at least one must be set.

type DatabasesAPI

type DatabasesAPI struct {

	// Snapshots takes, lists and restores the database's snapshots.
	Snapshots SnapshotsAPI
	// contains filtered or unexported fields
}

DatabasesAPI creates and controls databases.

func (DatabasesAPI) Certificate

func (d DatabasesAPI) Certificate(ctx context.Context, id string) (string, error)

Certificate returns the database's TLS file, encoded in base64. It is a PEM file with the private key followed by the certificate. The database must be running.

func (DatabasesAPI) Create

Create creates a database and returns its connection details. Save Password from the result, because the API returns it only once. DatabasesAPI.ResetCredentials sets a new one. Creating a database can take up to 95 seconds, so without a deadline on ctx, Create waits at least 2 minutes.

Create returns 403 UPGRADE_REQUIRED on plans other than Standard, Pro and Enterprise, and 400 INSUFFICIENT_MEMORY when your plan does not have enough free memory.

Example
ctx := context.Background()
c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))

db, err := c.Databases.Create(ctx, squarecloud.DatabaseCreate{
	Name: "cache", Memory: 512, Type: squarecloud.DatabaseRedis, Version: "8",
})
if err != nil {
	log.Fatal(err)
}
// Save Password, Certificate and ConnectionURL now. The API never shows
// them again.
fmt.Println(db.ID, db.ConnectionURL != "")

func (DatabasesAPI) Delete

func (d DatabasesAPI) Delete(ctx context.Context, id string) error

Delete deletes the database. It returns 409 RESTORE_IN_PROGRESS while a snapshot is being restored, so try again when the restore ends.

func (DatabasesAPI) Get

func (d DatabasesAPI) Get(ctx context.Context, id string) (Database, error)

Get returns the database's name, engine, memory, port and owner.

func (DatabasesAPI) Metrics

func (d DatabasesAPI) Metrics(ctx context.Context, id, rng string) ([]MetricPoint, error)

Metrics returns the database's CPU, memory, network and disk usage over time, newest point first. rng is "24h" (the default), with a point every 5 minutes, or "7d", with a point every hour that holds the hour's average and its CPUMax and RAMMax peaks. "7d" needs a Pro or Enterprise plan, and other plans get the 24-hour answer without an error.

func (DatabasesAPI) ResetCredentials

func (d DatabasesAPI) ResetCredentials(ctx context.Context, id string, reset DatabaseReset) (string, error)

ResetCredentials replaces the database's password or TLS certificate, as reset selects. With ResetPassword it returns the new password, which the API shows only this once. With ResetCertificate it returns "", and DatabasesAPI.Certificate returns the new certificate. The database must be running.

func (DatabasesAPI) Start

func (d DatabasesAPI) Start(ctx context.Context, id string) error

Start starts the database. Without a deadline on ctx, it waits at least 2 minutes for the API to answer.

When the database cannot start, Start returns a 409 error with no message and one of these codes: CONTAINER_ALREADY_STARTED, CONTAINER_ALREADY_STOPPED, CONTAINER_NOT_FOUND, CONTAINER_INSUFFICIENT_DISK_SPACE, CONTAINER_NETWORK_CONFLICT, ACTION_FAILED, or RESTORE_IN_PROGRESS while a snapshot is being restored. The "already" codes mean that the database is already in the state you asked for. They are still returned as errors, so treat them as success when that is what your code needs.

func (DatabasesAPI) Status

func (d DatabasesAPI) Status(ctx context.Context, id string) (RuntimeStats, error)

Status returns the database's current CPU, memory, network and storage usage as formatted strings such as "120.4MB". Use DatabasesAPI.StatusRaw for numbers.

func (DatabasesAPI) StatusAll

func (d DatabasesAPI) StatusAll(ctx context.Context) ([]StatusListItem, error)

StatusAll reports whether each of your databases is running, with its CPU and memory usage.

func (DatabasesAPI) StatusRaw

func (d DatabasesAPI) StatusRaw(ctx context.Context, id string) (RuntimeStatsRaw, error)

StatusRaw returns the same usage as DatabasesAPI.Status as numbers: CPU in percent, memory in MB, and storage and network traffic in bytes.

func (DatabasesAPI) Stop

func (d DatabasesAPI) Stop(ctx context.Context, id string) error

Stop stops the database. Its time limit and errors are the same as for DatabasesAPI.Start.

func (DatabasesAPI) Update

func (d DatabasesAPI) Update(ctx context.Context, id string, in DatabaseUpdate) error

Update renames the database or changes its memory. Fields of in that are left at their zero value do not change.

type DeployCurrent

type DeployCurrent struct {
	// App is the repository linked through the GitHub App, or nil when none
	// is linked.
	App *DeployRepository `json:"app,omitempty"`
	// Webhook is the deploy webhook URL, or "" when no webhook is set. It is
	// masked unless your API key may configure the webhook, which needs the
	// apps:deploy scope.
	Webhook string `json:"webhook,omitempty"`
}

DeployCurrent is the deploy setup that AppDeploysAPI.Current returns.

type DeployEvent

type DeployEvent struct {
	// ID is the SHA of the commit being deployed.
	ID string `json:"id"`
	// State is the step, one of the Deploy constants such as [DeploySuccess].
	State string    `json:"state"`
	Date  time.Time `json:"date"`
	// Source is always "git", because only deploys from Git are listed.
	Source string `json:"source"`
	// Branch is the branch being deployed. It is set on "clone" events.
	Branch string `json:"branch,omitempty"`
	// Code says why the deploy failed, such as "CLONE_FAILED". It is set on
	// "error" events.
	Code string `json:"code,omitempty"`
	// Message gives the details of the failure on some "error" events.
	Message string `json:"message,omitempty"`
	// Files lists the changed files on "commit" events.
	Files *DeployFiles `json:"files,omitempty"`
}

DeployEvent is one step of a deploy. AppDeploysAPI.List returns one list of events per deploy.

type DeployFiles

type DeployFiles struct {
	Added    []string `json:"added"`
	Removed  []string `json:"removed"`
	Modified []string `json:"modified"`
}

DeployFiles lists the files that a deploy added, removed and modified.

type DeployRepository

type DeployRepository struct {
	// ID is the GitHub id of the repository.
	ID     *int64  `json:"id"`
	Name   *string `json:"name"`
	Branch *string `json:"branch"`
}

DeployRepository is the repository linked through the GitHub App, as DeployCurrent reports it. A field is nil when the API does not send it.

type EnvVars

type EnvVars map[string]string

EnvVars maps environment variable names to their values.

type FileEntry

type FileEntry struct {
	// Name is the name of the file or directory, without its path.
	Name string `json:"name"`
	// Type is "file" or "directory".
	Type string `json:"type"`
	// Size is the size in bytes. It is 0 for directories.
	Size int64 `json:"size"`
	// LastModified is when the entry last changed, in Unix milliseconds. It
	// can have a fractional part, such as 1790520641499.565, and is nil when
	// the API could not read it.
	LastModified *float64 `json:"lastModified"`
}

FileEntry is one entry of AppFilesAPI.List.

type IOCounter

type IOCounter struct {
	In  float64 `json:"i"`
	Out float64 `json:"o"`
}

IOCounter is a pair of byte counts, one for each direction.

type LinkedRepository

type LinkedRepository struct {
	// ID is the GitHub id of the repository.
	ID int64 `json:"id"`
	// FullName is the repository written as "owner/name".
	FullName string `json:"full_name"`
	Branch   string `json:"branch"`
}

LinkedRepository is the repository that AppDeploysAPI.LinkGithubApp linked.

type LoadBalancer

type LoadBalancer struct {
	Hostname string            `json:"hostname"`
	Apps     []LoadBalancerApp `json:"apps"`
}

LoadBalancer is a custom domain and the applications that serve it. When there are two or more, the traffic is spread across them.

type LoadBalancerApp

type LoadBalancerApp struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Cluster identifies where the application is hosted.
	Cluster string `json:"cluster,omitempty"`
}

LoadBalancerApp is one application behind a LoadBalancer.

type LoadBalancers

type LoadBalancers struct {
	// Limit is how many applications can share one custom domain on your
	// plan.
	Limit int `json:"limit"`
	// Balancers holds one entry for each custom domain.
	Balancers []LoadBalancer `json:"balancers"`
}

LoadBalancers is the result of AppsAPI.LoadBalancers.

type MetricPoint

type MetricPoint struct {
	Date time.Time `json:"date"`
	// CPU is the CPU usage, in percent of the CPU your plan allocates. On "7d"
	// points it is the hour's average.
	CPU float64 `json:"cpu"`
	// RAM is the memory in use, in MB. On "7d" points it is the hour's
	// average.
	RAM float64 `json:"ram"`
	// Net holds the bytes received and sent since the application or database
	// last started. A value lower than on the previous point means that it
	// restarted.
	Net []float64 `json:"net"`
	// Disk holds the bytes read and written, counted the same way as Net. It
	// is nil on a point without a reading.
	Disk []int64 `json:"disk"`
	// Storage is the disk space in use, in bytes. It is nil on a point
	// without a reading.
	Storage *int64 `json:"storage"`
	// CPUMax is the hour's highest CPU usage. It is set only on "7d" points.
	CPUMax *float64 `json:"cpu_max,omitempty"`
	// RAMMax is the hour's highest memory use. It is set only on "7d" points.
	RAMMax *float64 `json:"ram_max,omitempty"`
}

MetricPoint is one point of AppsAPI.Metrics or DatabasesAPI.Metrics.

type NetIO

type NetIO struct {
	In  float64   `json:"i"`
	Out float64   `json:"o"`
	New IOCounter `json:"new"`
}

NetIO is the network traffic of a RealtimeStatus. In and Out are the total bytes received and sent, and New is the current rate in bytes per second.

type NetworkAnalytics

type NetworkAnalytics struct {
	Visits    []AnalyticsTimeBucket `json:"visits"`
	Countries []AnalyticsBucket     `json:"countries"`
	Devices   []AnalyticsBucket     `json:"devices"`
	OS        []AnalyticsBucket     `json:"os"`
	Browsers  []AnalyticsBucket     `json:"browsers"`
	Protocols []AnalyticsBucket     `json:"protocols"`
	Methods   []AnalyticsBucket     `json:"methods"`
	Paths     []AnalyticsBucket     `json:"paths"`
	// Referers uses "Direct" for requests without a referer.
	Referers []AnalyticsBucket `json:"referers"`
	// Providers breaks the traffic down by network provider, written as
	// "NAME (ASN)".
	Providers []AnalyticsBucket `json:"providers"`
	// IPs lists the client IP addresses with the most requests.
	IPs []AnalyticsTotalBucket `json:"ips"`
	// StatusCodes counts every response status, not only errors.
	StatusCodes []AnalyticsTotalBucket `json:"status_codes"`
	// Bots uses "Unverified" for traffic that is not from a verified bot.
	Bots         []AnalyticsTotalBucket `json:"bots"`
	ContentTypes []AnalyticsTotalBucket `json:"content_types"`
}

NetworkAnalytics is the traffic summary that AppNetworkAPI.Analytics returns. Visits is the traffic over time, and every other field breaks the traffic down by one dimension.

type NetworkErrors

type NetworkErrors struct {
	Summary NetworkErrorsSummary `json:"summary"`
	// ByStatus counts the requests of each status code.
	ByStatus []NetworkErrorsStatus `json:"by_status"`
	// Timeseries is the errors over time.
	Timeseries []NetworkErrorsBucket `json:"timeseries"`
	// TopPaths lists the paths with the most errors.
	TopPaths []NetworkErrorsPath `json:"top_paths"`
	// ByMethod counts the errors of each HTTP method.
	ByMethod []NetworkErrorsMethod `json:"by_method"`
}

NetworkErrors is the error summary that AppNetworkAPI.Errors returns.

type NetworkErrorsBucket

type NetworkErrorsBucket struct {
	Date    time.Time        `json:"date"`
	Buckets map[string]int64 `json:"buckets"`
	Total   int64            `json:"total"`
}

NetworkErrorsBucket is the errors of one time slot in NetworkErrors.Timeseries. Buckets maps each status code, written as a string, to its number of requests.

type NetworkErrorsMethod

type NetworkErrorsMethod struct {
	Method   *string          `json:"method"`
	Total    int64            `json:"total"`
	ByStatus map[string]int64 `json:"by_status"`
}

NetworkErrorsMethod is the errors of one HTTP method. ByStatus maps each status code, written as a string, to its number of requests. Method is nil when it is unknown.

type NetworkErrorsPath

type NetworkErrorsPath struct {
	Path     string           `json:"path"`
	Method   *string          `json:"method"`
	Total    int64            `json:"total"`
	ByStatus map[string]int64 `json:"by_status"`
}

NetworkErrorsPath is one of the paths with the most errors. ByStatus maps each status code, written as a string, to its number of requests. Method is nil when it is unknown.

type NetworkErrorsStatus

type NetworkErrorsStatus struct {
	Status   int   `json:"status"`
	Requests int64 `json:"requests"`
}

NetworkErrorsStatus is the number of requests that got one status code.

type NetworkErrorsSummary

type NetworkErrorsSummary struct {
	Total   int64            `json:"total"`
	ByClass map[string]int64 `json:"by_class"`
}

NetworkErrorsSummary is the total number of errors. ByClass splits it into the keys "4xx" and "5xx".

type NetworkLog

type NetworkLog struct {
	Timestamp time.Time          `json:"timestamp"`
	Client    NetworkLogClient   `json:"client"`
	Request   NetworkLogRequest  `json:"request"`
	Response  NetworkLogResponse `json:"response"`
}

NetworkLog is one request served from the application's domains, as AppNetworkAPI.Logs returns it.

type NetworkLogClient

type NetworkLogClient struct {
	IP       *string `json:"ip"`
	Country  *string `json:"country"`
	Location *string `json:"location"`
	// ASN is the client's network, written as its autonomous system number.
	ASN string `json:"asn"`
	// Agent is the client's User-Agent header.
	Agent    *string `json:"agent"`
	Category *string `json:"category"`
}

NetworkLogClient is who sent the request of a NetworkLog. A pointer field is nil when it is unknown.

type NetworkLogRequest

type NetworkLogRequest struct {
	// Mitigated is true when the edge's protection acted on the request.
	Mitigated bool    `json:"mitigated"`
	Method    string  `json:"method"`
	Host      string  `json:"host"`
	Path      string  `json:"path"`
	Query     *string `json:"query"`
	Protocol  string  `json:"protocol"`
	Referer   *string `json:"referer"`
}

NetworkLogRequest is the request of a NetworkLog. A pointer field is nil when the request did not have it.

type NetworkLogResponse

type NetworkLogResponse struct {
	Status      int     `json:"status"`
	ContentType *string `json:"contentType"`
	// Cache is the edge cache status of the response.
	Cache *string `json:"cache"`
}

NetworkLogResponse is the response of a NetworkLog. A pointer field is nil when it is unknown.

type NetworkPerformance

type NetworkPerformance struct {
	Summary    PerformanceSummary  `json:"summary"`
	Timeseries []PerformanceBucket `json:"timeseries"`
	// Countries breaks the latency down by the visitor's country.
	Countries []PerformanceRegion `json:"countries"`
	// Colos breaks the latency down by edge location.
	Colos        []PerformanceRegion `json:"colos"`
	SlowestPaths []PerformancePath   `json:"slowest_paths"`
}

NetworkPerformance is the latency summary that AppNetworkAPI.Performance returns. Edge latency is the time until the edge sends the first byte, and origin latency is how long your application took to respond.

type Option

type Option func(*Client)

Option changes a setting of a Client. Pass options to New.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL sends requests to u instead of DefaultBaseURL, for example to a proxy or a test server. A trailing slash is removed.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient makes the client send its requests through hc. A nil hc keeps the default, an empty http.Client.

Do not set hc.Timeout. That limit also covers reading the response, so it would cut realtime streams and large downloads. Use WithTimeout, contexts and the timeouts of hc.Transport instead.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how many times a failed call is repeated when that is safe. The default is 2, and 0 or a negative n turns retries off. See APIError for the failures that are retried.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets how long a call may take when its context has no deadline. The default is 30 seconds. A deadline on the context always wins.

Calls that the API can hold open get at least 2 minutes. They are Start, Stop and Restart of applications and databases, DatabasesAPI.Create, snapshot Create and Restore, and AIAPI.Chat. Uploads, AppFilesAPI.Write with more than 1 MiB of content, and Client.DownloadSnapshot have no time limit, so only the context stops them. AppsAPI.Realtime applies the timeout only until the stream opens.

A d of 0 or less turns every time limit off, the 2-minute minimum included.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent replaces the whole User-Agent header, which is "squarecloud-sdk-go/<Version>" by default.

type Percentiles

type Percentiles struct {
	P50 *float64 `json:"p50"`
	P95 *float64 `json:"p95"`
	P99 *float64 `json:"p99"`
}

Percentiles holds the 50th, 95th and 99th percentile latencies, in milliseconds. A field is nil when there were no requests.

type PerformanceBucket

type PerformanceBucket struct {
	Date     time.Time   `json:"date"`
	Requests int64       `json:"requests"`
	Edge     Percentiles `json:"edge"`
	Origin   Percentiles `json:"origin"`
}

PerformanceBucket is the latency in one time slot of NetworkPerformance.Timeseries.

type PerformancePath

type PerformancePath struct {
	Path     string   `json:"path"`
	P95      *float64 `json:"p95"`
	P99      *float64 `json:"p99"`
	Requests int64    `json:"requests"`
}

PerformancePath is one of the slowest paths, with latencies in milliseconds. A latency is nil when there is no data.

type PerformanceRegion

type PerformanceRegion struct {
	Type     string   `json:"type"`
	City     *string  `json:"city,omitempty"`
	Country  *string  `json:"country,omitempty"`
	P50      *float64 `json:"p50"`
	P95      *float64 `json:"p95"`
	Requests int64    `json:"requests"`
}

PerformanceRegion is the latency in one country or edge location, in milliseconds. For a country, Type is the country code. For an edge location, Type is the location code, and City and Country say where it is. A pointer field is nil when there is no data.

type PerformanceSummary

type PerformanceSummary struct {
	Edge     Percentiles `json:"edge"`
	Origin   Percentiles `json:"origin"`
	Requests int64       `json:"requests"`
}

PerformanceSummary is the latency over the whole period.

type Plan

type Plan struct {
	// Name is the plan, such as "standard-8". "free" means that the account
	// has no active plan.
	Name string `json:"name"`
	// Memory is the memory of the plan and how much of it is in use.
	Memory PlanMemory `json:"memory"`
	// Duration is when the plan expires, in Unix milliseconds. It is nil when
	// the account has no active plan.
	Duration *int64 `json:"duration"`
}

Plan is the account's plan.

type PlanMemory

type PlanMemory struct {
	Limit     int `json:"limit"`
	Available int `json:"available"`
	Used      int `json:"used"`
}

PlanMemory is the memory of a Plan in MB. Limit is the total, Available is what is left, and Used is what your applications and databases take.

type Realtime

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

Realtime is a live stream of an application's logs and resource usage, opened with AppsAPI.Realtime. Call Realtime.Next in a loop until it returns an error, and always call Realtime.Close when you are done.

Next returns io.EOF when the stream ends normally, which happens after the server's 10-minute limit or right after a REALTIME_DISCONNECTED event. When the connection drops, or the server sends REALTIME_RECONNECT, the stream reopens by itself. The API allows one open per application every 5 seconds, so a reopen waits until at least 5.5 seconds have passed since the previous one. After 3 reopens in a row without a logs or status event, Next returns an *APIError with code CodeNetworkError that wraps the last error.

Cancel the context passed to AppsAPI.Realtime to stop the stream at any time. Next then returns the context's error, such as context.Canceled.

func (*Realtime) Close

func (s *Realtime) Close() error

Close ends the stream and releases its connection. To interrupt a Next call that is waiting in another goroutine, cancel the context passed to AppsAPI.Realtime instead.

func (*Realtime) Next

func (s *Realtime) Next() (RealtimeEvent, error)

Next waits for the next event and returns it. It returns io.EOF when the server ends the stream, after a REALTIME_DISCONNECTED event, and after Realtime.Close. See Realtime for reconnects and the other errors.

type RealtimeEvent

type RealtimeEvent struct {
	// Event is the kind of event, such as "logs" or "status".
	Event string
	// Data is the text of the event as the server sent it.
	Data string
	// ID is the id of the latest event on the current connection that carried
	// one, or "" when none did.
	ID string
	// Stream is "stdout" or "stderr" on a logs event, and "" otherwise.
	Stream string
	// Line is the log text on a logs event, and "" otherwise.
	Line string
	// Status is the full resource usage on a status event, where it is never
	// nil. It is nil on every other event.
	Status *RealtimeStatus
}

RealtimeEvent is one event of a Realtime stream. Event names its kind, and the kind decides which other fields are set:

  • "logs" is a line of output. Line holds the text, and Stream is "stdout" or "stderr".
  • "status" is the application's resource usage. Status holds the full state. Each status event can carry only some of the values, so the SDK keeps the others from earlier events, across reconnects too. A malformed status event leaves the state unchanged.
  • "system" is a notice from the server. Data is a code such as REALTIME_CONNECTING, REALTIME_TIMEOUT, REALTIME_DISCONNECTED, REALTIME_RECONNECT or REALTIME_ERROR.
  • "error" is a problem with the application. Data is a code such as CONTAINER_NOT_FOUND.
  • "message" is an event the server sent without a kind.

type RealtimeStatus

type RealtimeStatus struct {
	// CPU is the CPU usage in percent.
	CPU float64 `json:"cpu"`
	// CPULimit is the number of CPU cores allocated, such as 1 or 0.5.
	CPULimit float64 `json:"cpuLimit"`
	// RAM holds the memory in use and the memory limit, both in MB.
	RAM [2]float64 `json:"ram"`
	// Status is the state of the application, such as "running".
	Status string `json:"status"`
	// NetIO is the network traffic.
	NetIO NetIO `json:"netIO"`
	// BlockIO is the disk traffic, in bytes read and written.
	BlockIO IOCounter `json:"bIO"`
	// Uptime is when the application started, in Unix milliseconds.
	Uptime int64 `json:"uptime"`
}

RealtimeStatus is the resource usage that a status RealtimeEvent reports.

type RuntimeStats

type RuntimeStats struct {
	// CPU is the CPU usage, such as "0.5%".
	CPU string `json:"cpu"`
	// RAM is the memory in use, such as "120.4MB".
	RAM string `json:"ram"`
	// Status is the lifecycle state, such as "running" or "exited".
	Status string `json:"status"`
	// Running is true when Status is "running".
	Running bool `json:"running"`
	// Restoring is true while a snapshot restore is queued or running. Status
	// keeps its own value meanwhile, which is "exited" while the restore holds
	// the application or database stopped.
	Restoring bool `json:"restoring,omitempty"`
	// Storage is the disk space in use.
	Storage string `json:"storage"`
	// Network is the network traffic.
	Network StatsNetwork `json:"network"`
	// Uptime is when the application or database last started, in Unix
	// milliseconds. It is nil when it is not running.
	Uptime *int64 `json:"uptime"`
}

RuntimeStats is the current usage of an application or database as formatted strings. AppsAPI.Status and DatabasesAPI.Status return it.

type RuntimeStatsRaw

type RuntimeStatsRaw struct {
	// CPU is the CPU usage in percent.
	CPU float64 `json:"cpu"`
	// RAM is the memory in use, in MB.
	RAM       float64 `json:"ram"`
	Status    string  `json:"status"`
	Running   bool    `json:"running"`
	Restoring bool    `json:"restoring,omitempty"`
	// Storage is the disk space in use, in bytes.
	Storage int64 `json:"storage"`
	// Network is the network traffic in bytes.
	Network StatsNetworkRaw `json:"network"`
	Uptime  *int64          `json:"uptime"`
}

RuntimeStatsRaw is the current usage of an application or database as numbers. AppsAPI.StatusRaw and DatabasesAPI.StatusRaw return it. Fields without a comment mean the same as in RuntimeStats.

type ServiceAPI

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

ServiceAPI reports the status of the Square Cloud platform.

func (ServiceAPI) Status

func (s ServiceAPI) Status(ctx context.Context) (ServiceStatus, error)

Status returns the current status of the Square Cloud services and of the outside services they depend on, with the open incidents and maintenance windows. It works without an API key.

type ServiceComponent

type ServiceComponent struct {
	Name   string `json:"name"`
	Status string `json:"status"`
}

ServiceComponent is a part of the platform that is not fully working. Status is "maintenance", "degraded" or "outage".

type ServiceEntry

type ServiceEntry struct {
	Name string `json:"name"`
	// Status is "operational", "degraded", "outage", "maintenance" or
	// "unknown". "unknown" means that the state could not be confirmed, not
	// that the service is down.
	Status string `json:"status"`
	// Summary says what is wrong and what it affects. It is "" while the
	// service is operational.
	Summary string `json:"summary,omitempty"`
	// UnresolvedIncidents is the number of open incidents.
	UnresolvedIncidents int `json:"unresolved_incidents,omitempty"`
	// DegradedComponents is the number of components that are not fully
	// working.
	DegradedComponents int `json:"degraded_components,omitempty"`
	// APILatency is the response time of the service's API, or nil when it is
	// not measured.
	APILatency *APILatency `json:"api_latency,omitempty"`
}

ServiceEntry is the state of one service in ServiceStatus.

type ServiceIncident

type ServiceIncident struct {
	// Type is "maintenance" or "incident".
	Type  string `json:"type"`
	Title string `json:"title"`
	// Status is "maintenance", "degraded", "outage", "operational" or
	// "unknown".
	Status    string    `json:"status"`
	StartedAt time.Time `json:"started_at"`
	// EndsAt is when the maintenance is expected to end, or nil when no end
	// was announced.
	EndsAt *time.Time `json:"ends_at"`
	// Affected names the affected components.
	Affected []string `json:"affected"`
	// Update is the latest update as written on the status page. It can use
	// Markdown.
	Update    string     `json:"update,omitempty"`
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
}

ServiceIncident is an open incident or maintenance window in ServiceStatus.

type ServiceStatus

type ServiceStatus struct {
	// Status is the overall state of Square Cloud: "online", "maintenance",
	// "degraded" or "unknown". "unknown" means that the check itself could not
	// run, not that the platform is down.
	Status string `json:"status"`
	// Message describes the overall state.
	Message string `json:"message"`
	// CheckedAt is when the status was checked.
	CheckedAt time.Time `json:"checked_at"`
	// Stale is true when the regular status report was unavailable and the
	// status was checked on the spot instead.
	Stale bool `json:"stale"`
	// Services holds the state of each Square Cloud service, keyed by a name
	// such as "blob_storage". The API can leave out services and fields.
	Services map[string]ServiceEntry `json:"services"`
	// Dependencies holds the state of each outside service that the platform
	// relies on, keyed by a name such as "github". An incident there does not
	// change Status.
	Dependencies map[string]ServiceEntry `json:"dependencies"`
	// Incidents lists the open incidents and maintenance windows, newest
	// first.
	Incidents []ServiceIncident `json:"incidents,omitempty"`
	// Components lists the parts of the platform that are not fully working.
	Components []ServiceComponent `json:"components,omitempty"`
}

ServiceStatus is the platform status that ServiceAPI.Status returns.

type Snapshot

type Snapshot struct {
	// Name identifies the snapshot.
	Name string `json:"name"`
	// Size is the size of the archive, in bytes.
	Size int64 `json:"size"`
	// Modified is when the snapshot was taken.
	Modified time.Time `json:"modified"`
	// Key is the signed part of URL.
	Key string `json:"key"`
	// VersionID identifies this version of the snapshot.
	VersionID string `json:"version_id"`
	// URL is the download link. It is valid for 1 hour.
	URL string `json:"url"`
	// Runtime is what the archive holds: the application's language, such as
	// "python", or the database engine, such as "postgres". It is nil on old
	// snapshots.
	Runtime *string `json:"runtime"`
	// Origin is "automatic" for the daily snapshot or "manual" for one that
	// was requested. It is nil on old snapshots.
	Origin *string `json:"origin"`
}

Snapshot is one snapshot in a listing. Pass Name and VersionID to SnapshotsAPI.Restore, and URL to Client.DownloadSnapshot.

type SnapshotCreated

type SnapshotCreated struct {
	// URL is the download link, valid for 1 hour. It is "" while Pending is
	// true, and also when the API key lacks the snapshots:read scope.
	URL string `json:"url"`
	// Key is the signed part of URL. It is "" in the same cases as URL.
	Key string `json:"key"`
	// Pending is true when the snapshot is still being taken, which is not an
	// error. It appears in [SnapshotsAPI.List] within about 2 minutes.
	Pending bool `json:"-"`
}

SnapshotCreated is the result of SnapshotsAPI.Create.

type SnapshotRestoreState

type SnapshotRestoreState struct {
	// State is "queued" or "running" while the restore runs, "success" or
	// "error" for 1 hour after it ends, and "none" otherwise.
	State string `json:"state"`
	// Step is the current step while the restore runs, and "done" once it
	// ends.
	Step string `json:"step,omitempty"`
	// Code says why the restore failed when State is "error".
	Code string `json:"code,omitempty"`
	// StartedAt is when the restore started, in Unix milliseconds, or nil when
	// the API does not report it.
	StartedAt *int64 `json:"started_at,omitempty"`
	// FinishedAt is when the restore ended, in Unix milliseconds, or nil when
	// the API does not report it.
	FinishedAt *int64 `json:"finished_at,omitempty"`
}

SnapshotRestoreState is the progress of the last restore, as SnapshotsAPI.RestoreState reports it.

type SnapshotRestored

type SnapshotRestored struct {
	// Pending is true when the restore is still running after the call
	// returned, which is not an error. Follow it with
	// [SnapshotsAPI.RestoreState].
	Pending bool `json:"-"`
}

SnapshotRestored is the result of SnapshotsAPI.Restore.

type SnapshotScope

type SnapshotScope string

SnapshotScope selects whether AccountAPI.Snapshots lists the snapshots of applications or of databases.

const (
	SnapshotScopeApplications SnapshotScope = "applications"
	SnapshotScopeDatabases    SnapshotScope = "databases"
)

SnapshotScope values.

type SnapshotsAPI

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

SnapshotsAPI takes, lists and restores the snapshots of one application or database. AppsAPI.Snapshots works on applications and DatabasesAPI.Snapshots on databases. Every method takes the id of the application or database.

func (SnapshotsAPI) Create

func (s SnapshotsAPI) Create(ctx context.Context, id string) (SnapshotCreated, error)

Create takes a snapshot of the application or database id and returns its download link, which is valid for 1 hour. Use Client.DownloadSnapshot to save it. Without a deadline on ctx, Create waits at least 2 minutes. See AppsAPI for workspace applications.

A large snapshot can take longer than the API waits. Create then returns a result with Pending set and no URL, which is not an error. The snapshot appears in SnapshotsAPI.List within about 2 minutes. Do not call Create again, because it allows one call every 3 minutes and each call counts against your plan's daily snapshot quota. With an API key that lacks the snapshots:read scope, a finished snapshot comes back with URL and Key empty.

Create returns 409 RESTORE_IN_PROGRESS while a snapshot is being restored, so try again when the restore ends. It returns 429 DAILY_SNAPSHOTS_LIMIT_REACHED when you have used your plan's daily snapshots, and 503 CLUSTER_MAINTENANCE_TRY_LATER during maintenance, so try again in a few minutes.

Example
ctx := context.Background()
c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))
appID := "a1b2c3d4e5f60718293a4b5c6d7e8f90"

snap, err := c.Apps.Snapshots.Create(ctx, appID)
if err != nil {
	log.Fatal(err)
}
if snap.Pending {
	fmt.Println("The snapshot is still being taken. List the snapshots in a few minutes.")
	return
}
out, err := os.Create("snapshot.zip")
if err != nil {
	log.Fatal(err)
}
defer out.Close()
if err := c.DownloadSnapshot(ctx, snap.URL, out); err != nil {
	log.Fatal(err)
}

func (SnapshotsAPI) List

func (s SnapshotsAPI) List(ctx context.Context, id string) ([]Snapshot, error)

List returns the snapshots of the application or database id, each with a download link. It returns 503 SNAPSHOTS_UNAVAILABLE while snapshot storage cannot answer. The SDK does not retry that error, and the API suggests waiting about 30 seconds. See AppsAPI for workspace applications.

func (SnapshotsAPI) Restore

func (s SnapshotsAPI) Restore(ctx context.Context, id, name, versionID string) (SnapshotRestored, error)

Restore restores the application or database id from a snapshot. name and versionID are the Name and VersionID fields of a Snapshot. Without a deadline on ctx, Restore waits at least 2 minutes. See AppsAPI for workspace applications.

A restore that takes longer than about 90 seconds keeps running after the call returns. Restore then returns a result with Pending set, which is not an error. Follow the restore with SnapshotsAPI.RestoreState, and do not call Restore again.

A restore can fail with these errors:

  • 400 MISSING_PARAMETERS, INVALID_SNAPSHOT_ID or INVALID_VERSION_ID, and SNAPSHOT_DATABASE_MISMATCH for databases.
  • 404 APP_NOT_FOUND or DATABASE_NOT_FOUND, SNAPSHOT_NOT_FOUND, SNAPSHOT_RESTORE_FAILED, SNAPSHOT_CORRUPT, RESTORE_INTERRUPTED or CONTAINER_NOT_FOUND.
  • 409 RESTORE_IN_PROGRESS or SNAPSHOT_IN_PROGRESS, while another restore or a snapshot is running.
  • 413 PAYLOAD_TOO_LARGE.
  • 503 CLUSTER_MAINTENANCE_TRY_LATER, during maintenance.
Example
ctx := context.Background()
c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))
appID := "a1b2c3d4e5f60718293a4b5c6d7e8f90"

// Restore the first listed snapshot. Restore takes its Name and
// VersionID.
snaps, err := c.Apps.Snapshots.List(ctx, appID)
if err != nil || len(snaps) == 0 {
	log.Fatal("no snapshots", err)
}
res, err := c.Apps.Snapshots.Restore(ctx, appID, snaps[0].Name, snaps[0].VersionID)
if err != nil {
	log.Fatal(err)
}
// A large restore keeps running after Restore returns. Follow it with
// RestoreState until it is no longer queued or running, and never call
// Restore again.
st := squarecloud.SnapshotRestoreState{State: "success"}
for res.Pending {
	time.Sleep(10 * time.Second)
	if st, err = c.Apps.Snapshots.RestoreState(ctx, appID); err != nil {
		log.Fatal(err)
	}
	res.Pending = st.State == "queued" || st.State == "running"
}
switch st.State {
case "success":
	fmt.Println("restored")
case "error":
	log.Fatal("restore failed: ", st.Code)
default: // "none" means that the result is no longer available.
	fmt.Println("restore result unknown")
}

func (SnapshotsAPI) RestoreState

func (s SnapshotsAPI) RestoreState(ctx context.Context, id string) (SnapshotRestoreState, error)

RestoreState reports the progress of the last restore of the application or database id. State is "queued" or "running" while the restore runs, and Step names the current step. When the restore ends, State becomes "success" or "error", and Code says why it failed. That result stays for 1 hour. After that, or when there was no recent restore, State is "none". See AppsAPI for workspace applications.

RestoreState allows up to 30 calls a minute, so poll it every few seconds.

type StatsNetwork

type StatsNetwork struct {
	Total string `json:"total"`
	Now   string `json:"now"`
}

StatsNetwork is the network traffic of RuntimeStats. Each field holds the incoming and outgoing traffic in one formatted string. Total is the overall traffic and Now the current traffic.

type StatsNetworkRaw

type StatsNetworkRaw struct {
	Total [2]int64 `json:"total"`
	Now   [2]int64 `json:"now"`
}

StatsNetworkRaw is the network traffic of RuntimeStatsRaw. Each pair holds the bytes received and the bytes sent. Total is the overall traffic and Now the current traffic.

type StatusListItem

type StatusListItem struct {
	ID      string `json:"id"`
	Running bool   `json:"running"`
	CPU     string `json:"cpu,omitempty"`
	RAM     string `json:"ram,omitempty"`
}

StatusListItem is the state of one application or database in AppsAPI.StatusAll or DatabasesAPI.StatusAll. CPU and RAM are formatted strings such as "0.00%" and "0.00MB". They are set only while it is running.

type User

type User struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
	// Locale is the user's preferred language, such as "en-US".
	Locale    string    `json:"locale"`
	Plan      Plan      `json:"plan"`
	CreatedAt time.Time `json:"created_at"`
}

User is the owner of the API key.

type Workspace

type Workspace struct {
	// ID is 32 hexadecimal characters, or 40 for older workspaces.
	ID   string `json:"id"`
	Name string `json:"name"`
	// Owner is the user id of the workspace's owner.
	Owner        string            `json:"owner"`
	Members      []WorkspaceMember `json:"members"`
	Applications []WorkspaceApp    `json:"applications"`
	CreatedAt    time.Time         `json:"createdAt"`
}

Workspace is a workspace with its members and shared applications.

type WorkspaceApp

type WorkspaceApp struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Description is nil when the application has none.
	Description *string `json:"desc"`
	// RAM is the memory allocated to the application, in MB.
	RAM int `json:"ram"`
	// Lang is the application's language, such as "javascript".
	Lang string `json:"lang"`
	// Domain is the default hostname, or nil when the application has none.
	Domain *string `json:"domain"`
	// Custom is the custom domain, or nil when none is set.
	Custom *string `json:"custom"`
}

WorkspaceApp is an application shared in a Workspace.

type WorkspaceAppsAPI

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

WorkspaceAppsAPI shares applications in a workspace.

func (WorkspaceAppsAPI) Add

func (a WorkspaceAppsAPI) Add(ctx context.Context, workspaceID, appID string) error

Add shares your application appID in the workspace. Its members then reach it with the composite id described in AppsAPI.

func (WorkspaceAppsAPI) Remove

func (a WorkspaceAppsAPI) Remove(ctx context.Context, workspaceID, appID string) error

Remove stops sharing the application appID in the workspace. Only the workspace owner can do this.

type WorkspaceCreated

type WorkspaceCreated struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

WorkspaceCreated is the workspace that WorkspacesAPI.Create created.

type WorkspaceGroup

type WorkspaceGroup string

WorkspaceGroup is the permission level of a workspace member, which you pass to WorkspaceMembersAPI.Add and WorkspaceMembersAPI.Update. The owner's group is "owner", which cannot be assigned.

const (
	GroupAdmin    WorkspaceGroup = "admin"    // An admin has full control, like the owner.
	GroupMaintain WorkspaceGroup = "maintain" // A maintainer has manager access, plus commits, files, DNS and the cache.
	GroupManager  WorkspaceGroup = "manager"  // A manager can monitor, start, stop and restart applications.
	GroupView     WorkspaceGroup = "view"     // A viewer can only read.
)

WorkspaceGroup values.

type WorkspaceMember

type WorkspaceMember struct {
	// ID is the member's user id.
	ID string `json:"id"`
	// Name is the member's name, or nil when it cannot be found, for example
	// for a deleted account.
	Name *string `json:"name"`
	// Group is "owner" or one of the [WorkspaceGroup] values.
	Group    string    `json:"group"`
	JoinedAt time.Time `json:"joinedAt"`
}

WorkspaceMember is a member of a Workspace.

type WorkspaceMembersAPI

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

WorkspaceMembersAPI adds, changes and removes the members of a workspace.

func (WorkspaceMembersAPI) Add

func (m WorkspaceMembersAPI) Add(ctx context.Context, workspaceID, code string, group WorkspaceGroup) error

Add adds a user to the workspace with the permissions of group. code is the invite code that the user got from WorkspaceMembersAPI.InviteCode.

func (WorkspaceMembersAPI) InviteCode

func (m WorkspaceMembersAPI) InviteCode(ctx context.Context) (string, error)

InviteCode returns an invite code for your own account. Give it to a workspace owner, who passes it to WorkspaceMembersAPI.Add. The code expires after 5 minutes, and you can get a new one every 5 minutes.

func (WorkspaceMembersAPI) Remove

func (m WorkspaceMembersAPI) Remove(ctx context.Context, workspaceID, memberID string) error

Remove removes the member memberID from the workspace.

func (WorkspaceMembersAPI) Update

func (m WorkspaceMembersAPI) Update(ctx context.Context, workspaceID, memberID string, group WorkspaceGroup) error

Update changes the group, and so the permissions, of the member memberID.

type WorkspacesAPI

type WorkspacesAPI struct {

	// Members adds, changes and removes the members of a workspace.
	Members WorkspaceMembersAPI
	// Apps shares applications in a workspace.
	Apps WorkspaceAppsAPI
	// contains filtered or unexported fields
}

WorkspacesAPI creates workspaces, which let other Square Cloud accounts work on your applications.

func (WorkspacesAPI) Create

func (w WorkspacesAPI) Create(ctx context.Context, name string) (WorkspaceCreated, error)

Create creates a workspace that you own and returns its id. It returns 403 UPGRADE_REQUIRED on plans other than Standard, Pro and Enterprise, and 400 WORKSPACE_LIMIT_REACHED when you already own as many workspaces as your plan allows.

Example
ctx := context.Background()
c := squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))

ws, err := c.Workspaces.Create(ctx, "Acme")
if err != nil {
	log.Fatal(err)
}
if err := c.Workspaces.Apps.Add(ctx, ws.ID, "a1b2c3d4e5f60718293a4b5c6d7e8f90"); err != nil {
	log.Fatal(err)
}
fmt.Println(ws.ID, ws.Name)

func (WorkspacesAPI) Delete

func (w WorkspacesAPI) Delete(ctx context.Context, workspaceID string) error

Delete deletes the workspace. Only its owner can delete it.

func (WorkspacesAPI) Get

func (w WorkspacesAPI) Get(ctx context.Context, workspaceID string) (Workspace, error)

Get returns the workspace with its members and shared applications.

func (WorkspacesAPI) Leave

func (w WorkspacesAPI) Leave(ctx context.Context, workspaceID string) error

Leave removes you from a workspace that you belong to. The owner cannot leave a workspace and must delete it instead.

func (WorkspacesAPI) List

func (w WorkspacesAPI) List(ctx context.Context) ([]Workspace, error)

List returns the workspaces you own or belong to.

Jump to

Keyboard shortcuts

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