lmjtfy.git / third-party / rustcrates / cloud-mock-lightsail

cloud-mock-lightsail

Last changed

AWS Lightsail as a cloud-mock world: instances, snapshots and operations that finish on a virtual clock, tags, bundles, blueprints, regions and paging, behind the awsJson1.1 wire (POST /, the action in X-Amz-Target, SigV4 headers checked for their shape) and the service's error shapes, with every request and answer held against AWS's own Smithy model, pinned in spec/lightsail-2016-11-28.json (spec/SOURCE.md says where and when).

let mock = cloud_mock_lightsail::mock("us-east-1");
let creds = Credentials { access_key_id: DEFAULT_ACCESS_KEY.into(), secret_access_key: DEFAULT_SECRET_KEY.into(), session_token: None };
let ls = sandbox_lightsail::Lightsail::new(mock.io(), creds, "us-east-1")?;
let vm = sandbox_vm::Vm::new(ls, mock.io());
// open, rest, wake: the adapter's own waits move the world's clock
mock.assert_conforms();

AWS publishes this API as a Smithy model, not OpenAPI, and every call is POST /, so cloud-mock's path-based contract cannot read it. spec::openapi_of turns the model's shapes into JSON Schema in memory (the module header says how) and LightsailChecker knows the wire: the action, the headers, the body against the action's input shape, the answer against its output shape, and an error against the exceptions the action may raise with the HTTP status the model gives each.

What it models

AreaBehaviour
InstancesCreateInstances (names, zone, blueprint, bundle, userData, tags, ipAddressType), CreateInstancesFromSnapshot, GetInstance, GetInstances, GetInstanceState, StartInstance, StopInstance (graceful, or force for one stuck in stopping), RebootInstance, DeleteInstance. An instance is pending until its work is done, then running with a public address; stopping, then stopped without the address (a start gives another); shutting-down until a delete is done. A call that does not fit the state is an InvalidInputException.
SnapshotsCreateInstanceSnapshot (two operations, one for the snapshot and one for its instance), GetInstanceSnapshot(s), DeleteInstanceSnapshot. pending until the clock says available; carries its tags, sizeInGb, fromInstanceName and fromBundleId. An instance can be made from an available one, on a bundle at least as powerful as the source's.
OperationsStarted until the clock reaches the end of the work, then Succeeded with isTerminal; or Failed at once, with errorCode and errorDetails, when a test says so. GetOperation, GetOperations, GetOperationsForResource, newest first.
TagsTagResource, UntagResource for instances, snapshots and every other resource that has tags.
CatalogueGetBundles and GetBlueprints (includeInactive, pageToken), GetRegions (includeAvailabilityZones).
RulesAccess key, credential scope (region and service) and clock skew; a request limit (ThrottlingException); the vCPU quota; a plan size an account may not use; the protocol's SerializationException, UnknownOperationException, IncompleteSignature, MissingAuthenticationToken, UnrecognizedClientException, InvalidSignatureException; every exception with __type, message, code for the service's own, and x-amzn-ErrorType.
Storage and addressesDisks and their snapshots (create, attach, detach, delete, from a snapshot), static IPs, key pairs, public ports, add-ons and automatic snapshots (disks, disk_snapshots, static_ips, key_pairs, ports, addons).
DomainsCreateDomain, DeleteDomain, GetDomain(s) and the entries (CreateDomainEntry, UpdateDomainEntry, DeleteDomainEntry). The model's ResourceName pattern has no dot, so a domain's name in an operation or in GetDomain is a finding of the model, not of the world.
Contact methods and alarmsOne contact method a protocol, PendingVerification until a test calls verify_contact_method; PutAlarm, GetAlarms, TestAlarm, DeleteAlarm on any resource the world has.
Metric dataGetInstanceMetricData, GetLoadBalancerMetricData, GetDistributionMetricData, GetBucketMetricData, GetContainerServiceMetricData, GetRelationalDatabaseMetricData: one deterministic point a period; none for an instance that is not running.
Load balancersCreate, attach and detach instances, attributes, TLS policies, and their own TLS certificates (PENDING_VALIDATION, then ISSUED; an attach needs ISSUED; a delete of an attached one needs force).
Certificates and distributionsCreateCertificate, GetCertificates, DeleteCertificate (refused while a distribution uses it); distributions with bundles, origin, certificate attach and detach, cache reset, update, delete.
BucketsCreate, update, bundle, delete (forceDelete with keys), two access keys a bucket, access for resources, bundles.
Container servicesCreate (with a deployment), update, deployments, images, powers, API metadata, registry login, log, delete.
DatabasesMySQL databases: create, from a snapshot, snapshots, start, stop, reboot, update, parameters, events, log streams, master password, blueprints, bundles, delete with or without a final snapshot.
Exports and small callsExportSnapshot and its records, CreateCloudFormationStack and its records, CopySnapshot (from a snapshot a test puts in another region with add_foreign_snapshot), GetActiveNames, GetProfile, VPC peering, GetCostEstimate, setup history, GUI sessions, SetIpAddressType, UpdateInstanceMetadataOptions.
Not modelledNothing of the model: every action has a handler, and a test walks the model to say so. An action a future model adds answers 501 naming it; the envelope is the mock's own and is not held against the model.

