Operations
Idempotency keys, long-running calls, and the operations service
Eight calls run on the orchestrator as operations: Environments.Create,
Destroy, Fork, Migrate and Drain, Snapshots.Create and Restore, and
Images.Convert.
The server waits for the operation up to its attach bound (10 seconds below
its -write-timeout, so 50s by default) and answers as it always has. One that
outlasts the bound is answered with a 202 and an operation id, and the SDK
follows it until it finishes. Either way the method returns exactly what a
direct answer would have given, so callers need no changes.
Idempotency keys
Every one of those eight methods takes trailing ...CallOption:
func WithIdempotencyKey(key string) CallOption
The key is sent as the Idempotency-Key header. A retry of the same request
with the same key attaches to the first call’s operation instead of running
again: it waits for one still running, or gets a finished one’s answer back.
Without the option the SDK sends a fresh random key on every call, which is
enough for the SDK’s own following of a 202, but not for a retry you make
yourself. Pass your own key when you retry:
key := uuid.NewString()
env, err := client.Environments.Create(ctx, req, fuse.WithIdempotencyKey(key))
var apiErr *fuse.APIError
if err != nil && !errors.As(err, &apiErr) {
// the connection dropped or the client timed out. the create may still be
// running, so retry with the same key to attach to it rather than create a
// second environment.
env, err = client.Environments.Create(ctx, req, fuse.WithIdempotencyKey(key))
}
Keys are 1 to 255 visible ascii characters; anything else is a 400
invalid_argument. They are scoped to the credential that sent them, so two
API keys never collide. The same key with a different request (another
method, path, action or body) is a 409 conflict whose Details["reason"]
is idempotency_key_reused, with the first call’s id in
Details["operation_id"]. A finished operation is kept for 24 hours; one that
finished with a 5xx is not kept at all, so its retry runs again. A failure
restate recorded reruns as a new restate invocation; one from before restate
answered (a timeout, a dropped connection) attaches to the first invocation.
Keys live in the orchestrator’s memory and an orchestrator restart forgets
them, except that the key also names the operation’s restate invocation, so a
retry after a restart attaches to the same invocation. A destroy that already
finished is the exception: its vm is gone, so that retry answers 404. After a
restart, a key whose earlier try failed with a 5xx may replay that failure for
up to restate’s idempotency retention (24 hours); retry with a fresh key.
Retrying unavailable
func WithRetry(retries int) Option
A 503 unavailable from one of those calls means the orchestrator could
not take it right now: no host has room, no host is registered, or restate is
down. Nothing was started, so the SDK sends the call again, 3 times by
default. WithRetry(0) turns that off. Cancelling ctx stops the wait.
Each retry reuses the call’s idempotency key, so a create that the server
did run is attached to rather than run twice. It waits at least the
server’s Retry-After (seconds, capped at a minute), or a backoff doubling
from 1s up to 30s when there is none, plus up to half again as random jitter,
so a burst of refused callers spreads out instead of coming back at once.
Builds’ create is retried the same way. A 503 from any other call (a
computer action on an environment with no display) is never retried. Once
the retries run out the 503 comes back as an unavailable error.
Following an accepted operation
func WithOnOperation(fn func(*OperationAccepted)) Option
fn is called once, with the 202 body, whenever a call outlasts the
server’s attach bound, before the SDK starts following it. The fuse CLI
uses it to print the operation id. The following itself polls
GET /v1/operations/{id} with ?wait=30s on the SDK’s no-timeout client, so
only ctx bounds it. Cancelling ctx returns ctx.Err() and leaves the
operation running on the orchestrator.
client, err := fuse.New(baseURL, token,
fuse.WithOnOperation(func(acc *fuse.OperationAccepted) {
log.Printf("%s still running as %s", acc.Operation.Kind, acc.OperationID)
}),
)
client.Operations
func (s *OperationsService) Get(ctx context.Context, id string, opt GetOperationOptions) (*Operation, error)
func (s *OperationsService) Wait(ctx context.Context, id string) (*Operation, error)
Get reports an operation at once, or, with GetOperationOptions.Wait set,
attaches until it finishes for at most that long (capped by the server’s
attach bound). Wait blocks until it finishes; ctx bounds the wait and the
operation keeps running if ctx ends first. Neither returns an error for a
failed operation: check State, then StatusCode and Error.
An operation is readable by the credential that started it, and by the master
token, for 24 hours after it finishes. An unknown, expired or other caller’s
id is a 404 not_found *APIError.
Operation
type Operation struct {
ID string `json:"id"`
Kind string `json:"kind"`
State string `json:"state"`
Step string `json:"step,omitempty"`
StartedAt time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
StatusCode int `json:"status_code,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *ErrorBody `json:"error,omitempty"`
RetryAfter int `json:"retry_after,omitempty"`
}
type OperationAccepted struct {
OperationID string `json:"operation_id"`
Operation Operation `json:"operation"`
}
const (
OperationRunning = "running"
OperationSucceeded = "succeeded"
OperationFailed = "failed"
)
func (o *Operation) Done() bool
Kindiscreate,destroy,fork,migrate,snapshot,restore,drainorimage.convert.Stateissucceededwhen the call answered 2xx andfailedotherwise.Donereports whether it is anything butrunning.Stepis the step the operation last reported starting. No operation reports one now (every operation runs on restate, whose steps show in the restate ui), so it is empty.StatusCode, withResulton success orErroron failure, is what the call itself would have answered.Resultis the raw response body: anEnvironmentInfofor create, migrate and drain,{"children": [...]}for fork, aSnapshotfor snapshot, anImagefor image.convert (withStatusCode202), and empty for destroy and restore.RetryAfteris the seconds the call’sRetry-Afterasked for, set on a failed operation that answered a retry-later503. The retry waits at least that long, as it would for a503answered directly.ErrorBodyis theerrormember of the API’s error envelope:Code,MessageandDetails.