stackport 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 DaviReisVieira
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ recursive-include ui/dist *
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: stackport
3
+ Version: 0.1.0
4
+ Summary: Universal AWS resource browser for local emulators
5
+ Author: Davi Reis Vieira
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/DaviReisVieira/stackport
8
+ Project-URL: Repository, https://github.com/DaviReisVieira/stackport
9
+ Project-URL: Issues, https://github.com/DaviReisVieira/stackport/issues
10
+ Keywords: aws,localstack,s3,browser,devtools,emulator
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Framework :: FastAPI
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Testing
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: fastapi>=0.115.0
25
+ Requires-Dist: uvicorn>=0.30.0
26
+ Requires-Dist: boto3>=1.35.0
27
+ Dynamic: license-file
28
+
29
+ # StackPort
30
+
31
+ [![CI](https://github.com/DaviReisVieira/stackport/actions/workflows/ci.yml/badge.svg)](https://github.com/DaviReisVieira/stackport/actions/workflows/ci.yml)
32
+ [![PyPI](https://img.shields.io/pypi/v/stackport)](https://pypi.org/project/stackport/)
33
+ [![Docker](https://img.shields.io/docker/pulls/davireis/stackport)](https://hub.docker.com/r/davireis/stackport)
34
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
35
+
36
+ Universal AWS resource browser for local emulators. Works with **LocalStack**, **MiniStack**, **Moto**, or any AWS-compatible endpoint.
37
+
38
+ <!-- TODO: Add screenshot here -->
39
+ <!-- ![StackPort Dashboard](docs/screenshot.png) -->
40
+
41
+ ## Features
42
+
43
+ - Browse and inspect resources across **35 AWS services**
44
+ - S3 file browser with folder navigation, search, pagination, and download
45
+ - Dashboard with service health, resource counts, and auto-refresh
46
+ - Single Docker image, zero AWS dependencies
47
+
48
+ ## Quick Start
49
+
50
+ ### pip
51
+
52
+ ```bash
53
+ pip install stackport
54
+ AWS_ENDPOINT_URL=http://localhost:4566 stackport
55
+ # Open http://localhost:8080
56
+ ```
57
+
58
+ ### Docker
59
+
60
+ ```bash
61
+ docker run -p 8080:8080 -e AWS_ENDPOINT_URL=http://host.docker.internal:4566 davireis/stackport
62
+ ```
63
+
64
+ ### Docker Compose
65
+
66
+ ```bash
67
+ curl -O https://raw.githubusercontent.com/DaviReisVieira/stackport/main/docker-compose.yml
68
+ docker compose up -d
69
+ # Open http://localhost:8080
70
+ ```
71
+
72
+ ## Configuration
73
+
74
+ | Variable | Default | Description |
75
+ |---|---|---|
76
+ | `AWS_ENDPOINT_URL` | `http://localhost:4566` | Target AWS endpoint |
77
+ | `AWS_REGION` | `us-east-1` | AWS region |
78
+ | `AWS_ACCESS_KEY_ID` | `test` | AWS access key |
79
+ | `AWS_SECRET_ACCESS_KEY` | `test` | AWS secret key |
80
+ | `STACKPORT_PORT` | `8080` | StackPort server port |
81
+ | `STACKPORT_SERVICES` | *(35 services)* | Comma-separated services to probe |
82
+
83
+ ## Supported Services (35)
84
+
85
+ ACM, API Gateway, AppSync, Athena, CloudFormation, CloudFront, Cognito (IDP + Identity), DynamoDB, EC2, ECR, ECS, ElastiCache, EFS, ELB, EMR, EventBridge, Firehose, Glue, IAM, Kinesis, KMS, Lambda, CloudWatch Logs, CloudWatch Monitoring, RDS, Route 53, S3, Secrets Manager, SES, SNS, SQS, SSM, Step Functions, WAFv2
86
+
87
+ S3 has a dedicated file browser. All other services use the generic resource table with detail view.
88
+
89
+ ## Development
90
+
91
+ ```bash
92
+ git clone https://github.com/DaviReisVieira/stackport.git
93
+ cd stackport
94
+ pip install -e .
95
+ cd ui && npm install && npm run dev
96
+ ```
97
+
98
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for full details.
99
+
100
+ ## License
101
+
102
+ MIT
@@ -0,0 +1,74 @@
1
+ # StackPort
2
+
3
+ [![CI](https://github.com/DaviReisVieira/stackport/actions/workflows/ci.yml/badge.svg)](https://github.com/DaviReisVieira/stackport/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/stackport)](https://pypi.org/project/stackport/)
5
+ [![Docker](https://img.shields.io/docker/pulls/davireis/stackport)](https://hub.docker.com/r/davireis/stackport)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ Universal AWS resource browser for local emulators. Works with **LocalStack**, **MiniStack**, **Moto**, or any AWS-compatible endpoint.
9
+
10
+ <!-- TODO: Add screenshot here -->
11
+ <!-- ![StackPort Dashboard](docs/screenshot.png) -->
12
+
13
+ ## Features
14
+
15
+ - Browse and inspect resources across **35 AWS services**
16
+ - S3 file browser with folder navigation, search, pagination, and download
17
+ - Dashboard with service health, resource counts, and auto-refresh
18
+ - Single Docker image, zero AWS dependencies
19
+
20
+ ## Quick Start
21
+
22
+ ### pip
23
+
24
+ ```bash
25
+ pip install stackport
26
+ AWS_ENDPOINT_URL=http://localhost:4566 stackport
27
+ # Open http://localhost:8080
28
+ ```
29
+
30
+ ### Docker
31
+
32
+ ```bash
33
+ docker run -p 8080:8080 -e AWS_ENDPOINT_URL=http://host.docker.internal:4566 davireis/stackport
34
+ ```
35
+
36
+ ### Docker Compose
37
+
38
+ ```bash
39
+ curl -O https://raw.githubusercontent.com/DaviReisVieira/stackport/main/docker-compose.yml
40
+ docker compose up -d
41
+ # Open http://localhost:8080
42
+ ```
43
+
44
+ ## Configuration
45
+
46
+ | Variable | Default | Description |
47
+ |---|---|---|
48
+ | `AWS_ENDPOINT_URL` | `http://localhost:4566` | Target AWS endpoint |
49
+ | `AWS_REGION` | `us-east-1` | AWS region |
50
+ | `AWS_ACCESS_KEY_ID` | `test` | AWS access key |
51
+ | `AWS_SECRET_ACCESS_KEY` | `test` | AWS secret key |
52
+ | `STACKPORT_PORT` | `8080` | StackPort server port |
53
+ | `STACKPORT_SERVICES` | *(35 services)* | Comma-separated services to probe |
54
+
55
+ ## Supported Services (35)
56
+
57
+ ACM, API Gateway, AppSync, Athena, CloudFormation, CloudFront, Cognito (IDP + Identity), DynamoDB, EC2, ECR, ECS, ElastiCache, EFS, ELB, EMR, EventBridge, Firehose, Glue, IAM, Kinesis, KMS, Lambda, CloudWatch Logs, CloudWatch Monitoring, RDS, Route 53, S3, Secrets Manager, SES, SNS, SQS, SSM, Step Functions, WAFv2
58
+
59
+ S3 has a dedicated file browser. All other services use the generic resource table with detail view.
60
+
61
+ ## Development
62
+
63
+ ```bash
64
+ git clone https://github.com/DaviReisVieira/stackport.git
65
+ cd stackport
66
+ pip install -e .
67
+ cd ui && npm install && npm run dev
68
+ ```
69
+
70
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for full details.
71
+
72
+ ## License
73
+
74
+ MIT
File without changes
@@ -0,0 +1,22 @@
1
+ import functools
2
+
3
+ import boto3
4
+
5
+ from backend.config import (
6
+ AWS_ACCESS_KEY_ID,
7
+ AWS_ENDPOINT_URL,
8
+ AWS_REGION,
9
+ AWS_SECRET_ACCESS_KEY,
10
+ )
11
+
12
+
13
+ @functools.lru_cache(maxsize=64)
14
+ def get_client(service_name: str):
15
+ """Return a boto3 client configured for the target AWS-compatible endpoint."""
16
+ return boto3.client(
17
+ service_name,
18
+ endpoint_url=AWS_ENDPOINT_URL,
19
+ region_name=AWS_REGION,
20
+ aws_access_key_id=AWS_ACCESS_KEY_ID,
21
+ aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
22
+ )
@@ -0,0 +1,24 @@
1
+ import threading
2
+ import time
3
+
4
+
5
+ class TTLCache:
6
+ def __init__(self):
7
+ self._store: dict = {}
8
+ self._lock = threading.Lock()
9
+
10
+ def get(self, key: str):
11
+ with self._lock:
12
+ if key in self._store:
13
+ value, expiry = self._store[key]
14
+ if time.time() < expiry:
15
+ return value
16
+ del self._store[key]
17
+ return None
18
+
19
+ def set(self, key: str, value, ttl: float = 5):
20
+ with self._lock:
21
+ self._store[key] = (value, time.time() + ttl)
22
+
23
+
24
+ cache = TTLCache()
@@ -0,0 +1,14 @@
1
+ import os
2
+
3
+ AWS_ENDPOINT_URL: str = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566")
4
+ AWS_REGION: str = os.environ.get("AWS_REGION", "us-east-1")
5
+ AWS_ACCESS_KEY_ID: str = os.environ.get("AWS_ACCESS_KEY_ID", "test")
6
+ AWS_SECRET_ACCESS_KEY: str = os.environ.get("AWS_SECRET_ACCESS_KEY", "test")
7
+ STACKPORT_PORT: int = int(os.environ.get("STACKPORT_PORT", "8080"))
8
+ STACKPORT_SERVICES: str = os.environ.get(
9
+ "STACKPORT_SERVICES",
10
+ "s3,sqs,sns,dynamodb,lambda,iam,logs,ssm,secretsmanager,kinesis,events,ec2,"
11
+ "route53,kms,cloudformation,stepfunctions,rds,ecs,monitoring,ses,acm,wafv2,"
12
+ "ecr,elasticache,glue,athena,apigateway,firehose,cognito-idp,cognito-identity,"
13
+ "elasticmapreduce,elasticloadbalancing,elasticfilesystem,cloudfront,appsync",
14
+ )
@@ -0,0 +1,53 @@
1
+ import logging
2
+ import os
3
+ import time
4
+
5
+ import uvicorn
6
+ from fastapi import FastAPI
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from fastapi.responses import FileResponse
9
+ from fastapi.staticfiles import StaticFiles
10
+
11
+ from backend.config import STACKPORT_PORT
12
+ from backend.routes import resources, s3, stats
13
+
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format="%(asctime)s %(name)s %(levelname)s %(message)s",
17
+ )
18
+ logger = logging.getLogger(__name__)
19
+
20
+ app = FastAPI(title="StackPort", docs_url="/api/docs")
21
+
22
+ app.add_middleware(
23
+ CORSMiddleware,
24
+ allow_origins=["*"],
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+ app.include_router(stats.router, prefix="/api")
30
+ app.include_router(s3.router, prefix="/api/s3")
31
+ app.include_router(resources.router, prefix="/api")
32
+
33
+ # Serve UI static files — mount assets under /assets, SPA fallback for everything else
34
+ ui_dist = os.path.join(os.path.dirname(__file__), "..", "ui", "dist")
35
+ if os.path.isdir(ui_dist):
36
+ app.mount("/assets", StaticFiles(directory=os.path.join(ui_dist, "assets")), name="assets")
37
+
38
+ @app.get("/{path:path}")
39
+ def spa_fallback(path: str):
40
+ # Try to serve the file directly
41
+ file_path = os.path.join(ui_dist, path)
42
+ if path and os.path.isfile(file_path):
43
+ return FileResponse(file_path)
44
+ # SPA fallback: return index.html
45
+ return FileResponse(os.path.join(ui_dist, "index.html"))
46
+
47
+
48
+ def cli():
49
+ uvicorn.run("backend.main:app", host="0.0.0.0", port=STACKPORT_PORT, reload=False)
50
+
51
+
52
+ if __name__ == "__main__":
53
+ cli()
File without changes
@@ -0,0 +1,248 @@
1
+ import logging
2
+
3
+ from fastapi import APIRouter, HTTPException
4
+
5
+ from backend.aws_client import get_client
6
+ from backend.cache import cache
7
+ from backend.routes.stats import SERVICE_REGISTRY, _METHOD_KWARGS, _count_items
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ router = APIRouter()
12
+
13
+ # Maps (service, resource_type) -> (boto3_service, method, id_param, response_key)
14
+ # response_key=None means return the full response (minus ResponseMetadata)
15
+ DESCRIBE_REGISTRY: dict[tuple[str, str], tuple[str, str, str, str | None]] = {
16
+ # Storage
17
+ ("s3", "buckets"): ("s3", "list_objects_v2", "Bucket", "Contents"),
18
+ # Compute
19
+ ("lambda", "functions"): ("lambda", "get_function", "FunctionName", None),
20
+ ("ecs", "clusters"): ("ecs", "describe_clusters", "clusters", "clusters"),
21
+ ("ecs", "task_definitions"): ("ecs", "describe_task_definition", "taskDefinition", "taskDefinition"),
22
+ # Database
23
+ ("dynamodb", "tables"): ("dynamodb", "describe_table", "TableName", "Table"),
24
+ ("rds", "db_instances"): ("rds", "describe_db_instances", "DBInstanceIdentifier", "DBInstances"),
25
+ ("rds", "db_clusters"): ("rds", "describe_db_clusters", "DBClusterIdentifier", "DBClusters"),
26
+ ("elasticache", "cache_clusters"): ("elasticache", "describe_cache_clusters", "CacheClusterId", None),
27
+ # Messaging
28
+ ("sqs", "queues"): ("sqs", "get_queue_attributes", "QueueUrl", "Attributes"),
29
+ ("sns", "topics"): ("sns", "get_topic_attributes", "TopicArn", "Attributes"),
30
+ ("kinesis", "streams"): ("kinesis", "describe_stream", "StreamName", "StreamDescription"),
31
+ ("firehose", "delivery_streams"): ("firehose", "describe_delivery_stream", "DeliveryStreamName", "DeliveryStreamDescription"),
32
+ ("events", "rules"): ("events", "describe_rule", "Name", None),
33
+ ("events", "event_buses"): ("events", "describe_event_bus", "Name", None),
34
+ # Security & Identity
35
+ ("iam", "roles"): ("iam", "get_role", "RoleName", "Role"),
36
+ ("iam", "users"): ("iam", "get_user", "UserName", "User"),
37
+ ("iam", "policies"): ("iam", "get_policy", "PolicyArn", "Policy"),
38
+ ("secretsmanager", "secrets"): ("secretsmanager", "describe_secret", "SecretId", None),
39
+ ("kms", "keys"): ("kms", "describe_key", "KeyId", "KeyMetadata"),
40
+ ("acm", "certificates"): ("acm", "describe_certificate", "CertificateArn", "Certificate"),
41
+ ("cognito-idp", "user_pools"): ("cognito-idp", "describe_user_pool", "UserPoolId", "UserPool"),
42
+ ("cognito-identity", "identity_pools"): ("cognito-identity", "describe_identity_pool", "IdentityPoolId", None),
43
+ # Management
44
+ ("logs", "log_groups"): ("logs", "describe_log_groups", "logGroupNamePrefix", "logGroups"),
45
+ ("ssm", "parameters"): ("ssm", "get_parameter", "Name", "Parameter"),
46
+ ("cloudformation", "stacks"): ("cloudformation", "describe_stacks", "StackName", "Stacks"),
47
+ ("stepfunctions", "state_machines"): ("stepfunctions", "describe_state_machine", "stateMachineArn", None),
48
+ ("monitoring", "alarms"): ("cloudwatch", "describe_alarms", "AlarmNames", "MetricAlarms"),
49
+ ("monitoring", "dashboards"): ("cloudwatch", "get_dashboard", "DashboardName", None),
50
+ # Networking & CDN
51
+ ("route53", "hosted_zones"): ("route53", "get_hosted_zone", "Id", "HostedZone"),
52
+ ("cloudfront", "distributions"): ("cloudfront", "get_distribution", "Id", "Distribution"),
53
+ ("elasticloadbalancing", "load_balancers"): ("elbv2", "describe_load_balancers", "LoadBalancerArns", "LoadBalancers"),
54
+ # EC2
55
+ ("ec2", "instances"): ("ec2", "describe_instances", "InstanceIds", "Reservations"),
56
+ ("ec2", "vpcs"): ("ec2", "describe_vpcs", "VpcIds", "Vpcs"),
57
+ ("ec2", "subnets"): ("ec2", "describe_subnets", "SubnetIds", "Subnets"),
58
+ ("ec2", "security_groups"): ("ec2", "describe_security_groups", "GroupIds", "SecurityGroups"),
59
+ ("ec2", "volumes"): ("ec2", "describe_volumes", "VolumeIds", "Volumes"),
60
+ ("elasticfilesystem", "file_systems"): ("efs", "describe_file_systems", "FileSystemId", "FileSystems"),
61
+ # Containers
62
+ ("ecr", "repositories"): ("ecr", "describe_repositories", "repositoryNames", "repositories"),
63
+ # Analytics & ETL
64
+ ("glue", "databases"): ("glue", "get_database", "Name", "Database"),
65
+ ("glue", "crawlers"): ("glue", "get_crawler", "Name", "Crawler"),
66
+ ("athena", "workgroups"): ("athena", "get_work_group", "WorkGroup", "WorkGroup"),
67
+ # API
68
+ ("apigateway", "apis"): ("apigatewayv2", "get_api", "ApiId", None),
69
+ ("appsync", "graphql_apis"): ("appsync", "get_graphql_api", "apiId", "graphqlApi"),
70
+ # EMR
71
+ ("elasticmapreduce", "clusters"): ("emr", "describe_cluster", "ClusterId", "Cluster"),
72
+ }
73
+
74
+ # Known ID field names for extracting a resource identifier from list results
75
+ _ID_FIELDS = [
76
+ "BucketName",
77
+ "FunctionName",
78
+ "TableName",
79
+ "TopicArn",
80
+ "QueueUrl",
81
+ "RoleName",
82
+ "UserName",
83
+ "PolicyName",
84
+ "Arn",
85
+ "PolicyArn",
86
+ "logGroupName",
87
+ "Name",
88
+ "SecretName",
89
+ "StreamName",
90
+ "RuleName",
91
+ "InstanceId",
92
+ "VpcId",
93
+ "SubnetId",
94
+ "GroupId",
95
+ "VolumeId",
96
+ "HostedZoneId",
97
+ "Id",
98
+ "KeyId",
99
+ "StackName",
100
+ "stateMachineArn",
101
+ "DBInstanceIdentifier",
102
+ "DBClusterIdentifier",
103
+ "clusterArn",
104
+ "CertificateArn",
105
+ "repositoryName",
106
+ "CacheClusterId",
107
+ "DeliveryStreamName",
108
+ "WorkGroupName",
109
+ "ApiId",
110
+ "UserPoolId",
111
+ "IdentityPoolId",
112
+ "LoadBalancerArn",
113
+ "FileSystemId",
114
+ "AlarmName",
115
+ "DashboardName",
116
+ "CrawlerName",
117
+ "DatabaseName",
118
+ "DistributionId",
119
+ ]
120
+
121
+
122
+ def _extract_id(item) -> str:
123
+ """Extract a usable ID from a list API result item."""
124
+ if isinstance(item, str):
125
+ return item
126
+ if isinstance(item, dict):
127
+ for field in _ID_FIELDS:
128
+ if field in item:
129
+ return str(item[field])
130
+ # Fallback: first string value
131
+ for v in item.values():
132
+ if isinstance(v, str):
133
+ return v
134
+ return str(item)
135
+
136
+
137
+ def _summarize_item(item) -> dict:
138
+ """Create a summary dict from a list API result item."""
139
+ if isinstance(item, str):
140
+ return {"id": item}
141
+ if isinstance(item, dict):
142
+ summary = {"id": _extract_id(item)}
143
+ for key, value in item.items():
144
+ if isinstance(value, (str, int, float, bool)) or value is None:
145
+ summary[key] = value
146
+ elif hasattr(value, "isoformat"):
147
+ summary[key] = value.isoformat()
148
+ return summary
149
+ return {"id": str(item)}
150
+
151
+
152
+ @router.get("/resources/{service}")
153
+ def list_resources(service: str):
154
+ cache_key = f"resources:{service}"
155
+ cached = cache.get(cache_key)
156
+ if cached is not None:
157
+ return cached
158
+
159
+ registry_entries = SERVICE_REGISTRY.get(service)
160
+ if not registry_entries:
161
+ raise HTTPException(status_code=404, detail=f"Unknown service: {service}")
162
+
163
+ resources: dict[str, list[dict]] = {}
164
+ for resource_type, boto3_service, method_name, response_key in registry_entries:
165
+ try:
166
+ client = get_client(boto3_service)
167
+ method = getattr(client, method_name)
168
+ kwargs = _METHOD_KWARGS.get((boto3_service, method_name), {})
169
+ resp = method(**kwargs)
170
+ items = resp.get(response_key, [])
171
+ # Handle nested structures (e.g., cloudfront DistributionList.Items)
172
+ if isinstance(items, dict) and "Items" in items:
173
+ items = items.get("Items", []) or []
174
+ resources[resource_type] = [_summarize_item(item) for item in items]
175
+ except Exception:
176
+ logger.debug("Failed to list %s/%s", service, resource_type, exc_info=True)
177
+ resources[resource_type] = []
178
+
179
+ result = {"service": service, "resources": resources}
180
+ cache.set(cache_key, result, ttl=5)
181
+ return result
182
+
183
+
184
+ @router.get("/resources/{service}/{res_type}/{res_id:path}")
185
+ def get_resource_detail(service: str, res_type: str, res_id: str):
186
+ cache_key = f"detail:{service}:{res_type}:{res_id}"
187
+ cached = cache.get(cache_key)
188
+ if cached is not None:
189
+ return cached
190
+
191
+ lookup = DESCRIBE_REGISTRY.get((service, res_type))
192
+ if not lookup:
193
+ raise HTTPException(
194
+ status_code=404,
195
+ detail=f"No detail lookup registered for {service}/{res_type}",
196
+ )
197
+
198
+ boto3_service, method_name, id_param, response_key = lookup
199
+
200
+ # Some APIs take list parameters (e.g., InstanceIds, VpcIds)
201
+ _LIST_PARAMS = {
202
+ "InstanceIds", "VpcIds", "SubnetIds", "GroupIds", "VolumeIds",
203
+ "repositoryNames", "clusters", "AlarmNames", "LoadBalancerArns",
204
+ }
205
+
206
+ try:
207
+ client = get_client(boto3_service)
208
+ method = getattr(client, method_name)
209
+ if id_param in _LIST_PARAMS:
210
+ resp = method(**{id_param: [res_id]})
211
+ else:
212
+ resp = method(**{id_param: res_id})
213
+
214
+ # Remove boto3 metadata
215
+ resp.pop("ResponseMetadata", None)
216
+
217
+ if response_key is not None:
218
+ detail = resp.get(response_key, resp)
219
+ else:
220
+ detail = resp
221
+
222
+ # Convert datetime objects for JSON serialization
223
+ detail = _serialize(detail)
224
+
225
+ result = {
226
+ "service": service,
227
+ "type": res_type,
228
+ "id": res_id,
229
+ "detail": detail,
230
+ }
231
+ cache.set(cache_key, result, ttl=5)
232
+ return result
233
+ except Exception as exc:
234
+ logger.warning("Failed to get detail for %s/%s/%s", service, res_type, res_id, exc_info=True)
235
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
236
+
237
+
238
+ def _serialize(obj):
239
+ """Recursively convert non-JSON-serializable types."""
240
+ if isinstance(obj, dict):
241
+ return {k: _serialize(v) for k, v in obj.items()}
242
+ if isinstance(obj, list):
243
+ return [_serialize(v) for v in obj]
244
+ if hasattr(obj, "isoformat"):
245
+ return obj.isoformat()
246
+ if isinstance(obj, bytes):
247
+ return obj.decode("utf-8", errors="replace")
248
+ return obj