Times, by default (Config, virtual): a create takes 25 s, a start 20 s, a graceful stop 15 s (a forced one 3 s), a reboot 10 s, a delete 10 s, a snapshot 120 s. An account holds 20 vCPUs in the region, 100 requests a second, and a page is 100 items.

For a test

CallWhat
mock(region)A Mock<LightsailWorld> with the contract checks on. LightsailWorld::new(region) is the bare world.
mock.world(|w| w.config.max_vcpus = 2)Change how long things take, the limits and the page size.
w.block_bundle("nano_3_0")The account may not make that plan size: InvalidInputException, "Sorry, your account can not create an instance using this Lightsail plan size."
w.fail_next("StartInstance", Failure::operation_failed(code, details))The next StartInstance answers 200 and its operation has Failed; nothing changes. Also Failure::Throttle and Failure::exception(name, message) (the status is the model's).
w.config.stop_hangsA graceful stop never completes; a forced one does.
w.config.limit_exception, w.config.limit_messageThe words and exception of a full quota: INSTANCE_LIMIT_MESSAGE with ServiceException gives the other report.
mock.fault("POST /", Fault::RateLimit { .. }, Times::Once)The mock's own faults: every call is POST /, so a fault hits the next call whatever its action. Also Limit, Status(503), Latency, Disconnect.
w.accept_access_key(k), w.revoke_access_keys()Who may sign. DEFAULT_ACCESS_KEY is known to every world.
w.actions(), w.count_of(a), w.state_of(n), w.user_data_of(n)What the API never returns in one piece.

The call log has no action in its METHOD path line (all are POST /): the tests read the x-amz-target of the logged request headers.

Where the docs are silent

What this world does where AWS's model and docs say nothing, and what was found, read 2026-10-21. Grades: primary = AWS's model or documentation; secondary = a third-party client or the adapter's own notes; anecdotal = a forum or blog report. Mock marks the world's own choice.

QuestionFoundSource, gradeWhat the world does
The HTTP status of NotFoundException and the othersThe model: AccessDenied 403, NotFound 404, Unauthenticated 401, ServiceException 500, InvalidInput 400, AccountSetupInProgress and RegionSetupInProgress 428. The API reference lists 400 for every onethe pinned model; https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetInstance.html, primary, and they disagreeThe model's. The adapter reads __type, not the status
The wirePOST, X-Amz-Target: Lightsail_20161128.<Action>, Content-Type: application/x-amz-json-1.1, errors with __typehttps://smithy.io/2.0/aws/protocols/aws-json-1_1-protocol.html, primaryAs specified
Which headers are signedThe host header, Content-Type when present, and every x-amz-* headerhttps://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html, primaryChecked on every request (SignedHeaders sorted, lower-case, with those); the signature itself is not verified
Signature and scope errors"Signature expired: date is now earlier than date", "Signature not yet current: date is still later than date", "Credential should be scoped to a valid Region, not region-code", "Date in Credential scope does not match YYYYMMDD"https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-troubleshooting.html, primaryThese words, InvalidSignatureException, 403 (Mock: the type; the page gives only the text)
How far the date may be offNot stated on the pages readnoneMock: five minutes, Config::max_skew (the figure is widely reported, anecdotal)
Missing or malformed credentialsIncompleteSignature and MissingAuthenticationToken are 403; ExpiredToken 403https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/CommonErrors.html, primary403 with those types; Mock: the messages
A key AWS does not knowUnrecognizedClientException, 403, "The security token included in the request is invalid."not on the CommonErrors page; secondary403, secondary (reported for AWS's JSON services); Mock: the text
ThrottlingThrottlingException, "Your request rate is too high", HTTP 400CommonErrors page, primary400; Mock: the rate (100 a second), the text "Rate exceeded", and a Retry-After the API is not described to send
The instance quota"Instances, each supported Region: 20, adjustable. The maximum number of vCPUs per Region for Lightsail instances."https://docs.aws.amazon.com/general/latest/gr/lightsail.html, primary20 vCPUs; a bundle has 2 here. Mock: the exception and words: InvalidInputException with "You reached the quota of total vCPUs that you can create in your account." (the adapter's notes, secondary); another report has a ServiceException "You have reached the maximum number of instances allowed for your account" (anecdotal), limit_exception and limit_message give it
A plan size the account may not use"Sorry, your account can not create an instance using this Lightsail plan size." as an InvalidInputExceptionthe adapter's fixture, secondary (forum reports, anecdotal)block_bundle
An operation's statusNotStarted, Started, Failed, Completed, Succeeded; isTerminal; errorCode, errorDetails; timestamps in epoch secondshttps://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_Operation.html and the model, primaryStarted, Succeeded, Failed; Mock: never NotStarted or Completed
An operation's type for taggingThe model's OperationType has no value for itthe pinned model, primary (absence)The operation leaves operationType out
Snapshot statespending, error, availablethe model, primarypending for 120 s (Mock: the time), available; error is not reached
Instance statesThe page names running and pending only; the adapter assumes the EC2 words and codeshttps://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_InstanceState.html, primary (absence); the adapter's notes, secondarypending 0, running 16, shutting-down 32, stopping 64, stopped 80 (Mock: the codes beyond running)
The address after a stop"When you start a stopped instance, Lightsail assigns a new public IP address to the instance."https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_StopInstance.html, primaryA stopped instance has none; a start gives another. Mock: none while pending
What force is for"forces a Lightsail instance that is stuck in a stopping state to stop"; "only use if stuck"the same page, primaryAllowed on a running or stopping instance; a graceful stop of a stopping one is refused
A start of a running instance, a stop of a stopped oneNot documentednoneMock: InvalidInputException "Instance x is running, not stopped"
What a delete looks like meanwhileNot documentednoneMock: shutting-down for 10 s (the adapter treats it as deleting), then NotFoundException; a second delete meanwhile is NotFoundException too
Making an instance from a snapshot"You can't create an instance that uses a smaller bundle size than the original"; the snapshot must be availablehttps://docs.aws.amazon.com/lightsail/latest/userguide/lightsail-how-to-create-larger-instance-from-snapshot-using-aws-cli.html, primaryRefused for a lower power (Mock: the powers, ordered by size) and for a pending snapshot (Mock: the message)
An instance's address typeipAddressType is ipv4, ipv6 or dualstack; CreateInstances and CreateInstancesFromSnapshot default to dualstackhttps://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_CreateInstancesFromSnapshot.html, primarydualstack when the request names none
Expired credentialsExpiredTokenException, HTTP 403https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/CommonErrors.html, primaryIn the common errors the checker accepts; the world never raises it
PagingpageToken, "if your results are paginated, the response will return a next page token"; the page size is not statedhttps://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetInstances.html, primaryMock: 100 items, tokens opaque; a foreign token is InvalidInputException
Bundlesnano_3_0 $5, micro_3_0 $7, small_3_0 $12 with their disks, RAM and transfer; power 500 for microhttps://docs.aws.amazon.com/cli/latest/reference/lightsail/get-bundles.html, primaryThose, plus Mock: medium_3_0 ($24, 4 GB, 80 GB, from memory and not checked) and the inactive nano_2_0 ($3.50, the same), so includeInactive means something
BlueprintsThe default blueprint ubuntu_24_04 is used by third parties and is not on AWS's pages the adapter readthe adapter's notes, secondaryMock: ubuntu_24_04, ubuntu_22_04, debian_12, amazon_linux_2023, and the inactive ubuntu_20_04
A blueprint's nameThe model's ResourceName pattern (no spaces)the pinned model, primaryAmazon_Linux_2023
Regions and zonesThe user guide lists themhttps://docs.aws.amazon.com/lightsail/latest/userguide/understanding-regions-and-availability-zones-in-amazon-lightsail.html, primaryMock: six regions, three zones each (us-east-1: six)
An error's fieldsThe model's exceptions have code, docs, message, tipthe pinned model, primary__type, message, and code for the service's own; Mock: no docs or tip
The address ranges, ARNs, idsNot a record of AWS'snoneMock: RFC 5737 and 3849-style documentation addresses; AWS's example account 111122223333; the IPv6 written as the model's pattern needs (eight groups, upper case)

The families added after those: every row below was read from AWS's pages on 2026-10-26 (grade primary; the API reference pages are https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_<Action>.html and API_<Type>.html, the quotas are on https://docs.aws.amazon.com/general/latest/gr/lightsail.html). Documented rows say what the world takes from the page; Mock rows are the world's own choice where the page is silent.

FamilyDocumentedMock
Domainsexample.com as a domain name (the model's ResourceName pattern has no dot: the contract holds a Domain's name, and an operation on a Domain, to a domain name, spec::DOMAIN_NAME_PATTERN, and nothing else); ARN region global; entry types A, AAAA, CNAME, MX, NS, SOA, SRV, TXT; 6 zonesDone at once; an entry's name is the domain or under it; duplicate entries refused
Contact methodsOne email and one SMS a region; SMS only in us-east-1, us-west-2, eu-west-1, ap-northeast-1, ap-southeast-1, ap-southeast-2; E.164; SMS needs no verification; email is PendingVerification; SendContactMethodVerification is for EmailVerification is a test's call (verify_contact_method) and never expires; named by its protocol
AlarmsPutAlarm creates (INSUFFICIENT_DATA) or overwrites (state kept); instances, balancers and databases only, each with its own metrics; 1 to 288 five-minute periods; notificationEnabled true, trigger ALARM (and ALARM required), treatMissingData missing by default; a contact protocol never set up is not an error; two alarms a metric"Two a metric" per resource and metric; statistic and unit follow the metric; TestAlarm changes nothing (it shows a banner)
Metric dataEach metric's published unit; 60 s granularity for status checks, load balancers, databases and distributions, 300 s for the other instance metrics and for container servicesOnly the published unit is accepted and a period must be a multiple of the granularity (a reading of "valid units depend on the metric"); values are deterministic
Load balancers10 a region; port -1 to 65535; path / and dualstack by default; certificate name and domain together; an instance must be running to attach; 2 certificates, one attached, attaching the other replaces it; force to delete the attached one while instances are attached; deleting the balancer deletes its certificates; attribute value shapes; 9 alternative names, no wildcard, nothing Amazon-ownedTimes (Config::provision, cert_issue); two TLS policy names; health healthy for a running instance; HTTPS redirection needs an attached certificate
Certificatesus-east-1 only for distributions; 9 alternative names; no wildcards; no Amazon-owned names; cannot be deleted while attached; summary unless includeCertificateDetails; 10 active, 20 in 365 days (shared with the balancers')PENDING_VALIDATION then ISSUED after Config::cert_issue; domain-validation records are made up
DistributionsLocated in us-east-1 only; origin an instance, bucket, container service or load balancer; response timeout 1 to 60 s (the quota page says 4 to 60) and 30 by default; private origin access only for a bucket origin and an update sets it with the origin; dualstack (default) or ipv4; only an ISSUED certificate attaches; update replaces cache settings; bundle changes once a billing cycle (ableToUpdateBundle); latest cache reset of all when no name; 20 distributionsOther regions refuse with InvalidInputException; bundles and prices; InProgress then Deployed; a missing name is refused; resets complete at once
BucketsNeverEnabled, Enabled, Suspended versioning; bundle once a billing cycle, up or down; forceDelete for a distribution origin, instances with access, objects, keys; access only for instances, running or stopped; 2 keys, secret shown once; cors only when asked for or updating; resourcesReceivingAccess only with includeConnectedResources; 20 bucketsBundle ids and prices; the cycle is 30 days
Container servicesStates and their meaning; stateDetail only in PENDING, DEPLOYING, UPDATING; scale 1 to 20; 4 public domains and 4 certificates, each issued first; 10 containers a deployment; 50 deployments kept (oldest replaced) listed newest first; 150 images; :service.label.N; a log for a container that ran; 100 servicesPower sizes and prices; UPDATING for Config::provision after a power, scale or domain change; an unregistered :image is refused
DatabasesMySQL name, user and password rules; backup and maintenance windows (format, 30 minutes, no conflict); from a snapshot: no smaller bundle, one restore mode, restore time not after the latest restorable; delete needs skipFinalSnapshot or a name, not both; updates at once with applyImmediately, backup retention always in the window, PENDING password; dynamic parameters at once, static at a reboot; stopped databases start after 7 days; events 1 to 20160 minutes; 40 databasesBlueprints and bundles; which updates are "outage-capable" beyond backup retention (a blueprint and a password); log lines; the states' words
Snapshots movedA manual snapshot of an instance or disk, or an automatic one (resource and date or latest, exclusive), copied in or across regions; an export goes to the same region; one stack entry at a timeAnother region's snapshots exist only when a test adds them; Config::export
Small callsSetIpAddressType for a distribution, instance or balancer, with acceptBundleUpdate to or from ipv6 on an instance; metadata options pending then applied on a running instance, httpProtocolIpv6 in eu-north-1 only; a GUI session lasts an hour, has two URLs, resumes with StartGUISession; five setup attempts keptThe bundle does not change on an IP type change; 5 seconds to apply; the cost estimate is the bundle price by the hour; peering is a flag
QuotasThe table on https://docs.aws.amazon.com/general/latest/gr/lightsail.html; 50 tags a resourceOver a quota is an InvalidInputException (the table names none)

What it is not

The signature is not verified (the world holds no secret to check it against, by design): a request signed with the wrong secret is accepted. Add-ons, key pairs, static IPs, ports, disks and the instance's metadata options are not modelled, and an instance always has the default key pair and port 22 open.

Files

PathWhat
src/world.rsLightsailWorld: state, authentication, the request limit, failures a test arms, dispatch, Config; mock.
src/instances.rs, src/snapshots.rs, src/ops.rs, src/tags.rs, src/catalog.rsThe handlers. ops.rs owns the clock's events.
src/errors.rs, src/page.rs, src/time.rsThe error shapes, page tokens, x-amz-date and epoch seconds.
src/families.rs, src/domains.rs, src/alarms.rs, src/metrics.rs, src/load_balancers.rs, src/certificates.rs, src/distributions.rs, src/buckets.rs, src/containers.rs, src/databases.rs, src/exports.rsThe later families and their rules, each header citing the pages it follows. families.rs holds the shared helpers, the quotas and the small calls.
src/spec.rsThe Smithy model as JSON Schema, the exceptions with their status, LightsailChecker.
src/tests.rsThe world call by call, each test ending in assert_conforms where the calls keep to the model.
tests/adapter.rsThe real sandbox_lightsail::Lightsail and a sandbox_vm::Vm over it: open, rest (snapshot, delete) and wake from the snapshot; a snapshot followed to available; fallback sizes on a plan size and a quota; a stuck graceful stop cut by a forced one; stop and resume; a failed operation; state errors; a throttle, a bad key and a wrong region; paging; price over pages; a dropped connection.
spec/The pinned model and where it is from.