"""SSM-backed state for tracking chart freshness across invocations.""" import json import boto3 from botocore.exceptions import ClientError import config logger = config.logger _ssm = boto3.client('ssm') # Shape: {"pending_date": "2026-06-29", "detected_at": "2026-06-30T10:00:00+00:00", "alerted": false} # noqa: E501 # Empty dict means no new Spotify date is pending. def load() -> dict: """Return current state from SSM, or {} if none exists.""" try: resp = _ssm.get_parameter(Name=config.SSM_STATE_PARAM) try: value = json.loads(resp['Parameter']['Value']) except json.JSONDecodeError: logger.warning('SSM state contains invalid JSON; returning empty state') return {} if not isinstance(value, dict): logger.warning( f'SSM state is not a JSON object (got {type(value).__name__}); ' 'returning empty state' ) return {} return value except ClientError as e: if e.response['Error']['Code'] == 'ParameterNotFound': return {} raise def save(state: dict) -> None: """Persist state to SSM.""" _ssm.put_parameter( Name=config.SSM_STATE_PARAM, Value=json.dumps(state), Type='String', Overwrite=True, ) logger.info(f'State saved: {state}') def clear() -> None: """Clear state — called when charts are back in sync.""" save({})