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(kinesisanalyticsv2): Managed Service for Apache Flink control plane (#2134)
Luke Dutton34b84b030643
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4da11f9d..f4328441 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added++- **Managed Service for Apache Flink — control plane** — `kinesisanalyticsv2` applications for the `FLINK-*` runtimes: create, describe, update and delete, start and stop with the model's status transitions, snapshots, CloudWatch logging options and tags, per account and region. Updates bump `ApplicationVersionId` and the `ConditionalToken`, and a stale one returns `ConcurrentModificationException`. CloudFormation creates, updates and deletes `AWS::KinesisAnalyticsV2::Application`, `AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption` and `AWS::Logs::LogStream`, so a CDK Flink stack deploys. The Flink job itself does not run (control plane only).## [1.5.28] — 2026-10-16### Addeddiff --git a/README.md b/README.mdindex 633df6e6..e5a93d07 100644--- a/README.md+++ b/README.md@@ -450,6 +450,7 @@ subnet = ec2.create_subnet(| **Cloud Control API** | CreateResource, GetResource, UpdateResource, DeleteResource, ListResources, ListResourceRequests, GetResourceRequestStatus, CancelResourceRequest | Generic resource control plane behind Terraform's `awscc` provider and CDK L1 constructs; AWS `ProgressEvent` and `ResourceDescription` shapes (`Properties` as a JSON string); resource-request status + cancel || **Cost & Usage Reports** | DeleteReportDefinition, DescribeReportDefinitions, ListTagsForResource, ModifyReportDefinition, PutReportDefinition, TagResource, UntagResource | 7 of 7 spec ops || **AWS Budgets** | CreateBudget, DescribeBudget, DescribeBudgets, UpdateBudget, DeleteBudget, CreateNotification, UpdateNotification, DeleteNotification, DescribeNotificationsForBudget, CreateSubscriber, UpdateSubscriber, DeleteSubscriber, DescribeSubscribersForNotification, TagResource, UntagResource, ListTagsForResource | Global (account-scoped) service; `CreateBudget` accepts inline `NotificationsWithSubscribers` and `ResourceTags`; enforces the 10-notification/budget and 11-subscriber/notification quotas (`CreationLimitExceededException`); deleting a notification's last subscriber deletes the notification; a budget's `CalculatedSpend` always reports zero (no billing engine); verified against Terraform's `aws_budgets_budget` resource |+| **Managed Service for Apache Flink** | CreateApplication, DescribeApplication, UpdateApplication, DeleteApplication, StartApplication, StopApplication, CreateApplicationSnapshot, ListApplicationSnapshots, DescribeApplicationSnapshot, DeleteApplicationSnapshot, AddApplicationCloudWatchLoggingOption, DeleteApplicationCloudWatchLoggingOption, TagResource, UntagResource, ListTagsForResource | `kinesisanalyticsv2` control plane for Apache Flink applications (`FLINK-*` runtimes; SQL and Studio applications are not implemented): application versions and `ConditionalToken` with `ConcurrentModificationException` on a stale one, the model's status transitions on start, stop and update (without a running job, a transitional status settles on the next read), snapshots (a graceful stop takes one when snapshots are enabled, `Force` does not), CloudWatch logging options and tags. The Flink job itself does not run (control plane only), and an application restored after a restart comes back `READY` || **Inspector2** | Enable, Disable, ListFindings, BatchGetFindingDetails, ListCoverage, ListCoverageStatistics, ListFindingAggregations, SearchVulnerabilities, TagResource, UntagResource, ListTagsForResource, CreateFilter, ListFilters, DeleteFilter | 14 operations; deterministic stub vulnerability findings for ECR images, Lambda functions, and EC2 instances; filtering, sorting, pagination || **AmazonMQ** | CreateBroker, ListBrokers, DescribeBrokers, DeleteBrokers, UpdateBroker, RebootBroker, DescribeBrokerEngineTypes, DescribeBrokerInstanceOptions, CreateTags, ListTags, DeleteTags, CreateUser, DeleteUser, ListUsers, UpdateUser, DescribeUser | 16 of 24 spec ops; No real container support || **Amazon Location (trackers)** | CreateTracker, DescribeTracker, UpdateTracker, ListTrackers, DeleteTracker, BatchUpdateDevicePosition, GetDevicePosition, BatchGetDevicePosition, GetDevicePositionHistory | Tracker control plane + in-memory device-position store; signs with credential scope `geo` (the client is named `location`); ISO 8601 `SampleTime`/`ReceivedTime`, `Position` as the modeled `[lon, lat]` double pair, out-of-range coordinates as per-entry `Errors`; `GetDevicePositionHistory` ascending, defaulting to the last 24 h; `ListTrackers` and the history page at `MaxResults` 1..100 with `NextToken`; every sample is stored (no position filtering, no 30-day expiry), newest 100 per device; `KmsKeyId`/`PositionFiltering`/`EventBridgeEnabled`/`Tags` stored without effect; no consumers, geofences, maps, places or routes; CFN `AWS::Location::Tracker` supported |@@ -496,9 +497,12 @@ subnet = ec2.create_subnet(| `AWS::SSM::Parameter` | Parameter name | Type, Value || `AWS::Logs::LogGroup` | Log group name | Arn || `AWS::Logs::MetricFilter` | Filter name | — |+| `AWS::Logs::LogStream` | Log stream name | — || `AWS::Events::EventBus` | EventBus name | Arn, Name || `AWS::Events::Rule` | Rule name | Arn || `AWS::Kinesis::Stream` | Stream name | Arn, StreamId |+| `AWS::KinesisAnalyticsV2::Application` | Application name | — |+| `AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption` | Logging option id | — || `AWS::ElastiCache::SubnetGroup` | Subnet group name | — || `AWS::ElastiCache::ParameterGroup` | Generated parameter group name | CacheParameterGroupName || `AWS::ElastiCache::CacheCluster` | Cluster name | Id, RedisEndpoint.Address, RedisEndpoint.Port (Valkey / Redis OSS), ConfigurationEndpoint.Address, ConfigurationEndpoint.Port (Memcached) |diff --git a/ministack/app.py b/ministack/app.pyindex eff78cda..a4d686da 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -204,6 +204,7 @@ _NON_S3_VHOST_NAMES = frozenset("transfer","cur","budgets",+ "kinesisanalytics","cloudfront-kvs","appsync-api","appsync-realtime-api",@@ -458,6 +459,7 @@ SERVICE_REGISTRY = {"cloudtrail": {"module": "cloudtrail"},"cur": {"module": "cur"},"budgets": {"module": "budgets"},+ "kinesisanalyticsv2": {"module": "kinesisanalyticsv2"},"inspector2": {"module": "inspector2"},"mq": {"module": "mq"},"s3tables": {"module": "s3tables"},diff --git a/ministack/core/router.py b/ministack/core/router.pyindex 5a57563c..6de98991 100644--- a/ministack/core/router.py+++ b/ministack/core/router.py@@ -532,6 +532,14 @@ SERVICE_PATTERNS = {"host_patterns": [r"budgets\."],"credential_scope": "budgets",},+ # Managed Service for Apache Flink. The v1 API (KinesisAnalytics_20150814)+ # shares the `kinesisanalytics` signing name and is not implemented, so+ # requests route on the v2 target prefix.+ "kinesisanalyticsv2": {+ "target_prefixes": ["KinesisAnalytics_20180523"],+ "host_patterns": [r"kinesisanalytics\."],+ "credential_scope": "kinesisanalytics",+ },"inspector2": {"host_patterns": [r"inspector2\."],"credential_scope": "inspector2",@@ -864,6 +872,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->"cloudtrail": "cloudtrail","cur": "cur","budgets": "budgets",+ "kinesisanalytics": "kinesisanalyticsv2","inspector2": "inspector2","dsql": "dsql","s3tables": "s3tables",diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex cad6328f..98adf366 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -45,6 +45,7 @@ import ministack.services.glue as _glueimport ministack.services.iam as _iamimport ministack.services.iot as _iotimport ministack.services.kinesis as _kinesis+import ministack.services.kinesisanalyticsv2 as _kdaimport ministack.services.kms as _kmsimport ministack.services.lambda_svc as _lambda_svcimport ministack.services.opensearch as _opensearch@@ -1148,6 +1149,7 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {"AWS::IoT::TopicRule": ("Tags", "list"),"AWS::KMS::Key": ("Tags", "list"),"AWS::Kinesis::Stream": ("Tags", "list"),+ "AWS::KinesisAnalyticsV2::Application": ("Tags", "list"),"AWS::Lambda::Function": ("Tags", "list"),"AWS::Location::Tracker": ("Tags", "list"),"AWS::Logs::LogGroup": ("Tags", "list"),@@ -3440,6 +3442,111 @@ def _cwlogs_delete(physical_id, props):_cw_logs._delete_log_group({"logGroupName": physical_id})+# --- Managed Service for Apache Flink (kinesisanalyticsv2) ---++def _kda_call(fn, data, resource_type):+ """Run a kinesisanalyticsv2 operation and raise its error message."""+ status, _, body = fn(data)+ payload = json.loads(body) if body else {}+ if status >= 400:+ raise ValueError(f"{resource_type}: {payload.get('message') or payload.get('Message') or payload}")+ return payload+++def _kda_application_create(logical_id, props, stack_name):+ name = props.get("ApplicationName") or _physical_name(stack_name, logical_id)+ data = {key: props[key] for key in (+ "RuntimeEnvironment", "ServiceExecutionRole", "ApplicationConfiguration",+ "ApplicationDescription", "ApplicationMode", "Tags") if props.get(key) is not None}+ data["ApplicationName"] = name+ _kda_call(_kda.create_application, data, "AWS::KinesisAnalyticsV2::Application")+ if props.get("RunConfiguration"):+ # Stored for the next StartApplication; CloudFormation does not start the application.+ _kda._applications[name]["_RunConfiguration"] = copy.deepcopy(props["RunConfiguration"])+ # Ref returns the application name (aws-resource-kinesisanalyticsv2-application).+ return name, {}+++def _kda_application_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ """ApplicationName replaces; the rest updates in place."""+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id,+ new_props.get("ApplicationName") or physical_id,+ physical_id if physical_id in _kda._applications else None,+ _kda_application_create, _kda_application_delete,+ )+ if replaced is not None:+ return replaced+ _kda.replace_from_template(physical_id, new_props)+ arn = _kda._applications[physical_id]["ApplicationARN"]+ tags = _tag_map(new_props.get("Tags"))+ if tags:+ _kda._tags[arn] = tags+ else:+ _kda._tags.pop(arn, None)+ return physical_id, {}+++def _kda_application_delete(physical_id, props):+ if physical_id in _kda._applications:+ _kda_call(lambda data: _kda.delete_application(data, check_timestamp=False),+ {"ApplicationName": physical_id}, "AWS::KinesisAnalyticsV2::Application")+++def _kda_logging_option_create(logical_id, props, stack_name):+ option = props.get("CloudWatchLoggingOption") or {}+ payload = _kda_call(_kda.add_logging_option, {+ "ApplicationName": props.get("ApplicationName"), "CloudWatchLoggingOption": option,+ }, "AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption")+ option_id = next(o["CloudWatchLoggingOptionId"] for o in payload["CloudWatchLoggingOptionDescriptions"]+ if o["LogStreamARN"] == option.get("LogStreamARN"))+ # The physical id is the logging option id the service assigns.+ return option_id, {}+++def _kda_logging_option_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ """Both properties are create-only, so any change replaces the option."""+ if old_props == new_props:+ return physical_id, {}+ _kda_logging_option_delete(physical_id, old_props)+ return _kda_logging_option_create(logical_id or physical_id, new_props, stack_name)+++def _kda_logging_option_delete(physical_id, props):+ name = props.get("ApplicationName")+ if name in _kda._applications:+ _kda.delete_logging_option({"ApplicationName": name, "CloudWatchLoggingOptionId": physical_id})+++# --- CloudWatch Logs LogStream ---++def _cwlogs_stream_create(logical_id, props, stack_name):+ group = props.get("LogGroupName")+ if not group:+ raise ValueError("AWS::Logs::LogStream requires LogGroupName")+ name = props.get("LogStreamName") or _physical_name(stack_name, logical_id, max_len=512)+ status, _, body = _cw_logs._create_log_stream({"logGroupName": group, "logStreamName": name})+ if status >= 400:+ raise ValueError(f"AWS::Logs::LogStream: {json.loads(body).get('message')}")+ # Ref returns the log stream name (aws-resource-logs-logstream).+ return name, {}+++def _cwlogs_stream_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ """LogGroupName and LogStreamName are create-only: a change replaces the stream."""+ if (old_props.get("LogGroupName") == new_props.get("LogGroupName")+ and (new_props.get("LogStreamName") or physical_id) == physical_id):+ return physical_id, {}+ created = _cwlogs_stream_create(logical_id or physical_id, new_props, stack_name)+ _delete_predecessor(_cwlogs_stream_delete, physical_id, old_props)+ return created+++def _cwlogs_stream_delete(physical_id, props):+ group = _cw_logs._log_groups.get(props.get("LogGroupName"))+ if group:+ group["streams"].pop(physical_id, None)+# --- CloudWatch Logs ResourcePolicy ---def _cwlogs_resource_policy_create(logical_id, props, stack_name):@@ -14727,6 +14834,24 @@ _RESOURCE_HANDLERS = {"delete": _cwlogs_delete,"import": _cwlogs_import,},+ "AWS::Logs::LogStream": {+ "create": _cwlogs_stream_create,+ "update": _cwlogs_stream_update,+ "update_with_logical_id": True,+ "delete": _cwlogs_stream_delete,+ },+ "AWS::KinesisAnalyticsV2::Application": {+ "create": _kda_application_create,+ "update": _kda_application_update,+ "update_with_logical_id": True,+ "delete": _kda_application_delete,+ },+ "AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption": {+ "create": _kda_logging_option_create,+ "update": _kda_logging_option_update,+ "update_with_logical_id": True,+ "delete": _kda_logging_option_delete,+ },"AWS::Logs::ResourcePolicy": {"create": _cwlogs_resource_policy_create,"update": _cwlogs_resource_policy_update,diff --git a/ministack/services/kinesisanalyticsv2.py b/ministack/services/kinesisanalyticsv2.pynew file mode 100644index 00000000..7302b0b2--- /dev/null+++ b/ministack/services/kinesisanalyticsv2.py@@ -0,0 +1,697 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""+Amazon Managed Service for Apache Flink (kinesisanalyticsv2) control plane.+JSON 1.1 via X-Amz-Target (prefix: KinesisAnalytics_20180523).++Verified against botocore kinesisanalyticsv2/2018-05-23/service-2.json:+ metadata.targetPrefix = "KinesisAnalytics_20180523"+ metadata.signingName = "kinesisanalytics"+ metadata.protocol = "json", jsonVersion "1.1"++Supports the operations a CDK deploy and a lifecycle script use:+ CreateApplication, DescribeApplication, UpdateApplication, DeleteApplication,+ StartApplication, StopApplication,+ CreateApplicationSnapshot, ListApplicationSnapshots,+ DescribeApplicationSnapshot, DeleteApplicationSnapshot,+ AddApplicationCloudWatchLoggingOption, DeleteApplicationCloudWatchLoggingOption,+ TagResource, UntagResource, ListTagsForResource.++This is the control plane: applications move through the model's statuses+and keep snapshot records, but no Flink job runs.++Records keep the request shape of ApplicationConfiguration; DescribeApplication+renders the Description shape from it. Stores are per account and region.+"""++import base64+import copy+import hashlib+import json+import logging+import time++from ministack.core.responses import (+ AccountRegionScopedDict,+ error_response_json,+ get_account_id,+ get_region,+ json_response,+ new_uuid,+)++logger = logging.getLogger("kinesisanalyticsv2")++_applications = AccountRegionScopedDict() # ApplicationName -> record+_snapshots = AccountRegionScopedDict() # ApplicationName -> {SnapshotName -> snapshot}+_tags = AccountRegionScopedDict() # ApplicationARN -> {Key: Value}++_SUPPORTED_RUNTIME_PREFIX = "FLINK-"+# Statuses in which the application is busy with an operation.+_TRANSITIONAL = ("STARTING", "STOPPING", "FORCE_STOPPING", "UPDATING", "DELETING")+# What a transitional status settles into on the next read.+_SETTLES_TO = {+ "STARTING": "RUNNING",+ "UPDATING": "RUNNING",+ "STOPPING": "READY",+ "FORCE_STOPPING": "READY",+}++# Defaults AWS reports for ConfigurationType DEFAULT (Managed Service for+# Apache Flink developer guide: checkpointing, parallelism and monitoring).+_CHECKPOINT_DEFAULTS = {"CheckpointingEnabled": True, "CheckpointInterval": 60000,+ "MinPauseBetweenCheckpoints": 5000}+_MONITORING_DEFAULTS = {"MetricsLevel": "APPLICATION", "LogLevel": "INFO"}+_PARALLELISM_DEFAULTS = {"Parallelism": 1, "ParallelismPerKPU": 1, "AutoScalingEnabled": True}+++# ---------------------------------------------------------------------------+# Persistence+# ---------------------------------------------------------------------------++def get_state():+ return copy.deepcopy({+ "applications": _applications,+ "snapshots": _snapshots,+ "tags": _tags,+ })+++def load_persisted_state(data):+ if not data:+ return+ for store, key in ((_applications, "applications"), (_snapshots, "snapshots"), (_tags, "tags")):+ store.clear()+ store.update(data.get(key) or {})+ # No Flink job survives a restart, so a running or busy application+ # comes back READY and can be started again.+ for record in _applications.all_values():+ record["ApplicationStatus"] = "READY"+++def reset():+ _applications.clear()+ _snapshots.clear()+ _tags.clear()+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _arn(name):+ return f"arn:aws:kinesisanalytics:{get_region()}:{get_account_id()}:application/{name}"+++def _error(code, message, status=400):+ return error_response_json(code, message, status)+++def _not_found(name):+ return _error("ResourceNotFoundException", f"Application '{name}' does not exist.")+++def _new_token():+ return new_uuid().replace("-", "")[:16]+++def _bump_version(record):+ record["ApplicationVersionId"] += 1+ record["ConditionalToken"] = _new_token()+ record["LastUpdateTimestamp"] = time.time()+++def _check_concurrency(record, data):+ """ConcurrentModificationException on a stale version id or conditional token."""+ version = data.get("CurrentApplicationVersionId")+ if version is not None and version != record["ApplicationVersionId"]:+ return _error("ConcurrentModificationException",+ "The provided application version ID does not match the most recent version "+ "for the application.")+ token = data.get("ConditionalToken")+ if token is not None and token != record["ConditionalToken"]:+ return _error("ConcurrentModificationException",+ "The provided conditional token does not match the current conditional token "+ "for the application.")+ return None+++def _settle(record):+ """No Flink job runs, so a transitional status settles on the next read+ and a script polling DescribeApplication sees each status once."""+ target = _SETTLES_TO.get(record["ApplicationStatus"])+ if target:+ record["ApplicationStatus"] = target+++def _get(name):+ record = _applications.get(name)+ if record is not None:+ _settle(record)+ return record+++# ---------------------------------------------------------------------------+# Rendering: request-shape configuration -> Description shapes+# ---------------------------------------------------------------------------++def _code_description(code_config, code_stats=None):+ content = code_config.get("CodeContent") or {}+ described = {}+ if "S3ContentLocation" in content:+ loc = content["S3ContentLocation"]+ described["S3ApplicationCodeLocationDescription"] = {+ k: loc[k] for k in ("BucketARN", "FileKey", "ObjectVersion") if k in loc+ }+ # AWS reports the size and MD5 of the S3 object too.+ described.update(code_stats or {})+ if "TextContent" in content:+ described["TextContent"] = content["TextContent"]+ if "ZipFileContent" in content:+ raw = base64.b64decode(content["ZipFileContent"])+ described["CodeMD5"] = hashlib.md5(raw).hexdigest()+ described["CodeSize"] = len(raw)+ return {"CodeContentType": code_config.get("CodeContentType", "ZIPFILE"),+ "CodeContentDescription": described}+++def _with_defaults(section, defaults):+ out = {"ConfigurationType": section.get("ConfigurationType", "DEFAULT")}+ if out["ConfigurationType"] == "DEFAULT":+ out.update(defaults)+ else:+ out.update({k: section[k] for k in defaults if k in section})+ return out+++def _flink_description(flink):+ parallelism = _with_defaults(flink.get("ParallelismConfiguration") or {}, _PARALLELISM_DEFAULTS)+ parallelism["CurrentParallelism"] = parallelism.get("Parallelism", 1)+ return {+ "CheckpointConfigurationDescription":+ _with_defaults(flink.get("CheckpointConfiguration") or {}, _CHECKPOINT_DEFAULTS),+ "MonitoringConfigurationDescription":+ _with_defaults(flink.get("MonitoringConfiguration") or {}, _MONITORING_DEFAULTS),+ "ParallelismConfigurationDescription": parallelism,+ }+++def _configuration_description(record):+ config = record.get("_Configuration") or {}+ described = {}+ if "ApplicationCodeConfiguration" in config:+ described["ApplicationCodeConfigurationDescription"] = _code_description(+ config["ApplicationCodeConfiguration"], record.get("_CodeStats"))+ described["FlinkApplicationConfigurationDescription"] = _flink_description(+ config.get("FlinkApplicationConfiguration") or {})+ groups = (config.get("EnvironmentProperties") or {}).get("PropertyGroups")+ if groups is not None:+ described["EnvironmentPropertyDescriptions"] = {"PropertyGroupDescriptions": copy.deepcopy(groups)}+ snapshots = config.get("ApplicationSnapshotConfiguration") or {}+ described["ApplicationSnapshotConfigurationDescription"] = {+ "SnapshotsEnabled": bool(snapshots.get("SnapshotsEnabled", False))}+ rollback = config.get("ApplicationSystemRollbackConfiguration") or {}+ described["ApplicationSystemRollbackConfigurationDescription"] = {+ "RollbackEnabled": bool(rollback.get("RollbackEnabled", False))}+ described["ApplicationEncryptionConfigurationDescription"] = _encryption_description(record)+ if record.get("_RunConfiguration"):+ run = record["_RunConfiguration"]+ described["RunConfigurationDescription"] = {+ "ApplicationRestoreConfigurationDescription": copy.deepcopy(+ run.get("ApplicationRestoreConfiguration") or {"ApplicationRestoreType": "RESTORE_FROM_LATEST_SNAPSHOT"}),+ "FlinkRunConfigurationDescription": copy.deepcopy(+ run.get("FlinkRunConfiguration") or {"AllowNonRestoredState": False}),+ }+ return described+++def _encryption_description(record):+ """AWS reports an AWS-owned key when none is configured."""+ configured = (record.get("_Configuration") or {}).get("ApplicationEncryptionConfiguration")+ return copy.deepcopy(configured) if configured else {"KeyType": "AWS_OWNED_KEY"}+++# The maintenance window AWS reported for a new application (us-east-1).+_MAINTENANCE_WINDOW = {"ApplicationMaintenanceWindowStartTime": "03:00",+ "ApplicationMaintenanceWindowEndTime": "11:00"}+++def _refresh_code_stats(record):+ """Size and MD5 of the application's S3 code, as DescribeApplication reports them."""+ loc = (((record.get("_Configuration") or {}).get("ApplicationCodeConfiguration") or {})+ .get("CodeContent") or {}).get("S3ContentLocation")+ record.pop("_CodeStats", None)+ if not loc:+ return+ try:+ from ministack.services import s3 as _s3++ data = _s3._get_object_data(loc.get("BucketARN", "").split(":::", 1)[-1], loc.get("FileKey", ""),+ loc.get("ObjectVersion") or None)+ except Exception:+ data = None+ if data is not None:+ record["_CodeStats"] = {"CodeMD5": hashlib.md5(data).hexdigest(), "CodeSize": len(data)}+++def application_detail(record):+ """The ApplicationDetail shape for a stored record."""+ detail = {k: copy.deepcopy(v) for k, v in record.items() if not k.startswith("_")}+ detail["ApplicationConfigurationDescription"] = _configuration_description(record)+ detail["CloudWatchLoggingOptionDescriptions"] = copy.deepcopy(record.get("_LoggingOptions", []))+ detail["ApplicationMaintenanceConfigurationDescription"] = dict(_MAINTENANCE_WINDOW)+ return detail+++# ---------------------------------------------------------------------------+# Applications+# ---------------------------------------------------------------------------++def _logging_option(option, option_id):+ return {+ "CloudWatchLoggingOptionId": option_id,+ "LogStreamARN": option["LogStreamARN"],+ **({"RoleARN": option["RoleARN"]} if option.get("RoleARN") else {}),+ }+++def create_application(data):+ """CreateApplication; also used by the CloudFormation provisioner."""+ name = data.get("ApplicationName")+ runtime = data.get("RuntimeEnvironment")+ role = data.get("ServiceExecutionRole")+ if not name or not runtime or not role:+ return _error("InvalidArgumentException",+ "ApplicationName, RuntimeEnvironment and ServiceExecutionRole are required.")+ if not runtime.startswith(_SUPPORTED_RUNTIME_PREFIX):+ return _error("InvalidArgumentException",+ f"MiniStack supports Apache Flink applications only; RuntimeEnvironment {runtime} "+ "(SQL and Studio applications) is not implemented.")+ if name in _applications:+ return _error("ResourceInUseException", f"Application '{name}' already exists.")+ now = time.time()+ record = {+ "ApplicationARN": _arn(name),+ "ApplicationName": name,+ "RuntimeEnvironment": runtime,+ "ServiceExecutionRole": role,+ "ApplicationStatus": "READY",+ "ApplicationVersionId": 1,+ "CreateTimestamp": now,+ "LastUpdateTimestamp": now,+ "ConditionalToken": _new_token(),+ "ApplicationMode": data.get("ApplicationMode", "STREAMING"),+ "_Configuration": copy.deepcopy(data.get("ApplicationConfiguration") or {}),+ "_LoggingOptions": [_logging_option(o, f"1.{i + 1}")+ for i, o in enumerate(data.get("CloudWatchLoggingOptions") or [])],+ }+ _refresh_code_stats(record)+ if data.get("ApplicationDescription"):+ record["ApplicationDescription"] = data["ApplicationDescription"]+ _applications[name] = record+ _snapshots[name] = {}+ tags = {t["Key"]: t.get("Value", "") for t in data.get("Tags") or [] if "Key" in t}+ if tags:+ _tags[record["ApplicationARN"]] = tags+ logger.info("CreateApplication %s (%s)", name, runtime)+ return json_response({"ApplicationDetail": application_detail(record)})+++def _describe_application(data):+ record = _get(data.get("ApplicationName"))+ if record is None:+ return _not_found(data.get("ApplicationName"))+ return json_response({"ApplicationDetail": application_detail(record)})+++def _strip_update_suffix(update):+ """Turn an ApplicationConfigurationUpdate into ApplicationConfiguration+ form: every member is named after its target plus "Update"."""+ if not isinstance(update, dict):+ return update+ out = {}+ for key, value in update.items():+ if key == "EnvironmentPropertyUpdates":+ out["EnvironmentProperties"] = copy.deepcopy(value)+ continue+ target = key[: -len("Update")] if key.endswith("Update") else key+ out[target] = _strip_update_suffix(value)+ return out+++def _merge(base, patch):+ for key, value in patch.items():+ if isinstance(value, dict) and isinstance(base.get(key), dict) and key != "EnvironmentProperties":+ _merge(base[key], value)+ else:+ base[key] = copy.deepcopy(value)+++def update_application(data):+ """UpdateApplication; also used by the CloudFormation provisioner."""+ name = data.get("ApplicationName")+ record = _get(name)+ if record is None:+ return _not_found(name)+ if record["ApplicationStatus"] not in ("READY", "RUNNING"):+ return _error("ResourceInUseException",+ f"Application cannot be updated in '{record['ApplicationStatus']}' state")+ conflict = _check_concurrency(record, data)+ if conflict:+ return conflict+ if data.get("ApplicationConfigurationUpdate"):+ _merge(record["_Configuration"], _strip_update_suffix(data["ApplicationConfigurationUpdate"]))+ if data.get("ServiceExecutionRoleUpdate"):+ record["ServiceExecutionRole"] = data["ServiceExecutionRoleUpdate"]+ if data.get("RuntimeEnvironmentUpdate"):+ record["RuntimeEnvironment"] = data["RuntimeEnvironmentUpdate"]+ for option in data.get("CloudWatchLoggingOptionUpdates") or []:+ for existing in record["_LoggingOptions"]:+ if existing["CloudWatchLoggingOptionId"] == option.get("CloudWatchLoggingOptionId"):+ if option.get("LogStreamARNUpdate"):+ existing["LogStreamARN"] = option["LogStreamARNUpdate"]+ if data.get("RunConfigurationUpdate"):+ run = record.setdefault("_RunConfiguration", {})+ _merge(run, _strip_update_suffix(data["RunConfigurationUpdate"]))+ previous_version = record["ApplicationVersionId"]+ _bump_version(record)+ _refresh_code_stats(record)+ operation_id = _new_token()+ if record["ApplicationStatus"] == "RUNNING":+ _restart_for_update(record, previous_version)+ logger.info("UpdateApplication %s -> version %d", name, record["ApplicationVersionId"])+ return json_response({"ApplicationDetail": application_detail(record), "OperationId": operation_id})+++def replace_from_template(name, props):+ """CloudFormation update: the template's ApplicationConfiguration replaces+ the stored one (UpdateApplication takes a diff, a template carries the+ whole desired state). A running application restarts on it."""+ record = _get(name)+ if record is None:+ raise ValueError(f"Application {name} is not found.")+ record["_Configuration"] = copy.deepcopy(props.get("ApplicationConfiguration") or {})+ for key in ("RuntimeEnvironment", "ServiceExecutionRole"):+ if props.get(key):+ record[key] = props[key]+ if props.get("ApplicationDescription") is not None:+ record["ApplicationDescription"] = props["ApplicationDescription"]+ if props.get("RunConfiguration") is not None:+ record["_RunConfiguration"] = copy.deepcopy(props["RunConfiguration"])+ previous_version = record["ApplicationVersionId"]+ _bump_version(record)+ _refresh_code_stats(record)+ if record["ApplicationStatus"] == "RUNNING":+ _restart_for_update(record, previous_version)+++def delete_application(data, check_timestamp=True):+ """DeleteApplication; also used by the CloudFormation provisioner."""+ name = data.get("ApplicationName")+ record = _get(name)+ if record is None:+ return _not_found(name)+ if check_timestamp:+ stamp = data.get("CreateTimestamp")+ if stamp is None or abs(float(stamp) - record["CreateTimestamp"]) >= 1:+ return _error("ConcurrentModificationException",+ f"The application with name: '{name}' has a different create timestamp than the "+ "one you provided. Please call DescribeApplication to fetch valid create timestamp.")+ if record["ApplicationStatus"] in _TRANSITIONAL:+ return _error("ResourceInUseException",+ f"Application {name} is in {record['ApplicationStatus']} status and cannot be deleted.")+ del _applications[name]+ _snapshots.pop(name, None)+ _tags.pop(record["ApplicationARN"], None)+ logger.info("DeleteApplication %s", name)+ return json_response({})+++# ---------------------------------------------------------------------------+# Start / stop+# ---------------------------------------------------------------------------++def _snapshots_enabled(record):+ return bool((record["_Configuration"].get("ApplicationSnapshotConfiguration") or {}).get("SnapshotsEnabled"))+++def _restart_for_update(record, previous_version):+ """A running application restarts on its new configuration. With snapshots+ enabled, Managed Flink first takes an UPDATEAPPLICATION-<app>-<ms> snapshot+ carrying the version before the update (observed on AWS)."""+ record["ApplicationStatus"] = "UPDATING"+ snapshot_name = None+ if _snapshots_enabled(record):+ snapshot_name = f"UPDATEAPPLICATION-{record['ApplicationName']}-{int(time.time() * 1000)}"+ if snapshot_name:+ _add_snapshot(record, snapshot_name)["ApplicationVersionId"] = previous_version+++def _start_application(data):+ name = data.get("ApplicationName")+ record = _get(name)+ if record is None:+ return _not_found(name)+ if record["ApplicationStatus"] != "READY":+ return _error("ResourceInUseException",+ f"Application cannot be started in '{record['ApplicationStatus']}' state")+ run = copy.deepcopy(data.get("RunConfiguration") or {})+ restore = run.get("ApplicationRestoreConfiguration") or {}+ if restore.get("ApplicationRestoreType") == "RESTORE_FROM_CUSTOM_SNAPSHOT":+ snap = (_snapshots.get(name) or {}).get(restore.get("SnapshotName", ""))+ if not snap:+ return _error("InvalidArgumentException",+ f"The snapshot name {restore.get('SnapshotName')} provided for restore configuration "+ "does not exist.")+ record["_RunConfiguration"] = run+ record["ApplicationStatus"] = "STARTING"+ logger.info("StartApplication %s: control plane only, so the Flink job does not run", name)+ return json_response({"OperationId": _new_token()})+++def _stop_application(data):+ name = data.get("ApplicationName")+ record = _get(name)+ if record is None:+ return _not_found(name)+ force = bool(data.get("Force"))+ status = record["ApplicationStatus"]+ if status != "RUNNING" and not (force and status in ("STARTING", "UPDATING")):+ return _error("ResourceInUseException", f"Application cannot be Stopped in '{status}' state")+ take_snapshot = _snapshots_enabled(record) and not force+ record["ApplicationStatus"] = "FORCE_STOPPING" if force else "STOPPING"+ # Managed Flink takes a snapshot on a graceful stop when snapshots are enabled.+ snapshot_name = f"STOP-{name}-{int(time.time() * 1000)}" if take_snapshot else None+ if snapshot_name:+ _add_snapshot(record, snapshot_name)+ return json_response({"OperationId": _new_token()})+++# ---------------------------------------------------------------------------+# Snapshots+# ---------------------------------------------------------------------------++def _add_snapshot(record, snapshot_name):+ snap = {+ "SnapshotName": snapshot_name,+ "SnapshotStatus": "READY",+ "ApplicationVersionId": record["ApplicationVersionId"],+ "SnapshotCreationTimestamp": time.time(),+ "RuntimeEnvironment": record["RuntimeEnvironment"],+ "ApplicationEncryptionConfigurationDescription": _encryption_description(record),+ }+ _snapshots.setdefault(record["ApplicationName"], {})[snapshot_name] = snap+ return snap+++def _snapshot_view(snap):+ return {k: v for k, v in snap.items() if not k.startswith("_")}+++def _create_application_snapshot(data):+ name = data.get("ApplicationName")+ snapshot_name = data.get("SnapshotName")+ record = _get(name)+ if record is None:+ return _not_found(name)+ # AWS accepts a manual snapshot with SnapshotsEnabled false; it only needs RUNNING.+ if record["ApplicationStatus"] != "RUNNING":+ return _error("InvalidRequestException",+ f"Application {name} is in {record['ApplicationStatus']} status. Snapshot creation "+ "is only allowed when application is in RUNNING status")+ if snapshot_name in (_snapshots.get(name) or {}):+ return _error("ResourceInUseException",+ f"Provided Snapshot name {snapshot_name} already exists for application {name}")+ # No job runs, so the snapshot is a record without saved state.+ _add_snapshot(record, snapshot_name)+ return json_response({})+++def _list_application_snapshots(data):+ name = data.get("ApplicationName")+ if _get(name) is None:+ return _not_found(name)+ # Oldest first, as AWS lists them.+ snaps = sorted((_snapshots.get(name) or {}).values(), key=lambda s: s["SnapshotCreationTimestamp"])+ limit = int(data.get("Limit") or 50)+ start = int(data.get("NextToken") or 0)+ page = snaps[start:start + limit]+ out = {"SnapshotSummaries": [_snapshot_view(s) for s in page]}+ if start + limit < len(snaps):+ out["NextToken"] = str(start + limit)+ return json_response(out)+++def _describe_application_snapshot(data):+ name = data.get("ApplicationName")+ if _get(name) is None:+ return _not_found(name)+ snap = (_snapshots.get(name) or {}).get(data.get("SnapshotName"))+ if not snap:+ return _error("ResourceNotFoundException",+ f"Snapshot '{data.get('SnapshotName')}' does not exist for application {name}.")+ return json_response({"SnapshotDetails": _snapshot_view(snap)})+++def _delete_application_snapshot(data):+ name = data.get("ApplicationName")+ if _get(name) is None:+ return _not_found(name)+ snaps = _snapshots.get(name) or {}+ snap = snaps.get(data.get("SnapshotName"))+ if not snap:+ return _error("ResourceNotFoundException",+ f"Snapshot '{data.get('SnapshotName')}' does not exist for application {name}.")+ stamp = data.get("SnapshotCreationTimestamp")+ if stamp is None or abs(float(stamp) - snap["SnapshotCreationTimestamp"]) >= 1:+ return _error("InvalidArgumentException",+ f"Snapshot '{data['SnapshotName']}' has a different SnapshotCreationTimestamp than the one "+ f"you provided '{int(float(stamp or 0) * 1000)}'. Please call DescribeApplicationSnapshot "+ "to fetch valid SnapshotCreationTimestamp.")+ del snaps[data["SnapshotName"]]+ return json_response({})+++# ---------------------------------------------------------------------------+# CloudWatch logging options+# ---------------------------------------------------------------------------++def add_logging_option(data):+ """AddApplicationCloudWatchLoggingOption; also used by CloudFormation."""+ name = data.get("ApplicationName")+ record = _get(name)+ if record is None:+ return _not_found(name)+ conflict = _check_concurrency(record, data)+ if conflict:+ return conflict+ option = data.get("CloudWatchLoggingOption") or {}+ if not option.get("LogStreamARN"):+ return _error("InvalidArgumentException", "CloudWatchLoggingOption.LogStreamARN is required.")+ if record["_LoggingOptions"]:+ return _error("InvalidArgumentException", "Kinesis Analytics currently supports only 1 logging option.")+ _bump_version(record)+ # The id carries the version the add creates ("5.1" for an add that made version 5 on AWS).+ record["_LoggingOptions"].append(_logging_option(option, f"{record['ApplicationVersionId']}.1"))+ return json_response(_logging_response(record, with_options=True))+++def delete_logging_option(data):+ """DeleteApplicationCloudWatchLoggingOption; also used by CloudFormation."""+ name = data.get("ApplicationName")+ record = _get(name)+ if record is None:+ return _not_found(name)+ conflict = _check_concurrency(record, data)+ if conflict:+ return conflict+ option_id = data.get("CloudWatchLoggingOptionId")+ remaining = [o for o in record["_LoggingOptions"] if o["CloudWatchLoggingOptionId"] != option_id]+ if len(remaining) == len(record["_LoggingOptions"]):+ return _error("ResourceNotFoundException", f"Logging option {option_id} is not found.")+ record["_LoggingOptions"] = remaining+ _bump_version(record)+ return json_response(_logging_response(record, with_options=False))+++def _logging_response(record, with_options):+ """AWS answers an add with the options and a delete with the ARN and version only."""+ out = {"ApplicationARN": record["ApplicationARN"], "ApplicationVersionId": record["ApplicationVersionId"]}+ if with_options:+ out["CloudWatchLoggingOptionDescriptions"] = copy.deepcopy(record["_LoggingOptions"])+ return out+++# ---------------------------------------------------------------------------+# Tags+# ---------------------------------------------------------------------------++def _application_for_arn(arn):+ name = arn.split("application/", 1)[-1] if "application/" in arn else ""+ record = _applications.get(name)+ return record if record is not None and record["ApplicationARN"] == arn else None+++def _tag_resource(data):+ arn = data.get("ResourceARN", "")+ if _application_for_arn(arn) is None:+ return _error("ResourceNotFoundException", f"Resource {arn} is not found.")+ tags = _tags.get(arn) or {}+ tags.update({t["Key"]: t.get("Value", "") for t in data.get("Tags") or [] if "Key" in t})+ _tags[arn] = tags+ return json_response({})+++def _untag_resource(data):+ arn = data.get("ResourceARN", "")+ if _application_for_arn(arn) is None:+ return _error("ResourceNotFoundException", f"Resource {arn} is not found.")+ tags = _tags.get(arn) or {}+ for key in data.get("TagKeys") or []:+ tags.pop(key, None)+ _tags[arn] = tags+ return json_response({})+++def _list_tags_for_resource(data):+ arn = data.get("ResourceARN", "")+ if _application_for_arn(arn) is None:+ return _error("ResourceNotFoundException", f"Resource {arn} is not found.")+ return json_response({"Tags": [{"Key": k, "Value": v} for k, v in (_tags.get(arn) or {}).items()]})+++# ---------------------------------------------------------------------------+# Dispatch+# ---------------------------------------------------------------------------++_HANDLERS = {+ "CreateApplication": create_application,+ "DescribeApplication": _describe_application,+ "UpdateApplication": update_application,+ "DeleteApplication": delete_application,+ "StartApplication": _start_application,+ "StopApplication": _stop_application,+ "CreateApplicationSnapshot": _create_application_snapshot,+ "ListApplicationSnapshots": _list_application_snapshots,+ "DescribeApplicationSnapshot": _describe_application_snapshot,+ "DeleteApplicationSnapshot": _delete_application_snapshot,+ "AddApplicationCloudWatchLoggingOption": add_logging_option,+ "DeleteApplicationCloudWatchLoggingOption": delete_logging_option,+ "TagResource": _tag_resource,+ "UntagResource": _untag_resource,+ "ListTagsForResource": _list_tags_for_resource,+}+++async def handle_request(method, path, headers, body, query_params):+ target = headers.get("x-amz-target", "")+ action = target.split(".")[-1] if "." in target else ""+ try:+ data = json.loads(body) if body else {}+ except json.JSONDecodeError:+ return _error("SerializationException", "Invalid JSON")+ handler = _HANDLERS.get(action)+ if handler is None:+ return _error("UnsupportedOperationException",+ f"MiniStack does not implement kinesisanalyticsv2 {action or 'request'}.")+ return handler(data)diff --git a/tests/conftest.py b/tests/conftest.pyindex 3e3f83e9..af1cc243 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -945,6 +945,11 @@ def budgets():return make_client("budgets")[email protected](scope="session")+def kinesisanalyticsv2():+ return make_client("kinesisanalyticsv2")++@pytest.fixture(scope="session")def inspector2():return make_client("inspector2")diff --git a/tests/test_kinesisanalyticsv2.py b/tests/test_kinesisanalyticsv2.pynew file mode 100644index 00000000..6a50690f--- /dev/null+++ b/tests/test_kinesisanalyticsv2.py@@ -0,0 +1,488 @@+"""+Managed Service for Apache Flink (kinesisanalyticsv2) control plane.++Without the Docker data plane, a transitional status (STARTING, STOPPING,+UPDATING) settles on the next read, so each test sees it once and then the+settled status.+"""++import uuid++import pytest+from botocore.exceptions import ClientError++from ministack.core.responses import set_request_account_id, set_request_region+from ministack.services import kinesisanalyticsv2 as kda++RUNTIME = "FLINK-1_20"+ROLE = "arn:aws:iam::000000000000:role/flink-app"+CODE = {+ "ApplicationCodeConfiguration": {+ "CodeContentType": "ZIPFILE",+ "CodeContent": {"S3ContentLocation": {"BucketARN": "arn:aws:s3:::jars", "FileKey": "app.jar"}},+ },+}+++def _name(prefix="app"):+ return f"{prefix}-{uuid.uuid4().hex[:8]}"+++def _create(client, name=None, **config):+ name = name or _name()+ client.create_application(+ ApplicationName=name, RuntimeEnvironment=RUNTIME, ServiceExecutionRole=ROLE,+ ApplicationConfiguration={**CODE, **config},+ )+ return name+++def _detail(client, name):+ return client.describe_application(ApplicationName=name)["ApplicationDetail"]+++def _code(exc):+ return exc.value.response["Error"]["Code"]+++# ---------------------------------------------------------------------------+# Create / describe / delete+# ---------------------------------------------------------------------------++def test_create_and_describe_application(kinesisanalyticsv2):+ name = _name()+ created = kinesisanalyticsv2.create_application(+ ApplicationName=name, RuntimeEnvironment=RUNTIME, ServiceExecutionRole=ROLE,+ ApplicationDescription="orders job",+ ApplicationConfiguration={+ **CODE,+ "EnvironmentProperties": {"PropertyGroups": [+ {"PropertyGroupId": "app", "PropertyMap": {"stream": "orders"}}]},+ "ApplicationSnapshotConfiguration": {"SnapshotsEnabled": True},+ },+ )["ApplicationDetail"]+ assert created["ApplicationARN"].endswith(f":application/{name}")+ assert created["ApplicationARN"].startswith("arn:aws:kinesisanalytics:us-east-1:")+ assert created["ApplicationStatus"] == "READY"+ assert created["ApplicationVersionId"] == 1+ assert created["ApplicationMode"] == "STREAMING"+ assert created["ConditionalToken"]++ detail = _detail(kinesisanalyticsv2, name)+ config = detail["ApplicationConfigurationDescription"]+ assert config["ApplicationCodeConfigurationDescription"] == {+ "CodeContentType": "ZIPFILE",+ "CodeContentDescription": {"S3ApplicationCodeLocationDescription": {+ "BucketARN": "arn:aws:s3:::jars", "FileKey": "app.jar"}},+ }+ assert config["EnvironmentPropertyDescriptions"]["PropertyGroupDescriptions"] == [+ {"PropertyGroupId": "app", "PropertyMap": {"stream": "orders"}}]+ assert config["ApplicationSnapshotConfigurationDescription"] == {"SnapshotsEnabled": True}+ flink = config["FlinkApplicationConfigurationDescription"]+ assert flink["CheckpointConfigurationDescription"] == {+ "ConfigurationType": "DEFAULT", "CheckpointingEnabled": True,+ "CheckpointInterval": 60000, "MinPauseBetweenCheckpoints": 5000}+ assert flink["ParallelismConfigurationDescription"]["Parallelism"] == 1+ assert flink["MonitoringConfigurationDescription"]["LogLevel"] == "INFO"+++def test_custom_parallelism_is_reported(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2, FlinkApplicationConfiguration={+ "ParallelismConfiguration": {"ConfigurationType": "CUSTOM", "Parallelism": 4,+ "ParallelismPerKPU": 2, "AutoScalingEnabled": False}})+ parallelism = (_detail(kinesisanalyticsv2, name)["ApplicationConfigurationDescription"]+ ["FlinkApplicationConfigurationDescription"]["ParallelismConfigurationDescription"])+ assert parallelism == {"ConfigurationType": "CUSTOM", "Parallelism": 4, "ParallelismPerKPU": 2,+ "AutoScalingEnabled": False, "CurrentParallelism": 4}+++def test_create_rejects_duplicates_and_non_flink_runtimes(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2)+ with pytest.raises(ClientError) as exc:+ _create(kinesisanalyticsv2, name=name)+ assert _code(exc) == "ResourceInUseException"+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.create_application(+ ApplicationName=_name(), RuntimeEnvironment="SQL-1_0", ServiceExecutionRole=ROLE)+ assert _code(exc) == "InvalidArgumentException"+++def test_describe_unknown_application(kinesisanalyticsv2):+ with pytest.raises(ClientError) as exc:+ _detail(kinesisanalyticsv2, _name("missing"))+ assert _code(exc) == "ResourceNotFoundException"+++def test_delete_requires_the_create_timestamp(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2)+ created = _detail(kinesisanalyticsv2, name)["CreateTimestamp"]+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.delete_application(ApplicationName=name, CreateTimestamp=0)+ assert _code(exc) == "ConcurrentModificationException" # observed on AWS+ kinesisanalyticsv2.delete_application(ApplicationName=name, CreateTimestamp=created)+ with pytest.raises(ClientError) as exc:+ _detail(kinesisanalyticsv2, name)+ assert _code(exc) == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Start / stop / update+# ---------------------------------------------------------------------------++def test_start_and_stop_move_through_statuses(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2)+ assert kinesisanalyticsv2.start_application(+ ApplicationName=name,+ RunConfiguration={"ApplicationRestoreConfiguration": {+ "ApplicationRestoreType": "SKIP_RESTORE_FROM_SNAPSHOT"}},+ )["OperationId"]+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.start_application(ApplicationName=name)+ assert _code(exc) == "ResourceInUseException"+ detail = _detail(kinesisanalyticsv2, name)+ assert detail["ApplicationStatus"] == "RUNNING"+ assert (detail["ApplicationConfigurationDescription"]["RunConfigurationDescription"]+ ["ApplicationRestoreConfigurationDescription"]["ApplicationRestoreType"]+ == "SKIP_RESTORE_FROM_SNAPSHOT")++ kinesisanalyticsv2.stop_application(ApplicationName=name)+ assert _detail(kinesisanalyticsv2, name)["ApplicationStatus"] == "READY"+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.stop_application(ApplicationName=name)+ assert _code(exc) == "ResourceInUseException"+++def test_force_stop(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2, ApplicationSnapshotConfiguration={"SnapshotsEnabled": True})+ kinesisanalyticsv2.start_application(ApplicationName=name)+ assert _detail(kinesisanalyticsv2, name)["ApplicationStatus"] == "RUNNING"+ kinesisanalyticsv2.stop_application(ApplicationName=name, Force=True)+ assert _detail(kinesisanalyticsv2, name)["ApplicationStatus"] == "READY"+ # StopApplication with Force "stops the application without taking a snapshot".+ assert kinesisanalyticsv2.list_application_snapshots(ApplicationName=name)["SnapshotSummaries"] == []+++def test_update_bumps_version_and_replaces_properties(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2, EnvironmentProperties={"PropertyGroups": [+ {"PropertyGroupId": "app", "PropertyMap": {"a": "1"}},+ {"PropertyGroupId": "old", "PropertyMap": {"b": "2"}}]})+ before = _detail(kinesisanalyticsv2, name)+ updated = kinesisanalyticsv2.update_application(+ ApplicationName=name, CurrentApplicationVersionId=1,+ ApplicationConfigurationUpdate={+ "EnvironmentPropertyUpdates": {"PropertyGroups": [+ {"PropertyGroupId": "app", "PropertyMap": {"a": "9"}}]},+ "FlinkApplicationConfigurationUpdate": {"ParallelismConfigurationUpdate": {+ "ConfigurationTypeUpdate": "CUSTOM", "ParallelismUpdate": 3}},+ "ApplicationCodeConfigurationUpdate": {"CodeContentUpdate": {+ "S3ContentLocationUpdate": {"FileKeyUpdate": "app-v2.jar"}}},+ },+ )+ detail = updated["ApplicationDetail"]+ assert updated["OperationId"]+ assert detail["ApplicationVersionId"] == 2+ assert detail["ConditionalToken"] != before["ConditionalToken"]+ config = detail["ApplicationConfigurationDescription"]+ # EnvironmentPropertyUpdates replaces every property group.+ assert config["EnvironmentPropertyDescriptions"]["PropertyGroupDescriptions"] == [+ {"PropertyGroupId": "app", "PropertyMap": {"a": "9"}}]+ assert (config["FlinkApplicationConfigurationDescription"]["ParallelismConfigurationDescription"]+ ["Parallelism"]) == 3+ assert (config["ApplicationCodeConfigurationDescription"]["CodeContentDescription"]+ ["S3ApplicationCodeLocationDescription"]) == {"BucketARN": "arn:aws:s3:::jars",+ "FileKey": "app-v2.jar"}+++def test_update_rejects_stale_version_and_token(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2)+ token = _detail(kinesisanalyticsv2, name)["ConditionalToken"]+ kinesisanalyticsv2.update_application(ApplicationName=name, ConditionalToken=token,+ ServiceExecutionRoleUpdate=ROLE + "-2")+ for kwargs in ({"CurrentApplicationVersionId": 1}, {"ConditionalToken": token}):+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.update_application(ApplicationName=name,+ ServiceExecutionRoleUpdate=ROLE, **kwargs)+ assert _code(exc) == "ConcurrentModificationException"+++def test_update_of_running_application_passes_through_updating(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2)+ kinesisanalyticsv2.start_application(ApplicationName=name)+ assert _detail(kinesisanalyticsv2, name)["ApplicationStatus"] == "RUNNING"+ updated = kinesisanalyticsv2.update_application(ApplicationName=name, ServiceExecutionRoleUpdate=ROLE)+ assert updated["ApplicationDetail"]["ApplicationStatus"] == "UPDATING"+ assert _detail(kinesisanalyticsv2, name)["ApplicationStatus"] == "RUNNING"+++# ---------------------------------------------------------------------------+# Snapshots+# ---------------------------------------------------------------------------++def test_snapshot_lifecycle(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2, ApplicationSnapshotConfiguration={"SnapshotsEnabled": True})+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.create_application_snapshot(ApplicationName=name, SnapshotName="s1")+ assert _code(exc) == "InvalidRequestException" # not running yet (observed on AWS)++ kinesisanalyticsv2.start_application(ApplicationName=name)+ _detail(kinesisanalyticsv2, name)+ kinesisanalyticsv2.create_application_snapshot(ApplicationName=name, SnapshotName="s1")+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.create_application_snapshot(ApplicationName=name, SnapshotName="s1")+ assert _code(exc) == "ResourceInUseException"++ snap = kinesisanalyticsv2.describe_application_snapshot(+ ApplicationName=name, SnapshotName="s1")["SnapshotDetails"]+ assert snap["SnapshotStatus"] == "READY"+ assert snap["ApplicationVersionId"] == 1+ assert snap["RuntimeEnvironment"] == RUNTIME+ assert snap["ApplicationEncryptionConfigurationDescription"] == {"KeyType": "AWS_OWNED_KEY"}++ # A graceful stop with snapshots enabled takes another snapshot.+ kinesisanalyticsv2.stop_application(ApplicationName=name)+ summaries = kinesisanalyticsv2.list_application_snapshots(ApplicationName=name)["SnapshotSummaries"]+ assert len(summaries) == 2+ assert summaries[0]["SnapshotName"] == "s1" # oldest first, as AWS lists them+ assert summaries[1]["SnapshotName"].startswith(f"STOP-{name}-")++ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.delete_application_snapshot(+ ApplicationName=name, SnapshotName="s1", SnapshotCreationTimestamp=0)+ assert _code(exc) == "InvalidArgumentException"+ kinesisanalyticsv2.delete_application_snapshot(+ ApplicationName=name, SnapshotName="s1",+ SnapshotCreationTimestamp=snap["SnapshotCreationTimestamp"])+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.describe_application_snapshot(ApplicationName=name, SnapshotName="s1")+ assert _code(exc) == "ResourceNotFoundException"+++def test_manual_snapshot_with_snapshots_disabled(kinesisanalyticsv2):+ """AWS accepts CreateApplicationSnapshot on a RUNNING app with SnapshotsEnabled false."""+ name = _create(kinesisanalyticsv2)+ kinesisanalyticsv2.start_application(ApplicationName=name)+ _detail(kinesisanalyticsv2, name)+ kinesisanalyticsv2.create_application_snapshot(ApplicationName=name, SnapshotName="s1")+ snap = kinesisanalyticsv2.describe_application_snapshot(ApplicationName=name, SnapshotName="s1")+ assert snap["SnapshotDetails"]["SnapshotStatus"] == "READY"+++def test_update_of_running_application_takes_a_snapshot(kinesisanalyticsv2):+ """With snapshots enabled, AWS records UPDATEAPPLICATION-<app>-<ms> with the pre-update version."""+ name = _create(kinesisanalyticsv2, ApplicationSnapshotConfiguration={"SnapshotsEnabled": True})+ kinesisanalyticsv2.start_application(ApplicationName=name)+ _detail(kinesisanalyticsv2, name)+ kinesisanalyticsv2.update_application(+ ApplicationName=name, CurrentApplicationVersionId=1,+ ApplicationConfigurationUpdate={"EnvironmentPropertyUpdates": {"PropertyGroups": [+ {"PropertyGroupId": "g", "PropertyMap": {"k": "v"}}]}})+ [snap] = kinesisanalyticsv2.list_application_snapshots(ApplicationName=name)["SnapshotSummaries"]+ assert snap["SnapshotName"].startswith(f"UPDATEAPPLICATION-{name}-")+ assert snap["ApplicationVersionId"] == 1+++def test_describe_reports_aws_defaults(kinesisanalyticsv2, s3):+ """Code size and MD5 of the S3 object, the AWS-owned key and the maintenance window."""+ import hashlib++ bucket = f"kda-code-{uuid.uuid4().hex[:8]}"+ s3.create_bucket(Bucket=bucket)+ s3.put_object(Bucket=bucket, Key="app.jar", Body=b"jar-bytes")+ name = _name()+ kinesisanalyticsv2.create_application(+ ApplicationName=name, RuntimeEnvironment=RUNTIME, ServiceExecutionRole=ROLE,+ ApplicationConfiguration={"ApplicationCodeConfiguration": {+ "CodeContentType": "ZIPFILE",+ "CodeContent": {"S3ContentLocation": {"BucketARN": f"arn:aws:s3:::{bucket}", "FileKey": "app.jar"}}}})+ detail = _detail(kinesisanalyticsv2, name)+ code = detail["ApplicationConfigurationDescription"]["ApplicationCodeConfigurationDescription"][+ "CodeContentDescription"]+ assert code["CodeSize"] == len(b"jar-bytes")+ assert code["CodeMD5"] == hashlib.md5(b"jar-bytes").hexdigest()+ assert detail["ApplicationConfigurationDescription"]["ApplicationEncryptionConfigurationDescription"] == {+ "KeyType": "AWS_OWNED_KEY"}+ assert detail["ApplicationMaintenanceConfigurationDescription"] == {+ "ApplicationMaintenanceWindowStartTime": "03:00", "ApplicationMaintenanceWindowEndTime": "11:00"}+++def test_restore_from_unknown_custom_snapshot(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2, ApplicationSnapshotConfiguration={"SnapshotsEnabled": True})+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.start_application(ApplicationName=name, RunConfiguration={+ "ApplicationRestoreConfiguration": {"ApplicationRestoreType": "RESTORE_FROM_CUSTOM_SNAPSHOT",+ "SnapshotName": "nope"}})+ assert _code(exc) == "InvalidArgumentException"+++def test_snapshot_list_pagination(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2, ApplicationSnapshotConfiguration={"SnapshotsEnabled": True})+ kinesisanalyticsv2.start_application(ApplicationName=name)+ _detail(kinesisanalyticsv2, name)+ for i in range(3):+ kinesisanalyticsv2.create_application_snapshot(ApplicationName=name, SnapshotName=f"s{i}")+ first = kinesisanalyticsv2.list_application_snapshots(ApplicationName=name, Limit=2)+ assert len(first["SnapshotSummaries"]) == 2+ rest = kinesisanalyticsv2.list_application_snapshots(+ ApplicationName=name, Limit=2, NextToken=first["NextToken"])+ assert len(rest["SnapshotSummaries"]) == 1+ assert "NextToken" not in rest+++# ---------------------------------------------------------------------------+# Logging options and tags+# ---------------------------------------------------------------------------++def test_cloudwatch_logging_options(kinesisanalyticsv2):+ name = _create(kinesisanalyticsv2)+ stream = "arn:aws:logs:us-east-1:000000000000:log-group:flink:log-stream:app"+ added = kinesisanalyticsv2.add_application_cloud_watch_logging_option(+ ApplicationName=name, CurrentApplicationVersionId=1,+ CloudWatchLoggingOption={"LogStreamARN": stream})+ assert added["ApplicationVersionId"] == 2+ assert "OperationId" not in added+ [option] = added["CloudWatchLoggingOptionDescriptions"]+ assert option["LogStreamARN"] == stream+ assert option["CloudWatchLoggingOptionId"] == "2.1" # the version the add created+ assert _detail(kinesisanalyticsv2, name)["CloudWatchLoggingOptionDescriptions"] == [option]++ with pytest.raises(ClientError) as exc: # AWS allows only one logging option+ kinesisanalyticsv2.add_application_cloud_watch_logging_option(+ ApplicationName=name, CloudWatchLoggingOption={"LogStreamARN": stream + "-other"})+ assert _code(exc) == "InvalidArgumentException"++ removed = kinesisanalyticsv2.delete_application_cloud_watch_logging_option(+ ApplicationName=name, CloudWatchLoggingOptionId=option["CloudWatchLoggingOptionId"])+ assert removed["ApplicationVersionId"] == 3+ assert "CloudWatchLoggingOptionDescriptions" not in removed+ assert _detail(kinesisanalyticsv2, name)["CloudWatchLoggingOptionDescriptions"] == []+++def test_tags(kinesisanalyticsv2):+ name = _name()+ kinesisanalyticsv2.create_application(+ ApplicationName=name, RuntimeEnvironment=RUNTIME, ServiceExecutionRole=ROLE,+ Tags=[{"Key": "team", "Value": "data"}])+ arn = _detail(kinesisanalyticsv2, name)["ApplicationARN"]+ kinesisanalyticsv2.tag_resource(ResourceARN=arn, Tags=[{"Key": "env", "Value": "dev"}])+ kinesisanalyticsv2.untag_resource(ResourceARN=arn, TagKeys=["team"])+ assert kinesisanalyticsv2.list_tags_for_resource(ResourceARN=arn)["Tags"] == [+ {"Key": "env", "Value": "dev"}]+ with pytest.raises(ClientError) as exc:+ kinesisanalyticsv2.list_tags_for_resource(ResourceARN=arn + "-missing")+ assert _code(exc) == "ResourceNotFoundException"+++# ---------------------------------------------------------------------------+# Isolation and persistence+# ---------------------------------------------------------------------------++def test_applications_are_region_scoped(kinesisanalyticsv2):+ import boto3+ from botocore.config import Config++ name = _create(kinesisanalyticsv2)+ west = boto3.client(+ "kinesisanalyticsv2", endpoint_url=kinesisanalyticsv2.meta.endpoint_url,+ region_name="us-west-2", aws_access_key_id="test", aws_secret_access_key="test",+ config=Config(retries={"max_attempts": 0}))+ with pytest.raises(ClientError) as exc:+ west.describe_application(ApplicationName=name)+ assert _code(exc) == "ResourceNotFoundException"+++def local_state():+ set_request_account_id("test")+ set_request_region("us-east-1")+ saved = kda.get_state()+ kda.reset()+ yield+ kda.reset()+ kda.load_persisted_state(saved)+++def test_restored_running_application_comes_back_ready(local_state):+ kda.create_application({"ApplicationName": "persisted", "RuntimeEnvironment": RUNTIME,+ "ServiceExecutionRole": ROLE})+ kda._applications["persisted"]["ApplicationStatus"] = "RUNNING"+ state = kda.get_state()+ kda.reset()+ kda.load_persisted_state(state)+ assert kda._applications["persisted"]["ApplicationStatus"] == "READY"+++# ---------------------------------------------------------------------------+# CloudFormation (the resources a CDK Flink stack synthesizes)+# ---------------------------------------------------------------------------++def _wait_stack(cfn, name, timeout=30):+ import time++ deadline = time.time() + timeout+ while time.time() < deadline:+ try:+ stack = cfn.describe_stacks(StackName=name)["Stacks"][0]+ except ClientError as exc:+ if "does not exist" in str(exc):+ return {"StackStatus": "DELETE_COMPLETE"}+ raise+ if not stack["StackStatus"].endswith("_IN_PROGRESS"):+ return stack+ time.sleep(0.3)+ raise AssertionError(f"stack {name} did not settle")+++def _flink_template(app_name, group, value):+ import json++ return json.dumps({"Resources": {+ "Logs": {"Type": "AWS::Logs::LogGroup", "Properties": {"LogGroupName": group}},+ "Stream": {"Type": "AWS::Logs::LogStream",+ "Properties": {"LogGroupName": {"Ref": "Logs"}, "LogStreamName": "flink"}},+ "App": {"Type": "AWS::KinesisAnalyticsV2::Application", "Properties": {+ "ApplicationName": app_name,+ "RuntimeEnvironment": RUNTIME,+ "ServiceExecutionRole": ROLE,+ "ApplicationConfiguration": {+ **CODE,+ "ApplicationSnapshotConfiguration": {"SnapshotsEnabled": True},+ "EnvironmentProperties": {"PropertyGroups": [+ {"PropertyGroupId": "app", "PropertyMap": {"value": value}}]},+ },+ }},+ "AppLogging": {"Type": "AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption",+ "DependsOn": "Stream",+ "Properties": {"ApplicationName": {"Ref": "App"}, "CloudWatchLoggingOption": {+ "LogStreamARN": {"Fn::Sub": "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:"+ f"log-group:{group}:log-stream:flink"}}}},+ }})+++def test_cloudformation_flink_stack(cfn, logs, kinesisanalyticsv2):+ stack, app, group = _name("flink-stack"), _name("cfn-app"), f"/flink/{_name()}"+ cfn.create_stack(StackName=stack, TemplateBody=_flink_template(app, group, "1"))+ assert _wait_stack(cfn, stack)["StackStatus"] == "CREATE_COMPLETE"++ detail = _detail(kinesisanalyticsv2, app)+ assert detail["ApplicationStatus"] == "READY"+ groups = detail["ApplicationConfigurationDescription"]["EnvironmentPropertyDescriptions"]+ assert groups["PropertyGroupDescriptions"][0]["PropertyMap"] == {"value": "1"}+ [option] = detail["CloudWatchLoggingOptionDescriptions"]+ assert option["LogStreamARN"].endswith(f"log-group:{group}:log-stream:flink")+ streams = logs.describe_log_streams(logGroupName=group)["logStreams"]+ assert [s["logStreamName"] for s in streams] == ["flink"]+ version = detail["ApplicationVersionId"]++ cfn.update_stack(StackName=stack, TemplateBody=_flink_template(app, group, "2"))+ assert _wait_stack(cfn, stack)["StackStatus"] == "UPDATE_COMPLETE"+ detail = _detail(kinesisanalyticsv2, app)+ groups = detail["ApplicationConfigurationDescription"]["EnvironmentPropertyDescriptions"]+ assert groups["PropertyGroupDescriptions"][0]["PropertyMap"] == {"value": "2"}+ assert detail["ApplicationVersionId"] > version+ assert len(detail["CloudWatchLoggingOptionDescriptions"]) == 1++ cfn.delete_stack(StackName=stack)+ assert _wait_stack(cfn, stack)["StackStatus"] == "DELETE_COMPLETE"+ with pytest.raises(ClientError) as exc:+ _detail(kinesisanalyticsv2, app)+ assert _code(exc) == "ResourceNotFoundException"diff --git a/tests/test_router.py b/tests/test_router.pyindex 61fa95ab..a4445663 100644--- a/tests/test_router.py+++ b/tests/test_router.py@@ -206,6 +206,7 @@ _TOKEN_ROUTES = {"athena": "athena", "autoscaling": "autoscaling", "backup": "backup","batch": "batch", "bedrock": "bedrock", "bedrock-runtime": "bedrock-runtime","budgets": "budgets",+ "kinesisanalytics": "kinesisanalyticsv2","cloudcontrolapi": "cloudcontrol", "cloudformation": "cloudformation","cloudfront": "cloudfront", "cloudfront-kvs": "cloudfront-keyvaluestore","cloudtrail": "cloudtrail", "codebuild": "codebuild",