Skip to main content

fakecloud_ec2/
state.rs

1//! EC2 service state.
2//!
3//! Partitioned per account+region via [`fakecloud_core::multi_account`]. The
4//! `tags` map is keyed by EC2 resource id (e.g. `vpc-…`, `i-…`, `sg-…`) and is
5//! the backing store for `CreateTags`/`DeleteTags`/`DescribeTags` plus the
6//! `tag:`/`tag-key` describe filters shared across every resource family.
7
8use std::collections::BTreeMap;
9use std::sync::Arc;
10
11use parking_lot::RwLock;
12use serde::{Deserialize, Serialize};
13
14/// Shared, account-partitioned EC2 state handle.
15pub type SharedEc2State = Arc<RwLock<fakecloud_core::multi_account::MultiAccountState<Ec2State>>>;
16
17/// On-disk snapshot envelope for EC2 state. Versioned so format changes fail
18/// loudly on upgrade rather than silently mis-parsing. Backing containers are
19/// not serialized -- on restore the server reconciles them via
20/// `Ec2Service::recover_persisted_containers`.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct Ec2Snapshot {
23    pub schema_version: u32,
24    #[serde(default)]
25    pub accounts: Option<fakecloud_core::multi_account::MultiAccountState<Ec2State>>,
26}
27
28pub const EC2_SNAPSHOT_SCHEMA_VERSION: u32 = 1;
29
30impl fakecloud_core::multi_account::AccountState for Ec2State {
31    fn new_for_account(account_id: &str, region: &str, _endpoint: &str) -> Self {
32        Self::new(account_id, region)
33    }
34}
35
36/// A single EC2 resource tag.
37#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
38pub struct Tag {
39    pub key: String,
40    pub value: String,
41}
42
43/// A secondary CIDR-block association on a VPC.
44#[derive(Clone, Debug, Serialize, Deserialize)]
45pub struct VpcCidrAssoc {
46    pub association_id: String,
47    pub cidr_block: String,
48    /// `associated` | `disassociated`.
49    pub state: String,
50}
51
52/// A Virtual Private Cloud.
53#[derive(Clone, Debug, Serialize, Deserialize)]
54pub struct Vpc {
55    pub vpc_id: String,
56    pub cidr_block: String,
57    /// `pending` | `available`.
58    pub state: String,
59    pub dhcp_options_id: String,
60    /// `default` | `dedicated` | `host`.
61    pub instance_tenancy: String,
62    pub is_default: bool,
63    pub enable_dns_support: bool,
64    pub enable_dns_hostnames: bool,
65    #[serde(default)]
66    pub cidr_associations: Vec<VpcCidrAssoc>,
67    /// Amazon-provided IPv6 /56 CIDR, set when the VPC was created (or updated)
68    /// with `AmazonProvidedIpv6CidrBlock=true`. Reported in the
69    /// `Ipv6CidrBlockAssociationSet`; the `aws_vpc` resource reads
70    /// `ipv6_cidr_block` / `assign_generated_ipv6_cidr_block` from it.
71    #[serde(default)]
72    pub ipv6_cidr_block: Option<String>,
73}
74
75/// One `key -> values` entry in a DHCP options set.
76#[derive(Clone, Debug, Serialize, Deserialize)]
77pub struct DhcpConfig {
78    pub key: String,
79    pub values: Vec<String>,
80}
81
82/// A DHCP options set.
83#[derive(Clone, Debug, Serialize, Deserialize)]
84pub struct DhcpOptions {
85    pub dhcp_options_id: String,
86    pub configurations: Vec<DhcpConfig>,
87}
88
89/// A subnet within a VPC.
90#[derive(Clone, Debug, Serialize, Deserialize)]
91pub struct Subnet {
92    pub subnet_id: String,
93    pub vpc_id: String,
94    pub cidr_block: String,
95    pub availability_zone: String,
96    pub availability_zone_id: String,
97    /// `pending` | `available`.
98    pub state: String,
99    pub available_ip_address_count: i32,
100    pub default_for_az: bool,
101    pub map_public_ip_on_launch: bool,
102    pub assign_ipv6_address_on_creation: bool,
103    pub map_customer_owned_ip_on_launch: bool,
104    pub enable_dns64: bool,
105    /// `ip-name` | `resource-name`.
106    pub private_dns_hostname_type: String,
107    /// IPv6 /64 associated with the subnet (via CreateSubnet `Ipv6CidrBlock` or
108    /// AssociateSubnetCidrBlock). Reported in the `ipv6CidrBlockAssociationSet`;
109    /// the `aws_subnet` resource waits for this association.
110    #[serde(default)]
111    pub ipv6_cidr_block: Option<String>,
112}
113
114/// A CIDR reservation within a subnet.
115#[derive(Clone, Debug, Serialize, Deserialize)]
116pub struct SubnetCidrReservation {
117    pub subnet_cidr_reservation_id: String,
118    pub subnet_id: String,
119    pub cidr: String,
120    /// `prefix` | `explicit`.
121    pub reservation_type: String,
122    pub description: String,
123}
124
125/// A security-group rule (ingress or egress), stored flat.
126#[derive(Clone, Debug, Serialize, Deserialize)]
127pub struct SecurityGroupRule {
128    pub rule_id: String,
129    pub group_id: String,
130    pub is_egress: bool,
131    pub ip_protocol: String,
132    pub from_port: i64,
133    pub to_port: i64,
134    pub cidr_ipv4: Option<String>,
135    pub cidr_ipv6: Option<String>,
136    pub prefix_list_id: Option<String>,
137    pub referenced_group_id: Option<String>,
138    pub description: String,
139}
140
141/// A security group.
142#[derive(Clone, Debug, Serialize, Deserialize)]
143pub struct SecurityGroup {
144    pub group_id: String,
145    pub group_name: String,
146    pub description: String,
147    pub vpc_id: String,
148    #[serde(default)]
149    pub rules: Vec<SecurityGroupRule>,
150}
151
152/// A route within a route table.
153#[derive(Clone, Debug, Default, Serialize, Deserialize)]
154pub struct Route {
155    pub destination_cidr_block: Option<String>,
156    pub destination_ipv6_cidr_block: Option<String>,
157    pub destination_prefix_list_id: Option<String>,
158    pub gateway_id: Option<String>,
159    pub nat_gateway_id: Option<String>,
160    pub network_interface_id: Option<String>,
161    pub instance_id: Option<String>,
162    pub vpc_peering_connection_id: Option<String>,
163    pub transit_gateway_id: Option<String>,
164    pub egress_only_internet_gateway_id: Option<String>,
165    /// `active` | `blackhole`.
166    pub state: String,
167    /// `CreateRouteTable` | `CreateRoute`.
168    pub origin: String,
169}
170
171/// A route-table association (to a subnet or gateway, or the VPC main table).
172#[derive(Clone, Debug, Serialize, Deserialize)]
173pub struct RouteTableAssociation {
174    pub association_id: String,
175    pub route_table_id: String,
176    pub subnet_id: Option<String>,
177    pub gateway_id: Option<String>,
178    pub main: bool,
179}
180
181/// A route table.
182#[derive(Clone, Debug, Serialize, Deserialize)]
183pub struct RouteTable {
184    pub route_table_id: String,
185    pub vpc_id: String,
186    #[serde(default)]
187    pub routes: Vec<Route>,
188    #[serde(default)]
189    pub associations: Vec<RouteTableAssociation>,
190}
191
192/// An internet gateway (or egress-only IGW) with its VPC attachments.
193#[derive(Clone, Debug, Serialize, Deserialize)]
194pub struct InternetGateway {
195    pub internet_gateway_id: String,
196    /// (vpc_id, state) pairs.
197    #[serde(default)]
198    pub attachments: Vec<(String, String)>,
199}
200
201/// A NAT gateway.
202#[derive(Clone, Debug, Serialize, Deserialize)]
203pub struct NatGateway {
204    pub nat_gateway_id: String,
205    pub subnet_id: String,
206    pub vpc_id: String,
207    /// `pending` | `available` | `deleting` | `deleted`.
208    pub state: String,
209    /// `public` | `private`.
210    pub connectivity_type: String,
211    pub allocation_id: Option<String>,
212}
213
214/// An Elastic IP allocation.
215#[derive(Clone, Debug, Serialize, Deserialize)]
216pub struct ElasticIp {
217    pub allocation_id: String,
218    pub public_ip: String,
219    /// `vpc` | `standard`.
220    pub domain: String,
221    pub association_id: Option<String>,
222    pub instance_id: Option<String>,
223    pub network_interface_id: Option<String>,
224    pub private_ip_address: Option<String>,
225}
226
227/// An EC2 key pair (public-key metadata only).
228#[derive(Clone, Debug, Serialize, Deserialize)]
229pub struct KeyPair {
230    pub key_pair_id: String,
231    pub key_name: String,
232    /// `rsa` | `ed25519`.
233    pub key_type: String,
234    pub key_fingerprint: String,
235}
236
237/// A placement group.
238#[derive(Clone, Debug, Serialize, Deserialize)]
239pub struct PlacementGroup {
240    pub group_id: String,
241    pub group_name: String,
242    /// `cluster` | `spread` | `partition`.
243    pub strategy: String,
244    /// `available`.
245    pub state: String,
246    pub partition_count: Option<i64>,
247    pub spread_level: Option<String>,
248}
249
250/// An ENI attachment.
251#[derive(Clone, Debug, Serialize, Deserialize)]
252pub struct EniAttachment {
253    pub attachment_id: String,
254    pub instance_id: String,
255    pub device_index: i64,
256    /// `attaching` | `attached` | `detaching` | `detached`.
257    pub status: String,
258}
259
260/// An elastic network interface.
261#[derive(Clone, Debug, Serialize, Deserialize)]
262pub struct NetworkInterface {
263    pub network_interface_id: String,
264    pub subnet_id: String,
265    pub vpc_id: String,
266    pub availability_zone: String,
267    pub description: String,
268    pub mac_address: String,
269    pub private_ip_address: String,
270    /// `available` | `in-use`.
271    pub status: String,
272    pub interface_type: String,
273    pub source_dest_check: bool,
274    #[serde(default)]
275    pub group_ids: Vec<String>,
276    #[serde(default)]
277    pub private_ips: Vec<String>,
278    #[serde(default)]
279    pub ipv6_addresses: Vec<String>,
280    pub attachment: Option<EniAttachment>,
281}
282
283/// A network-interface permission grant.
284#[derive(Clone, Debug, Serialize, Deserialize)]
285pub struct NetworkInterfacePermission {
286    pub permission_id: String,
287    pub network_interface_id: String,
288    pub aws_account_id: String,
289    /// `INSTANCE-ATTACH` | `EIP-ASSOCIATE`.
290    pub permission: String,
291}
292
293/// An EC2 instance (metadata-faithful; a Docker-backed runtime layers on top).
294#[derive(Clone, Debug, Serialize, Deserialize)]
295pub struct Instance {
296    pub instance_id: String,
297    pub image_id: String,
298    pub instance_type: String,
299    /// EC2 state code: 0 pending, 16 running, 32 shutting-down, 48 terminated,
300    /// 64 stopping, 80 stopped.
301    pub state_code: i64,
302    pub state_name: String,
303    pub private_ip: String,
304    pub public_ip: Option<String>,
305    pub subnet_id: Option<String>,
306    pub vpc_id: Option<String>,
307    pub key_name: Option<String>,
308    #[serde(default)]
309    pub security_group_ids: Vec<String>,
310    pub reservation_id: String,
311    pub ami_launch_index: i64,
312    pub monitoring: bool,
313    pub az: String,
314    pub launch_time: String,
315    /// Id of the backing container/Pod, when this instance is backed by a
316    /// real container runtime. `None` in metadata-only mode.
317    #[serde(default)]
318    pub container_id: Option<String>,
319    // ---- modifiable instance attributes (ModifyInstanceAttribute et al.) ----
320    /// `disableApiTermination` — when true, TerminateInstances is rejected.
321    #[serde(default)]
322    pub disable_api_termination: bool,
323    /// `disableApiStop` — when true, StopInstances is rejected.
324    #[serde(default)]
325    pub disable_api_stop: bool,
326    /// `sourceDestCheck` — defaults to true on AWS.
327    #[serde(default = "default_true")]
328    pub source_dest_check: bool,
329    /// `ebsOptimized`.
330    #[serde(default)]
331    pub ebs_optimized: bool,
332    /// `instanceInitiatedShutdownBehavior` — `stop` (default) | `terminate`.
333    #[serde(default = "default_shutdown_behavior")]
334    pub instance_initiated_shutdown_behavior: String,
335    /// `userData` — base64-encoded, as supplied at launch / via Modify.
336    #[serde(default)]
337    pub user_data: Option<String>,
338    // ---- Modify*Options round-trip state ----
339    /// `metadataOptions` (`ModifyInstanceMetadataOptions`).
340    #[serde(default)]
341    pub metadata_options: MetadataOptions,
342    /// `cpuOptions` (`ModifyInstanceCpuOptions`).
343    #[serde(default)]
344    pub cpu_options: Option<CpuOptions>,
345    /// `bandwidthWeighting` (`ModifyInstanceNetworkPerformanceOptions`).
346    #[serde(default)]
347    pub bandwidth_weighting: Option<String>,
348    /// `maintenanceOptions` (`ModifyInstanceMaintenanceOptions`).
349    #[serde(default)]
350    pub maintenance_options: MaintenanceOptions,
351    /// `placement` tenancy/affinity overrides (`ModifyInstancePlacement`).
352    #[serde(default)]
353    pub placement_tenancy: Option<String>,
354    #[serde(default)]
355    pub placement_affinity: Option<String>,
356    #[serde(default)]
357    pub placement_group_name: Option<String>,
358}
359
360fn default_true() -> bool {
361    true
362}
363
364fn default_shutdown_behavior() -> String {
365    "stop".to_string()
366}
367
368/// IMDS (instance-metadata service) options, round-tripped by
369/// `ModifyInstanceMetadataOptions` and reflected in DescribeInstances.
370#[derive(Clone, Debug, Serialize, Deserialize)]
371pub struct MetadataOptions {
372    /// `optional` | `required`.
373    pub http_tokens: String,
374    /// `disabled` | `enabled`.
375    pub http_endpoint: String,
376    pub http_put_response_hop_limit: i64,
377    /// `disabled` | `enabled`.
378    pub http_protocol_ipv6: String,
379    /// `disabled` | `enabled`.
380    pub instance_metadata_tags: String,
381}
382
383impl Default for MetadataOptions {
384    fn default() -> Self {
385        Self {
386            http_tokens: "optional".to_string(),
387            http_endpoint: "enabled".to_string(),
388            http_put_response_hop_limit: 1,
389            http_protocol_ipv6: "disabled".to_string(),
390            instance_metadata_tags: "disabled".to_string(),
391        }
392    }
393}
394
395/// CPU options round-tripped by `ModifyInstanceCpuOptions`.
396#[derive(Clone, Debug, Serialize, Deserialize)]
397pub struct CpuOptions {
398    pub core_count: i64,
399    pub threads_per_core: i64,
400}
401
402/// Maintenance options round-tripped by `ModifyInstanceMaintenanceOptions`.
403#[derive(Clone, Debug, Serialize, Deserialize)]
404pub struct MaintenanceOptions {
405    /// `disabled` | `default`.
406    pub auto_recovery: String,
407    /// `disabled` | `default`.
408    pub reboot_migration: String,
409}
410
411impl Default for MaintenanceOptions {
412    fn default() -> Self {
413        Self {
414            auto_recovery: "default".to_string(),
415            reboot_migration: "default".to_string(),
416        }
417    }
418}
419
420/// An EBS volume attachment.
421#[derive(Clone, Debug, Serialize, Deserialize)]
422pub struct VolumeAttachment {
423    pub volume_id: String,
424    pub instance_id: String,
425    pub device: String,
426    /// `attaching` | `attached` | `detaching` | `detached`.
427    pub status: String,
428    pub delete_on_termination: bool,
429}
430
431/// An EBS volume.
432#[derive(Clone, Debug, Serialize, Deserialize)]
433pub struct Volume {
434    pub volume_id: String,
435    pub size: i64,
436    pub snapshot_id: Option<String>,
437    pub availability_zone: String,
438    /// `creating` | `available` | `in-use` | `deleting` | `deleted`.
439    pub state: String,
440    pub volume_type: String,
441    pub iops: Option<i64>,
442    pub throughput: Option<i64>,
443    pub encrypted: bool,
444    pub kms_key_id: Option<String>,
445    pub multi_attach_enabled: bool,
446    pub auto_enable_io: bool,
447    #[serde(default)]
448    pub attachments: Vec<VolumeAttachment>,
449    #[serde(default)]
450    pub in_recycle_bin: bool,
451}
452
453/// An EBS snapshot.
454#[derive(Clone, Debug, Serialize, Deserialize)]
455pub struct Snapshot {
456    pub snapshot_id: String,
457    pub volume_id: String,
458    /// `pending` | `completed` | `error`.
459    pub state: String,
460    pub volume_size: i64,
461    pub description: String,
462    pub encrypted: bool,
463    /// `standard` | `archive`.
464    pub storage_tier: String,
465    #[serde(default)]
466    pub in_recycle_bin: bool,
467    #[serde(default)]
468    pub locked: bool,
469    pub lock_mode: Option<String>,
470}
471
472/// An AMI (machine image).
473#[derive(Clone, Debug, Serialize, Deserialize)]
474pub struct Image {
475    pub image_id: String,
476    pub name: String,
477    pub description: String,
478    /// `pending` | `available` | `disabled` | `deregistered`.
479    pub state: String,
480    pub architecture: String,
481    pub public: bool,
482    pub source_instance_id: Option<String>,
483    #[serde(default)]
484    pub in_recycle_bin: bool,
485    pub deprecation_time: Option<String>,
486    #[serde(default)]
487    pub deregistration_protection: bool,
488    /// `launchPermission` — AWS account ids the AMI is explicitly shared with
489    /// (cross-account share via `ModifyImageAttribute`).
490    #[serde(default)]
491    pub launch_permission_users: Vec<String>,
492    /// `launchPermission` groups — only `all` is valid in AWS (public share).
493    #[serde(default)]
494    pub launch_permission_groups: Vec<String>,
495    /// `bootMode` — `legacy-bios` | `uefi` | `uefi-preferred`. `None` reports
496    /// the default `uefi`; settable via `ModifyImageAttribute`.
497    #[serde(default)]
498    pub boot_mode: Option<String>,
499}
500
501/// A network ACL entry (rule).
502#[derive(Clone, Debug, Serialize, Deserialize)]
503pub struct NetworkAclEntry {
504    pub rule_number: i64,
505    pub protocol: String,
506    /// `allow` | `deny`.
507    pub rule_action: String,
508    pub egress: bool,
509    pub cidr_block: Option<String>,
510    pub ipv6_cidr_block: Option<String>,
511    /// TCP/UDP port range (from, to).
512    pub port_range: Option<(i64, i64)>,
513    /// ICMP (type, code).
514    pub icmp_type_code: Option<(i64, i64)>,
515}
516
517/// A network ACL <-> subnet association.
518#[derive(Clone, Debug, Serialize, Deserialize)]
519pub struct NetworkAclAssoc {
520    pub association_id: String,
521    pub subnet_id: String,
522}
523
524/// A network ACL.
525#[derive(Clone, Debug, Serialize, Deserialize)]
526pub struct NetworkAcl {
527    pub network_acl_id: String,
528    pub vpc_id: String,
529    pub is_default: bool,
530    #[serde(default)]
531    pub entries: Vec<NetworkAclEntry>,
532    #[serde(default)]
533    pub associations: Vec<NetworkAclAssoc>,
534}
535
536/// A VPC peering connection.
537#[derive(Clone, Debug, Serialize, Deserialize)]
538pub struct VpcPeering {
539    pub id: String,
540    pub requester_vpc_id: String,
541    pub accepter_vpc_id: String,
542    /// `pending-acceptance` | `active` | `rejected` | `deleted`.
543    pub status: String,
544    /// Requester-side DNS-resolution-from-remote-VPC option.
545    #[serde(default)]
546    pub requester_allow_dns: bool,
547    /// Accepter-side DNS-resolution-from-remote-VPC option.
548    #[serde(default)]
549    pub accepter_allow_dns: bool,
550}
551
552/// A VPC endpoint.
553#[derive(Clone, Debug, Serialize, Deserialize)]
554pub struct VpcEndpoint {
555    pub id: String,
556    /// `Interface` | `Gateway` | `GatewayLoadBalancer` | ...
557    pub endpoint_type: String,
558    pub vpc_id: String,
559    pub service_name: String,
560    pub state: String,
561    #[serde(default)]
562    pub subnet_ids: Vec<String>,
563    #[serde(default)]
564    pub route_table_ids: Vec<String>,
565    #[serde(default)]
566    pub private_dns_enabled: bool,
567}
568
569/// A VPC endpoint service configuration (PrivateLink provider side).
570#[derive(Clone, Debug, Serialize, Deserialize)]
571pub struct EndpointService {
572    pub service_id: String,
573    pub service_name: String,
574    pub state: String,
575    pub acceptance_required: bool,
576    pub payer_responsibility: String,
577    #[serde(default)]
578    pub nlb_arns: Vec<String>,
579}
580
581/// A VPC endpoint connection notification.
582#[derive(Clone, Debug, Serialize, Deserialize)]
583pub struct ConnectionNotification {
584    pub id: String,
585    pub arn: String,
586    pub service_id: Option<String>,
587    #[serde(default)]
588    pub events: Vec<String>,
589}
590
591/// A VPC flow log.
592#[derive(Clone, Debug, Serialize, Deserialize)]
593pub struct FlowLog {
594    pub id: String,
595    pub resource_id: String,
596    pub traffic_type: String,
597    pub log_destination_type: String,
598    pub log_group_name: Option<String>,
599    /// Destination ARN for `s3` / `kinesis-data-firehose` deliveries.
600    pub log_destination: Option<String>,
601}
602
603/// A launch template (versions tracked as monotonic counters).
604#[derive(Clone, Debug, Serialize, Deserialize)]
605pub struct LaunchTemplate {
606    pub id: String,
607    pub name: String,
608    pub default_version: i64,
609    pub latest_version: i64,
610}
611
612/// A Spot instance request.
613#[derive(Clone, Debug, Serialize, Deserialize)]
614pub struct SpotRequest {
615    pub id: String,
616    /// `open` | `active` | `cancelled` | `closed`.
617    pub state: String,
618    pub request_type: String,
619    pub spot_price: String,
620}
621
622/// A Spot fleet request.
623#[derive(Clone, Debug, Serialize, Deserialize)]
624pub struct SpotFleet {
625    pub id: String,
626    pub state: String,
627}
628
629/// An EC2 fleet.
630#[derive(Clone, Debug, Serialize, Deserialize)]
631pub struct Fleet {
632    pub id: String,
633    pub state: String,
634    pub fleet_type: String,
635}
636
637/// An on-demand capacity reservation.
638#[derive(Clone, Debug, Serialize, Deserialize)]
639pub struct CapacityReservation {
640    pub id: String,
641    pub instance_type: String,
642    pub instance_platform: String,
643    pub availability_zone: String,
644    pub tenancy: String,
645    pub total_instance_count: i64,
646    pub available_instance_count: i64,
647    /// `active` | `expired` | `cancelled` | `pending` | `failed`.
648    pub state: String,
649    pub end_date_type: String,
650    pub instance_match_criteria: String,
651}
652
653/// A Reserved Instance purchase.
654#[derive(Clone, Debug, Serialize, Deserialize)]
655pub struct ReservedInstances {
656    pub id: String,
657    pub instance_type: String,
658    pub availability_zone: String,
659    pub instance_count: i64,
660    pub product_description: String,
661    pub state: String,
662    pub duration: i64,
663    pub fixed_price: String,
664    pub usage_price: String,
665}
666
667/// A Reserved Instances listing in the Reserved Instance Marketplace.
668#[derive(Clone, Debug, Serialize, Deserialize)]
669pub struct ReservedInstancesListing {
670    pub listing_id: String,
671    pub reserved_instances_id: String,
672    pub instance_count: i64,
673    pub client_token: String,
674    /// `active` | `cancelled` | `closed`.
675    pub status: String,
676    pub status_message: String,
677}
678
679/// A Reserved Instances modification request.
680#[derive(Clone, Debug, Serialize, Deserialize)]
681pub struct ReservedInstancesModification {
682    pub modification_id: String,
683    pub reserved_instances_ids: Vec<String>,
684    /// `processing` | `fulfilled` | `failed`.
685    pub status: String,
686    pub client_token: String,
687}
688
689/// A Dedicated Host.
690#[derive(Clone, Debug, Serialize, Deserialize)]
691pub struct DedicatedHost {
692    pub id: String,
693    pub auto_placement: String,
694    pub availability_zone: String,
695    pub instance_type: String,
696    pub state: String,
697    pub host_recovery: String,
698    pub host_maintenance: String,
699}
700
701/// A Transit Gateway.
702#[derive(Clone, Debug, Serialize, Deserialize)]
703pub struct TransitGateway {
704    pub id: String,
705    pub description: String,
706    /// `pending` | `available` | `modifying` | `deleting` | `deleted`.
707    #[serde(default = "tgw_default_state")]
708    pub state: String,
709}
710
711fn tgw_default_state() -> String {
712    "available".to_string()
713}
714
715/// A Transit Gateway attachment (VPC and others).
716#[derive(Clone, Debug, Serialize, Deserialize)]
717pub struct TgwAttachment {
718    pub id: String,
719    pub tgw_id: String,
720    pub resource_id: String,
721    pub resource_type: String,
722    #[serde(default)]
723    pub subnet_ids: Vec<String>,
724    pub state: String,
725}
726
727/// A Transit Gateway route table.
728#[derive(Clone, Debug, Serialize, Deserialize)]
729pub struct TgwRouteTable {
730    pub id: String,
731    pub tgw_id: String,
732}
733
734/// A static Transit Gateway route within a route table.
735#[derive(Clone, Debug, Serialize, Deserialize)]
736pub struct TgwRoute {
737    pub cidr: String,
738    pub attachment_id: String,
739    pub state: String,
740}
741
742/// A Transit Gateway multicast domain.
743#[derive(Clone, Debug, Serialize, Deserialize)]
744pub struct TgwMulticastDomain {
745    pub id: String,
746    pub tgw_id: String,
747}
748
749/// A Transit Gateway metering policy.
750#[derive(Clone, Debug, Serialize, Deserialize)]
751pub struct TgwMeteringPolicy {
752    pub id: String,
753    pub tgw_id: String,
754}
755
756/// A customer gateway (on-prem side of a VPN).
757#[derive(Clone, Debug, Serialize, Deserialize)]
758pub struct CustomerGateway {
759    pub id: String,
760    pub state: String,
761    pub ip_address: String,
762    pub bgp_asn: String,
763}
764
765/// A virtual private gateway.
766#[derive(Clone, Debug, Serialize, Deserialize)]
767pub struct VpnGateway {
768    pub id: String,
769    pub state: String,
770    #[serde(default)]
771    pub attachments: Vec<String>,
772}
773
774/// A Site-to-Site VPN connection.
775#[derive(Clone, Debug, Serialize, Deserialize)]
776pub struct VpnConnection {
777    pub id: String,
778    pub state: String,
779    pub customer_gateway_id: String,
780    pub vpn_gateway_id: Option<String>,
781    #[serde(default)]
782    pub routes: Vec<String>,
783}
784
785/// A VPN concentrator.
786#[derive(Clone, Debug, Serialize, Deserialize)]
787pub struct VpnConcentrator {
788    pub id: String,
789    pub state: String,
790}
791
792/// An IPAM (IP Address Manager).
793#[derive(Clone, Debug, Serialize, Deserialize)]
794pub struct Ipam {
795    pub id: String,
796    pub public_scope_id: String,
797    pub private_scope_id: String,
798    pub tier: String,
799    #[serde(default)]
800    pub description: String,
801}
802
803/// An IPAM scope.
804#[derive(Clone, Debug, Serialize, Deserialize)]
805pub struct IpamScope {
806    pub id: String,
807    pub ipam_id: String,
808    /// "public" or "private".
809    #[serde(default)]
810    pub scope_type: String,
811    #[serde(default)]
812    pub description: String,
813}
814
815/// An IPAM pool.
816#[derive(Clone, Debug, Serialize, Deserialize)]
817pub struct IpamPool {
818    pub id: String,
819    pub scope_id: String,
820    pub address_family: String,
821    #[serde(default)]
822    pub description: String,
823}
824
825/// An IPAM resource discovery.
826#[derive(Clone, Debug, Serialize, Deserialize)]
827pub struct IpamResourceDiscovery {
828    pub id: String,
829    #[serde(default)]
830    pub description: String,
831}
832
833/// An IPAM policy.
834#[derive(Clone, Debug, Serialize, Deserialize)]
835pub struct IpamPolicy {
836    pub id: String,
837    pub ipam_id: String,
838}
839
840/// An IPAM prefix-list resolver.
841#[derive(Clone, Debug, Serialize, Deserialize)]
842pub struct IpamPrefixListResolver {
843    pub id: String,
844    pub ipam_id: String,
845    pub address_family: String,
846    #[serde(default)]
847    pub description: String,
848}
849
850/// An IPAM prefix-list resolver target.
851#[derive(Clone, Debug, Serialize, Deserialize)]
852pub struct IpamPrefixListResolverTarget {
853    pub id: String,
854    pub resolver_id: String,
855    pub prefix_list_id: String,
856    pub prefix_list_region: String,
857    #[serde(default)]
858    pub track_latest_version: bool,
859}
860
861/// A Verified Access instance.
862#[derive(Clone, Debug, Serialize, Deserialize)]
863pub struct VerifiedAccessInstance {
864    pub id: String,
865    pub description: String,
866    #[serde(default)]
867    pub trust_providers: Vec<String>,
868}
869
870/// A Verified Access trust provider.
871#[derive(Clone, Debug, Serialize, Deserialize)]
872pub struct VerifiedAccessTrustProvider {
873    pub id: String,
874    pub trust_provider_type: String,
875    pub policy_reference_name: String,
876    pub description: String,
877}
878
879/// A Verified Access group.
880#[derive(Clone, Debug, Serialize, Deserialize)]
881pub struct VerifiedAccessGroup {
882    pub id: String,
883    pub instance_id: String,
884    pub description: String,
885}
886
887/// A Verified Access endpoint.
888#[derive(Clone, Debug, Serialize, Deserialize)]
889pub struct VerifiedAccessEndpoint {
890    pub id: String,
891    pub group_id: String,
892    pub instance_id: String,
893    pub endpoint_type: String,
894    pub attachment_type: String,
895}
896
897/// A Network Insights reachability path.
898#[derive(Clone, Debug, Serialize, Deserialize)]
899pub struct NetworkInsightsPath {
900    pub id: String,
901    pub source: String,
902    pub destination: String,
903    pub protocol: String,
904}
905
906/// A Network Insights path analysis.
907#[derive(Clone, Debug, Serialize, Deserialize)]
908pub struct NetworkInsightsAnalysis {
909    pub id: String,
910    pub path_id: String,
911}
912
913/// A Network Insights access scope.
914#[derive(Clone, Debug, Serialize, Deserialize)]
915pub struct NetworkInsightsAccessScope {
916    pub id: String,
917}
918
919/// A Network Insights access-scope analysis.
920#[derive(Clone, Debug, Serialize, Deserialize)]
921pub struct NetworkInsightsAccessScopeAnalysis {
922    pub id: String,
923    pub scope_id: String,
924}
925
926/// A carrier gateway (Wavelength).
927#[derive(Clone, Debug, Serialize, Deserialize)]
928pub struct CarrierGateway {
929    pub id: String,
930    pub vpc_id: String,
931}
932
933/// An EC2 Instance Connect endpoint.
934#[derive(Clone, Debug, Serialize, Deserialize)]
935pub struct InstanceConnectEndpoint {
936    pub id: String,
937    pub subnet_id: String,
938}
939
940/// A customer-owned IP (CoIP) pool.
941#[derive(Clone, Debug, Serialize, Deserialize)]
942pub struct CoipPool {
943    pub id: String,
944    pub route_table_id: String,
945}
946
947/// A local-gateway route table.
948#[derive(Clone, Debug, Serialize, Deserialize)]
949pub struct LocalGatewayRouteTable {
950    pub id: String,
951    pub local_gateway_id: String,
952    pub mode: String,
953}
954
955/// A local-gateway route-table <-> VPC association.
956#[derive(Clone, Debug, Serialize, Deserialize)]
957pub struct LocalGatewayRouteTableVpcAssoc {
958    pub id: String,
959    pub route_table_id: String,
960    pub vpc_id: String,
961}
962
963/// A local-gateway virtual interface.
964#[derive(Clone, Debug, Serialize, Deserialize)]
965pub struct LocalGatewayVif {
966    pub id: String,
967    pub group_id: String,
968    pub vlan: String,
969    pub local_address: String,
970    pub peer_address: String,
971}
972
973/// A local-gateway virtual-interface group.
974#[derive(Clone, Debug, Serialize, Deserialize)]
975pub struct LocalGatewayVifGroup {
976    pub id: String,
977    pub local_gateway_id: String,
978}
979
980/// A local-gateway route-table <-> virtual-interface-group association.
981#[derive(Clone, Debug, Serialize, Deserialize)]
982pub struct LocalGatewayRouteTableVifgAssoc {
983    pub id: String,
984    pub route_table_id: String,
985    pub vif_group_id: String,
986}
987
988/// A Client VPN endpoint.
989#[derive(Clone, Debug, Serialize, Deserialize)]
990pub struct ClientVpnEndpoint {
991    pub id: String,
992    pub description: String,
993    pub status: String,
994    pub server_cert_arn: String,
995    pub transport_protocol: String,
996    pub client_cidr: String,
997    #[serde(default)]
998    pub routes: Vec<String>,
999    /// (association id, subnet id) for each associated target network.
1000    #[serde(default)]
1001    pub target_networks: Vec<(String, String)>,
1002    /// Ingress authorization rule target CIDRs.
1003    #[serde(default)]
1004    pub auth_rules: Vec<String>,
1005}
1006
1007/// A Transit Gateway peering attachment.
1008#[derive(Clone, Debug, Serialize, Deserialize)]
1009pub struct TgwPeering {
1010    pub id: String,
1011    pub tgw_id: String,
1012    pub peer_tgw_id: String,
1013    pub peer_account: String,
1014    pub peer_region: String,
1015    pub state: String,
1016}
1017
1018/// Per-account, per-region EC2 state. Resource families are added to this
1019/// struct as their batches land.
1020#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1021pub struct Ec2State {
1022    pub account_id: String,
1023    pub region: String,
1024    /// resource-id -> tags. Shared by every Describe* `tag:` filter.
1025    #[serde(default)]
1026    pub tags: BTreeMap<String, Vec<Tag>>,
1027    #[serde(default)]
1028    pub vpcs: BTreeMap<String, Vpc>,
1029    #[serde(default)]
1030    pub dhcp_options: BTreeMap<String, DhcpOptions>,
1031    #[serde(default)]
1032    pub subnets: BTreeMap<String, Subnet>,
1033    #[serde(default)]
1034    pub subnet_cidr_reservations: BTreeMap<String, SubnetCidrReservation>,
1035    #[serde(default)]
1036    pub security_groups: BTreeMap<String, SecurityGroup>,
1037    #[serde(default)]
1038    pub route_tables: BTreeMap<String, RouteTable>,
1039    #[serde(default)]
1040    pub internet_gateways: BTreeMap<String, InternetGateway>,
1041    #[serde(default)]
1042    pub egress_only_igws: BTreeMap<String, InternetGateway>,
1043    #[serde(default)]
1044    pub nat_gateways: BTreeMap<String, NatGateway>,
1045    /// keyed by allocation id.
1046    #[serde(default)]
1047    pub elastic_ips: BTreeMap<String, ElasticIp>,
1048    /// keyed by key name.
1049    #[serde(default)]
1050    pub key_pairs: BTreeMap<String, KeyPair>,
1051    /// keyed by group name.
1052    #[serde(default)]
1053    pub placement_groups: BTreeMap<String, PlacementGroup>,
1054    #[serde(default)]
1055    pub network_interfaces: BTreeMap<String, NetworkInterface>,
1056    /// keyed by permission id.
1057    #[serde(default)]
1058    pub eni_permissions: BTreeMap<String, NetworkInterfacePermission>,
1059    #[serde(default)]
1060    pub instances: BTreeMap<String, Instance>,
1061    #[serde(default)]
1062    pub volumes: BTreeMap<String, Volume>,
1063    /// Account-level EBS default encryption toggle.
1064    #[serde(default)]
1065    pub ebs_encryption_default: bool,
1066    /// Account-level EBS default KMS key (None = `alias/aws/ebs`).
1067    #[serde(default)]
1068    pub ebs_default_kms_key_id: Option<String>,
1069    #[serde(default)]
1070    pub snapshots: BTreeMap<String, Snapshot>,
1071    /// Account-level snapshot block-public-access state.
1072    #[serde(default)]
1073    pub snapshot_block_public_access: String,
1074    #[serde(default)]
1075    pub images: BTreeMap<String, Image>,
1076    /// Watermarks attached to AMIs: image_id -> watermark_key -> watermark_name.
1077    #[serde(default)]
1078    pub image_watermarks: BTreeMap<String, BTreeMap<String, String>>,
1079    /// Account-level image block-public-access state.
1080    #[serde(default)]
1081    pub image_block_public_access: String,
1082    /// Account-level allowed-images settings state.
1083    #[serde(default)]
1084    pub allowed_images_settings: String,
1085    #[serde(default)]
1086    pub network_acls: BTreeMap<String, NetworkAcl>,
1087    #[serde(default)]
1088    pub vpc_peerings: BTreeMap<String, VpcPeering>,
1089    #[serde(default)]
1090    pub vpc_endpoints: BTreeMap<String, VpcEndpoint>,
1091    #[serde(default)]
1092    pub endpoint_services: BTreeMap<String, EndpointService>,
1093    #[serde(default)]
1094    pub connection_notifications: BTreeMap<String, ConnectionNotification>,
1095    #[serde(default)]
1096    pub flow_logs: BTreeMap<String, FlowLog>,
1097    #[serde(default)]
1098    pub launch_templates: BTreeMap<String, LaunchTemplate>,
1099    #[serde(default)]
1100    pub spot_requests: BTreeMap<String, SpotRequest>,
1101    #[serde(default)]
1102    pub spot_fleets: BTreeMap<String, SpotFleet>,
1103    #[serde(default)]
1104    pub fleets: BTreeMap<String, Fleet>,
1105    /// Account-level spot datafeed subscription (bucket, prefix).
1106    #[serde(default)]
1107    pub spot_datafeed: Option<(String, String)>,
1108    #[serde(default)]
1109    pub capacity_reservations: BTreeMap<String, CapacityReservation>,
1110    /// Capacity reservation fleet ids (metadata-only).
1111    #[serde(default)]
1112    pub capacity_reservation_fleets: BTreeMap<String, String>,
1113    #[serde(default)]
1114    pub reserved_instances: BTreeMap<String, ReservedInstances>,
1115    #[serde(default)]
1116    pub reserved_instances_listings: BTreeMap<String, ReservedInstancesListing>,
1117    #[serde(default)]
1118    pub reserved_instances_modifications: BTreeMap<String, ReservedInstancesModification>,
1119    #[serde(default)]
1120    pub dedicated_hosts: BTreeMap<String, DedicatedHost>,
1121    #[serde(default)]
1122    pub transit_gateways: BTreeMap<String, TransitGateway>,
1123    #[serde(default)]
1124    pub tgw_attachments: BTreeMap<String, TgwAttachment>,
1125    #[serde(default)]
1126    pub tgw_route_tables: BTreeMap<String, TgwRouteTable>,
1127    /// route-table-id -> static routes.
1128    #[serde(default)]
1129    pub tgw_routes: BTreeMap<String, Vec<TgwRoute>>,
1130    /// route-table-id -> associated attachment ids.
1131    #[serde(default)]
1132    pub tgw_rt_associations: BTreeMap<String, Vec<String>>,
1133    /// route-table-id -> propagated attachment ids.
1134    #[serde(default)]
1135    pub tgw_rt_propagations: BTreeMap<String, Vec<String>>,
1136    /// route-table-id -> prefix-list ids referenced.
1137    #[serde(default)]
1138    pub tgw_prefix_list_refs: BTreeMap<String, Vec<String>>,
1139    #[serde(default)]
1140    pub tgw_peerings: BTreeMap<String, TgwPeering>,
1141    /// connect-attachment-id -> (transport attachment id, tgw id).
1142    #[serde(default)]
1143    pub tgw_connects: BTreeMap<String, (String, String)>,
1144    /// connect-peer-id -> attachment id.
1145    #[serde(default)]
1146    pub tgw_connect_peers: BTreeMap<String, String>,
1147    /// policy-table-id -> tgw id.
1148    #[serde(default)]
1149    pub tgw_policy_tables: BTreeMap<String, String>,
1150    /// policy-table-id -> associated attachment ids.
1151    #[serde(default)]
1152    pub tgw_policy_table_associations: BTreeMap<String, Vec<String>>,
1153    /// announcement-id -> (route-table id, peering-attachment id).
1154    #[serde(default)]
1155    pub tgw_announcements: BTreeMap<String, (String, String)>,
1156    #[serde(default)]
1157    pub tgw_multicast_domains: BTreeMap<String, TgwMulticastDomain>,
1158    #[serde(default)]
1159    pub tgw_metering_policies: BTreeMap<String, TgwMeteringPolicy>,
1160    #[serde(default)]
1161    pub customer_gateways: BTreeMap<String, CustomerGateway>,
1162    #[serde(default)]
1163    pub vpn_gateways: BTreeMap<String, VpnGateway>,
1164    #[serde(default)]
1165    pub vpn_connections: BTreeMap<String, VpnConnection>,
1166    #[serde(default)]
1167    pub vpn_concentrators: BTreeMap<String, VpnConcentrator>,
1168    #[serde(default)]
1169    pub client_vpn_endpoints: BTreeMap<String, ClientVpnEndpoint>,
1170    #[serde(default)]
1171    pub ipams: BTreeMap<String, Ipam>,
1172    #[serde(default)]
1173    pub ipam_scopes: BTreeMap<String, IpamScope>,
1174    #[serde(default)]
1175    pub ipam_pools: BTreeMap<String, IpamPool>,
1176    /// pool-id -> provisioned (cidr, cidr-id).
1177    #[serde(default)]
1178    pub ipam_pool_cidrs: BTreeMap<String, Vec<(String, String)>>,
1179    /// pool-id -> allocations (cidr, allocation-id).
1180    #[serde(default)]
1181    pub ipam_pool_allocations: BTreeMap<String, Vec<(String, String)>>,
1182    #[serde(default)]
1183    pub ipam_resource_discoveries: BTreeMap<String, IpamResourceDiscovery>,
1184    /// association-id -> (discovery-id, ipam-id).
1185    #[serde(default)]
1186    pub ipam_rd_associations: BTreeMap<String, (String, String)>,
1187    /// asn -> associated cidr.
1188    #[serde(default)]
1189    pub ipam_byoasns: BTreeMap<String, String>,
1190    /// external-token-id -> ipam-id.
1191    #[serde(default)]
1192    pub ipam_ext_tokens: BTreeMap<String, String>,
1193    #[serde(default)]
1194    pub ipam_policies: BTreeMap<String, IpamPolicy>,
1195    #[serde(default)]
1196    pub ipam_pl_resolvers: BTreeMap<String, IpamPrefixListResolver>,
1197    #[serde(default)]
1198    pub ipam_pl_resolver_targets: BTreeMap<String, IpamPrefixListResolverTarget>,
1199    /// policy-id -> (locale, resource-type) allocation-rule documents.
1200    #[serde(default)]
1201    pub ipam_policy_alloc_rules: BTreeMap<String, Vec<(String, String)>>,
1202    /// The single enabled IPAM policy id, if any.
1203    #[serde(default)]
1204    pub ipam_enabled_policy: Option<String>,
1205    #[serde(default)]
1206    pub va_instances: BTreeMap<String, VerifiedAccessInstance>,
1207    #[serde(default)]
1208    pub va_trust_providers: BTreeMap<String, VerifiedAccessTrustProvider>,
1209    #[serde(default)]
1210    pub va_groups: BTreeMap<String, VerifiedAccessGroup>,
1211    #[serde(default)]
1212    pub va_endpoints: BTreeMap<String, VerifiedAccessEndpoint>,
1213    /// group-id -> policy document.
1214    #[serde(default)]
1215    pub va_group_policies: BTreeMap<String, String>,
1216    /// endpoint-id -> policy document.
1217    #[serde(default)]
1218    pub va_endpoint_policies: BTreeMap<String, String>,
1219    #[serde(default)]
1220    pub ni_paths: BTreeMap<String, NetworkInsightsPath>,
1221    #[serde(default)]
1222    pub ni_analyses: BTreeMap<String, NetworkInsightsAnalysis>,
1223    #[serde(default)]
1224    pub ni_access_scopes: BTreeMap<String, NetworkInsightsAccessScope>,
1225    #[serde(default)]
1226    pub ni_scope_analyses: BTreeMap<String, NetworkInsightsAccessScopeAnalysis>,
1227    #[serde(default)]
1228    pub carrier_gateways: BTreeMap<String, CarrierGateway>,
1229    #[serde(default)]
1230    pub coip_pools: BTreeMap<String, CoipPool>,
1231    /// coip-pool-id -> CIDRs.
1232    #[serde(default)]
1233    pub coip_pool_cidrs: BTreeMap<String, Vec<String>>,
1234    #[serde(default)]
1235    pub lg_route_tables: BTreeMap<String, LocalGatewayRouteTable>,
1236    /// route-table-id -> destination CIDRs.
1237    #[serde(default)]
1238    pub lg_routes: BTreeMap<String, Vec<String>>,
1239    #[serde(default)]
1240    pub lg_rt_vpc_assocs: BTreeMap<String, LocalGatewayRouteTableVpcAssoc>,
1241    #[serde(default)]
1242    pub lg_virtual_interfaces: BTreeMap<String, LocalGatewayVif>,
1243    #[serde(default)]
1244    pub lg_vif_groups: BTreeMap<String, LocalGatewayVifGroup>,
1245    #[serde(default)]
1246    pub lg_rt_vifg_assocs: BTreeMap<String, LocalGatewayRouteTableVifgAssoc>,
1247    #[serde(default)]
1248    pub instance_connect_endpoints: BTreeMap<String, InstanceConnectEndpoint>,
1249    /// Image ids with fast-launch enabled.
1250    #[serde(default)]
1251    pub fast_launch_images: std::collections::HashSet<String>,
1252    #[serde(default)]
1253    pub serial_console_access: bool,
1254}
1255
1256impl Ec2State {
1257    pub fn new(account_id: &str, region: &str) -> Self {
1258        let mut state = Self {
1259            account_id: account_id.to_string(),
1260            region: region.to_string(),
1261            ..Default::default()
1262        };
1263        // Seed the default VPC topology (VPC, IGW, subnets, route table,
1264        // security group, NACL) the way every AWS account+region ships one, so
1265        // callers that never touch the VPC APIs still launch into a real,
1266        // isolatable network. Ids are deterministic, so the throwaway empty
1267        // states the read paths build report the same ids as this one.
1268        crate::defaults::bootstrap_default_network(&mut state);
1269        state
1270    }
1271
1272    /// Replace the tag set for `resource_id` with `tags` merged over any
1273    /// existing tags (CreateTags is upsert-by-key, matching AWS).
1274    pub fn upsert_tags(&mut self, resource_id: &str, new_tags: &[Tag]) {
1275        let entry = self.tags.entry(resource_id.to_string()).or_default();
1276        for t in new_tags {
1277            if let Some(existing) = entry.iter_mut().find(|e| e.key == t.key) {
1278                existing.value = t.value.clone();
1279            } else {
1280                entry.push(t.clone());
1281            }
1282        }
1283    }
1284
1285    /// Remove tags for `resource_id`. When a tag's value is `None`, the key is
1286    /// removed regardless of value; when `Some`, only a key+value match is
1287    /// removed (AWS DeleteTags semantics).
1288    pub fn remove_tags(&mut self, resource_id: &str, to_remove: &[(String, Option<String>)]) {
1289        if let Some(entry) = self.tags.get_mut(resource_id) {
1290            for (key, value) in to_remove {
1291                entry.retain(|e| {
1292                    if &e.key != key {
1293                        return true;
1294                    }
1295                    match value {
1296                        Some(v) => &e.value != v,
1297                        None => false,
1298                    }
1299                });
1300            }
1301            if entry.is_empty() {
1302                self.tags.remove(resource_id);
1303            }
1304        }
1305    }
1306
1307    /// Tags for `resource_id`, or an empty slice when none.
1308    pub fn tags_for(&self, resource_id: &str) -> &[Tag] {
1309        self.tags.get(resource_id).map(Vec::as_slice).unwrap_or(&[])
1310    }
1311}
1312
1313#[cfg(test)]
1314mod tests {
1315    use super::*;
1316
1317    fn tag(k: &str, v: &str) -> Tag {
1318        Tag {
1319            key: k.to_string(),
1320            value: v.to_string(),
1321        }
1322    }
1323
1324    #[test]
1325    fn upsert_tags_inserts_then_overwrites_by_key() {
1326        let mut s = Ec2State::new("123456789012", "us-east-1");
1327        s.upsert_tags("vpc-1", &[tag("Name", "a"), tag("env", "dev")]);
1328        s.upsert_tags("vpc-1", &[tag("Name", "b")]);
1329        let tags = s.tags_for("vpc-1");
1330        assert_eq!(tags.len(), 2);
1331        assert_eq!(tags.iter().find(|t| t.key == "Name").unwrap().value, "b");
1332    }
1333
1334    #[test]
1335    fn remove_tags_by_key_and_by_key_value() {
1336        let mut s = Ec2State::new("123456789012", "us-east-1");
1337        s.upsert_tags(
1338            "i-1",
1339            &[tag("Name", "x"), tag("env", "prod"), tag("team", "a")],
1340        );
1341        // key-only removal
1342        s.remove_tags("i-1", &[("Name".to_string(), None)]);
1343        // key+value removal that does NOT match -> kept
1344        s.remove_tags("i-1", &[("env".to_string(), Some("dev".to_string()))]);
1345        // key+value removal that matches -> removed
1346        s.remove_tags("i-1", &[("team".to_string(), Some("a".to_string()))]);
1347        let tags = s.tags_for("i-1");
1348        assert_eq!(tags.len(), 1);
1349        assert_eq!(tags[0].key, "env");
1350    }
1351
1352    #[test]
1353    fn empty_tag_set_drops_resource_entry() {
1354        let mut s = Ec2State::new("123456789012", "us-east-1");
1355        s.upsert_tags("sg-1", &[tag("Name", "x")]);
1356        s.remove_tags("sg-1", &[("Name".to_string(), None)]);
1357        assert!(!s.tags.contains_key("sg-1"));
1358    }
1359
1360    fn sample_instance() -> Instance {
1361        Instance {
1362            instance_id: "i-1".to_string(),
1363            image_id: "ami-1".to_string(),
1364            instance_type: "t3.micro".to_string(),
1365            state_code: 16,
1366            state_name: "running".to_string(),
1367            private_ip: "10.0.0.1".to_string(),
1368            public_ip: Some("52.0.0.1".to_string()),
1369            subnet_id: Some("subnet-1".to_string()),
1370            vpc_id: Some("vpc-1".to_string()),
1371            key_name: None,
1372            security_group_ids: vec!["sg-1".to_string()],
1373            reservation_id: "r-1".to_string(),
1374            ami_launch_index: 0,
1375            monitoring: false,
1376            az: "us-east-1a".to_string(),
1377            launch_time: "2024-01-01T00:00:00.000Z".to_string(),
1378            container_id: Some("abc".to_string()),
1379            disable_api_termination: true,
1380            disable_api_stop: true,
1381            source_dest_check: false,
1382            ebs_optimized: true,
1383            instance_initiated_shutdown_behavior: "terminate".to_string(),
1384            user_data: Some("ZWNobyBoaQ==".to_string()),
1385            metadata_options: MetadataOptions {
1386                http_tokens: "required".to_string(),
1387                ..MetadataOptions::default()
1388            },
1389            cpu_options: Some(CpuOptions {
1390                core_count: 4,
1391                threads_per_core: 2,
1392            }),
1393            bandwidth_weighting: Some("vpc-1".to_string()),
1394            maintenance_options: MaintenanceOptions::default(),
1395            placement_tenancy: Some("dedicated".to_string()),
1396            placement_affinity: None,
1397            placement_group_name: Some("cluster-1".to_string()),
1398        }
1399    }
1400
1401    #[test]
1402    fn instance_attributes_round_trip_through_serde() {
1403        let inst = sample_instance();
1404        let json = serde_json::to_string(&inst).unwrap();
1405        let back: Instance = serde_json::from_str(&json).unwrap();
1406        assert!(back.disable_api_termination);
1407        assert!(back.disable_api_stop);
1408        assert!(!back.source_dest_check);
1409        assert!(back.ebs_optimized);
1410        assert_eq!(back.instance_initiated_shutdown_behavior, "terminate");
1411        assert_eq!(back.user_data.as_deref(), Some("ZWNobyBoaQ=="));
1412        assert_eq!(back.metadata_options.http_tokens, "required");
1413        assert_eq!(back.cpu_options.as_ref().unwrap().core_count, 4);
1414        assert_eq!(back.bandwidth_weighting.as_deref(), Some("vpc-1"));
1415        assert_eq!(back.placement_tenancy.as_deref(), Some("dedicated"));
1416        assert_eq!(back.placement_group_name.as_deref(), Some("cluster-1"));
1417    }
1418
1419    #[test]
1420    fn instance_attribute_defaults_load_from_legacy_snapshot() {
1421        // A snapshot written before the attribute fields existed (only the
1422        // pre-existing members) must deserialize, with AWS defaults filled in.
1423        let legacy = r#"{
1424            "instance_id":"i-1","image_id":"ami-1","instance_type":"t3.micro",
1425            "state_code":16,"state_name":"running","private_ip":"10.0.0.1",
1426            "public_ip":null,"subnet_id":null,"vpc_id":null,"key_name":null,
1427            "reservation_id":"r-1","ami_launch_index":0,"monitoring":false,
1428            "az":"us-east-1a","launch_time":"2024-01-01T00:00:00.000Z"
1429        }"#;
1430        let inst: Instance = serde_json::from_str(legacy).unwrap();
1431        assert!(!inst.disable_api_termination);
1432        assert!(inst.source_dest_check, "sourceDestCheck defaults to true");
1433        assert_eq!(inst.instance_initiated_shutdown_behavior, "stop");
1434        assert_eq!(inst.metadata_options.http_tokens, "optional");
1435        assert!(inst.cpu_options.is_none());
1436    }
1437}