Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(mwaa.2-3) (#653)
Nahuel Nucerac3381817bc0c
diff --git a/README.md b/README.mdindex 0cf5d258..dc8fa68c 100644--- a/README.md+++ b/README.md@@ -1004,7 +1004,7 @@ pip install boto3 pytest duckdb docker cbor2# Start MiniStackdocker compose up -d-# Run the full test suite (2,200+ tests across all services)+# Run the full test suite (2,400+ tests across all services)pytest tests/ -v```diff --git a/ministack/app.py b/ministack/app.pyindex 31c54c8e..3dc475e6 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -95,7 +95,7 @@ _ALB_PATH_PREFIX = "/_alb/"_NON_S3_VHOST_NAMES = frozenset({"s3", "s3-control", "sqs", "sns", "dynamodb", "lambda", "iam", "sts","secretsmanager", "logs", "ssm", "events", "kinesis", "monitoring", "ses",- "states", "ecs", "rds", "rds-data", "elasticache", "glue", "athena",+ "states", "ecs", "rds", "rds-data", "elasticache", "glue", "athena", "airflow","apigateway", "cloudformation", "autoscaling", "codebuild", "transfer", "cur","cloudfront-kvs","appsync-api", "appsync-realtime-api",@@ -222,6 +222,7 @@ SERVICE_REGISTRY = {"events": {"module": "eventbridge", "aliases": ("eventbridge",)},"firehose": {"module": "firehose", "aliases": ("kinesis-firehose",)},"glue": {"module": "glue"},+ "airflow": {"module": "mwaa", "aliases": ("mwaa",)},"iam": {"module": "iam"},"imds": {"module": "imds"},"kinesis": {"module": "kinesis"},@@ -277,7 +278,7 @@ _state_map = {"elasticache": "elasticache", "appsync": "appsync","appsync_events": "appsync_events","stepfunctions": "stepfunctions", "alb": "alb",- "glue": "glue", "efs": "efs", "waf": "waf",+ "glue": "glue", "mwaa": "mwaa", "efs": "efs", "waf": "waf","athena": "athena", "emr": "emr", "cloudfront": "cloudfront","codebuild": "codebuild", "acm": "acm", "firehose": "firehose","ses": "ses", "ses_v2": "ses_v2",@@ -1096,6 +1097,21 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d# so guard explicitly here too.if path.startswith("/key-value-stores/"):return None+ # MWAA REST endpoints (api.airflow.{region}, env.airflow.{region}) — boto3+ # expands the model's hostPrefix even when endpoint_url is overridden, so+ # the host arrives as `api.localhost:4566`, and `api` looks like an S3+ # bucket. Short-circuit any path that matches a real MWAA operation:+ # /environments, /environments/{Name}, /webtoken/{Name},+ # /clitoken/{Name}, /restapi/{Name}, /metrics/environments/{Name}+ if (+ path == "/environments"+ or path.startswith("/environments/")+ or path.startswith("/webtoken/")+ or path.startswith("/clitoken/")+ or path.startswith("/restapi/")+ or path.startswith("/metrics/environments/")+ ):+ return Nonevhost_path = "/" + bucket + path if path != "/" else "/" + bucket + "/"try:diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 34ee99ab..92f7b437 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -124,6 +124,17 @@ SERVICE_PATTERNS = {"target_prefixes": ["AmazonAthena"],"host_patterns": [r"athena\."],},+ "airflow": {+ "host_patterns": [r"airflow\."],+ "path_patterns": [+ r"^/environments",+ r"^/webtoken/",+ r"^/clitoken/",+ r"^/restapi/",+ r"^/metrics/environments/",+ ],+ "credential_scope": "airflow",+ },"firehose": {"target_prefixes": ["Firehose_20150804"],"host_patterns": [r"firehose\.", r"kinesis-firehose\."],diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.pyindex 0704af60..0fa6acdf 100644--- a/ministack/services/cloudwatch.py+++ b/ministack/services/cloudwatch.py@@ -223,6 +223,7 @@ def _evaluate_alarm(alarm):alarm["StateReason"] = reasonalarm["StateUpdatedTimestamp"] = int(time.time())_record_history(alarm["AlarmName"], old_state, new_state, reason)+ _dispatch_alarm_actions(alarm, old_state, new_state, reason)def _evaluate_all_alarms():@@ -252,6 +253,88 @@ def _record_history(alarm_name, old_state, new_state, reason):)+def record_metric(namespace: str, metric_name: str, value: float,+ unit: str = "None", dimensions: dict | None = None) -> None:+ """Internal entry point for other services to publish CloudWatch metrics+ against AWS namespaces (``AWS/Lambda``, ``AWS/SQS``, etc.) without going+ through the public PutMetricData wire path.++ Multi-tenancy: writes into the *current* account-scoped bucket, so the+ caller's contextvar account_id is used automatically. Safe to call from+ any service handler. Errors are swallowed — instrumentation must never+ break the primary operation.+ """+ dims = dimensions or {}+ try:+ _metric_bucket((namespace, metric_name, _dims_key(dims))).append(+ {+ "Timestamp": time.time(),+ "Value": float(value),+ "Unit": unit,+ "Dimensions": dict(dims),+ }+ )+ except Exception:+ logger.debug("record_metric failed for %s/%s", namespace, metric_name, exc_info=True)+++def _dispatch_alarm_actions(alarm, old_state, new_state, reason):+ """Fire SNS notifications for AlarmActions/OKActions/InsufficientDataActions+ on alarm state transitions.++ Mirrors real CloudWatch: each *Actions list is consulted only for the+ matching destination state. Only SNS topic ARNs are dispatched; other+ action types (autoscaling, EC2, SSM) are stored but not yet executed.+ """+ if not alarm.get("ActionsEnabled", True):+ return+ action_field = {+ "ALARM": "AlarmActions",+ "OK": "OKActions",+ "INSUFFICIENT_DATA": "InsufficientDataActions",+ }.get(new_state)+ if not action_field:+ return+ actions = alarm.get(action_field) or []+ sns_arns = [a for a in actions if isinstance(a, str) and a.startswith("arn:aws:sns:")]+ if not sns_arns:+ return+ try:+ from ministack.services import sns as _sns+ except Exception:+ logger.debug("alarm actions: SNS module unavailable", exc_info=True)+ return++ payload = {+ "AlarmName": alarm.get("AlarmName", ""),+ "AlarmDescription": alarm.get("AlarmDescription", ""),+ "AWSAccountId": get_account_id(),+ "NewStateValue": new_state,+ "NewStateReason": reason,+ "StateChangeTime": _ts_iso(time.time()),+ "Region": get_region(),+ "OldStateValue": old_state,+ "Trigger": {+ "MetricName": alarm.get("MetricName", ""),+ "Namespace": alarm.get("Namespace", ""),+ "Statistic": alarm.get("Statistic", ""),+ "Unit": alarm.get("Unit"),+ "Period": alarm.get("Period", 60),+ "EvaluationPeriods": alarm.get("EvaluationPeriods", 1),+ "ComparisonOperator": alarm.get("ComparisonOperator", ""),+ "Threshold": alarm.get("Threshold", 0),+ "Dimensions": alarm.get("Dimensions", []),+ },+ }+ message = json.dumps(payload)+ subject = f'{new_state}: "{alarm.get("AlarmName", "")}" in {get_region()}'[:100]+ for topic_arn in sns_arns:+ try:+ _sns._fanout(topic_arn, new_uuid(), message, subject)+ except Exception:+ logger.exception("alarm actions: SNS fanout failed for %s", topic_arn)++# ---------------------------------------------------------------------------# Request dispatcher# ---------------------------------------------------------------------------@@ -1140,6 +1223,7 @@ def _set_alarm_state(params, cbor_data, is_cbor, is_json=False):if old_state != new_state:_record_history(name, old_state, new_state, reason)+ _dispatch_alarm_actions(alarm, old_state, new_state, reason)if is_cbor:return _cbor_ok({})diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 573c564c..dffc1322 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -63,6 +63,35 @@ from ministack.core.responses import (logger = logging.getLogger("lambda")+def _emit_lambda_metrics(function_name: str, duration_ms: float,+ error: bool, throttle: bool) -> None:+ """Publish ``AWS/Lambda`` metrics for a single invocation.++ Mirrors the four headline CloudWatch metrics every Lambda function emits:+ Invocations (count), Errors (count), Duration (ms), Throttles (count).+ Errors are swallowed; instrumentation must never break the primary call.+ """+ try:+ from ministack.services import cloudwatch as _cw+ except Exception:+ return+ dims = {"FunctionName": function_name}+ try:+ _cw.record_metric("AWS/Lambda", "Invocations", 1, "Count", dims)+ _cw.record_metric(+ "AWS/Lambda", "Errors", 1 if error else 0, "Count", dims,+ )+ _cw.record_metric(+ "AWS/Lambda", "Throttles", 1 if throttle else 0, "Count", dims,+ )+ if duration_ms > 0:+ _cw.record_metric(+ "AWS/Lambda", "Duration", duration_ms, "Milliseconds", dims,+ )+ except Exception:+ logger.debug("emit lambda metrics failed", exc_info=True)++def _account_from_arn(arn: str) -> str:"""Extract the 12-digit account ID from a Lambda function ARN.@@ -1404,11 +1433,20 @@ async def _invoke(name: str, event: dict, headers: dict, path_qualifier: str | N# helper so event-source fan-out (S3, EventBridge, SNS → Lambda, etc.)# gets identical semantics.invoke_async_with_retry(exec_record, event)+ _emit_lambda_metrics(name, duration_ms=0.0, error=False, throttle=False)return 202, {"X-Amz-Executed-Version": executed_version}, b""# RequestResponse — execute in worker thread so nested SDK calls# from the Lambda process can still reach this ASGI server.+ _t_start = time.time()result = await asyncio.to_thread(_execute_function, exec_record, event)+ _duration_ms = (time.time() - _t_start) * 1000.0+ _emit_lambda_metrics(+ name,+ duration_ms=_duration_ms,+ error=bool(result.get("error")),+ throttle=bool(result.get("throttle")),+ )resp_headers: dict = {"Content-Type": "application/json",diff --git a/ministack/services/mwaa.py b/ministack/services/mwaa.pynew file mode 100644index 00000000..b510438d--- /dev/null+++ b/ministack/services/mwaa.py@@ -0,0 +1,635 @@+"""+MWAA (Managed Workflows for Apache Airflow) Service Emulator.+REST API (path-based routing) for the MWAA control plane.+Supports: CreateEnvironment, GetEnvironment, DeleteEnvironment, UpdateEnvironment,+ ListEnvironments, CreateWebLoginToken, CreateCliToken.++When Docker is available, CreateEnvironment spins up a real Apache Airflow 3.x+container (standalone mode) and returns the actual host:port as the WebserverUrl.+DAGs are synced from the S3 bucket configured in DagS3Path.++The Airflow REST API (v2) is served directly by the container — no proxying needed.+Callers use the WebserverUrl from GetEnvironment to hit Airflow's /api/v2/ endpoints.+"""++import asyncio+import copy+import json+import logging+import os+import socket+import threading+import time++from ministack.core.persistence import load_state+from ministack.core.responses import (+ AccountScopedDict,+ apply_image_prefix,+ error_response_json,+ get_account_id,+ get_region,+ json_response,+ new_uuid,+)++logger = logging.getLogger("mwaa")++BASE_PORT = int(os.environ.get("MWAA_BASE_PORT", "18080"))+MWAA_PERSIST = os.environ.get("MWAA_PERSIST", "0").lower() in ("1", "true", "yes")+DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")+DEFAULT_AIRFLOW_IMAGE = os.environ.get("MWAA_AIRFLOW_IMAGE", "apache/airflow:3.0.6")++_environments = AccountScopedDict()+_port_counter = [BASE_PORT]+_allocated_ports: set[int] = set()+_freed_ports: list[int] = []+_port_lock = threading.Lock()+_docker = None+_ministack_network = None+++def get_state():+ envs = copy.deepcopy(_environments)+ for key in list(envs._data):+ envs._data[key].pop("_docker_container_id", None)+ return {"environments": envs}+++def restore_state(data):+ if not data:+ return+ envs_data = data.get("environments")+ if not envs_data:+ return+ names_to_restart = []+ if isinstance(envs_data, AccountScopedDict):+ for key, env in list(envs_data._data.items()):+ env["_docker_container_id"] = None+ env["Status"] = "CREATING"+ _environments._data[key] = env+ names_to_restart.append((env.get("Name", key), env))+ else:+ for name, env in envs_data.items():+ env["_docker_container_id"] = None+ env["Status"] = "CREATING"+ _environments[name] = env+ names_to_restart.append((name, env))++ # Re-spin containers for persisted environments+ for name, env in names_to_restart:+ threading.Thread(target=_start_airflow_container, args=(name, env), daemon=True).start()+++try:+ _restored = load_state("mwaa")+ if _restored:+ restore_state(_restored)+except Exception:+ logger.exception("Failed to restore persisted state; continuing with fresh store")+++def _get_docker():+ global _docker+ if _docker is None:+ try:+ import docker+ _docker = docker.from_env()+ except Exception:+ pass+ return _docker+++def _get_ministack_network(docker_client):+ global _ministack_network+ if _ministack_network is not None:+ return _ministack_network or None+ if DOCKER_NETWORK:+ _ministack_network = DOCKER_NETWORK+ return DOCKER_NETWORK+ try:+ self_container = docker_client.containers.get(+ os.environ.get("HOSTNAME", ""))+ nets = list(self_container.attrs["NetworkSettings"]["Networks"].keys())+ if nets:+ _ministack_network = nets[0]+ return _ministack_network+ except Exception:+ _ministack_network = ""+ return None+++def _next_port():+ with _port_lock:+ if _freed_ports:+ port = _freed_ports.pop()+ else:+ port = _port_counter[0]+ _port_counter[0] += 1+ _allocated_ports.add(port)+ return port+++def _release_port(port):+ if not port:+ return+ with _port_lock:+ if port in _allocated_ports:+ _allocated_ports.discard(port)+ _freed_ports.append(port)+++def _wait_for_port(host, port, timeout=120):+ deadline = time.time() + timeout+ while time.time() < deadline:+ try:+ with socket.create_connection((host, port), timeout=2):+ return True+ except OSError:+ time.sleep(2)+ return False+++def _capture_v2_admin_password(env, container):+ """Pull the Airflow 2 standalone admin password out of the container so+ proxied REST calls can authenticate. Standalone writes the password to+ ``/opt/airflow/standalone_admin_password.txt`` on first launch.+ """+ for _ in range(12): # up to ~60s — standalone writes the file after webserver init+ try:+ rc, out = container.exec_run(+ "cat /opt/airflow/standalone_admin_password.txt"+ )+ if rc == 0:+ pw = (out.decode("utf-8") if isinstance(out, bytes) else str(out)).strip()+ if pw:+ env["_v2_admin_password"] = pw+ logger.info("MWAA: captured Airflow 2 standalone admin password for %s", env.get("Name"))+ return+ except Exception:+ pass+ time.sleep(5)+ logger.warning("MWAA: failed to capture Airflow 2 standalone admin password for %s", env.get("Name"))+++def _sync_dags_from_s3(env, docker_client, container):+ """Copy DAG files from ministack S3 into the Airflow container's dags folder.++ Reads directly from the S3 service's internal ``_buckets`` store rather+ than going through HTTP — same process, same account context, much faster.+ """+ try:+ from ministack.services import s3 as s3_svc+ bucket_arn = env.get("SourceBucketArn", "")+ bucket_name = bucket_arn.split(":")[-1] if bucket_arn else ""+ dag_path = env.get("DagS3Path", "dags/")++ if not bucket_name:+ return++ bucket = s3_svc._buckets.get(bucket_name)+ if not bucket:+ logger.info("MWAA: source bucket %s not found in S3", bucket_name)+ return++ # Collect every object under DagS3Path. S3 keys are flat strings; treat+ # DagS3Path as a prefix and recurse implicitly (any key starting with+ # it is in scope).+ prefix = dag_path if dag_path.endswith("/") else dag_path + "/"+ matched = [+ (key, obj) for key, obj in bucket.get("objects", {}).items()+ if key.startswith(prefix) and key.endswith(".py")+ ]+ if not matched:+ logger.info("MWAA: no DAGs found in s3://%s/%s", bucket_name, prefix)+ return++ import io+ import tarfile++ tar_buffer = io.BytesIO()+ with tarfile.open(fileobj=tar_buffer, mode="w") as tar:+ for obj_key, obj_data in matched:+ relative = obj_key[len(prefix):].lstrip("/")+ if not relative:+ continue+ body = obj_data.get("body", b"") if isinstance(obj_data, dict) else b""+ if isinstance(body, str):+ body = body.encode("utf-8")+ info = tarfile.TarInfo(name=f"dags/{relative}")+ info.size = len(body)+ info.mode = 0o644+ info.mtime = int(time.time())+ tar.addfile(info, io.BytesIO(body))++ tar_buffer.seek(0)+ container.put_archive("/opt/airflow", tar_buffer)+ logger.info(+ "MWAA: synced %d DAG file(s) from s3://%s/%s",+ len(matched), bucket_name, prefix,+ )+ except Exception:+ logger.exception("MWAA: failed to sync DAGs from S3")+++def _start_airflow_container(env_name, env):+ docker_client = _get_docker()+ if not docker_client:+ logger.warning("MWAA: Docker not available — environment %s will be stub-only", env_name)+ env["Status"] = "AVAILABLE"+ env["WebserverUrl"] = f"localhost:{_next_port()}"+ return++ host_port = _next_port()+ env["_host_port"] = host_port+ ms_network = _get_ministack_network(docker_client)++ airflow_version = env.get("AirflowVersion", "3.0.6")+ is_v3 = airflow_version.startswith("3.")+ image = os.environ.get("MWAA_AIRFLOW_IMAGE", f"apache/airflow:{airflow_version}")+ image = apply_image_prefix(image)++ container_port = 8080+ container_env = {+ "AIRFLOW__CORE__EXECUTOR": "SequentialExecutor",+ "AIRFLOW__CORE__LOAD_EXAMPLES": "false",+ "AIRFLOW__CORE__DAGS_FOLDER": "/opt/airflow/dags",+ # Force the dag-processor to scan aggressively so DAGs synced after+ # container boot become visible within seconds, not minutes. MWAA in+ # real AWS lets users tune this via AirflowConfigurationOptions; we+ # default to fast to keep local iteration tight.+ "AIRFLOW__SCHEDULER__MIN_FILE_PROCESS_INTERVAL": "5",+ "AIRFLOW__SCHEDULER__DAG_DIR_LIST_INTERVAL": "5",+ }++ if is_v3:+ # Airflow 3: SQLAlchemy conn under [database], auth via Simple Auth Manager+ container_env["AIRFLOW__DATABASE__SQL_ALCHEMY_CONN"] = "sqlite:////opt/airflow/airflow.db"+ container_env["AIRFLOW__CORE__SIMPLE_AUTH_MANAGER_ALL_ADMINS"] = "true"+ else:+ # Airflow 2: SQLAlchemy conn under [core] or [database], auth via basic_auth backend+ container_env["AIRFLOW__CORE__SQL_ALCHEMY_CONN"] = "sqlite:////opt/airflow/airflow.db"+ container_env["AIRFLOW__API__AUTH_BACKENDS"] = "airflow.api.auth.backend.basic_auth"+ container_env["_AIRFLOW_WWW_USER_USERNAME"] = "admin"+ container_env["_AIRFLOW_WWW_USER_PASSWORD"] = "admin"++ env["_is_v3"] = is_v3++ # Merge user-supplied Airflow config options+ for key, value in env.get("AirflowConfigurationOptions", {}).items():+ env_key = key.replace(".", "__").upper()+ container_env[f"AIRFLOW__{env_key}"] = value++ try:+ container_kwargs = dict(+ image=image,+ detach=True,+ command="standalone",+ environment=container_env,+ ports={f"{container_port}/tcp": host_port},+ name=f"ministack-mwaa-{env_name}",+ labels={"ministack": "mwaa", "env_name": env_name},+ )++ if ms_network:+ container_kwargs["network"] = ms_network++ if MWAA_PERSIST:+ container_kwargs["volumes"] = {+ f"ministack-mwaa-{env_name}-dags": {"bind": "/opt/airflow/dags", "mode": "rw"},+ f"ministack-mwaa-{env_name}-db": {"bind": "/opt/airflow", "mode": "rw"},+ }++ container = docker_client.containers.run(**container_kwargs)+ env["_docker_container_id"] = container.id++ internal_host = "localhost"+ internal_port = host_port++ if ms_network:+ container.reload()+ networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})+ container_ip = networks.get(ms_network, {}).get("IPAddress", "")+ if container_ip:+ internal_host = container_ip+ internal_port = container_port++ env["WebserverUrl"] = f"{internal_host}:{internal_port}"++ def _bg_init():+ if _wait_for_port(internal_host, internal_port, timeout=120):+ logger.info("MWAA: Airflow container for %s ready at %s:%s",+ env_name, internal_host, internal_port)+ env["Status"] = "AVAILABLE"+ # Sync DAGs from S3 once Airflow is ready+ _sync_dags_from_s3(env, docker_client, container)+ # Airflow 2 standalone generates a random admin password and+ # writes it to standalone_admin_password.txt. Capture it so+ # _invoke_rest_api can authenticate against /api/v1/ — basic+ # auth `admin:admin` from the env vars only takes effect+ # outside standalone mode. v3 uses Simple Auth Manager with+ # ALL_ADMINS=true so no token is needed.+ if not is_v3:+ _capture_v2_admin_password(env, container)+ else:+ logger.warning("MWAA: Airflow container for %s not ready after timeout", env_name)+ env["Status"] = "CREATE_FAILED"+ env.setdefault("LastUpdate", {})["Error"] = {+ "ErrorCode": "CONTAINER_STARTUP_TIMEOUT",+ "ErrorMessage": "Airflow container did not become healthy within 120s",+ }++ threading.Thread(target=_bg_init, daemon=True).start()++ except Exception as e:+ logger.exception("MWAA: failed to start Airflow container for %s", env_name)+ env["Status"] = "CREATE_FAILED"+ env["WebserverUrl"] = ""+ env.setdefault("LastUpdate", {})["Error"] = {+ "ErrorCode": "CONTAINER_LAUNCH_FAILED",+ "ErrorMessage": str(e)[:500],+ }+++def _build_env_response(env):+ """Build the Environment response object (strip internal fields)."""+ result = {k: v for k, v in env.items() if not k.startswith("_")}+ return result+++# ── API Handlers ──────────────────────────────────────────────────────────────+++def _create_environment(method, path, headers, body, query_params):+ data = json.loads(body) if body else {}+ name = path.strip("/").split("/")[-1]++ if name in _environments:+ return error_response_json("ResourceAlreadyExistsException",+ f"Environment {name} already exists", 409)++ account_id = get_account_id()+ region = get_region()++ env = {+ "Name": name,+ "Arn": f"arn:aws:airflow:{region}:{account_id}:environment/{name}",+ "Status": "CREATING",+ "AirflowVersion": data.get("AirflowVersion", "3.0.6"),+ "EnvironmentClass": data.get("EnvironmentClass", "mw1.small"),+ "WebserverAccessMode": data.get("WebserverAccessMode", "PUBLIC_ONLY"),+ "SourceBucketArn": data.get("SourceBucketArn", ""),+ "DagS3Path": data.get("DagS3Path", "dags/"),+ "ExecutionRoleArn": data.get("ExecutionRoleArn", ""),+ "NetworkConfiguration": data.get("NetworkConfiguration", {}),+ "AirflowConfigurationOptions": data.get("AirflowConfigurationOptions", {}),+ "LoggingConfiguration": data.get("LoggingConfiguration", {}),+ "MaxWorkers": data.get("MaxWorkers", 5),+ "MinWorkers": data.get("MinWorkers", 1),+ "Schedulers": data.get("Schedulers", 2),+ "MaxWebservers": data.get("MaxWebservers", 2),+ "MinWebservers": data.get("MinWebservers", 2),+ "WebserverUrl": "",+ "Tags": data.get("Tags", {}),+ "CreatedAt": time.time(),+ "LastUpdate": {"Status": "SUCCESS"},+ "ServiceRoleArn": f"arn:aws:iam::{account_id}:role/aws-service-role/airflow.amazonaws.com/AWSServiceRoleForAmazonMWAA",+ "_docker_container_id": None,+ }++ _environments[name] = env++ # Start container in background+ threading.Thread(target=_start_airflow_container, args=(name, env), daemon=True).start()++ return json_response({"Arn": env["Arn"]}, status=200)+++def _get_environment(method, path, headers, body, query_params):+ name = path.strip("/").split("/")[-1]+ env = _environments.get(name)+ if not env:+ return error_response_json("ResourceNotFoundException",+ f"Environment {name} not found", 404)+ return json_response({"Environment": _build_env_response(env)})+++def _delete_environment(method, path, headers, body, query_params):+ name = path.strip("/").split("/")[-1]+ env = _environments.get(name)+ if not env:+ return error_response_json("ResourceNotFoundException",+ f"Environment {name} not found", 404)++ container_id = env.get("_docker_container_id")+ if container_id:+ docker_client = _get_docker()+ if docker_client:+ try:+ container = docker_client.containers.get(container_id)+ container.stop(timeout=5)+ container.remove(force=True)+ except Exception:+ logger.debug("MWAA: container cleanup for %s failed (may be already gone)", name)++ _release_port(env.get("_host_port"))+ del _environments[name]+ return json_response({}, status=200)+++def _update_environment(method, path, headers, body, query_params):+ data = json.loads(body) if body else {}+ name = path.strip("/").split("/")[-1]+ env = _environments.get(name)+ if not env:+ return error_response_json("ResourceNotFoundException",+ f"Environment {name} not found", 404)++ for field in ("AirflowConfigurationOptions", "LoggingConfiguration",+ "MaxWorkers", "MinWorkers", "Schedulers",+ "EnvironmentClass", "ExecutionRoleArn", "SourceBucketArn",+ "DagS3Path", "NetworkConfiguration", "WebserverAccessMode"):+ if field in data:+ env[field] = data[field]++ env["LastUpdate"] = {"Status": "SUCCESS"}+ return json_response({"Arn": env["Arn"]})+++def _list_environments(method, path, headers, body, query_params):+ names = list(_environments.keys())+ return json_response({"Environments": names})+++def _create_web_login_token(method, path, headers, body, query_params):+ data = json.loads(body) if body else {}+ parts = [p for p in path.strip("/").split("/") if p]+ name = data.get("Name") or (parts[-1] if parts else "")+ env = _environments.get(name)+ if not env:+ return error_response_json("ResourceNotFoundException",+ f"Environment {name} not found", 404)++ webserver_url = env.get("WebserverUrl", "")+ token = new_uuid()++ return json_response({+ "WebToken": token,+ "WebServerHostname": webserver_url,+ "IamIdentity": f"arn:aws:iam::{get_account_id()}:user/ministack",+ "AirflowIdentity": "admin",+ })+++def _create_cli_token(method, path, headers, body, query_params):+ data = json.loads(body) if body else {}+ parts = [p for p in path.strip("/").split("/") if p]+ name = data.get("Name") or (parts[-1] if parts else "")+ env = _environments.get(name)+ if not env:+ return error_response_json("ResourceNotFoundException",+ f"Environment {name} not found", 404)++ webserver_url = env.get("WebserverUrl", "")+ token = new_uuid()++ return json_response({+ "CliToken": token,+ "WebServerHostname": webserver_url,+ })+++async def _invoke_rest_api(method, path, headers, body, query_params):+ """Proxy InvokeRestApi to the local Airflow container's REST API.++ The outbound HTTP call uses the blocking ``requests`` client off-loaded+ to a worker thread so it does not stall the single-process event loop+ while Airflow processes the request (which can take seconds).++ boto3 places the environment ``Name`` in the URL path (``/restapi/{Name}``)+ per the MWAA service model, not in the JSON body. Extract from the path,+ fall back to the body for callers that bypass the SDK.+ """+ data = json.loads(body) if body else {}+ parts = [p for p in path.strip("/").split("/") if p]+ name = (parts[-1] if parts else "") or data.get("Name", "")+ env = _environments.get(name)+ if not env:+ return error_response_json("ResourceNotFoundException",+ f"Environment {name} not found", 404)++ webserver_url = env.get("WebserverUrl", "")+ if not webserver_url:+ return error_response_json("InternalServerException",+ "Environment webserver not available", 500)++ api_method = (data.get("Method") or "GET").upper()+ if api_method not in ("GET", "POST", "PATCH", "DELETE"):+ return error_response_json("ValidationException",+ f"Unsupported method: {api_method}", 400)++ api_path = data.get("Path", "/")+ api_body = data.get("Body", {})++ is_v3 = env.get("_is_v3", True)+ api_base = "/api/v2" if is_v3 else "/api/v1"+ url = f"http://{webserver_url}{api_base}{api_path}"++ req_headers = {"Content-Type": "application/json"}+ if not is_v3:+ # Airflow 2 standalone generates a random admin password; we captured+ # it after the container reached AVAILABLE. Fall back to admin/admin+ # if capture failed so the caller at least sees a clean 401 instead+ # of a TypeError.+ import base64+ pw = env.get("_v2_admin_password") or "admin"+ creds = base64.b64encode(f"admin:{pw}".encode()).decode()+ req_headers["Authorization"] = f"Basic {creds}"++ def _do_call():+ import requests as req_lib+ if api_method == "GET":+ return req_lib.get(url, headers=req_headers, timeout=30)+ if api_method in ("POST", "PATCH"):+ return req_lib.request(api_method, url, headers=req_headers, json=api_body, timeout=30)+ return req_lib.delete(url, headers=req_headers, timeout=30)++ try:+ resp = await asyncio.to_thread(_do_call)+ ctype = resp.headers.get("content-type", "")+ payload = resp.json() if ctype.startswith("application/json") else {"body": resp.text}+ return json_response({+ "RestApiStatusCode": resp.status_code,+ "RestApiResponse": payload,+ })+ except Exception as e:+ return error_response_json("InternalServerException", str(e)[:500], 500)+++# ── Request Router ────────────────────────────────────────────────────────────+++async def handle_request(method, path, headers, body, query_params):+ """Route MWAA REST API requests.++ MWAA uses two API endpoints in AWS:+ - api.airflow.{region}.amazonaws.com — management (CRUD environments)+ - env.airflow.{region}.amazonaws.com — runtime (tokens, CLI, InvokeRestApi)++ In ministack, both are served from the same handler. Paths match the+ botocore MWAA service model exactly:+ PUT /environments/{Name} → CreateEnvironment+ GET /environments/{Name} → GetEnvironment+ PATCH /environments/{Name} → UpdateEnvironment+ DELETE /environments/{Name} → DeleteEnvironment+ GET /environments → ListEnvironments+ POST /webtoken/{Name} → CreateWebLoginToken (runtime)+ POST /clitoken/{Name} → CreateCliToken (runtime)+ POST /restapi/{Name} → InvokeRestApi (runtime)+ """+ clean_path = path.rstrip("/")++ # CreateWebLoginToken (real AWS path: /webtoken/{Name})+ if method == "POST" and clean_path.startswith("/webtoken/"):+ return _create_web_login_token(method, path, headers, body, query_params)++ # CreateCliToken (real AWS path: /clitoken/{Name})+ if method == "POST" and clean_path.startswith("/clitoken/"):+ return _create_cli_token(method, path, headers, body, query_params)++ # InvokeRestApi+ if method == "POST" and clean_path.startswith("/restapi/"):+ return await _invoke_rest_api(method, path, headers, body, query_params)++ # ListEnvironments+ if method == "GET" and clean_path in ("/environments", "/api/environments"):+ return _list_environments(method, path, headers, body, query_params)++ # CRUD on /environments/{Name}+ if clean_path.startswith("/environments/"):+ if method == "PUT":+ return _create_environment(method, path, headers, body, query_params)+ if method == "GET":+ return _get_environment(method, path, headers, body, query_params)+ if method == "PATCH":+ return _update_environment(method, path, headers, body, query_params)+ if method == "DELETE":+ return _delete_environment(method, path, headers, body, query_params)++ return error_response_json("InvalidRequestException",+ f"Unknown MWAA path: {method} {path}", 400)+++def reset():+ """Stop all containers and clear state."""+ docker_client = _get_docker()+ for name, env in list(_environments.items()):+ container_id = env.get("_docker_container_id")+ if container_id and docker_client:+ try:+ container = docker_client.containers.get(container_id)+ container.stop(timeout=5)+ container.remove(force=True)+ except Exception:+ pass+ _release_port(env.get("_host_port"))+ _environments.clear()diff --git a/tests/conftest.py b/tests/conftest.pyindex 8d9202d7..d44e9f6e 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -96,17 +96,56 @@ def pytest_collection_modifyitems(config, items):@pytest.fixture(scope="session", autouse=True)-def reset_server():- """Reset all server state once before the test session starts."""- req = urllib.request.Request(- f"{ENDPOINT}/_ministack/reset",- data=b"",- method="POST",- )+def reset_server(tmp_path_factory, worker_id):+ """Reset all server state once before the test session starts.++ Under pytest-xdist, every worker spawns its own session. If each worker+ calls /_ministack/reset on startup, a slow worker's reset can fire AFTER+ a faster worker has already begun creating fixtures, wiping that state+ mid-test. Use a filesystem barrier so only the first worker resets;+ the others wait for the marker and skip.+ """+ if worker_id == "master":+ # Single-process pytest run — no xdist.+ try:+ urllib.request.urlopen(+ urllib.request.Request(f"{ENDPOINT}/_ministack/reset",+ data=b"", method="POST"),+ timeout=5,+ )+ except Exception:+ pass+ return++ # xdist mode — coordinate via the shared root tmp dir (one level above+ # the per-worker tmp). Only the worker that creates the marker resets.+ root_tmp = tmp_path_factory.getbasetemp().parent+ marker = root_tmp / ".ministack_reset_done"+ lock = root_tmp / ".ministack_reset.lock"try:- urllib.request.urlopen(req, timeout=5)- except Exception:- pass # server may not be up yet; individual tests will fail naturally+ # O_CREAT|O_EXCL ensures only one worker wins the race.+ fd = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY)+ os.close(fd)+ won = True+ except FileExistsError:+ won = False+ if won:+ try:+ urllib.request.urlopen(+ urllib.request.Request(f"{ENDPOINT}/_ministack/reset",+ data=b"", method="POST"),+ timeout=5,+ )+ except Exception:+ pass+ marker.write_text("ok")+ else:+ # Wait briefly for the chosen worker to finish its reset before+ # any tests on this worker touch the server.+ import time as _t+ deadline = _t.time() + 10+ while not marker.exists() and _t.time() < deadline:+ _t.sleep(0.1)@pytest.fixture(scope="session")diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.pyindex a40b4003..5b880cfa 100644--- a/tests/test_cloudwatch.py+++ b/tests/test_cloudwatch.py@@ -411,6 +411,96 @@ def test_cloudwatch_enable_alarm_actions(cw):cw.delete_alarms(AlarmNames=["heimdall-enable-actions"])+def test_cloudwatch_alarm_actions_publish_to_sns(cw, sns, sqs):+ """AlarmActions/OKActions: state transition fans out to the SNS topic.++ Subscribes an SQS queue to a topic, sets that topic ARN as the alarm's+ AlarmActions + OKActions, flips state ALARM → OK, and asserts the SQS+ queue received both notifications with the AWS-shaped JSON payload.+ """+ topic_arn = sns.create_topic(Name="cw-alarm-actions-topic")["TopicArn"]+ queue_url = sqs.create_queue(QueueName="cw-alarm-actions-q")["QueueUrl"]+ queue_arn = sqs.get_queue_attributes(+ QueueUrl=queue_url, AttributeNames=["QueueArn"]+ )["Attributes"]["QueueArn"]+ sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn)++ cw.put_metric_alarm(+ AlarmName="cw-actions-fanout",+ MetricName="M",+ Namespace="N",+ Statistic="Sum",+ Period=60,+ EvaluationPeriods=1,+ Threshold=1.0,+ ComparisonOperator="GreaterThanThreshold",+ ActionsEnabled=True,+ AlarmActions=[topic_arn],+ OKActions=[topic_arn],+ )++ cw.set_alarm_state(+ AlarmName="cw-actions-fanout",+ StateValue="ALARM",+ StateReason="forced",+ )+ cw.set_alarm_state(+ AlarmName="cw-actions-fanout",+ StateValue="OK",+ StateReason="recovered",+ )++ seen_states = set()+ deadline = time.time() + 5+ while time.time() < deadline and len(seen_states) < 2:+ msgs = sqs.receive_message(+ QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=1,+ ).get("Messages", [])+ for m in msgs:+ envelope = json.loads(m["Body"])+ payload = json.loads(envelope["Message"])+ seen_states.add(payload["NewStateValue"])+ assert payload["AlarmName"] == "cw-actions-fanout"+ assert payload["Trigger"]["MetricName"] == "M"+ sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=m["ReceiptHandle"])+ assert seen_states == {"ALARM", "OK"}, f"got states: {seen_states}"+ cw.delete_alarms(AlarmNames=["cw-actions-fanout"])+++def test_cloudwatch_alarm_actions_disabled_does_not_publish(cw, sns, sqs):+ """ActionsEnabled=False suppresses dispatch even on state transition."""+ topic_arn = sns.create_topic(Name="cw-alarm-disabled-topic")["TopicArn"]+ queue_url = sqs.create_queue(QueueName="cw-alarm-disabled-q")["QueueUrl"]+ queue_arn = sqs.get_queue_attributes(+ QueueUrl=queue_url, AttributeNames=["QueueArn"]+ )["Attributes"]["QueueArn"]+ sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn)++ cw.put_metric_alarm(+ AlarmName="cw-actions-disabled",+ MetricName="M",+ Namespace="N",+ Statistic="Sum",+ Period=60,+ EvaluationPeriods=1,+ Threshold=1.0,+ ComparisonOperator="GreaterThanThreshold",+ ActionsEnabled=False,+ AlarmActions=[topic_arn],+ )+ cw.set_alarm_state(+ AlarmName="cw-actions-disabled",+ StateValue="ALARM",+ StateReason="forced",+ )+ time.sleep(0.5)+ msgs = sqs.receive_message(+ QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=1,+ ).get("Messages", [])+ assert msgs == []+ cw.delete_alarms(AlarmNames=["cw-actions-disabled"])++def test_cloudwatch_disable_alarm_actions(cw):cw.put_metric_alarm(AlarmName="heimdall-disable-actions",diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 9e938cf7..4d484bf6 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -253,6 +253,55 @@ def test_lambda_invoke_async(lam):)assert resp["StatusCode"] == 202++def test_lambda_invoke_emits_cloudwatch_metrics(lam, cw):+ """After invocation, AWS/Lambda namespace must carry Invocations + Duration+ metrics dimensioned by FunctionName. Mirrors real Lambda observability —+ the four canonical metrics (Invocations, Errors, Duration, Throttles) are+ published per call.++ Marked ``serial`` because xdist workers share one ministack container, and+ any concurrent test calling ``/_ministack/reset`` would wipe the metric+ store between our invoke and query. The function name is also UUID-suffixed+ so re-runs against a persistent store don't pick up stale datapoints.+ """+ fname = f"lam-cw-metrics-{_uuid_mod.uuid4().hex[:8]}"+ lam.create_function(+ FunctionName=fname,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(_LAMBDA_CODE)},+ )+ try:+ lam.invoke(FunctionName=fname, Payload=json.dumps({"x": 1}))+ lam.invoke(FunctionName=fname, Payload=json.dumps({"x": 2}))++ end = time.time()+ start = end - 600+ invocations = cw.get_metric_statistics(+ Namespace="AWS/Lambda",+ MetricName="Invocations",+ Dimensions=[{"Name": "FunctionName", "Value": fname}],+ StartTime=start, EndTime=end,+ Period=60, Statistics=["Sum"],+ )+ total = sum(p["Sum"] for p in invocations["Datapoints"])+ assert total >= 2, f"expected >=2 invocations, got {total}"++ duration = cw.get_metric_statistics(+ Namespace="AWS/Lambda",+ MetricName="Duration",+ Dimensions=[{"Name": "FunctionName", "Value": fname}],+ StartTime=start, EndTime=end,+ Period=60, Statistics=["Average", "Maximum"],+ )+ assert duration["Datapoints"], "no Duration datapoints recorded"+ assert duration["Datapoints"][0]["Average"] > 0+ finally:+ lam.delete_function(FunctionName=fname)+def test_lambda_update_code(lam):lam.update_function_code(FunctionName="lam-invoke-test",diff --git a/tests/test_mwaa.py b/tests/test_mwaa.pynew file mode 100644index 00000000..94a7884b--- /dev/null+++ b/tests/test_mwaa.py@@ -0,0 +1,166 @@+"""Tests for MWAA (Managed Workflows for Apache Airflow) service."""++import time++import pytest++from conftest import make_client++mwaa_client = make_client("mwaa")+s3_client = make_client("s3")+++ENV_NAME = "test-airflow-env"+++class TestCreateEnvironment:+ def test_create_returns_arn(self):+ resp = mwaa_client.create_environment(+ Name=ENV_NAME,+ DagS3Path="dags/",+ ExecutionRoleArn="arn:aws:iam::000000000000:role/test-role",+ SourceBucketArn="arn:aws:s3:::test-bucket",+ NetworkConfiguration={"SubnetIds": ["subnet-1", "subnet-2"], "SecurityGroupIds": ["sg-1"]},+ )+ assert "Arn" in resp+ assert ENV_NAME in resp["Arn"]++ def test_duplicate_create_fails(self):+ with pytest.raises(mwaa_client.exceptions.ClientError) as exc_info:+ mwaa_client.create_environment(+ Name=ENV_NAME,+ DagS3Path="dags/",+ ExecutionRoleArn="arn:aws:iam::000000000000:role/test-role",+ SourceBucketArn="arn:aws:s3:::test-bucket",+ NetworkConfiguration={"SubnetIds": ["subnet-1", "subnet-2"], "SecurityGroupIds": ["sg-1"]},+ )+ assert "already exists" in str(exc_info.value).lower() or "ResourceAlreadyExists" in str(exc_info.value)+++class TestGetEnvironment:+ def test_get_returns_environment(self):+ resp = mwaa_client.get_environment(Name=ENV_NAME)+ env = resp["Environment"]+ assert env["Name"] == ENV_NAME+ assert "Arn" in env+ assert env["Status"] in ("CREATING", "AVAILABLE", "CREATE_FAILED")+ assert env["AirflowVersion"] == "3.0.6"++ def test_get_nonexistent_fails(self):+ with pytest.raises(mwaa_client.exceptions.ClientError) as exc_info:+ mwaa_client.get_environment(Name="nonexistent-env")+ assert "ResourceNotFound" in str(exc_info.value) or "not found" in str(exc_info.value).lower()+++class TestListEnvironments:+ def test_list_includes_created(self):+ resp = mwaa_client.list_environments()+ assert ENV_NAME in resp["Environments"]+++class TestUpdateEnvironment:+ def test_update_workers(self):+ resp = mwaa_client.update_environment(+ Name=ENV_NAME,+ MaxWorkers=10,+ )+ assert "Arn" in resp++ updated = mwaa_client.get_environment(Name=ENV_NAME)["Environment"]+ assert updated["MaxWorkers"] == 10+++class TestCreateWebLoginToken:+ def test_returns_token(self):+ resp = mwaa_client.create_web_login_token(Name=ENV_NAME)+ assert "WebToken" in resp+ assert "WebServerHostname" in resp+++class TestCreateCliToken:+ def test_returns_token(self):+ resp = mwaa_client.create_cli_token(Name=ENV_NAME)+ assert "CliToken" in resp+ assert "WebServerHostname" in resp+++class TestDeleteEnvironment:+ def test_delete_succeeds(self):+ mwaa_client.delete_environment(Name=ENV_NAME)+ # Verify it's gone+ resp = mwaa_client.list_environments()+ assert ENV_NAME not in resp["Environments"]++ def test_delete_nonexistent_fails(self):+ with pytest.raises(mwaa_client.exceptions.ClientError):+ mwaa_client.delete_environment(Name="nonexistent-env")+++class TestAirflow2Environment:+ """Verify Airflow 2.x environment creation works with v2 config."""++ ENV_V2 = "test-airflow2-env"++ def test_create_v2_returns_arn(self):+ resp = mwaa_client.create_environment(+ Name=self.ENV_V2,+ AirflowVersion="2.10.4",+ DagS3Path="dags/",+ ExecutionRoleArn="arn:aws:iam::000000000000:role/test-role",+ SourceBucketArn="arn:aws:s3:::test-bucket",+ NetworkConfiguration={"SubnetIds": ["subnet-1", "subnet-2"], "SecurityGroupIds": ["sg-1"]},+ )+ assert "Arn" in resp++ def test_v2_version_stored(self):+ env = mwaa_client.get_environment(Name=self.ENV_V2)["Environment"]+ assert env["AirflowVersion"] == "2.10.4"++ def test_cleanup_v2(self):+ mwaa_client.delete_environment(Name=self.ENV_V2)+ resp = mwaa_client.list_environments()+ assert self.ENV_V2 not in resp["Environments"]+++class TestEnvironmentWithDags:+ """Test DAG sync from S3 when Docker is available."""++ def test_create_with_s3_dags(self):+ bucket_name = "mwaa-test-dags-bucket"+ s3_client.create_bucket(+ Bucket=bucket_name,+ CreateBucketConfiguration={"LocationConstraint": "eu-west-1"},+ )++ # Upload a simple DAG+ dag_content = '''+from datetime import datetime+from airflow import DAG+from airflow.operators.empty import EmptyOperator++with DAG("test_dag", start_date=datetime(2026, 1, 1), schedule=None, catchup=False):+ EmptyOperator(task_id="hello")+'''+ s3_client.put_object(Bucket=bucket_name, Key="dags/test_dag.py", Body=dag_content.encode())++ env_name = "test-env-with-dags"+ try:+ resp = mwaa_client.create_environment(+ Name=env_name,+ DagS3Path="dags/",+ ExecutionRoleArn="arn:aws:iam::000000000000:role/test-role",+ SourceBucketArn=f"arn:aws:s3:::{bucket_name}",+ NetworkConfiguration={"SubnetIds": ["subnet-1", "subnet-2"], "SecurityGroupIds": ["sg-1"]},+ )+ assert "Arn" in resp++ env = mwaa_client.get_environment(Name=env_name)["Environment"]+ assert env["SourceBucketArn"] == f"arn:aws:s3:::{bucket_name}"+ assert env["DagS3Path"] == "dags/"+ listed = mwaa_client.list_environments()["Environments"]+ assert env_name in listed+ finally:+ try:+ mwaa_client.delete_environment(Name=env_name)+ except Exception:+ pass