id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
4,980
from contextlib import contextmanager from dataclasses import dataclass, field from typing import Iterable, Iterator, List, Optional, Sequence, TYPE_CHECKING, Union from libcst._add_slots import add_slots from libcst._flatten_sentinel import FlattenSentinel from libcst._maybe_sentinel import MaybeSentinel from libcst._removal_sentinel import RemovalSentinel from libcst._types import CSTNodeT def visit_iterable( parent: "CSTNode", fieldname: str, children: Iterable[CSTNodeT], visitor: "CSTVisitorT", ) -> Iterable[CSTNodeT]: """ Given an iterable of children, visits each child with `visitor`, and yields the new children with any `RemovalSentinel` values removed. """ visitor.on_visit_attribute(parent, fieldname) for child in children: new_child = child.visit(visitor) if isinstance(new_child, FlattenSentinel): yield from new_child elif not isinstance(new_child, RemovalSentinel): yield new_child visitor.on_leave_attribute(parent, fieldname) CSTNodeT = TypeVar("CSTNodeT", bound="CSTNode") The provided code snippet includes necessary dependencies for implementing the `visit_sequence` function. Write a Python function `def visit_sequence( parent: "CSTNode", fieldname: str, children: Sequence[CSTNodeT], visitor: "CSTVisitorT", ) -> Sequence[CSTNodeT]` to solve the following problem: A convenience wrapper for `visit_iterable` that returns a sequence instead of an iterable. Here is the function: def visit_sequence( parent: "CSTNode", fieldname: str, children: Sequence[CSTNodeT], visitor: "CSTVisitorT", ) -> Sequence[CSTNodeT]: """ A convenience wrapper for `visit_iterable` that returns a sequence instead of an iterable. """ return tuple(visit_iterable(parent, fieldname, children, visitor))
A convenience wrapper for `visit_iterable` that returns a sequence instead of an iterable.
4,981
from contextlib import contextmanager from dataclasses import dataclass, field from typing import Iterable, Iterator, List, Optional, Sequence, TYPE_CHECKING, Union from libcst._add_slots import add_slots from libcst._flatten_sentinel import FlattenSentinel from libcst._maybe_sentinel import MaybeSentinel from libcst._removal_sentinel import RemovalSentinel from libcst._types import CSTNodeT def visit_body_iterable( parent: "CSTNode", fieldname: str, children: Sequence[CSTNodeT], visitor: "CSTVisitorT", ) -> Iterable[CSTNodeT]: """ Similar to visit_iterable above, but capable of discarding empty SimpleStatementLine nodes in order to preserve correct pass insertion behavior. """ visitor.on_visit_attribute(parent, fieldname) for child in children: new_child = child.visit(visitor) # Don't yield a child if we removed it. if isinstance(new_child, RemovalSentinel): continue # Don't yield a child if the old child wasn't empty # and the new child is. This means a RemovalSentinel # caused a child of this node to be dropped, and it # is now useless. if isinstance(new_child, FlattenSentinel): for child_ in new_child: if (not child._is_removable()) and child_._is_removable(): continue yield child_ else: if (not child._is_removable()) and new_child._is_removable(): continue # Safe to yield child in this case. yield new_child visitor.on_leave_attribute(parent, fieldname) CSTNodeT = TypeVar("CSTNodeT", bound="CSTNode") The provided code snippet includes necessary dependencies for implementing the `visit_body_sequence` function. Write a Python function `def visit_body_sequence( parent: "CSTNode", fieldname: str, children: Sequence[CSTNodeT], visitor: "CSTVisitorT", ) -> Sequence[CSTNodeT]` to solve the following problem: A convenience wrapper for `visit_body_iterable` that returns a sequence instead of an iterable. Here is the function: def visit_body_sequence( parent: "CSTNode", fieldname: str, children: Sequence[CSTNodeT], visitor: "CSTVisitorT", ) -> Sequence[CSTNodeT]: """ A convenience wrapper for `visit_body_iterable` that returns a sequence instead of an iterable. """ return tuple(visit_body_iterable(parent, fieldname, children, visitor))
A convenience wrapper for `visit_body_iterable` that returns a sequence instead of an iterable.
4,982
from enum import auto, Enum from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from typing_extensions import final from libcst._parser.parso.pgen2.generator import ReservedString from libcst._parser.parso.python.token import PythonTokenTypes, TokenType from libcst._parser.types.token import Token from libcst._tabs import expand_tabs _EOF_STR: str = "end of file (EOF)" _INDENT_STR: str = "an indent" _DEDENT_STR: str = "a dedent" class EOFSentinel(Enum): EOF = auto() class ReservedString: """ Most grammars will have certain keywords and operators that are mentioned in the grammar as strings (e.g. "if") and not token types (e.g. NUMBER). This class basically is the former. """ def __init__(self, value: str) -> None: self.value = value def __repr__(self) -> str: return "%s(%s)" % (self.__class__.__name__, self.value) def get_expected_str( encountered: Union[Token, EOFSentinel], expected: Union[Iterable[Union[TokenType, ReservedString]], EOFSentinel], ) -> str: if ( isinstance(encountered, EOFSentinel) or encountered.type is PythonTokenTypes.ENDMARKER ): encountered_str = _EOF_STR elif encountered.type is PythonTokenTypes.INDENT: encountered_str = _INDENT_STR elif encountered.type is PythonTokenTypes.DEDENT: encountered_str = _DEDENT_STR else: encountered_str = repr(encountered.string) if isinstance(expected, EOFSentinel): expected_names = [_EOF_STR] else: expected_names = sorted( [ repr(el.name) if isinstance(el, TokenType) else repr(el.value) for el in expected ] ) if len(expected_names) > 10: # There's too many possibilities, so it's probably not useful to list them. # Instead, let's just abbreviate the message. return f"Unexpectedly encountered {encountered_str}." else: if len(expected_names) == 1: expected_str = expected_names[0] else: expected_str = f"{', '.join(expected_names[:-1])}, or {expected_names[-1]}" return f"Encountered {encountered_str}, but expected {expected_str}."
null
4,983
from enum import auto, Enum from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union from typing_extensions import final from libcst._parser.parso.pgen2.generator import ReservedString from libcst._parser.parso.python.token import PythonTokenTypes, TokenType from libcst._parser.types.token import Token from libcst._tabs import expand_tabs class ParserSyntaxError(Exception): """ Contains an error encountered while trying to parse a piece of source code. This exception shouldn't be constructed directly by the user, but instead may be raised by calls to :func:`parse_module`, :func:`parse_expression`, or :func:`parse_statement`. This does not inherit from :class:`SyntaxError` because Python's may raise a :class:`SyntaxError` for any number of reasons, potentially leading to unintended behavior. """ #: A human-readable explanation of the syntax error without information about where #: the error occurred. #: #: For a human-readable explanation of the error alongside information about where #: it occurred, use :meth:`__str__` (via ``str(ex)``) instead. message: str # An internal value used to compute `editor_column` and to pretty-print where the # syntax error occurred in the code. _lines: Sequence[str] #: The one-indexed line where the error occured. raw_line: int #: The zero-indexed column as a number of characters from the start of the line #: where the error occured. raw_column: int def __init__( self, message: str, *, lines: Sequence[str], raw_line: int, raw_column: int ) -> None: super(ParserSyntaxError, self).__init__(message) self.message = message self._lines = lines self.raw_line = raw_line self.raw_column = raw_column def __reduce__( self, ) -> Tuple[Callable[..., "ParserSyntaxError"], Tuple[object, ...]]: return ( _parser_syntax_error_unpickle, ( { "message": self.message, "lines": self._lines, "raw_line": self.raw_line, "raw_column": self.raw_column, }, ), ) def __str__(self) -> str: """ A multi-line human-readable error message of where the syntax error is in their code. For example:: Syntax Error @ 2:1. Incomplete input. Encountered end of file (EOF), but expected 'except', or 'finally'. try: pass ^ """ context = self.context return ( f"Syntax Error @ {self.editor_line}:{self.editor_column}.\n" + f"{self.message}" + (f"\n\n{context}" if context is not None else "") ) def __repr__(self) -> str: return ( "ParserSyntaxError(" + f"{self.message!r}, lines=[...], raw_line={self.raw_line!r}, " + f"raw_column={self.raw_column!r})" ) def context(self) -> Optional[str]: """ A formatted string containing the line of code with the syntax error (or a non-empty line above it) along with a caret indicating the exact column where the error occurred. Return ``None`` if there's no relevant non-empty line to show. (e.g. the file consists of only blank lines) """ displayed_line = self.editor_line displayed_column = self.editor_column # we want to avoid displaying a blank line for context. If we're on a blank line # find the nearest line above us that isn't blank. while displayed_line >= 1 and not len(self._lines[displayed_line - 1].strip()): displayed_line -= 1 displayed_column = len(self._lines[displayed_line - 1]) # only show context if we managed to find a non-empty line if len(self._lines[displayed_line - 1].strip()): formatted_source_line = expand_tabs(self._lines[displayed_line - 1]).rstrip( _NEWLINE_CHARS ) # fmt: off return ( f"{formatted_source_line}\n" + f"{' ' * (displayed_column - 1)}^" ) # fmt: on else: return None def editor_line(self) -> int: """ The expected one-indexed line in the user's editor. This is the same as :attr:`raw_line`. """ return self.raw_line # raw_line is already one-indexed. def editor_column(self) -> int: """ The expected one-indexed column that's likely to match the behavior of the user's editor, assuming tabs expand to 1-8 spaces. This is the column number shown when the syntax error is printed out with `str`. This assumes single-width characters. However, because python doesn't ship with a wcwidth function, it's hard to handle this properly without a third-party dependency. For a raw zero-indexed character offset without tab expansion, see :attr:`raw_column`. """ prefix_str = self._lines[self.raw_line - 1][: self.raw_column] tab_adjusted_column = len(expand_tabs(prefix_str)) # Text editors use a one-indexed column, so we need to add one to our # zero-indexed column to get a human-readable result. return tab_adjusted_column + 1 def _parser_syntax_error_unpickle(kwargs: Any) -> "ParserSyntaxError": return ParserSyntaxError(**kwargs)
null
4,984
from enum import auto, Enum class RemovalSentinel(Enum): """ A :attr:`RemovalSentinel.REMOVE` value should be returned by a :meth:`CSTTransformer.on_leave` method when we want to remove that child from its parent. As a convenience, this can be constructed by calling :func:`libcst.RemoveFromParent`. The parent node should make a best-effort to remove the child, but may raise an exception when removing the child doesn't make sense, or could change the semantics in an unexpected way. For example, a function definition with no name doesn't make sense, but removing one of the arguments is valid. In we can't automatically remove the child, the developer should instead remove the child by constructing a new parent in the parent's :meth:`~CSTTransformer.on_leave` call. We use this instead of ``None`` to force developers to be explicit about deletions. Because ``None`` is the default return value for a function with no return statement, it would be too easy to accidentally delete nodes from the tree by forgetting to return a value. """ REMOVE = auto() The provided code snippet includes necessary dependencies for implementing the `RemoveFromParent` function. Write a Python function `def RemoveFromParent() -> RemovalSentinel` to solve the following problem: A convenience method for requesting that this node be removed by its parent. Use this in place of returning :class:`RemovalSentinel` directly. For example, to remove all arguments unconditionally:: def leave_Arg( self, original_node: cst.Arg, updated_node: cst.Arg ) -> Union[cst.Arg, cst.RemovalSentinel]: return RemoveFromParent() Here is the function: def RemoveFromParent() -> RemovalSentinel: """ A convenience method for requesting that this node be removed by its parent. Use this in place of returning :class:`RemovalSentinel` directly. For example, to remove all arguments unconditionally:: def leave_Arg( self, original_node: cst.Arg, updated_node: cst.Arg ) -> Union[cst.Arg, cst.RemovalSentinel]: return RemoveFromParent() """ return RemovalSentinel.REMOVE
A convenience method for requesting that this node be removed by its parent. Use this in place of returning :class:`RemovalSentinel` directly. For example, to remove all arguments unconditionally:: def leave_Arg( self, original_node: cst.Arg, updated_node: cst.Arg ) -> Union[cst.Arg, cst.RemovalSentinel]: return RemoveFromParent()
4,985
import os from contextlib import contextmanager from pathlib import Path from typing import Generator from libcst._types import StrPath StrPath = Union[str, PurePath] The provided code snippet includes necessary dependencies for implementing the `chdir` function. Write a Python function `def chdir(path: StrPath) -> Generator[Path, None, None]` to solve the following problem: Temporarily chdir to the given path, and then return to the previous path. Here is the function: def chdir(path: StrPath) -> Generator[Path, None, None]: """ Temporarily chdir to the given path, and then return to the previous path. """ try: path = Path(path).resolve() cwd = os.getcwd() os.chdir(path) yield path finally: os.chdir(cwd)
Temporarily chdir to the given path, and then return to the previous path.
4,986
from typing import Dict, Mapping, Optional, Set, Union import libcst as cst from libcst.helpers.common import ensure_type TEMPLATE_PREFIX: str = "__LIBCST_MANGLED_NAME_" TEMPLATE_SUFFIX: str = "_EMAN_DELGNAM_TSCBIL__" def unmangled_name(var: str) -> Optional[str]: if TEMPLATE_PREFIX in var and TEMPLATE_SUFFIX in var: prefix, name_and_suffix = var.split(TEMPLATE_PREFIX, 1) name, suffix = name_and_suffix.split(TEMPLATE_SUFFIX, 1) if not prefix and not suffix: return name # This is not a valid mangled name return None
null
4,987
from typing import Dict, Mapping, Optional, Set, Union import libcst as cst from libcst.helpers.common import ensure_type ValidReplacementType = Union[ cst.BaseExpression, cst.Annotation, cst.AssignTarget, cst.Param, cst.Parameters, cst.Arg, cst.BaseStatement, cst.BaseSmallStatement, cst.BaseSuite, cst.BaseSlice, cst.SubscriptElement, cst.Decorator, ] def mangle_template(template: str, template_vars: Set[str]) -> str: if TEMPLATE_PREFIX in template or TEMPLATE_SUFFIX in template: raise Exception("Cannot parse a template containing reserved strings") for var in template_vars: original = f"{{{var}}}" if original not in template: raise Exception( f'Template string is missing a reference to "{var}" referred to in kwargs' ) template = template.replace(original, mangled_name(var)) return template class TemplateChecker(cst.CSTVisitor): def __init__(self, template_vars: Set[str]) -> None: self.template_vars = template_vars def visit_Name(self, node: cst.Name) -> None: for var in self.template_vars: if node.value == mangled_name(var): raise Exception(f'Template variable "{var}" was not replaced properly') def unmangle_nodes( tree: cst.CSTNode, template_replacements: Mapping[str, ValidReplacementType], ) -> cst.CSTNode: unmangler = TemplateTransformer(template_replacements) return ensure_type(tree.visit(unmangler), cst.CSTNode) _DEFAULT_PARTIAL_PARSER_CONFIG: cst.PartialParserConfig = cst.PartialParserConfig() def ensure_type(node: object, nodetype: Type[T]) -> T: """ Takes any python object, and a LibCST :class:`~libcst.CSTNode` subclass and refines the type of the python object. This is most useful when you already know that a particular object is a certain type but your type checker is not convinced. Note that this does an instance check for you and raises an exception if it is not the right type, so this should be used in situations where you are sure of the type given previous checks. """ if not isinstance(node, nodetype): raise Exception( f"Expected a {nodetype.__name__} but got a {node.__class__.__name__}!" ) return node The provided code snippet includes necessary dependencies for implementing the `parse_template_module` function. Write a Python function `def parse_template_module( template: str, config: cst.PartialParserConfig = _DEFAULT_PARTIAL_PARSER_CONFIG, **template_replacements: ValidReplacementType, ) -> cst.Module` to solve the following problem: Accepts an entire python module template, including all leading and trailing whitespace. Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: module = parse_template_module("from {mod} import Foo\\n", mod=Name("bar")) The above code will parse to a module containing a single :class:`~libcst.FromImport` statement, referencing module ``bar`` and importing object ``Foo`` from it. Remember that if you are parsing a template as part of a substitution inside a transform, its considered :ref:`best practice <libcst-config_best_practice>` to pass in a ``config`` from the current module under transformation. Note that unlike :func:`~libcst.parse_module`, this function does not support bytes as an input. This is due to the fact that it is processed as a template before parsing as a module. Here is the function: def parse_template_module( template: str, config: cst.PartialParserConfig = _DEFAULT_PARTIAL_PARSER_CONFIG, **template_replacements: ValidReplacementType, ) -> cst.Module: """ Accepts an entire python module template, including all leading and trailing whitespace. Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: module = parse_template_module("from {mod} import Foo\\n", mod=Name("bar")) The above code will parse to a module containing a single :class:`~libcst.FromImport` statement, referencing module ``bar`` and importing object ``Foo`` from it. Remember that if you are parsing a template as part of a substitution inside a transform, its considered :ref:`best practice <libcst-config_best_practice>` to pass in a ``config`` from the current module under transformation. Note that unlike :func:`~libcst.parse_module`, this function does not support bytes as an input. This is due to the fact that it is processed as a template before parsing as a module. """ source = mangle_template(template, {name for name in template_replacements}) module = cst.parse_module(source, config) new_module = ensure_type(unmangle_nodes(module, template_replacements), cst.Module) new_module.visit(TemplateChecker({name for name in template_replacements})) return new_module
Accepts an entire python module template, including all leading and trailing whitespace. Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: module = parse_template_module("from {mod} import Foo\\n", mod=Name("bar")) The above code will parse to a module containing a single :class:`~libcst.FromImport` statement, referencing module ``bar`` and importing object ``Foo`` from it. Remember that if you are parsing a template as part of a substitution inside a transform, its considered :ref:`best practice <libcst-config_best_practice>` to pass in a ``config`` from the current module under transformation. Note that unlike :func:`~libcst.parse_module`, this function does not support bytes as an input. This is due to the fact that it is processed as a template before parsing as a module.
4,988
from typing import Dict, Mapping, Optional, Set, Union import libcst as cst from libcst.helpers.common import ensure_type ValidReplacementType = Union[ cst.BaseExpression, cst.Annotation, cst.AssignTarget, cst.Param, cst.Parameters, cst.Arg, cst.BaseStatement, cst.BaseSmallStatement, cst.BaseSuite, cst.BaseSlice, cst.SubscriptElement, cst.Decorator, ] def mangle_template(template: str, template_vars: Set[str]) -> str: if TEMPLATE_PREFIX in template or TEMPLATE_SUFFIX in template: raise Exception("Cannot parse a template containing reserved strings") for var in template_vars: original = f"{{{var}}}" if original not in template: raise Exception( f'Template string is missing a reference to "{var}" referred to in kwargs' ) template = template.replace(original, mangled_name(var)) return template class TemplateChecker(cst.CSTVisitor): def __init__(self, template_vars: Set[str]) -> None: self.template_vars = template_vars def visit_Name(self, node: cst.Name) -> None: for var in self.template_vars: if node.value == mangled_name(var): raise Exception(f'Template variable "{var}" was not replaced properly') def unmangle_nodes( tree: cst.CSTNode, template_replacements: Mapping[str, ValidReplacementType], ) -> cst.CSTNode: unmangler = TemplateTransformer(template_replacements) return ensure_type(tree.visit(unmangler), cst.CSTNode) _DEFAULT_PARTIAL_PARSER_CONFIG: cst.PartialParserConfig = cst.PartialParserConfig() The provided code snippet includes necessary dependencies for implementing the `parse_template_statement` function. Write a Python function `def parse_template_statement( template: str, config: cst.PartialParserConfig = _DEFAULT_PARTIAL_PARSER_CONFIG, **template_replacements: ValidReplacementType, ) -> Union[cst.SimpleStatementLine, cst.BaseCompoundStatement]` to solve the following problem: Accepts a statement template followed by a trailing newline. If a trailing newline is not provided, one will be added. Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: statement = parse_template_statement("assert x > 0, {msg}", msg=SimpleString('"Uh oh!"')) The above code will parse to an assert statement checking that some variable ``x`` is greater than zero, or providing the assert message ``"Uh oh!"``. Remember that if you are parsing a template as part of a substitution inside a transform, its considered :ref:`best practice <libcst-config_best_practice>` to pass in a ``config`` from the current module under transformation. Here is the function: def parse_template_statement( template: str, config: cst.PartialParserConfig = _DEFAULT_PARTIAL_PARSER_CONFIG, **template_replacements: ValidReplacementType, ) -> Union[cst.SimpleStatementLine, cst.BaseCompoundStatement]: """ Accepts a statement template followed by a trailing newline. If a trailing newline is not provided, one will be added. Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: statement = parse_template_statement("assert x > 0, {msg}", msg=SimpleString('"Uh oh!"')) The above code will parse to an assert statement checking that some variable ``x`` is greater than zero, or providing the assert message ``"Uh oh!"``. Remember that if you are parsing a template as part of a substitution inside a transform, its considered :ref:`best practice <libcst-config_best_practice>` to pass in a ``config`` from the current module under transformation. """ source = mangle_template(template, {name for name in template_replacements}) statement = cst.parse_statement(source, config) new_statement = unmangle_nodes(statement, template_replacements) if not isinstance( new_statement, (cst.SimpleStatementLine, cst.BaseCompoundStatement) ): raise Exception( f"Expected a statement but got a {new_statement.__class__.__name__}!" ) new_statement.visit(TemplateChecker({name for name in template_replacements})) return new_statement
Accepts a statement template followed by a trailing newline. If a trailing newline is not provided, one will be added. Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: statement = parse_template_statement("assert x > 0, {msg}", msg=SimpleString('"Uh oh!"')) The above code will parse to an assert statement checking that some variable ``x`` is greater than zero, or providing the assert message ``"Uh oh!"``. Remember that if you are parsing a template as part of a substitution inside a transform, its considered :ref:`best practice <libcst-config_best_practice>` to pass in a ``config`` from the current module under transformation.
4,989
from typing import Dict, Mapping, Optional, Set, Union import libcst as cst from libcst.helpers.common import ensure_type ValidReplacementType = Union[ cst.BaseExpression, cst.Annotation, cst.AssignTarget, cst.Param, cst.Parameters, cst.Arg, cst.BaseStatement, cst.BaseSmallStatement, cst.BaseSuite, cst.BaseSlice, cst.SubscriptElement, cst.Decorator, ] def mangle_template(template: str, template_vars: Set[str]) -> str: if TEMPLATE_PREFIX in template or TEMPLATE_SUFFIX in template: raise Exception("Cannot parse a template containing reserved strings") for var in template_vars: original = f"{{{var}}}" if original not in template: raise Exception( f'Template string is missing a reference to "{var}" referred to in kwargs' ) template = template.replace(original, mangled_name(var)) return template class TemplateChecker(cst.CSTVisitor): def __init__(self, template_vars: Set[str]) -> None: self.template_vars = template_vars def visit_Name(self, node: cst.Name) -> None: for var in self.template_vars: if node.value == mangled_name(var): raise Exception(f'Template variable "{var}" was not replaced properly') def unmangle_nodes( tree: cst.CSTNode, template_replacements: Mapping[str, ValidReplacementType], ) -> cst.CSTNode: unmangler = TemplateTransformer(template_replacements) return ensure_type(tree.visit(unmangler), cst.CSTNode) _DEFAULT_PARTIAL_PARSER_CONFIG: cst.PartialParserConfig = cst.PartialParserConfig() def ensure_type(node: object, nodetype: Type[T]) -> T: """ Takes any python object, and a LibCST :class:`~libcst.CSTNode` subclass and refines the type of the python object. This is most useful when you already know that a particular object is a certain type but your type checker is not convinced. Note that this does an instance check for you and raises an exception if it is not the right type, so this should be used in situations where you are sure of the type given previous checks. """ if not isinstance(node, nodetype): raise Exception( f"Expected a {nodetype.__name__} but got a {node.__class__.__name__}!" ) return node The provided code snippet includes necessary dependencies for implementing the `parse_template_expression` function. Write a Python function `def parse_template_expression( template: str, config: cst.PartialParserConfig = _DEFAULT_PARTIAL_PARSER_CONFIG, **template_replacements: ValidReplacementType, ) -> cst.BaseExpression` to solve the following problem: Accepts an expression template on a single line. Leading and trailing whitespace is not valid (there’s nowhere to store it on the expression node). Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: expression = parse_template_expression("x + {foo}", foo=Name("y"))) The above code will parse to a :class:`~libcst.BinaryOperation` expression adding two names (``x`` and ``y``) together. Remember that if you are parsing a template as part of a substitution inside a transform, its considered :ref:`best practice <libcst-config_best_practice>` to pass in a ``config`` from the current module under transformation. Here is the function: def parse_template_expression( template: str, config: cst.PartialParserConfig = _DEFAULT_PARTIAL_PARSER_CONFIG, **template_replacements: ValidReplacementType, ) -> cst.BaseExpression: """ Accepts an expression template on a single line. Leading and trailing whitespace is not valid (there’s nowhere to store it on the expression node). Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: expression = parse_template_expression("x + {foo}", foo=Name("y"))) The above code will parse to a :class:`~libcst.BinaryOperation` expression adding two names (``x`` and ``y``) together. Remember that if you are parsing a template as part of a substitution inside a transform, its considered :ref:`best practice <libcst-config_best_practice>` to pass in a ``config`` from the current module under transformation. """ source = mangle_template(template, {name for name in template_replacements}) expression = cst.parse_expression(source, config) new_expression = ensure_type( unmangle_nodes(expression, template_replacements), cst.BaseExpression ) new_expression.visit(TemplateChecker({name for name in template_replacements})) return new_expression
Accepts an expression template on a single line. Leading and trailing whitespace is not valid (there’s nowhere to store it on the expression node). Any :class:`~libcst.CSTNode` provided as a keyword argument to this function will be inserted into the template at the appropriate location similar to an f-string expansion. For example:: expression = parse_template_expression("x + {foo}", foo=Name("y"))) The above code will parse to a :class:`~libcst.BinaryOperation` expression adding two names (``x`` and ``y``) together. Remember that if you are parsing a template as part of a substitution inside a transform, its considered :ref:`best practice <libcst-config_best_practice>` to pass in a ``config`` from the current module under transformation.
4,990
from typing import Optional, Union import libcst as cst def get_full_name_for_node(node: Union[str, cst.CSTNode]) -> Optional[str]: """Return a dot concatenated full name for str, :class:`~libcst.Name`, :class:`~libcst.Attribute`. :class:`~libcst.Call`, :class:`~libcst.Subscript`, :class:`~libcst.FunctionDef`, :class:`~libcst.ClassDef`, :class:`~libcst.Decorator`. Return ``None`` for not supported Node. """ if isinstance(node, cst.Name): return node.value elif isinstance(node, str): return node elif isinstance(node, cst.Attribute): return f"{get_full_name_for_node(node.value)}.{node.attr.value}" elif isinstance(node, cst.Call): return get_full_name_for_node(node.func) elif isinstance(node, cst.Subscript): return get_full_name_for_node(node.value) elif isinstance(node, (cst.FunctionDef, cst.ClassDef)): return get_full_name_for_node(node.name) elif isinstance(node, cst.Decorator): return get_full_name_for_node(node.decorator) return None The provided code snippet includes necessary dependencies for implementing the `get_full_name_for_node_or_raise` function. Write a Python function `def get_full_name_for_node_or_raise(node: Union[str, cst.CSTNode]) -> str` to solve the following problem: Return a dot concatenated full name for str, :class:`~libcst.Name`, :class:`~libcst.Attribute`. :class:`~libcst.Call`, :class:`~libcst.Subscript`, :class:`~libcst.FunctionDef`, :class:`~libcst.ClassDef`. Raise Exception for not supported Node. Here is the function: def get_full_name_for_node_or_raise(node: Union[str, cst.CSTNode]) -> str: """Return a dot concatenated full name for str, :class:`~libcst.Name`, :class:`~libcst.Attribute`. :class:`~libcst.Call`, :class:`~libcst.Subscript`, :class:`~libcst.FunctionDef`, :class:`~libcst.ClassDef`. Raise Exception for not supported Node. """ full_name = get_full_name_for_node(node) if full_name is None: raise Exception(f"Not able to parse full name for: {node}") return full_name
Return a dot concatenated full name for str, :class:`~libcst.Name`, :class:`~libcst.Attribute`. :class:`~libcst.Call`, :class:`~libcst.Subscript`, :class:`~libcst.FunctionDef`, :class:`~libcst.ClassDef`. Raise Exception for not supported Node.
4,991
from dataclasses import dataclass from itertools import islice from pathlib import PurePath from typing import List, Optional from libcst import Comment, EmptyLine, ImportFrom, Module from libcst._types import StrPath from libcst.helpers.expression import get_full_name_for_node The provided code snippet includes necessary dependencies for implementing the `insert_header_comments` function. Write a Python function `def insert_header_comments(node: Module, comments: List[str]) -> Module` to solve the following problem: Insert comments after last non-empty line in header. Use this to insert one or more comments after any copyright preamble in a :class:`~libcst.Module`. Each comment in the list of ``comments`` must start with a ``#`` and will be placed on its own line in the appropriate location. Here is the function: def insert_header_comments(node: Module, comments: List[str]) -> Module: """ Insert comments after last non-empty line in header. Use this to insert one or more comments after any copyright preamble in a :class:`~libcst.Module`. Each comment in the list of ``comments`` must start with a ``#`` and will be placed on its own line in the appropriate location. """ # Split the lines up into a contiguous comment-containing section and # the empty whitespace section that follows last_comment_index = -1 for i, line in enumerate(node.header): if line.comment is not None: last_comment_index = i comment_lines = islice(node.header, last_comment_index + 1) empty_lines = islice(node.header, last_comment_index + 1, None) inserted_lines = [EmptyLine(comment=Comment(value=comment)) for comment in comments] # pyre-fixme[60]: Concatenation not yet support for multiple variadic tuples: # `*comment_lines, *inserted_lines, *empty_lines`. return node.with_changes(header=(*comment_lines, *inserted_lines, *empty_lines))
Insert comments after last non-empty line in header. Use this to insert one or more comments after any copyright preamble in a :class:`~libcst.Module`. Each comment in the list of ``comments`` must start with a ``#`` and will be placed on its own line in the appropriate location.
4,992
from dataclasses import dataclass from itertools import islice from pathlib import PurePath from typing import List, Optional from libcst import Comment, EmptyLine, ImportFrom, Module from libcst._types import StrPath from libcst.helpers.expression import get_full_name_for_node def get_absolute_module_for_import( current_module: Optional[str], import_node: ImportFrom ) -> Optional[str]: def get_absolute_module_for_import_or_raise( current_module: Optional[str], import_node: ImportFrom ) -> str: module = get_absolute_module_for_import(current_module, import_node) if module is None: raise Exception(f"Unable to compute absolute module for {import_node}") return module
null
4,993
from dataclasses import dataclass from itertools import islice from pathlib import PurePath from typing import List, Optional from libcst import Comment, EmptyLine, ImportFrom, Module from libcst._types import StrPath from libcst.helpers.expression import get_full_name_for_node def get_absolute_module_from_package_for_import( current_package: Optional[str], import_node: ImportFrom ) -> Optional[str]: # First, let's try to grab the module name, regardless of relative status. module = import_node.module module_name = get_full_name_for_node(module) if module is not None else None # Now, get the relative import location if it exists. num_dots = len(import_node.relative) return get_absolute_module_from_package(current_package, module_name, num_dots) def get_absolute_module_from_package_for_import_or_raise( current_package: Optional[str], import_node: ImportFrom ) -> str: module = get_absolute_module_from_package_for_import(current_package, import_node) if module is None: raise Exception(f"Unable to compute absolute module for {import_node}") return module
null
4,994
from dataclasses import dataclass from itertools import islice from pathlib import PurePath from typing import List, Optional from libcst import Comment, EmptyLine, ImportFrom, Module from libcst._types import StrPath from libcst.helpers.expression import get_full_name_for_node class ModuleNameAndPackage: name: str package: str StrPath = Union[str, PurePath] def calculate_module_and_package( repo_root: StrPath, filename: StrPath ) -> ModuleNameAndPackage: # Given an absolute repo_root and an absolute filename, calculate the # python module name for the file. relative_filename = PurePath(filename).relative_to(repo_root) relative_filename = relative_filename.with_suffix("") # handle special cases if relative_filename.stem in ["__init__", "__main__"]: relative_filename = relative_filename.parent package = name = ".".join(relative_filename.parts) else: name = ".".join(relative_filename.parts) package = ".".join(relative_filename.parts[:-1]) return ModuleNameAndPackage(name, package)
null
4,995
from typing import ( Any, ForwardRef, Iterable, Mapping, MutableMapping, MutableSequence, Tuple, ) from typing_extensions import Literal from typing_inspect import get_args, get_origin, is_classvar, is_typevar, is_union_type The provided code snippet includes necessary dependencies for implementing the `is_value_of_type` function. Write a Python function `def is_value_of_type( # noqa: C901 "too complex" # pyre-fixme[2]: Parameter annotation cannot be `Any`. value: Any, # pyre-fixme[2]: Parameter annotation cannot be `Any`. expected_type: Any, invariant_check: bool = False, ) -> bool` to solve the following problem: This method attempts to verify a given value is of a given type. If the type is not supported, it returns True but throws an exception in tests. It is similar to typeguard / enforce pypi modules, but neither of those have permissive options for types they do not support. Supported types for now: - List/Set/Iterable - Dict/Mapping - base types (str, int, etc) - Literal - Unions - Tuples - Concrete Classes - ClassVar Not supported: - Callables, which will likely not be used in XHP anyways - Generics, Type Vars (treated as Any) - Generators - Forward Refs -- use `typing.get_type_hints` to resolve these - Type[...] Here is the function: def is_value_of_type( # noqa: C901 "too complex" # pyre-fixme[2]: Parameter annotation cannot be `Any`. value: Any, # pyre-fixme[2]: Parameter annotation cannot be `Any`. expected_type: Any, invariant_check: bool = False, ) -> bool: """ This method attempts to verify a given value is of a given type. If the type is not supported, it returns True but throws an exception in tests. It is similar to typeguard / enforce pypi modules, but neither of those have permissive options for types they do not support. Supported types for now: - List/Set/Iterable - Dict/Mapping - base types (str, int, etc) - Literal - Unions - Tuples - Concrete Classes - ClassVar Not supported: - Callables, which will likely not be used in XHP anyways - Generics, Type Vars (treated as Any) - Generators - Forward Refs -- use `typing.get_type_hints` to resolve these - Type[...] """ if is_classvar(expected_type): classvar_args = get_args(expected_type) expected_type = (classvar_args[0] or Any) if classvar_args else Any if is_typevar(expected_type): # treat this the same as Any # TODO: evaluate bounds return True expected_origin_type = get_origin(expected_type) or expected_type if expected_origin_type == Any: return True elif is_union_type(expected_type): return any( is_value_of_type(value, subtype) for subtype in expected_type.__args__ ) elif isinstance(expected_origin_type, type(Literal)): literal_values = get_args(expected_type, evaluate=True) return any(value == literal for literal in literal_values) elif isinstance(expected_origin_type, ForwardRef): # not much we can do here for now, lets just return :( return True # Handle `Tuple[A, B, C]`. # We don't want to include Tuple subclasses, like NamedTuple, because they're # unlikely to behave similarly. elif expected_origin_type in [Tuple, tuple]: # py36 uses Tuple, py37+ uses tuple if not isinstance(value, tuple): return False type_args = get_args(expected_type, evaluate=True) if len(type_args) == 0: # `Tuple` (no subscript) is implicitly `Tuple[Any, ...]` return True if type_args is None: return True if len(value) != len(type_args): return False # TODO: Handle `Tuple[T, ...]` like `Iterable[T]` for subvalue, subtype in zip(value, type_args): if not is_value_of_type(subvalue, subtype): return False return True elif issubclass(expected_origin_type, Mapping): # We're expecting *some* kind of Mapping, but we also want to make sure it's # the correct Mapping subtype. That means we want {a: b, c: d} to match Mapping, # MutableMapping, and Dict, but we don't want MappingProxyType({a: b, c: d}) to # match MutableMapping or Dict. if not issubclass(type(value), expected_origin_type): return False type_args = get_args(expected_type, evaluate=True) if len(type_args) == 0: # `Mapping` (no subscript) is implicitly `Mapping[Any, Any]`. return True invariant_check = issubclass(expected_origin_type, MutableMapping) for subkey, subvalue in value.items(): if not is_value_of_type( subkey, type_args[0], # key type is always invariant invariant_check=True, ): return False if not is_value_of_type( subvalue, type_args[1], invariant_check=invariant_check ): return False return True # While this does technically work fine for str and bytes (they are iterables), it's # better to use the default isinstance behavior for them. # # Similarly, tuple subclasses tend to have pretty different behavior, and we should # fall back to the default check. elif issubclass(expected_origin_type, Iterable) and not issubclass( expected_origin_type, (str, bytes, tuple), ): # We know this thing is *some* kind of Iterable, but we want to # allow subclasses. That means we want [1,2,3] to match both # List[int] and Iterable[int], but we do NOT want that # to match Set[int]. if not issubclass(type(value), expected_origin_type): return False type_args = get_args(expected_type, evaluate=True) if len(type_args) == 0: # `Iterable` (no subscript) is implicitly `Iterable[Any]`. return True # We invariant check if its a mutable sequence invariant_check = issubclass(expected_origin_type, MutableSequence) return all( is_value_of_type(subvalue, type_args[0], invariant_check=invariant_check) for subvalue in value ) try: if not invariant_check: if expected_type is float: return isinstance(value, (int, float)) else: return isinstance(value, expected_type) return type(value) is expected_type except Exception as e: raise NotImplementedError( f"the value {value!r} was compared to type {expected_type!r} " + f"but support for that has not been implemented yet! Exception: {e!r}" )
This method attempts to verify a given value is of a given type. If the type is not supported, it returns True but throws an exception in tests. It is similar to typeguard / enforce pypi modules, but neither of those have permissive options for types they do not support. Supported types for now: - List/Set/Iterable - Dict/Mapping - base types (str, int, etc) - Literal - Unions - Tuples - Concrete Classes - ClassVar Not supported: - Callables, which will likely not be used in XHP anyways - Generics, Type Vars (treated as Any) - Generators - Forward Refs -- use `typing.get_type_hints` to resolve these - Type[...]
4,996
from typing import Any, Callable, cast, TypeVar F = TypeVar("F", bound=Callable) The provided code snippet includes necessary dependencies for implementing the `mark_no_op` function. Write a Python function `def mark_no_op(f: F) -> F` to solve the following problem: Annotates stubs with a field to indicate they should not be collected by BatchableCSTVisitor.get_visitors() to reduce function call overhead when running a batched visitor pass. Here is the function: def mark_no_op(f: F) -> F: """ Annotates stubs with a field to indicate they should not be collected by BatchableCSTVisitor.get_visitors() to reduce function call overhead when running a batched visitor pass. """ cast(Any, f)._is_no_op = True return f
Annotates stubs with a field to indicate they should not be collected by BatchableCSTVisitor.get_visitors() to reduce function call overhead when running a batched visitor pass.
4,997
import re import sys from pathlib import Path from subprocess import run from typing import Iterable, List, Pattern EXCEPTION_PATTERNS: List[Pattern[str]] = [ re.compile(pattern) for pattern in ( r"^native/libcst/tests/fixtures/", r"^libcst/_add_slots\.py$", r"^libcst/tests/test_(e2e|fuzz)\.py$", r"^libcst/_parser/base_parser\.py$", r"^libcst/_parser/parso/utils\.py$", r"^libcst/_parser/parso/pgen2/(generator|grammar_parser)\.py$", r"^libcst/_parser/parso/python/(py_token|tokenize)\.py$", r"^libcst/_parser/parso/tests/test_(fstring|tokenize|utils)\.py$", ) ] def tracked_files() -> Iterable[Path]: proc = run( ["git", "ls-tree", "-r", "--name-only", "HEAD"], check=True, capture_output=True, encoding="utf-8", ) yield from ( path for line in proc.stdout.splitlines() if not any(pattern.search(line) for pattern in EXCEPTION_PATTERNS) if (path := Path(line)) and path.is_file() and path.suffix in (".py", ".sh") )
null
4,998
from datetime import datetime from enum import Enum from io import StringIO from typing import Optional from aws_lambda_powertools.shared.types import List def _format_date(timestamp: datetime) -> str: # Specification example: Wed, 21 Oct 2015 07:28:00 GMT return timestamp.strftime("%a, %d %b %Y %H:%M:%S GMT")
null
4,999
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants def resolve_env_var_choice(env: Optional[str], choice: float) -> float: ...
null
5,000
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants def resolve_env_var_choice(env: Optional[str], choice: str) -> str: ...
null
5,001
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants def resolve_env_var_choice(env: Optional[str], choice: Optional[str]) -> str: ...
null
5,002
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants The provided code snippet includes necessary dependencies for implementing the `resolve_env_var_choice` function. Write a Python function `def resolve_env_var_choice( env: Optional[str] = None, choice: Optional[Union[str, float]] = None, ) -> Optional[Union[str, float]]` to solve the following problem: Pick explicit choice over env, if available, otherwise return env value received NOTE: Environment variable should be resolved by the caller. Parameters ---------- env : str, Optional environment variable actual value choice : str|float, optional explicit choice Returns ------- choice : str, Optional resolved choice as either bool or environment value Here is the function: def resolve_env_var_choice( env: Optional[str] = None, choice: Optional[Union[str, float]] = None, ) -> Optional[Union[str, float]]: """Pick explicit choice over env, if available, otherwise return env value received NOTE: Environment variable should be resolved by the caller. Parameters ---------- env : str, Optional environment variable actual value choice : str|float, optional explicit choice Returns ------- choice : str, Optional resolved choice as either bool or environment value """ return choice if choice is not None else env
Pick explicit choice over env, if available, otherwise return env value received NOTE: Environment variable should be resolved by the caller. Parameters ---------- env : str, Optional environment variable actual value choice : str|float, optional explicit choice Returns ------- choice : str, Optional resolved choice as either bool or environment value
5,003
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants logger = logging.getLogger(__name__) def base64_decode(value: str) -> bytes: try: logger.debug("Decoding base64 item to bytes") return base64.b64decode(value) except (BinAsciiError, TypeError): raise ValueError("base64 decode failed - is this base64 encoded string?")
null
5,004
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants logger = logging.getLogger(__name__) def bytes_to_base64_string(value: bytes) -> str: try: logger.debug("Encoding bytes to base64 string") return base64.b64encode(value).decode() except TypeError: raise ValueError(f"base64 encoding failed - is this bytes data? type: {type(value)}")
null
5,005
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants def bytes_to_string(value: bytes) -> str: try: return value.decode("utf-8") except (BinAsciiError, TypeError): raise ValueError("base64 UTF-8 decode failed")
null
5,006
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants def strtobool(value: str) -> bool: """Convert a string representation of truth to True or False. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'value' is anything else. > note:: Copied from distutils.util. """ value = value.lower() if value in ("1", "y", "yes", "t", "true", "on"): return True if value in ("0", "n", "no", "f", "false", "off"): return False raise ValueError(f"invalid truth value {value!r}") def powertools_dev_is_set() -> bool: is_on = strtobool(os.getenv(constants.POWERTOOLS_DEV_ENV, "0")) if is_on: warnings.warn( "POWERTOOLS_DEV environment variable is enabled. Increasing verbosity across utilities.", stacklevel=2, ) return True return False
null
5,007
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants def slice_dictionary(data: Dict, chunk_size: int) -> Generator[Dict, None, None]: for _ in range(0, len(data), chunk_size): yield {dict_key: data[dict_key] for dict_key in itertools.islice(data, chunk_size)}
null
5,008
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants def is_pydantic(data) -> bool: """Whether data is a Pydantic model by checking common field available in v1/v2 Parameters ---------- data: BaseModel Pydantic model Returns ------- bool Whether it's a Pydantic model """ return getattr(data, "json", False) def is_dataclass(data) -> bool: """Whether data is a dataclass Parameters ---------- data: dataclass Dataclass obj Returns ------- bool Whether it's a Dataclass """ return getattr(data, "__dataclass_fields__", False) def pydantic_to_dict(data) -> dict: """Dump Pydantic model v1 and v2 as dict. Note we use lazy import since Pydantic is an optional dependency. Parameters ---------- data: BaseModel Pydantic model Returns ------- dict: Pydantic model serialized to dict """ from aws_lambda_powertools.event_handler.openapi.compat import _model_dump return _model_dump(data) def dataclass_to_dict(data) -> dict: """Dump standard dataclass as dict. Note we use lazy import to prevent bloating other code parts. Parameters ---------- data: dataclass Dataclass Returns ------- dict: Pydantic model serialized to dict """ import dataclasses return dataclasses.asdict(data) The provided code snippet includes necessary dependencies for implementing the `extract_event_from_common_models` function. Write a Python function `def extract_event_from_common_models(data: Any) -> Dict | Any` to solve the following problem: Extract raw event from common types used in Powertools If event cannot be extracted, return received data as is. Common models: - Event Source Data Classes (DictWrapper) - Python Dataclasses - Pydantic Models (BaseModel) Parameters ---------- data : Any Original event, a potential instance of DictWrapper/BaseModel/Dataclass Notes ----- Why not using static type for function argument? DictWrapper would cause a circular import. Pydantic BaseModel could cause a ModuleNotFound or trigger init reflection worsening cold start. Here is the function: def extract_event_from_common_models(data: Any) -> Dict | Any: """Extract raw event from common types used in Powertools If event cannot be extracted, return received data as is. Common models: - Event Source Data Classes (DictWrapper) - Python Dataclasses - Pydantic Models (BaseModel) Parameters ---------- data : Any Original event, a potential instance of DictWrapper/BaseModel/Dataclass Notes ----- Why not using static type for function argument? DictWrapper would cause a circular import. Pydantic BaseModel could cause a ModuleNotFound or trigger init reflection worsening cold start. """ # Short-circuit most common type first for perf if isinstance(data, dict): return data # Is it an Event Source Data Class? if getattr(data, "raw_event", None): return data.raw_event # Is it a Pydantic Model? if is_pydantic(data): return pydantic_to_dict(data) # Is it a Dataclass? if is_dataclass(data): return dataclass_to_dict(data) # Return as is return data
Extract raw event from common types used in Powertools If event cannot be extracted, return received data as is. Common models: - Event Source Data Classes (DictWrapper) - Python Dataclasses - Pydantic Models (BaseModel) Parameters ---------- data : Any Original event, a potential instance of DictWrapper/BaseModel/Dataclass Notes ----- Why not using static type for function argument? DictWrapper would cause a circular import. Pydantic BaseModel could cause a ModuleNotFound or trigger init reflection worsening cold start.
5,009
from __future__ import annotations import base64 import itertools import logging import os import warnings from binascii import Error as BinAsciiError from pathlib import Path from typing import Any, Dict, Generator, Optional, Union, overload from aws_lambda_powertools.shared import constants The provided code snippet includes necessary dependencies for implementing the `abs_lambda_path` function. Write a Python function `def abs_lambda_path(relative_path: str = "") -> str` to solve the following problem: Return the absolute path from the given relative path to lambda handler. Parameters ---------- relative_path : str, optional The relative path to the lambda handler, by default an empty string. Returns ------- str The absolute path generated from the given relative path. If the environment variable LAMBDA_TASK_ROOT is set, it will use that value. Otherwise, it will use the current working directory. If the path is empty, it will return the current working directory. Here is the function: def abs_lambda_path(relative_path: str = "") -> str: """Return the absolute path from the given relative path to lambda handler. Parameters ---------- relative_path : str, optional The relative path to the lambda handler, by default an empty string. Returns ------- str The absolute path generated from the given relative path. If the environment variable LAMBDA_TASK_ROOT is set, it will use that value. Otherwise, it will use the current working directory. If the path is empty, it will return the current working directory. """ # Retrieve the LAMBDA_TASK_ROOT environment variable or default to an empty string current_working_directory = os.environ.get("LAMBDA_TASK_ROOT", "") # If LAMBDA_TASK_ROOT is not set, use the current working directory if not current_working_directory: current_working_directory = str(Path.cwd()) # Combine the current working directory and the relative path to get the absolute path absolute_path = str(Path(current_working_directory, relative_path)) return absolute_path
Return the absolute path from the given relative path to lambda handler. Parameters ---------- relative_path : str, optional The relative path to the lambda handler, by default an empty string. Returns ------- str The absolute path generated from the given relative path. If the environment variable LAMBDA_TASK_ROOT is set, it will use that value. Otherwise, it will use the current working directory. If the path is empty, it will return the current working directory.
5,010
import logging import os from aws_lambda_powertools.shared.version import VERSION logger = logging.getLogger(__name__) TARGET_SDK_EVENT = "request-created" def _create_feature_function(feature): """ Create and return the `add_powertools_feature` function. The `add_powertools_feature` function is designed to be registered in boto3's event system. When registered, it appends the given feature string to the User-Agent header of AWS SDK requests. Parameters ---------- feature : str The feature string to be appended to the User-Agent header. Returns ------- add_powertools_feature : Callable The `add_powertools_feature` function that modifies the User-Agent header. """ def add_powertools_feature(request, **kwargs): try: headers = request.headers header_user_agent = ( f"{headers['User-Agent']} {FEATURE_PREFIX}/{feature}/{powertools_version} PTEnv/{EXEC_ENV}" ) # This function is exclusive to client and resources objects created in Powertools # and must remove the no-op header, if present if HEADER_NO_OP in headers["User-Agent"] and feature != DEFAULT_FEATURE: # Remove HEADER_NO_OP + space header_user_agent = header_user_agent.replace(f"{HEADER_NO_OP} ", "") headers["User-Agent"] = f"{header_user_agent}" except Exception: logger.debug("Can't find User-Agent header") return add_powertools_feature The provided code snippet includes necessary dependencies for implementing the `register_feature_to_session` function. Write a Python function `def register_feature_to_session(session, feature)` to solve the following problem: Register the given feature string to the event system of the provided boto3 session and append the feature to the User-Agent header of the request Parameters ---------- session : boto3.session.Session The boto3 session to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "streaming" in Powertools. Raises ------ AttributeError If the provided session does not have an event system. Here is the function: def register_feature_to_session(session, feature): """ Register the given feature string to the event system of the provided boto3 session and append the feature to the User-Agent header of the request Parameters ---------- session : boto3.session.Session The boto3 session to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "streaming" in Powertools. Raises ------ AttributeError If the provided session does not have an event system. """ try: session.events.register(TARGET_SDK_EVENT, _create_feature_function(feature)) except AttributeError as e: logger.debug(f"session passed in doesn't have a event system:{e}")
Register the given feature string to the event system of the provided boto3 session and append the feature to the User-Agent header of the request Parameters ---------- session : boto3.session.Session The boto3 session to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "streaming" in Powertools. Raises ------ AttributeError If the provided session does not have an event system.
5,011
import logging import os from aws_lambda_powertools.shared.version import VERSION logger = logging.getLogger(__name__) TARGET_SDK_EVENT = "request-created" def _create_feature_function(feature): """ Create and return the `add_powertools_feature` function. The `add_powertools_feature` function is designed to be registered in boto3's event system. When registered, it appends the given feature string to the User-Agent header of AWS SDK requests. Parameters ---------- feature : str The feature string to be appended to the User-Agent header. Returns ------- add_powertools_feature : Callable The `add_powertools_feature` function that modifies the User-Agent header. """ def add_powertools_feature(request, **kwargs): try: headers = request.headers header_user_agent = ( f"{headers['User-Agent']} {FEATURE_PREFIX}/{feature}/{powertools_version} PTEnv/{EXEC_ENV}" ) # This function is exclusive to client and resources objects created in Powertools # and must remove the no-op header, if present if HEADER_NO_OP in headers["User-Agent"] and feature != DEFAULT_FEATURE: # Remove HEADER_NO_OP + space header_user_agent = header_user_agent.replace(f"{HEADER_NO_OP} ", "") headers["User-Agent"] = f"{header_user_agent}" except Exception: logger.debug("Can't find User-Agent header") return add_powertools_feature The provided code snippet includes necessary dependencies for implementing the `register_feature_to_botocore_session` function. Write a Python function `def register_feature_to_botocore_session(botocore_session, feature)` to solve the following problem: Register the given feature string to the event system of the provided botocore session Please notice this function is for patching botocore session and is different from previous one which is for patching boto3 session Parameters ---------- botocore_session : botocore.session.Session The botocore session to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "data-masking" in Powertools. Raises ------ AttributeError If the provided session does not have an event system. Examples -------- **register data-masking user-agent to botocore session** >>> from aws_lambda_powertools.shared.user_agent import ( >>> register_feature_to_botocore_session >>> ) >>> >>> session = botocore.session.Session() >>> register_feature_to_botocore_session(botocore_session=session, feature="data-masking") >>> key_provider = StrictAwsKmsMasterKeyProvider(key_ids=self.keys, botocore_session=session) Here is the function: def register_feature_to_botocore_session(botocore_session, feature): """ Register the given feature string to the event system of the provided botocore session Please notice this function is for patching botocore session and is different from previous one which is for patching boto3 session Parameters ---------- botocore_session : botocore.session.Session The botocore session to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "data-masking" in Powertools. Raises ------ AttributeError If the provided session does not have an event system. Examples -------- **register data-masking user-agent to botocore session** >>> from aws_lambda_powertools.shared.user_agent import ( >>> register_feature_to_botocore_session >>> ) >>> >>> session = botocore.session.Session() >>> register_feature_to_botocore_session(botocore_session=session, feature="data-masking") >>> key_provider = StrictAwsKmsMasterKeyProvider(key_ids=self.keys, botocore_session=session) """ try: botocore_session.register(TARGET_SDK_EVENT, _create_feature_function(feature)) except AttributeError as e: logger.debug(f"botocore session passed in doesn't have a event system:{e}")
Register the given feature string to the event system of the provided botocore session Please notice this function is for patching botocore session and is different from previous one which is for patching boto3 session Parameters ---------- botocore_session : botocore.session.Session The botocore session to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "data-masking" in Powertools. Raises ------ AttributeError If the provided session does not have an event system. Examples -------- **register data-masking user-agent to botocore session** >>> from aws_lambda_powertools.shared.user_agent import ( >>> register_feature_to_botocore_session >>> ) >>> >>> session = botocore.session.Session() >>> register_feature_to_botocore_session(botocore_session=session, feature="data-masking") >>> key_provider = StrictAwsKmsMasterKeyProvider(key_ids=self.keys, botocore_session=session)
5,012
import logging import os from aws_lambda_powertools.shared.version import VERSION logger = logging.getLogger(__name__) TARGET_SDK_EVENT = "request-created" def _create_feature_function(feature): """ Create and return the `add_powertools_feature` function. The `add_powertools_feature` function is designed to be registered in boto3's event system. When registered, it appends the given feature string to the User-Agent header of AWS SDK requests. Parameters ---------- feature : str The feature string to be appended to the User-Agent header. Returns ------- add_powertools_feature : Callable The `add_powertools_feature` function that modifies the User-Agent header. """ def add_powertools_feature(request, **kwargs): try: headers = request.headers header_user_agent = ( f"{headers['User-Agent']} {FEATURE_PREFIX}/{feature}/{powertools_version} PTEnv/{EXEC_ENV}" ) # This function is exclusive to client and resources objects created in Powertools # and must remove the no-op header, if present if HEADER_NO_OP in headers["User-Agent"] and feature != DEFAULT_FEATURE: # Remove HEADER_NO_OP + space header_user_agent = header_user_agent.replace(f"{HEADER_NO_OP} ", "") headers["User-Agent"] = f"{header_user_agent}" except Exception: logger.debug("Can't find User-Agent header") return add_powertools_feature The provided code snippet includes necessary dependencies for implementing the `register_feature_to_client` function. Write a Python function `def register_feature_to_client(client, feature)` to solve the following problem: Register the given feature string to the event system of the provided boto3 client and append the feature to the User-Agent header of the request Parameters ---------- client : boto3.session.Session.client The boto3 client to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "streaming" in Powertools. Raises ------ AttributeError If the provided client does not have an event system. Here is the function: def register_feature_to_client(client, feature): """ Register the given feature string to the event system of the provided boto3 client and append the feature to the User-Agent header of the request Parameters ---------- client : boto3.session.Session.client The boto3 client to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "streaming" in Powertools. Raises ------ AttributeError If the provided client does not have an event system. """ try: client.meta.events.register(TARGET_SDK_EVENT, _create_feature_function(feature)) except AttributeError as e: logger.debug(f"session passed in doesn't have a event system:{e}")
Register the given feature string to the event system of the provided boto3 client and append the feature to the User-Agent header of the request Parameters ---------- client : boto3.session.Session.client The boto3 client to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "streaming" in Powertools. Raises ------ AttributeError If the provided client does not have an event system.
5,013
import logging import os from aws_lambda_powertools.shared.version import VERSION logger = logging.getLogger(__name__) TARGET_SDK_EVENT = "request-created" def _create_feature_function(feature): """ Create and return the `add_powertools_feature` function. The `add_powertools_feature` function is designed to be registered in boto3's event system. When registered, it appends the given feature string to the User-Agent header of AWS SDK requests. Parameters ---------- feature : str The feature string to be appended to the User-Agent header. Returns ------- add_powertools_feature : Callable The `add_powertools_feature` function that modifies the User-Agent header. """ def add_powertools_feature(request, **kwargs): try: headers = request.headers header_user_agent = ( f"{headers['User-Agent']} {FEATURE_PREFIX}/{feature}/{powertools_version} PTEnv/{EXEC_ENV}" ) # This function is exclusive to client and resources objects created in Powertools # and must remove the no-op header, if present if HEADER_NO_OP in headers["User-Agent"] and feature != DEFAULT_FEATURE: # Remove HEADER_NO_OP + space header_user_agent = header_user_agent.replace(f"{HEADER_NO_OP} ", "") headers["User-Agent"] = f"{header_user_agent}" except Exception: logger.debug("Can't find User-Agent header") return add_powertools_feature The provided code snippet includes necessary dependencies for implementing the `register_feature_to_resource` function. Write a Python function `def register_feature_to_resource(resource, feature)` to solve the following problem: Register the given feature string to the event system of the provided boto3 resource and append the feature to the User-Agent header of the request Parameters ---------- resource : boto3.session.Session.resource The boto3 resource to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "streaming" in Powertools. Raises ------ AttributeError If the provided resource does not have an event system. Here is the function: def register_feature_to_resource(resource, feature): """ Register the given feature string to the event system of the provided boto3 resource and append the feature to the User-Agent header of the request Parameters ---------- resource : boto3.session.Session.resource The boto3 resource to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "streaming" in Powertools. Raises ------ AttributeError If the provided resource does not have an event system. """ try: resource.meta.client.meta.events.register(TARGET_SDK_EVENT, _create_feature_function(feature)) except AttributeError as e: logger.debug(f"resource passed in doesn't have a event system:{e}")
Register the given feature string to the event system of the provided boto3 resource and append the feature to the User-Agent header of the request Parameters ---------- resource : boto3.session.Session.resource The boto3 resource to which the feature will be registered. feature : str The feature string to be appended to the User-Agent header, e.g., "streaming" in Powertools. Raises ------ AttributeError If the provided resource does not have an event system.
5,014
import logging import os from aws_lambda_powertools.shared.version import VERSION inject_header = True try: import botocore except ImportError: # if botocore failed to import, user might be using custom runtime and we can't inject header inject_header = False def _initializer_botocore_session(session): def inject_user_agent(): if inject_header: # Some older botocore versions doesn't support register_initializer. In those cases, we disable the feature. if not hasattr(botocore, "register_initializer"): return # Customize botocore session to inject Powertools header # See: https://github.com/boto/botocore/pull/2682 botocore.register_initializer(_initializer_botocore_session)
null
5,015
import logging from typing import Callable, List, Optional, Set, Union from .logger import Logger PACKAGE_LOGGER = "aws_lambda_powertools" def _include_registered_loggers_filter(loggers: Set[str]): return [logging.getLogger(name) for name in logging.root.manager.loggerDict if "." not in name and name in loggers] def _exclude_registered_loggers_filter(loggers: Set[str]) -> List[logging.Logger]: return [ logging.getLogger(name) for name in logging.root.manager.loggerDict if "." not in name and name not in loggers ] def _find_registered_loggers( source_logger: Logger, loggers: Set[str], filter_func: Callable[[Set[str]], List[logging.Logger]], ) -> List[logging.Logger]: """Filter root loggers based on provided parameters.""" root_loggers = filter_func(loggers) source_logger.debug(f"Filtered root loggers: {root_loggers}") return root_loggers def _configure_logger(source_logger: Logger, logger: logging.Logger, level: Union[int, str]) -> None: logger.handlers = [] logger.setLevel(level) logger.propagate = False # ensure we don't propagate logs to existing loggers, #1073 source_logger.append_keys(name="%(name)s") # include logger name, see #1267 source_logger.debug(f"Logger {logger} reconfigured to use logging level {level}") for source_handler in source_logger.handlers: logger.addHandler(source_handler) source_logger.debug(f"Logger {logger} reconfigured to use {source_handler}") class Logger: """Creates and setups a logger to format statements in JSON. Includes service name and any additional key=value into logs It also accepts both service name or level explicitly via env vars Environment variables --------------------- POWERTOOLS_SERVICE_NAME : str service name POWERTOOLS_LOG_LEVEL: str logging level (e.g. INFO, DEBUG) POWERTOOLS_LOGGER_SAMPLE_RATE: float sampling rate ranging from 0 to 1, 1 being 100% sampling Parameters ---------- service : str, optional service name to be appended in logs, by default "service_undefined" level : str, int optional The level to set. Can be a string representing the level name: 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' or an integer representing the level value: 10 for 'DEBUG', 20 for 'INFO', 30 for 'WARNING', 40 for 'ERROR', 50 for 'CRITICAL'. by default "INFO" child: bool, optional create a child Logger named <service>.<caller_file_name>, False by default sample_rate: float, optional sample rate for debug calls within execution context defaults to 0.0 stream: sys.stdout, optional valid output for a logging stream, by default sys.stdout logger_formatter: PowertoolsFormatter, optional custom logging formatter that implements PowertoolsFormatter logger_handler: logging.Handler, optional custom logging handler e.g. logging.FileHandler("file.log") log_uncaught_exceptions: bool, by default False logs uncaught exception using sys.excepthook See: https://docs.python.org/3/library/sys.html#sys.excepthook Parameters propagated to LambdaPowertoolsFormatter -------------------------------------------------- datefmt: str, optional String directives (strftime) to format log timestamp using `time`, by default it uses 2021-05-03 11:47:12,494+0200. use_datetime_directive: bool, optional Interpret `datefmt` as a format string for `datetime.datetime.strftime`, rather than `time.strftime`. See https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior . This also supports a custom %F directive for milliseconds. use_rfc3339: bool, optional Whether to use a popular date format that complies with both RFC3339 and ISO8601. e.g., 2022-10-27T16:27:43.738+02:00. json_serializer : Callable, optional function to serialize `obj` to a JSON formatted `str`, by default json.dumps json_deserializer : Callable, optional function to deserialize `str`, `bytes`, bytearray` containing a JSON document to a Python `obj`, by default json.loads json_default : Callable, optional function to coerce unserializable values, by default `str()` Only used when no custom formatter is set utc : bool, optional set logging timestamp to UTC, by default False to continue to use local time as per stdlib log_record_order : list, optional set order of log keys when logging, by default ["level", "location", "message", "timestamp"] Example ------- **Setups structured logging in JSON for Lambda functions with explicit service name** >>> from aws_lambda_powertools import Logger >>> logger = Logger(service="payment") >>> >>> def handler(event, context): logger.info("Hello") **Setups structured logging in JSON for Lambda functions using env vars** $ export POWERTOOLS_SERVICE_NAME="payment" $ export POWERTOOLS_LOGGER_SAMPLE_RATE=0.01 # 1% debug sampling >>> from aws_lambda_powertools import Logger >>> logger = Logger() >>> >>> def handler(event, context): logger.info("Hello") **Append payment_id to previously setup logger** >>> from aws_lambda_powertools import Logger >>> logger = Logger(service="payment") >>> >>> def handler(event, context): logger.append_keys(payment_id=event["payment_id"]) logger.info("Hello") **Create child Logger using logging inheritance via child param** >>> # app.py >>> import another_file >>> from aws_lambda_powertools import Logger >>> logger = Logger(service="payment") >>> >>> # another_file.py >>> from aws_lambda_powertools import Logger >>> logger = Logger(service="payment", child=True) **Logging in UTC timezone** >>> # app.py >>> import logging >>> from aws_lambda_powertools import Logger >>> >>> logger = Logger(service="payment", utc=True) **Brings message as the first key in log statements** >>> # app.py >>> import logging >>> from aws_lambda_powertools import Logger >>> >>> logger = Logger(service="payment", log_record_order=["message"]) **Logging to a file instead of standard output for testing** >>> # app.py >>> import logging >>> from aws_lambda_powertools import Logger >>> >>> logger = Logger(service="payment", logger_handler=logging.FileHandler("log.json")) Raises ------ InvalidLoggerSamplingRateError When sampling rate provided is not a float """ # noqa: E501 def __init__( self, service: Optional[str] = None, level: Union[str, int, None] = None, child: bool = False, sampling_rate: Optional[float] = None, stream: Optional[IO[str]] = None, logger_formatter: Optional[PowertoolsFormatter] = None, logger_handler: Optional[logging.Handler] = None, log_uncaught_exceptions: bool = False, json_serializer: Optional[Callable[[Dict], str]] = None, json_deserializer: Optional[Callable[[Union[Dict, str, bool, int, float]], str]] = None, json_default: Optional[Callable[[Any], Any]] = None, datefmt: Optional[str] = None, use_datetime_directive: bool = False, log_record_order: Optional[List[str]] = None, utc: bool = False, use_rfc3339: bool = False, serialize_stacktrace: bool = True, **kwargs, ) -> None: self.service = resolve_env_var_choice( choice=service, env=os.getenv(constants.SERVICE_NAME_ENV, "service_undefined"), ) self.sampling_rate = resolve_env_var_choice( choice=sampling_rate, env=os.getenv(constants.LOGGER_LOG_SAMPLING_RATE), ) self.child = child self.logger_formatter = logger_formatter self._stream = stream or sys.stdout self.logger_handler = logger_handler or logging.StreamHandler(self._stream) self.log_uncaught_exceptions = log_uncaught_exceptions self._is_deduplication_disabled = resolve_truthy_env_var_choice( env=os.getenv(constants.LOGGER_LOG_DEDUPLICATION_ENV, "false"), ) self._default_log_keys = {"service": self.service, "sampling_rate": self.sampling_rate} self._logger = self._get_logger() # NOTE: This is primarily to improve UX, so IDEs can autocomplete LambdaPowertoolsFormatter options # previously, we masked all of them as kwargs thus limiting feature discovery formatter_options = { "json_serializer": json_serializer, "json_deserializer": json_deserializer, "json_default": json_default, "datefmt": datefmt, "use_datetime_directive": use_datetime_directive, "log_record_order": log_record_order, "utc": utc, "use_rfc3339": use_rfc3339, "serialize_stacktrace": serialize_stacktrace, } self._init_logger(formatter_options=formatter_options, log_level=level, **kwargs) if self.log_uncaught_exceptions: logger.debug("Replacing exception hook") sys.excepthook = functools.partial(log_uncaught_exception_hook, logger=self) # Prevent __getattr__ from shielding unknown attribute errors in type checkers # https://github.com/aws-powertools/powertools-lambda-python/issues/1660 if not TYPE_CHECKING: def __getattr__(self, name): # Proxy attributes not found to actual logger to support backward compatibility # https://github.com/aws-powertools/powertools-lambda-python/issues/97 return getattr(self._logger, name) def _get_logger(self) -> logging.Logger: """Returns a Logger named {self.service}, or {self.service.filename} for child loggers""" logger_name = self.service if self.child: logger_name = f"{self.service}.{_get_caller_filename()}" return logging.getLogger(logger_name) def _init_logger( self, formatter_options: Optional[Dict] = None, log_level: Union[str, int, None] = None, **kwargs, ) -> None: """Configures new logger""" # Skip configuration if it's a child logger or a pre-configured logger # to prevent the following: # a) multiple handlers being attached # b) different sampling mechanisms # c) multiple messages from being logged as handlers can be duplicated is_logger_preconfigured = getattr(self._logger, "init", False) if self.child or is_logger_preconfigured: return self.setLevel(log_level) self._configure_sampling() self.addHandler(self.logger_handler) self.structure_logs(formatter_options=formatter_options, **kwargs) # Pytest Live Log feature duplicates log records for colored output # but we explicitly add a filter for log deduplication. # This flag disables this protection when you explicit want logs to be duplicated (#262) if not self._is_deduplication_disabled: logger.debug("Adding filter in root logger to suppress child logger records to bubble up") for handler in logging.root.handlers: # It'll add a filter to suppress any child logger from self.service # Example: `Logger(service="order")`, where service is Order # It'll reject all loggers starting with `order` e.g. order.checkout, order.shared handler.addFilter(SuppressFilter(self.service)) # as per bug in #249, we should not be pre-configuring an existing logger # therefore we set a custom attribute in the Logger that will be returned # std logging will return the same Logger with our attribute if name is reused logger.debug(f"Marking logger {self.service} as preconfigured") self._logger.init = True # type: ignore[attr-defined] def _configure_sampling(self) -> None: """Dynamically set log level based on sampling rate Raises ------ InvalidLoggerSamplingRateError When sampling rate provided is not a float """ try: if self.sampling_rate and random.random() <= float(self.sampling_rate): logger.debug("Setting log level to Debug due to sampling rate") self._logger.setLevel(logging.DEBUG) except ValueError: raise InvalidLoggerSamplingRateError( ( f"Expected a float value ranging 0 to 1, but received {self.sampling_rate} instead." "Please review POWERTOOLS_LOGGER_SAMPLE_RATE environment variable." ), ) def inject_lambda_context( self, lambda_handler: AnyCallableT, log_event: Optional[bool] = None, correlation_id_path: Optional[str] = None, clear_state: Optional[bool] = False, ) -> AnyCallableT: ... def inject_lambda_context( self, lambda_handler: None = None, log_event: Optional[bool] = None, correlation_id_path: Optional[str] = None, clear_state: Optional[bool] = False, ) -> Callable[[AnyCallableT], AnyCallableT]: ... def inject_lambda_context( self, lambda_handler: Optional[AnyCallableT] = None, log_event: Optional[bool] = None, correlation_id_path: Optional[str] = None, clear_state: Optional[bool] = False, ) -> Any: """Decorator to capture Lambda contextual info and inject into logger Parameters ---------- clear_state : bool, optional Instructs logger to remove any custom keys previously added lambda_handler : Callable Method to inject the lambda context log_event : bool, optional Instructs logger to log Lambda Event, by default False correlation_id_path: str, optional Optional JMESPath for the correlation_id Environment variables --------------------- POWERTOOLS_LOGGER_LOG_EVENT : str instruct logger to log Lambda Event (e.g. `"true", "True", "TRUE"`) Example ------- **Captures Lambda contextual runtime info (e.g memory, arn, req_id)** from aws_lambda_powertools import Logger logger = Logger(service="payment") def handler(event, context): logger.info("Hello") **Captures Lambda contextual runtime info and logs incoming request** from aws_lambda_powertools import Logger logger = Logger(service="payment") def handler(event, context): logger.info("Hello") Returns ------- decorate : Callable Decorated lambda handler """ # If handler is None we've been called with parameters # Return a partial function with args filled if lambda_handler is None: logger.debug("Decorator called with parameters") return functools.partial( self.inject_lambda_context, log_event=log_event, correlation_id_path=correlation_id_path, clear_state=clear_state, ) log_event = resolve_truthy_env_var_choice( env=os.getenv(constants.LOGGER_LOG_EVENT_ENV, "false"), choice=log_event, ) def decorate(event, context, *args, **kwargs): lambda_context = build_lambda_context_model(context) cold_start = _is_cold_start() if clear_state: self.structure_logs(cold_start=cold_start, **lambda_context.__dict__) else: self.append_keys(cold_start=cold_start, **lambda_context.__dict__) if correlation_id_path: self.set_correlation_id( jmespath_utils.extract_data_from_envelope(envelope=correlation_id_path, data=event), ) if log_event: logger.debug("Event received") self.info(extract_event_from_common_models(event)) return lambda_handler(event, context, *args, **kwargs) return decorate def info( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.info( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def error( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.error( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def exception( self, msg: object, *args: object, exc_info: logging._ExcInfoType = True, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.exception( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def critical( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.critical( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def warning( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.warning( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def debug( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.debug( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def append_keys(self, **additional_keys) -> None: self.registered_formatter.append_keys(**additional_keys) def remove_keys(self, keys: Iterable[str]) -> None: self.registered_formatter.remove_keys(keys) def structure_logs(self, append: bool = False, formatter_options: Optional[Dict] = None, **keys) -> None: """Sets logging formatting to JSON. Optionally, it can append keyword arguments to an existing logger, so it is available across future log statements. Last keyword argument and value wins if duplicated. Parameters ---------- append : bool, optional append keys provided to logger formatter, by default False formatter_options : dict, optional LambdaPowertoolsFormatter options to be propagated, by default {} """ formatter_options = formatter_options or {} # There are 3 operational modes for this method ## 1. Register a Powertools for AWS Lambda (Python) Formatter for the first time ## 2. Append new keys to the current logger formatter; deprecated in favour of append_keys ## 3. Add new keys and discard existing to the registered formatter # Mode 1 log_keys = {**self._default_log_keys, **keys} is_logger_preconfigured = getattr(self._logger, "init", False) if not is_logger_preconfigured: formatter = self.logger_formatter or LambdaPowertoolsFormatter(**formatter_options, **log_keys) self.registered_handler.setFormatter(formatter) # when using a custom Powertools for AWS Lambda (Python) Formatter # standard and custom keys that are not Powertools for AWS Lambda (Python) Formatter parameters # should be appended and custom keys that might happen to be Powertools for AWS Lambda (Python) # Formatter parameters should be discarded this prevents adding them as custom keys, for example, # `json_default=<callable>` see https://github.com/aws-powertools/powertools-lambda-python/issues/1263 custom_keys = {k: v for k, v in log_keys.items() if k not in RESERVED_FORMATTER_CUSTOM_KEYS} return self.registered_formatter.append_keys(**custom_keys) # Mode 2 (legacy) if append: # Maintenance: Add deprecation warning for major version return self.append_keys(**keys) # Mode 3 self.registered_formatter.clear_state() self.registered_formatter.append_keys(**log_keys) def set_correlation_id(self, value: Optional[str]) -> None: """Sets the correlation_id in the logging json Parameters ---------- value : str, optional Value for the correlation id. None will remove the correlation_id """ self.append_keys(correlation_id=value) def get_correlation_id(self) -> Optional[str]: """Gets the correlation_id in the logging json Returns ------- str, optional Value for the correlation id """ if isinstance(self.registered_formatter, LambdaPowertoolsFormatter): return self.registered_formatter.log_format.get("correlation_id") return None def setLevel(self, level: Union[str, int, None]) -> None: return self._logger.setLevel(self._determine_log_level(level)) def addHandler(self, handler: logging.Handler) -> None: return self._logger.addHandler(handler) def addFilter(self, filter: logging._FilterType) -> None: # noqa: A002 # filter built-in usage return self._logger.addFilter(filter) def removeFilter(self, filter: logging._FilterType) -> None: # noqa: A002 # filter built-in usage return self._logger.removeFilter(filter) def registered_handler(self) -> logging.Handler: """Convenience property to access the first logger handler""" # We ignore mypy here because self.child encodes whether or not self._logger.parent is # None, mypy can't see this from context but we can handlers = self._logger.parent.handlers if self.child else self._logger.handlers # type: ignore[union-attr] return handlers[0] def registered_formatter(self) -> BasePowertoolsFormatter: """Convenience property to access the first logger formatter""" return self.registered_handler.formatter # type: ignore[return-value] def log_level(self) -> int: return self._logger.level def name(self) -> str: return self._logger.name def handlers(self) -> List[logging.Handler]: """List of registered logging handlers Notes ----- Looking for the first configured handler? Use registered_handler property instead. """ return self._logger.handlers def _get_aws_lambda_log_level(self) -> Optional[str]: """ Retrieve the log level for AWS Lambda from the Advanced Logging Controls feature. Returns: Optional[str]: The corresponding logging level. """ return constants.LAMBDA_ADVANCED_LOGGING_LEVELS.get(os.getenv(constants.LAMBDA_LOG_LEVEL_ENV)) def _get_powertools_log_level(self, level: Union[str, int, None]) -> Optional[str]: """Retrieve the log level for Powertools from the environment variable or level parameter. If log level is an integer, we convert to its respective string level `logging.getLevelName()`. If no log level is provided, we check env vars for the log level: POWERTOOLS_LOG_LEVEL_ENV and POWERTOOLS_LOG_LEVEL_LEGACY_ENV. Parameters: ----------- level : Union[str, int, None] The specified log level as a string, integer, or None. Environment variables --------------------- POWERTOOLS_LOG_LEVEL : str log level (e.g: INFO, DEBUG, WARNING, ERROR, CRITICAL) LOG_LEVEL (Legacy) : str log level (e.g: INFO, DEBUG, WARNING, ERROR, CRITICAL) Returns: -------- Optional[str]: The corresponding logging level. Returns None if the log level is not explicitly specified. """ # noqa E501 # Extract log level from Powertools Logger env vars log_level_env = os.getenv(constants.POWERTOOLS_LOG_LEVEL_ENV) or os.getenv( constants.POWERTOOLS_LOG_LEVEL_LEGACY_ENV, ) # If level is an int (logging.INFO), return its respective string ("INFO") if isinstance(level, int): return logging.getLevelName(level) return level or log_level_env def _determine_log_level(self, level: Union[str, int, None]) -> Union[str, int]: """Determine the effective log level considering Lambda and Powertools preferences. It emits an UserWarning if Lambda ALC log level is lower than Logger log level. Parameters: ----------- level: Union[str, int, None] The specified log level as a string, integer, or None. Returns: ---------- Union[str, int]: The effective logging level. """ # This function consider the following order of precedence: # 1 - If a log level is set using AWS Lambda Advanced Logging Controls, it sets it. # 2 - If a log level is passed to the constructor, it sets it # 3 - If a log level is set via setLevel, it sets it. # 4 - If a log level is set via Powertools env variables, it sets it. # 5 - If none of the above is true, the default log level applies INFO. lambda_log_level = self._get_aws_lambda_log_level() powertools_log_level = self._get_powertools_log_level(level) if powertools_log_level and lambda_log_level: # If Powertools log level is set and higher than AWS Lambda Advanced Logging Controls, emit a warning if logging.getLevelName(lambda_log_level) > logging.getLevelName(powertools_log_level): warnings.warn( f"Current log level ({powertools_log_level}) does not match AWS Lambda Advanced Logging Controls " f"minimum log level ({lambda_log_level}). This can lead to data loss, consider adjusting them.", UserWarning, stacklevel=2, ) # AWS Lambda Advanced Logging Controls takes precedence over Powertools log level and we use this if lambda_log_level: return lambda_log_level # Check if Powertools log level is None, which means it's not set # We assume INFO as the default log level if powertools_log_level is None: return logging.INFO # Powertools log level is set, we use this return powertools_log_level.upper() The provided code snippet includes necessary dependencies for implementing the `copy_config_to_registered_loggers` function. Write a Python function `def copy_config_to_registered_loggers( source_logger: Logger, log_level: Optional[Union[int, str]] = None, exclude: Optional[Set[str]] = None, include: Optional[Set[str]] = None, ) -> None` to solve the following problem: Copies source Logger level and handler to all registered loggers for consistent formatting. Parameters ---------- source_logger : Logger Powertools for AWS Lambda (Python) Logger to copy configuration from log_level : Union[int, str], optional Logging level to set to registered loggers, by default uses source_logger logging level include : Optional[Set[str]], optional List of logger names to include, by default all registered loggers are included exclude : Optional[Set[str]], optional List of logger names to exclude, by default None Here is the function: def copy_config_to_registered_loggers( source_logger: Logger, log_level: Optional[Union[int, str]] = None, exclude: Optional[Set[str]] = None, include: Optional[Set[str]] = None, ) -> None: """Copies source Logger level and handler to all registered loggers for consistent formatting. Parameters ---------- source_logger : Logger Powertools for AWS Lambda (Python) Logger to copy configuration from log_level : Union[int, str], optional Logging level to set to registered loggers, by default uses source_logger logging level include : Optional[Set[str]], optional List of logger names to include, by default all registered loggers are included exclude : Optional[Set[str]], optional List of logger names to exclude, by default None """ level = log_level or source_logger.log_level # Assumptions: Only take parent loggers not children (dot notation rule) # Steps: # 1. Default operation: Include all registered loggers # 2. Only include set? Only add Loggers in the list and ignore all else # 3. Include and exclude set? Add Logger if it’s in include and not in exclude # 4. Only exclude set? Ignore Logger in the excluding list # Exclude source and Powertools for AWS Lambda (Python) package logger by default # If source logger is a child ensure we exclude parent logger to not break child logger # from receiving/pushing updates to keys being added/removed source_logger_name = source_logger.name.split(".")[0] if exclude: exclude.update([source_logger_name, PACKAGE_LOGGER]) else: exclude = {source_logger_name, PACKAGE_LOGGER} # Prepare loggers set if include: loggers = include.difference(exclude) filter_func = _include_registered_loggers_filter else: loggers = exclude filter_func = _exclude_registered_loggers_filter registered_loggers = _find_registered_loggers(source_logger, loggers, filter_func) for logger in registered_loggers: _configure_logger(source_logger, logger, level)
Copies source Logger level and handler to all registered loggers for consistent formatting. Parameters ---------- source_logger : Logger Powertools for AWS Lambda (Python) Logger to copy configuration from log_level : Union[int, str], optional Logging level to set to registered loggers, by default uses source_logger logging level include : Optional[Set[str]], optional List of logger names to include, by default all registered loggers are included exclude : Optional[Set[str]], optional List of logger names to exclude, by default None
5,016
from typing import Any class LambdaContextModel: """A handful of Lambda Runtime Context fields Full Lambda Context object: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Parameters ---------- function_name: str Lambda function name, by default "UNDEFINED" e.g. "test" function_memory_size: int Lambda function memory in MB, by default 128 function_arn: str Lambda function ARN, by default "UNDEFINED" e.g. "arn:aws:lambda:eu-west-1:809313241:function:test" function_request_id: str Lambda function unique request id, by default "UNDEFINED" e.g. "52fdfc07-2182-154f-163f-5f0f9a621d72" """ def __init__( self, function_name: str = "UNDEFINED", function_memory_size: int = 128, function_arn: str = "UNDEFINED", function_request_id: str = "UNDEFINED", ): self.function_name = function_name self.function_memory_size = function_memory_size self.function_arn = function_arn self.function_request_id = function_request_id The provided code snippet includes necessary dependencies for implementing the `build_lambda_context_model` function. Write a Python function `def build_lambda_context_model(context: Any) -> LambdaContextModel` to solve the following problem: Captures Lambda function runtime info to be used across all log statements Parameters ---------- context : object Lambda context object Returns ------- LambdaContextModel Lambda context only with select fields Here is the function: def build_lambda_context_model(context: Any) -> LambdaContextModel: """Captures Lambda function runtime info to be used across all log statements Parameters ---------- context : object Lambda context object Returns ------- LambdaContextModel Lambda context only with select fields """ context = { "function_name": context.function_name, "function_memory_size": context.memory_limit_in_mb, "function_arn": context.invoked_function_arn, "function_request_id": context.aws_request_id, } return LambdaContextModel(**context)
Captures Lambda function runtime info to be used across all log statements Parameters ---------- context : object Lambda context object Returns ------- LambdaContextModel Lambda context only with select fields
5,017
from __future__ import annotations import functools import inspect import logging import os import random import sys import warnings from typing import ( IO, TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Mapping, Optional, TypeVar, Union, overload, ) from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( extract_event_from_common_models, resolve_env_var_choice, resolve_truthy_env_var_choice, ) from aws_lambda_powertools.utilities import jmespath_utils from ..shared.types import AnyCallableT from .exceptions import InvalidLoggerSamplingRateError from .filters import SuppressFilter from .formatter import ( RESERVED_FORMATTER_CUSTOM_KEYS, BasePowertoolsFormatter, LambdaPowertoolsFormatter, ) from .lambda_context import build_lambda_context_model is_cold_start = True The provided code snippet includes necessary dependencies for implementing the `_is_cold_start` function. Write a Python function `def _is_cold_start() -> bool` to solve the following problem: Verifies whether is cold start Returns ------- bool cold start bool value Here is the function: def _is_cold_start() -> bool: """Verifies whether is cold start Returns ------- bool cold start bool value """ cold_start = False global is_cold_start if is_cold_start: cold_start = is_cold_start is_cold_start = False return cold_start
Verifies whether is cold start Returns ------- bool cold start bool value
5,018
from __future__ import annotations import functools import inspect import logging import os import random import sys import warnings from typing import ( IO, TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Mapping, Optional, TypeVar, Union, overload, ) from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( extract_event_from_common_models, resolve_env_var_choice, resolve_truthy_env_var_choice, ) from aws_lambda_powertools.utilities import jmespath_utils from ..shared.types import AnyCallableT from .exceptions import InvalidLoggerSamplingRateError from .filters import SuppressFilter from .formatter import ( RESERVED_FORMATTER_CUSTOM_KEYS, BasePowertoolsFormatter, LambdaPowertoolsFormatter, ) from .lambda_context import build_lambda_context_model class Logger: """Creates and setups a logger to format statements in JSON. Includes service name and any additional key=value into logs It also accepts both service name or level explicitly via env vars Environment variables --------------------- POWERTOOLS_SERVICE_NAME : str service name POWERTOOLS_LOG_LEVEL: str logging level (e.g. INFO, DEBUG) POWERTOOLS_LOGGER_SAMPLE_RATE: float sampling rate ranging from 0 to 1, 1 being 100% sampling Parameters ---------- service : str, optional service name to be appended in logs, by default "service_undefined" level : str, int optional The level to set. Can be a string representing the level name: 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' or an integer representing the level value: 10 for 'DEBUG', 20 for 'INFO', 30 for 'WARNING', 40 for 'ERROR', 50 for 'CRITICAL'. by default "INFO" child: bool, optional create a child Logger named <service>.<caller_file_name>, False by default sample_rate: float, optional sample rate for debug calls within execution context defaults to 0.0 stream: sys.stdout, optional valid output for a logging stream, by default sys.stdout logger_formatter: PowertoolsFormatter, optional custom logging formatter that implements PowertoolsFormatter logger_handler: logging.Handler, optional custom logging handler e.g. logging.FileHandler("file.log") log_uncaught_exceptions: bool, by default False logs uncaught exception using sys.excepthook See: https://docs.python.org/3/library/sys.html#sys.excepthook Parameters propagated to LambdaPowertoolsFormatter -------------------------------------------------- datefmt: str, optional String directives (strftime) to format log timestamp using `time`, by default it uses 2021-05-03 11:47:12,494+0200. use_datetime_directive: bool, optional Interpret `datefmt` as a format string for `datetime.datetime.strftime`, rather than `time.strftime`. See https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior . This also supports a custom %F directive for milliseconds. use_rfc3339: bool, optional Whether to use a popular date format that complies with both RFC3339 and ISO8601. e.g., 2022-10-27T16:27:43.738+02:00. json_serializer : Callable, optional function to serialize `obj` to a JSON formatted `str`, by default json.dumps json_deserializer : Callable, optional function to deserialize `str`, `bytes`, bytearray` containing a JSON document to a Python `obj`, by default json.loads json_default : Callable, optional function to coerce unserializable values, by default `str()` Only used when no custom formatter is set utc : bool, optional set logging timestamp to UTC, by default False to continue to use local time as per stdlib log_record_order : list, optional set order of log keys when logging, by default ["level", "location", "message", "timestamp"] Example ------- **Setups structured logging in JSON for Lambda functions with explicit service name** >>> from aws_lambda_powertools import Logger >>> logger = Logger(service="payment") >>> >>> def handler(event, context): logger.info("Hello") **Setups structured logging in JSON for Lambda functions using env vars** $ export POWERTOOLS_SERVICE_NAME="payment" $ export POWERTOOLS_LOGGER_SAMPLE_RATE=0.01 # 1% debug sampling >>> from aws_lambda_powertools import Logger >>> logger = Logger() >>> >>> def handler(event, context): logger.info("Hello") **Append payment_id to previously setup logger** >>> from aws_lambda_powertools import Logger >>> logger = Logger(service="payment") >>> >>> def handler(event, context): logger.append_keys(payment_id=event["payment_id"]) logger.info("Hello") **Create child Logger using logging inheritance via child param** >>> # app.py >>> import another_file >>> from aws_lambda_powertools import Logger >>> logger = Logger(service="payment") >>> >>> # another_file.py >>> from aws_lambda_powertools import Logger >>> logger = Logger(service="payment", child=True) **Logging in UTC timezone** >>> # app.py >>> import logging >>> from aws_lambda_powertools import Logger >>> >>> logger = Logger(service="payment", utc=True) **Brings message as the first key in log statements** >>> # app.py >>> import logging >>> from aws_lambda_powertools import Logger >>> >>> logger = Logger(service="payment", log_record_order=["message"]) **Logging to a file instead of standard output for testing** >>> # app.py >>> import logging >>> from aws_lambda_powertools import Logger >>> >>> logger = Logger(service="payment", logger_handler=logging.FileHandler("log.json")) Raises ------ InvalidLoggerSamplingRateError When sampling rate provided is not a float """ # noqa: E501 def __init__( self, service: Optional[str] = None, level: Union[str, int, None] = None, child: bool = False, sampling_rate: Optional[float] = None, stream: Optional[IO[str]] = None, logger_formatter: Optional[PowertoolsFormatter] = None, logger_handler: Optional[logging.Handler] = None, log_uncaught_exceptions: bool = False, json_serializer: Optional[Callable[[Dict], str]] = None, json_deserializer: Optional[Callable[[Union[Dict, str, bool, int, float]], str]] = None, json_default: Optional[Callable[[Any], Any]] = None, datefmt: Optional[str] = None, use_datetime_directive: bool = False, log_record_order: Optional[List[str]] = None, utc: bool = False, use_rfc3339: bool = False, serialize_stacktrace: bool = True, **kwargs, ) -> None: self.service = resolve_env_var_choice( choice=service, env=os.getenv(constants.SERVICE_NAME_ENV, "service_undefined"), ) self.sampling_rate = resolve_env_var_choice( choice=sampling_rate, env=os.getenv(constants.LOGGER_LOG_SAMPLING_RATE), ) self.child = child self.logger_formatter = logger_formatter self._stream = stream or sys.stdout self.logger_handler = logger_handler or logging.StreamHandler(self._stream) self.log_uncaught_exceptions = log_uncaught_exceptions self._is_deduplication_disabled = resolve_truthy_env_var_choice( env=os.getenv(constants.LOGGER_LOG_DEDUPLICATION_ENV, "false"), ) self._default_log_keys = {"service": self.service, "sampling_rate": self.sampling_rate} self._logger = self._get_logger() # NOTE: This is primarily to improve UX, so IDEs can autocomplete LambdaPowertoolsFormatter options # previously, we masked all of them as kwargs thus limiting feature discovery formatter_options = { "json_serializer": json_serializer, "json_deserializer": json_deserializer, "json_default": json_default, "datefmt": datefmt, "use_datetime_directive": use_datetime_directive, "log_record_order": log_record_order, "utc": utc, "use_rfc3339": use_rfc3339, "serialize_stacktrace": serialize_stacktrace, } self._init_logger(formatter_options=formatter_options, log_level=level, **kwargs) if self.log_uncaught_exceptions: logger.debug("Replacing exception hook") sys.excepthook = functools.partial(log_uncaught_exception_hook, logger=self) # Prevent __getattr__ from shielding unknown attribute errors in type checkers # https://github.com/aws-powertools/powertools-lambda-python/issues/1660 if not TYPE_CHECKING: def __getattr__(self, name): # Proxy attributes not found to actual logger to support backward compatibility # https://github.com/aws-powertools/powertools-lambda-python/issues/97 return getattr(self._logger, name) def _get_logger(self) -> logging.Logger: """Returns a Logger named {self.service}, or {self.service.filename} for child loggers""" logger_name = self.service if self.child: logger_name = f"{self.service}.{_get_caller_filename()}" return logging.getLogger(logger_name) def _init_logger( self, formatter_options: Optional[Dict] = None, log_level: Union[str, int, None] = None, **kwargs, ) -> None: """Configures new logger""" # Skip configuration if it's a child logger or a pre-configured logger # to prevent the following: # a) multiple handlers being attached # b) different sampling mechanisms # c) multiple messages from being logged as handlers can be duplicated is_logger_preconfigured = getattr(self._logger, "init", False) if self.child or is_logger_preconfigured: return self.setLevel(log_level) self._configure_sampling() self.addHandler(self.logger_handler) self.structure_logs(formatter_options=formatter_options, **kwargs) # Pytest Live Log feature duplicates log records for colored output # but we explicitly add a filter for log deduplication. # This flag disables this protection when you explicit want logs to be duplicated (#262) if not self._is_deduplication_disabled: logger.debug("Adding filter in root logger to suppress child logger records to bubble up") for handler in logging.root.handlers: # It'll add a filter to suppress any child logger from self.service # Example: `Logger(service="order")`, where service is Order # It'll reject all loggers starting with `order` e.g. order.checkout, order.shared handler.addFilter(SuppressFilter(self.service)) # as per bug in #249, we should not be pre-configuring an existing logger # therefore we set a custom attribute in the Logger that will be returned # std logging will return the same Logger with our attribute if name is reused logger.debug(f"Marking logger {self.service} as preconfigured") self._logger.init = True # type: ignore[attr-defined] def _configure_sampling(self) -> None: """Dynamically set log level based on sampling rate Raises ------ InvalidLoggerSamplingRateError When sampling rate provided is not a float """ try: if self.sampling_rate and random.random() <= float(self.sampling_rate): logger.debug("Setting log level to Debug due to sampling rate") self._logger.setLevel(logging.DEBUG) except ValueError: raise InvalidLoggerSamplingRateError( ( f"Expected a float value ranging 0 to 1, but received {self.sampling_rate} instead." "Please review POWERTOOLS_LOGGER_SAMPLE_RATE environment variable." ), ) def inject_lambda_context( self, lambda_handler: AnyCallableT, log_event: Optional[bool] = None, correlation_id_path: Optional[str] = None, clear_state: Optional[bool] = False, ) -> AnyCallableT: ... def inject_lambda_context( self, lambda_handler: None = None, log_event: Optional[bool] = None, correlation_id_path: Optional[str] = None, clear_state: Optional[bool] = False, ) -> Callable[[AnyCallableT], AnyCallableT]: ... def inject_lambda_context( self, lambda_handler: Optional[AnyCallableT] = None, log_event: Optional[bool] = None, correlation_id_path: Optional[str] = None, clear_state: Optional[bool] = False, ) -> Any: """Decorator to capture Lambda contextual info and inject into logger Parameters ---------- clear_state : bool, optional Instructs logger to remove any custom keys previously added lambda_handler : Callable Method to inject the lambda context log_event : bool, optional Instructs logger to log Lambda Event, by default False correlation_id_path: str, optional Optional JMESPath for the correlation_id Environment variables --------------------- POWERTOOLS_LOGGER_LOG_EVENT : str instruct logger to log Lambda Event (e.g. `"true", "True", "TRUE"`) Example ------- **Captures Lambda contextual runtime info (e.g memory, arn, req_id)** from aws_lambda_powertools import Logger logger = Logger(service="payment") def handler(event, context): logger.info("Hello") **Captures Lambda contextual runtime info and logs incoming request** from aws_lambda_powertools import Logger logger = Logger(service="payment") def handler(event, context): logger.info("Hello") Returns ------- decorate : Callable Decorated lambda handler """ # If handler is None we've been called with parameters # Return a partial function with args filled if lambda_handler is None: logger.debug("Decorator called with parameters") return functools.partial( self.inject_lambda_context, log_event=log_event, correlation_id_path=correlation_id_path, clear_state=clear_state, ) log_event = resolve_truthy_env_var_choice( env=os.getenv(constants.LOGGER_LOG_EVENT_ENV, "false"), choice=log_event, ) def decorate(event, context, *args, **kwargs): lambda_context = build_lambda_context_model(context) cold_start = _is_cold_start() if clear_state: self.structure_logs(cold_start=cold_start, **lambda_context.__dict__) else: self.append_keys(cold_start=cold_start, **lambda_context.__dict__) if correlation_id_path: self.set_correlation_id( jmespath_utils.extract_data_from_envelope(envelope=correlation_id_path, data=event), ) if log_event: logger.debug("Event received") self.info(extract_event_from_common_models(event)) return lambda_handler(event, context, *args, **kwargs) return decorate def info( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.info( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def error( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.error( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def exception( self, msg: object, *args: object, exc_info: logging._ExcInfoType = True, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.exception( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def critical( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.critical( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def warning( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.warning( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def debug( self, msg: object, *args: object, exc_info: logging._ExcInfoType = None, stack_info: bool = False, stacklevel: int = 2, extra: Optional[Mapping[str, object]] = None, **kwargs: object, ) -> None: extra = extra or {} extra = {**extra, **kwargs} return self._logger.debug( msg, *args, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=extra, ) def append_keys(self, **additional_keys) -> None: self.registered_formatter.append_keys(**additional_keys) def remove_keys(self, keys: Iterable[str]) -> None: self.registered_formatter.remove_keys(keys) def structure_logs(self, append: bool = False, formatter_options: Optional[Dict] = None, **keys) -> None: """Sets logging formatting to JSON. Optionally, it can append keyword arguments to an existing logger, so it is available across future log statements. Last keyword argument and value wins if duplicated. Parameters ---------- append : bool, optional append keys provided to logger formatter, by default False formatter_options : dict, optional LambdaPowertoolsFormatter options to be propagated, by default {} """ formatter_options = formatter_options or {} # There are 3 operational modes for this method ## 1. Register a Powertools for AWS Lambda (Python) Formatter for the first time ## 2. Append new keys to the current logger formatter; deprecated in favour of append_keys ## 3. Add new keys and discard existing to the registered formatter # Mode 1 log_keys = {**self._default_log_keys, **keys} is_logger_preconfigured = getattr(self._logger, "init", False) if not is_logger_preconfigured: formatter = self.logger_formatter or LambdaPowertoolsFormatter(**formatter_options, **log_keys) self.registered_handler.setFormatter(formatter) # when using a custom Powertools for AWS Lambda (Python) Formatter # standard and custom keys that are not Powertools for AWS Lambda (Python) Formatter parameters # should be appended and custom keys that might happen to be Powertools for AWS Lambda (Python) # Formatter parameters should be discarded this prevents adding them as custom keys, for example, # `json_default=<callable>` see https://github.com/aws-powertools/powertools-lambda-python/issues/1263 custom_keys = {k: v for k, v in log_keys.items() if k not in RESERVED_FORMATTER_CUSTOM_KEYS} return self.registered_formatter.append_keys(**custom_keys) # Mode 2 (legacy) if append: # Maintenance: Add deprecation warning for major version return self.append_keys(**keys) # Mode 3 self.registered_formatter.clear_state() self.registered_formatter.append_keys(**log_keys) def set_correlation_id(self, value: Optional[str]) -> None: """Sets the correlation_id in the logging json Parameters ---------- value : str, optional Value for the correlation id. None will remove the correlation_id """ self.append_keys(correlation_id=value) def get_correlation_id(self) -> Optional[str]: """Gets the correlation_id in the logging json Returns ------- str, optional Value for the correlation id """ if isinstance(self.registered_formatter, LambdaPowertoolsFormatter): return self.registered_formatter.log_format.get("correlation_id") return None def setLevel(self, level: Union[str, int, None]) -> None: return self._logger.setLevel(self._determine_log_level(level)) def addHandler(self, handler: logging.Handler) -> None: return self._logger.addHandler(handler) def addFilter(self, filter: logging._FilterType) -> None: # noqa: A002 # filter built-in usage return self._logger.addFilter(filter) def removeFilter(self, filter: logging._FilterType) -> None: # noqa: A002 # filter built-in usage return self._logger.removeFilter(filter) def registered_handler(self) -> logging.Handler: """Convenience property to access the first logger handler""" # We ignore mypy here because self.child encodes whether or not self._logger.parent is # None, mypy can't see this from context but we can handlers = self._logger.parent.handlers if self.child else self._logger.handlers # type: ignore[union-attr] return handlers[0] def registered_formatter(self) -> BasePowertoolsFormatter: """Convenience property to access the first logger formatter""" return self.registered_handler.formatter # type: ignore[return-value] def log_level(self) -> int: return self._logger.level def name(self) -> str: return self._logger.name def handlers(self) -> List[logging.Handler]: """List of registered logging handlers Notes ----- Looking for the first configured handler? Use registered_handler property instead. """ return self._logger.handlers def _get_aws_lambda_log_level(self) -> Optional[str]: """ Retrieve the log level for AWS Lambda from the Advanced Logging Controls feature. Returns: Optional[str]: The corresponding logging level. """ return constants.LAMBDA_ADVANCED_LOGGING_LEVELS.get(os.getenv(constants.LAMBDA_LOG_LEVEL_ENV)) def _get_powertools_log_level(self, level: Union[str, int, None]) -> Optional[str]: """Retrieve the log level for Powertools from the environment variable or level parameter. If log level is an integer, we convert to its respective string level `logging.getLevelName()`. If no log level is provided, we check env vars for the log level: POWERTOOLS_LOG_LEVEL_ENV and POWERTOOLS_LOG_LEVEL_LEGACY_ENV. Parameters: ----------- level : Union[str, int, None] The specified log level as a string, integer, or None. Environment variables --------------------- POWERTOOLS_LOG_LEVEL : str log level (e.g: INFO, DEBUG, WARNING, ERROR, CRITICAL) LOG_LEVEL (Legacy) : str log level (e.g: INFO, DEBUG, WARNING, ERROR, CRITICAL) Returns: -------- Optional[str]: The corresponding logging level. Returns None if the log level is not explicitly specified. """ # noqa E501 # Extract log level from Powertools Logger env vars log_level_env = os.getenv(constants.POWERTOOLS_LOG_LEVEL_ENV) or os.getenv( constants.POWERTOOLS_LOG_LEVEL_LEGACY_ENV, ) # If level is an int (logging.INFO), return its respective string ("INFO") if isinstance(level, int): return logging.getLevelName(level) return level or log_level_env def _determine_log_level(self, level: Union[str, int, None]) -> Union[str, int]: """Determine the effective log level considering Lambda and Powertools preferences. It emits an UserWarning if Lambda ALC log level is lower than Logger log level. Parameters: ----------- level: Union[str, int, None] The specified log level as a string, integer, or None. Returns: ---------- Union[str, int]: The effective logging level. """ # This function consider the following order of precedence: # 1 - If a log level is set using AWS Lambda Advanced Logging Controls, it sets it. # 2 - If a log level is passed to the constructor, it sets it # 3 - If a log level is set via setLevel, it sets it. # 4 - If a log level is set via Powertools env variables, it sets it. # 5 - If none of the above is true, the default log level applies INFO. lambda_log_level = self._get_aws_lambda_log_level() powertools_log_level = self._get_powertools_log_level(level) if powertools_log_level and lambda_log_level: # If Powertools log level is set and higher than AWS Lambda Advanced Logging Controls, emit a warning if logging.getLevelName(lambda_log_level) > logging.getLevelName(powertools_log_level): warnings.warn( f"Current log level ({powertools_log_level}) does not match AWS Lambda Advanced Logging Controls " f"minimum log level ({lambda_log_level}). This can lead to data loss, consider adjusting them.", UserWarning, stacklevel=2, ) # AWS Lambda Advanced Logging Controls takes precedence over Powertools log level and we use this if lambda_log_level: return lambda_log_level # Check if Powertools log level is None, which means it's not set # We assume INFO as the default log level if powertools_log_level is None: return logging.INFO # Powertools log level is set, we use this return powertools_log_level.upper() The provided code snippet includes necessary dependencies for implementing the `log_uncaught_exception_hook` function. Write a Python function `def log_uncaught_exception_hook(exc_type, exc_value, exc_traceback, logger: Logger) -> None` to solve the following problem: Callback function for sys.excepthook to use Logger to log uncaught exceptions Here is the function: def log_uncaught_exception_hook(exc_type, exc_value, exc_traceback, logger: Logger) -> None: """Callback function for sys.excepthook to use Logger to log uncaught exceptions""" logger.exception(exc_value, exc_info=(exc_type, exc_value, exc_traceback)) # pragma: no cover
Callback function for sys.excepthook to use Logger to log uncaught exceptions
5,019
from __future__ import annotations import functools import inspect import logging import os import random import sys import warnings from typing import ( IO, TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Mapping, Optional, TypeVar, Union, overload, ) from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( extract_event_from_common_models, resolve_env_var_choice, resolve_truthy_env_var_choice, ) from aws_lambda_powertools.utilities import jmespath_utils from ..shared.types import AnyCallableT from .exceptions import InvalidLoggerSamplingRateError from .filters import SuppressFilter from .formatter import ( RESERVED_FORMATTER_CUSTOM_KEYS, BasePowertoolsFormatter, LambdaPowertoolsFormatter, ) from .lambda_context import build_lambda_context_model The provided code snippet includes necessary dependencies for implementing the `_get_caller_filename` function. Write a Python function `def _get_caller_filename() -> str` to solve the following problem: Return caller filename by finding the caller frame Here is the function: def _get_caller_filename() -> str: """Return caller filename by finding the caller frame""" # Current frame => _get_logger() # Previous frame => logger.py # Before previous frame => Caller # We ignore mypy here because *we* know that there will always be at least # 3 frames (above) so repeatedly calling f_back is safe here frame = inspect.currentframe() caller_frame = frame.f_back.f_back.f_back # type: ignore[union-attr] return caller_frame.f_globals["__name__"] # type: ignore[union-attr]
Return caller filename by finding the caller frame
5,020
import logging from aws_lambda_powertools.logging.logger import set_package_logger from aws_lambda_powertools.shared.functions import powertools_debug_is_set def set_package_logger( level: Union[str, int] = logging.DEBUG, stream: Optional[IO[str]] = None, formatter: Optional[logging.Formatter] = None, ) -> None: """Set an additional stream handler, formatter, and log level for aws_lambda_powertools package logger. **Package log by default is suppressed (NullHandler), this should only used for debugging. This is separate from application Logger class utility** Example ------- **Enables debug logging for Powertools for AWS Lambda (Python) package** >>> aws_lambda_powertools.logging.logger import set_package_logger >>> set_package_logger() Parameters ---------- level: str, int log level, DEBUG by default stream: sys.stdout log stream, stdout by default formatter: logging.Formatter log formatter, "%(asctime)s %(name)s [%(levelname)s] %(message)s" by default """ if formatter is None: formatter = logging.Formatter("%(asctime)s %(name)s [%(levelname)s] %(message)s") if stream is None: stream = sys.stdout logger = logging.getLogger("aws_lambda_powertools") logger.setLevel(level) handler = logging.StreamHandler(stream) handler.setFormatter(formatter) logger.addHandler(handler) def powertools_debug_is_set() -> bool: is_on = strtobool(os.getenv(constants.POWERTOOLS_DEBUG_ENV, "0")) if is_on: warnings.warn("POWERTOOLS_DEBUG environment variable is enabled. Setting logging level to DEBUG.", stacklevel=2) return True return False The provided code snippet includes necessary dependencies for implementing the `set_package_logger_handler` function. Write a Python function `def set_package_logger_handler(stream=None)` to solve the following problem: Sets up Powertools for AWS Lambda (Python) package logging. By default, we discard any output to not interfere with customers logging. When POWERTOOLS_DEBUG env var is set, we setup `aws_lambda_powertools` logger in DEBUG level. Parameters ---------- stream: sys.stdout log stream, stdout by default Here is the function: def set_package_logger_handler(stream=None): """Sets up Powertools for AWS Lambda (Python) package logging. By default, we discard any output to not interfere with customers logging. When POWERTOOLS_DEBUG env var is set, we setup `aws_lambda_powertools` logger in DEBUG level. Parameters ---------- stream: sys.stdout log stream, stdout by default """ if powertools_debug_is_set(): return set_package_logger(stream=stream) logger = logging.getLogger("aws_lambda_powertools") logger.addHandler(logging.NullHandler()) logger.propagate = False
Sets up Powertools for AWS Lambda (Python) package logging. By default, we discard any output to not interfere with customers logging. When POWERTOOLS_DEBUG env var is set, we setup `aws_lambda_powertools` logger in DEBUG level. Parameters ---------- stream: sys.stdout log stream, stdout by default
5,021
from __future__ import annotations from aws_lambda_powertools.metrics.provider.cloudwatch_emf.exceptions import ( MetricResolutionError, MetricUnitError, ) from aws_lambda_powertools.metrics.provider.cloudwatch_emf.metric_properties import MetricResolution, MetricUnit from aws_lambda_powertools.shared.types import List class MetricResolutionError(Exception): """When metric resolution is not supported by CloudWatch""" pass class MetricResolution(Enum): Standard = 60 High = 1 The provided code snippet includes necessary dependencies for implementing the `extract_cloudwatch_metric_resolution_value` function. Write a Python function `def extract_cloudwatch_metric_resolution_value(metric_resolutions: List, resolution: int | MetricResolution) -> int` to solve the following problem: Return metric value from CloudWatch metric unit whether that's str or MetricResolution enum Parameters ---------- unit : Union[int, MetricResolution] Metric resolution Returns ------- int Metric resolution value must be 1 or 60 Raises ------ MetricResolutionError When metric resolution is not supported by CloudWatch Here is the function: def extract_cloudwatch_metric_resolution_value(metric_resolutions: List, resolution: int | MetricResolution) -> int: """Return metric value from CloudWatch metric unit whether that's str or MetricResolution enum Parameters ---------- unit : Union[int, MetricResolution] Metric resolution Returns ------- int Metric resolution value must be 1 or 60 Raises ------ MetricResolutionError When metric resolution is not supported by CloudWatch """ if isinstance(resolution, MetricResolution): return resolution.value if isinstance(resolution, int) and resolution in metric_resolutions: return resolution raise MetricResolutionError( f"Invalid metric resolution '{resolution}', expected either option: {metric_resolutions}", # noqa: E501 )
Return metric value from CloudWatch metric unit whether that's str or MetricResolution enum Parameters ---------- unit : Union[int, MetricResolution] Metric resolution Returns ------- int Metric resolution value must be 1 or 60 Raises ------ MetricResolutionError When metric resolution is not supported by CloudWatch
5,022
from __future__ import annotations from aws_lambda_powertools.metrics.provider.cloudwatch_emf.exceptions import ( MetricResolutionError, MetricUnitError, ) from aws_lambda_powertools.metrics.provider.cloudwatch_emf.metric_properties import MetricResolution, MetricUnit from aws_lambda_powertools.shared.types import List class MetricUnitError(Exception): """When metric unit is not supported by CloudWatch""" pass class MetricUnit(Enum): Seconds = "Seconds" Microseconds = "Microseconds" Milliseconds = "Milliseconds" Bytes = "Bytes" Kilobytes = "Kilobytes" Megabytes = "Megabytes" Gigabytes = "Gigabytes" Terabytes = "Terabytes" Bits = "Bits" Kilobits = "Kilobits" Megabits = "Megabits" Gigabits = "Gigabits" Terabits = "Terabits" Percent = "Percent" Count = "Count" BytesPerSecond = "Bytes/Second" KilobytesPerSecond = "Kilobytes/Second" MegabytesPerSecond = "Megabytes/Second" GigabytesPerSecond = "Gigabytes/Second" TerabytesPerSecond = "Terabytes/Second" BitsPerSecond = "Bits/Second" KilobitsPerSecond = "Kilobits/Second" MegabitsPerSecond = "Megabits/Second" GigabitsPerSecond = "Gigabits/Second" TerabitsPerSecond = "Terabits/Second" CountPerSecond = "Count/Second" The provided code snippet includes necessary dependencies for implementing the `extract_cloudwatch_metric_unit_value` function. Write a Python function `def extract_cloudwatch_metric_unit_value(metric_units: List, metric_valid_options: List, unit: str | MetricUnit) -> str` to solve the following problem: Return metric value from CloudWatch metric unit whether that's str or MetricUnit enum Parameters ---------- unit : Union[str, MetricUnit] Metric unit Returns ------- str Metric unit value (e.g. "Seconds", "Count/Second") Raises ------ MetricUnitError When metric unit is not supported by CloudWatch Here is the function: def extract_cloudwatch_metric_unit_value(metric_units: List, metric_valid_options: List, unit: str | MetricUnit) -> str: """Return metric value from CloudWatch metric unit whether that's str or MetricUnit enum Parameters ---------- unit : Union[str, MetricUnit] Metric unit Returns ------- str Metric unit value (e.g. "Seconds", "Count/Second") Raises ------ MetricUnitError When metric unit is not supported by CloudWatch """ if isinstance(unit, str): if unit in metric_valid_options: unit = MetricUnit[unit].value if unit not in metric_units: raise MetricUnitError( f"Invalid metric unit '{unit}', expected either option: {metric_valid_options}", ) if isinstance(unit, MetricUnit): unit = unit.value return unit
Return metric value from CloudWatch metric unit whether that's str or MetricUnit enum Parameters ---------- unit : Union[str, MetricUnit] Metric unit Returns ------- str Metric unit value (e.g. "Seconds", "Count/Second") Raises ------ MetricUnitError When metric unit is not supported by CloudWatch
5,023
from __future__ import annotations is_cold_start = True def reset_cold_start_flag(): global is_cold_start if not is_cold_start: is_cold_start = True
null
5,024
from __future__ import annotations import functools import logging from abc import ABC, abstractmethod from typing import Any from aws_lambda_powertools.metrics.provider import cold_start from aws_lambda_powertools.shared.types import AnyCallableT from aws_lambda_powertools.utilities.typing import LambdaContext def reset_cold_start_flag_provider(): if not cold_start.is_cold_start: cold_start.is_cold_start = True
null
5,025
from __future__ import annotations import datetime import functools import json import logging import numbers import os import warnings from collections import defaultdict from contextlib import contextmanager from typing import Any, Callable, Dict, Generator, List, Optional, Union from aws_lambda_powertools.metrics.exceptions import ( MetricResolutionError, MetricUnitError, MetricValueError, SchemaValidationError, ) from aws_lambda_powertools.metrics.provider import cold_start from aws_lambda_powertools.metrics.provider.cloudwatch_emf.constants import MAX_DIMENSIONS, MAX_METRICS from aws_lambda_powertools.metrics.provider.cloudwatch_emf.metric_properties import MetricResolution, MetricUnit from aws_lambda_powertools.metrics.provider.cold_start import ( reset_cold_start_flag, # noqa: F401 # backwards compatibility ) from aws_lambda_powertools.metrics.types import MetricNameUnitResolution from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import resolve_env_var_choice class SingleMetric(MetricManager): """SingleMetric creates an EMF object with a single metric. EMF specification doesn't allow metrics with different dimensions. SingleMetric overrides MetricManager's add_metric method to do just that. Use `single_metric` when you need to create metrics with different dimensions, otherwise `aws_lambda_powertools.metrics.metrics.Metrics` is a more cost effective option Environment variables --------------------- POWERTOOLS_METRICS_NAMESPACE : str metric namespace Example ------- **Creates cold start metric with function_version as dimension** import json from aws_lambda_powertools.metrics import single_metric, MetricUnit, MetricResolution metric = single_metric(namespace="ServerlessAirline") metric.add_metric(name="ColdStart", unit=MetricUnit.Count, value=1, resolution=MetricResolution.Standard) metric.add_dimension(name="function_version", value=47) print(json.dumps(metric.serialize_metric_set(), indent=4)) Parameters ---------- MetricManager : MetricManager Inherits from `aws_lambda_powertools.metrics.base.MetricManager` """ def add_metric( self, name: str, unit: MetricUnit | str, value: float, resolution: MetricResolution | int = 60, ) -> None: """Method to prevent more than one metric being created Parameters ---------- name : str Metric name (e.g. BookingConfirmation) unit : MetricUnit Metric unit (e.g. "Seconds", MetricUnit.Seconds) value : float Metric value resolution : MetricResolution Metric resolution (e.g. 60, MetricResolution.Standard) """ if len(self.metric_set) > 0: logger.debug(f"Metric {name} already set, skipping...") return return super().add_metric(name, unit, value, resolution) class MetricUnit(Enum): Seconds = "Seconds" Microseconds = "Microseconds" Milliseconds = "Milliseconds" Bytes = "Bytes" Kilobytes = "Kilobytes" Megabytes = "Megabytes" Gigabytes = "Gigabytes" Terabytes = "Terabytes" Bits = "Bits" Kilobits = "Kilobits" Megabits = "Megabits" Gigabits = "Gigabits" Terabits = "Terabits" Percent = "Percent" Count = "Count" BytesPerSecond = "Bytes/Second" KilobytesPerSecond = "Kilobytes/Second" MegabytesPerSecond = "Megabytes/Second" GigabytesPerSecond = "Gigabytes/Second" TerabytesPerSecond = "Terabytes/Second" BitsPerSecond = "Bits/Second" KilobitsPerSecond = "Kilobits/Second" MegabitsPerSecond = "Megabits/Second" GigabitsPerSecond = "Gigabits/Second" TerabitsPerSecond = "Terabits/Second" CountPerSecond = "Count/Second" class MetricResolution(Enum): Standard = 60 High = 1 The provided code snippet includes necessary dependencies for implementing the `single_metric` function. Write a Python function `def single_metric( name: str, unit: MetricUnit, value: float, resolution: MetricResolution | int = 60, namespace: str | None = None, default_dimensions: Dict[str, str] | None = None, ) -> Generator[SingleMetric, None, None]` to solve the following problem: Context manager to simplify creation of a single metric Example ------- **Creates cold start metric with function_version as dimension** from aws_lambda_powertools import single_metric from aws_lambda_powertools.metrics import MetricUnit from aws_lambda_powertools.metrics import MetricResolution with single_metric(name="ColdStart", unit=MetricUnit.Count, value=1, resolution=MetricResolution.Standard, namespace="ServerlessAirline") as metric: metric.add_dimension(name="function_version", value="47") **Same as above but set namespace using environment variable** $ export POWERTOOLS_METRICS_NAMESPACE="ServerlessAirline" from aws_lambda_powertools import single_metric from aws_lambda_powertools.metrics import MetricUnit from aws_lambda_powertools.metrics import MetricResolution with single_metric(name="ColdStart", unit=MetricUnit.Count, value=1, resolution=MetricResolution.Standard) as metric: metric.add_dimension(name="function_version", value="47") Parameters ---------- name : str Metric name unit : MetricUnit `aws_lambda_powertools.helper.models.MetricUnit` resolution : MetricResolution `aws_lambda_powertools.helper.models.MetricResolution` value : float Metric value namespace: str Namespace for metrics Yields ------- SingleMetric SingleMetric class instance Raises ------ MetricUnitError When metric metric isn't supported by CloudWatch MetricResolutionError When metric resolution isn't supported by CloudWatch MetricValueError When metric value isn't a number SchemaValidationError When metric object fails EMF schema validation Here is the function: def single_metric( name: str, unit: MetricUnit, value: float, resolution: MetricResolution | int = 60, namespace: str | None = None, default_dimensions: Dict[str, str] | None = None, ) -> Generator[SingleMetric, None, None]: """Context manager to simplify creation of a single metric Example ------- **Creates cold start metric with function_version as dimension** from aws_lambda_powertools import single_metric from aws_lambda_powertools.metrics import MetricUnit from aws_lambda_powertools.metrics import MetricResolution with single_metric(name="ColdStart", unit=MetricUnit.Count, value=1, resolution=MetricResolution.Standard, namespace="ServerlessAirline") as metric: metric.add_dimension(name="function_version", value="47") **Same as above but set namespace using environment variable** $ export POWERTOOLS_METRICS_NAMESPACE="ServerlessAirline" from aws_lambda_powertools import single_metric from aws_lambda_powertools.metrics import MetricUnit from aws_lambda_powertools.metrics import MetricResolution with single_metric(name="ColdStart", unit=MetricUnit.Count, value=1, resolution=MetricResolution.Standard) as metric: metric.add_dimension(name="function_version", value="47") Parameters ---------- name : str Metric name unit : MetricUnit `aws_lambda_powertools.helper.models.MetricUnit` resolution : MetricResolution `aws_lambda_powertools.helper.models.MetricResolution` value : float Metric value namespace: str Namespace for metrics Yields ------- SingleMetric SingleMetric class instance Raises ------ MetricUnitError When metric metric isn't supported by CloudWatch MetricResolutionError When metric resolution isn't supported by CloudWatch MetricValueError When metric value isn't a number SchemaValidationError When metric object fails EMF schema validation """ # noqa: E501 metric_set: Dict | None = None try: metric: SingleMetric = SingleMetric(namespace=namespace) metric.add_metric(name=name, unit=unit, value=value, resolution=resolution) if default_dimensions: for dim_name, dim_value in default_dimensions.items(): metric.add_dimension(name=dim_name, value=dim_value) yield metric metric_set = metric.serialize_metric_set() finally: print(json.dumps(metric_set, separators=(",", ":")))
Context manager to simplify creation of a single metric Example ------- **Creates cold start metric with function_version as dimension** from aws_lambda_powertools import single_metric from aws_lambda_powertools.metrics import MetricUnit from aws_lambda_powertools.metrics import MetricResolution with single_metric(name="ColdStart", unit=MetricUnit.Count, value=1, resolution=MetricResolution.Standard, namespace="ServerlessAirline") as metric: metric.add_dimension(name="function_version", value="47") **Same as above but set namespace using environment variable** $ export POWERTOOLS_METRICS_NAMESPACE="ServerlessAirline" from aws_lambda_powertools import single_metric from aws_lambda_powertools.metrics import MetricUnit from aws_lambda_powertools.metrics import MetricResolution with single_metric(name="ColdStart", unit=MetricUnit.Count, value=1, resolution=MetricResolution.Standard) as metric: metric.add_dimension(name="function_version", value="47") Parameters ---------- name : str Metric name unit : MetricUnit `aws_lambda_powertools.helper.models.MetricUnit` resolution : MetricResolution `aws_lambda_powertools.helper.models.MetricResolution` value : float Metric value namespace: str Namespace for metrics Yields ------- SingleMetric SingleMetric class instance Raises ------ MetricUnitError When metric metric isn't supported by CloudWatch MetricResolutionError When metric resolution isn't supported by CloudWatch MetricValueError When metric value isn't a number SchemaValidationError When metric object fails EMF schema validation
5,026
from __future__ import annotations from typing import Any, Awaitable, Callable, Dict, List from aws_lambda_powertools.middleware_factory import lambda_handler_decorator from aws_lambda_powertools.utilities.batch import ( AsyncBatchProcessor, BasePartialBatchProcessor, BatchProcessor, EventType, ) from aws_lambda_powertools.utilities.batch.types import PartialItemFailureResponse from aws_lambda_powertools.utilities.typing import LambdaContext The provided code snippet includes necessary dependencies for implementing the `async_batch_processor` function. Write a Python function `def async_batch_processor( handler: Callable, event: Dict, context: LambdaContext, record_handler: Callable[..., Awaitable[Any]], processor: AsyncBatchProcessor, )` to solve the following problem: Middleware to handle batch event processing Notes ----- Consider using async_process_partial_response function for an easier experience. Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: LambdaContext Lambda's Context record_handler: Callable[..., Awaitable[Any]] Callable to process each record from the batch processor: AsyncBatchProcessor Batch Processor to handle partial failure cases Examples -------- **Processes Lambda's event with a BasePartialProcessor** >>> from aws_lambda_powertools.utilities.batch import async_batch_processor, AsyncBatchProcessor >>> from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord >>> >>> processor = AsyncBatchProcessor(event_type=EventType.SQS) >>> >>> async def async_record_handler(record: SQSRecord): >>> payload: str = record.body >>> return payload >>> >>> @async_batch_processor(record_handler=async_record_handler, processor=processor) >>> def lambda_handler(event, context): >>> return processor.response() Limitations ----------- * Sync batch processors. Use `batch_processor` instead. Here is the function: def async_batch_processor( handler: Callable, event: Dict, context: LambdaContext, record_handler: Callable[..., Awaitable[Any]], processor: AsyncBatchProcessor, ): """ Middleware to handle batch event processing Notes ----- Consider using async_process_partial_response function for an easier experience. Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: LambdaContext Lambda's Context record_handler: Callable[..., Awaitable[Any]] Callable to process each record from the batch processor: AsyncBatchProcessor Batch Processor to handle partial failure cases Examples -------- **Processes Lambda's event with a BasePartialProcessor** >>> from aws_lambda_powertools.utilities.batch import async_batch_processor, AsyncBatchProcessor >>> from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord >>> >>> processor = AsyncBatchProcessor(event_type=EventType.SQS) >>> >>> async def async_record_handler(record: SQSRecord): >>> payload: str = record.body >>> return payload >>> >>> @async_batch_processor(record_handler=async_record_handler, processor=processor) >>> def lambda_handler(event, context): >>> return processor.response() Limitations ----------- * Sync batch processors. Use `batch_processor` instead. """ records = event["Records"] with processor(records, record_handler, lambda_context=context): processor.async_process() return handler(event, context)
Middleware to handle batch event processing Notes ----- Consider using async_process_partial_response function for an easier experience. Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: LambdaContext Lambda's Context record_handler: Callable[..., Awaitable[Any]] Callable to process each record from the batch processor: AsyncBatchProcessor Batch Processor to handle partial failure cases Examples -------- **Processes Lambda's event with a BasePartialProcessor** >>> from aws_lambda_powertools.utilities.batch import async_batch_processor, AsyncBatchProcessor >>> from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord >>> >>> processor = AsyncBatchProcessor(event_type=EventType.SQS) >>> >>> async def async_record_handler(record: SQSRecord): >>> payload: str = record.body >>> return payload >>> >>> @async_batch_processor(record_handler=async_record_handler, processor=processor) >>> def lambda_handler(event, context): >>> return processor.response() Limitations ----------- * Sync batch processors. Use `batch_processor` instead.
5,027
from __future__ import annotations from typing import Any, Awaitable, Callable, Dict, List from aws_lambda_powertools.middleware_factory import lambda_handler_decorator from aws_lambda_powertools.utilities.batch import ( AsyncBatchProcessor, BasePartialBatchProcessor, BatchProcessor, EventType, ) from aws_lambda_powertools.utilities.batch.types import PartialItemFailureResponse from aws_lambda_powertools.utilities.typing import LambdaContext The provided code snippet includes necessary dependencies for implementing the `batch_processor` function. Write a Python function `def batch_processor( handler: Callable, event: Dict, context: LambdaContext, record_handler: Callable, processor: BatchProcessor, )` to solve the following problem: Middleware to handle batch event processing Notes ----- Consider using process_partial_response function for an easier experience. Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: LambdaContext Lambda's Context record_handler: Callable Callable or corutine to process each record from the batch processor: BatchProcessor Batch Processor to handle partial failure cases Examples -------- **Processes Lambda's event with a BatchProcessor** >>> from aws_lambda_powertools.utilities.batch import batch_processor, BatchProcessor, EventType >>> from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord >>> >>> processor = BatchProcessor(EventType.SQS) >>> >>> def record_handler(record): >>> return record["body"] >>> >>> @batch_processor(record_handler=record_handler, processor=BatchProcessor()) >>> def handler(event, context): >>> return processor.response() Limitations ----------- * Async batch processors. Use `async_batch_processor` instead. Here is the function: def batch_processor( handler: Callable, event: Dict, context: LambdaContext, record_handler: Callable, processor: BatchProcessor, ): """ Middleware to handle batch event processing Notes ----- Consider using process_partial_response function for an easier experience. Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: LambdaContext Lambda's Context record_handler: Callable Callable or corutine to process each record from the batch processor: BatchProcessor Batch Processor to handle partial failure cases Examples -------- **Processes Lambda's event with a BatchProcessor** >>> from aws_lambda_powertools.utilities.batch import batch_processor, BatchProcessor, EventType >>> from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord >>> >>> processor = BatchProcessor(EventType.SQS) >>> >>> def record_handler(record): >>> return record["body"] >>> >>> @batch_processor(record_handler=record_handler, processor=BatchProcessor()) >>> def handler(event, context): >>> return processor.response() Limitations ----------- * Async batch processors. Use `async_batch_processor` instead. """ records = event["Records"] with processor(records, record_handler, lambda_context=context): processor.process() return handler(event, context)
Middleware to handle batch event processing Notes ----- Consider using process_partial_response function for an easier experience. Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: LambdaContext Lambda's Context record_handler: Callable Callable or corutine to process each record from the batch processor: BatchProcessor Batch Processor to handle partial failure cases Examples -------- **Processes Lambda's event with a BatchProcessor** >>> from aws_lambda_powertools.utilities.batch import batch_processor, BatchProcessor, EventType >>> from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord >>> >>> processor = BatchProcessor(EventType.SQS) >>> >>> def record_handler(record): >>> return record["body"] >>> >>> @batch_processor(record_handler=record_handler, processor=BatchProcessor()) >>> def handler(event, context): >>> return processor.response() Limitations ----------- * Async batch processors. Use `async_batch_processor` instead.
5,028
from __future__ import annotations from typing import Any, Awaitable, Callable, Dict, List from aws_lambda_powertools.middleware_factory import lambda_handler_decorator from aws_lambda_powertools.utilities.batch import ( AsyncBatchProcessor, BasePartialBatchProcessor, BatchProcessor, EventType, ) from aws_lambda_powertools.utilities.batch.types import PartialItemFailureResponse from aws_lambda_powertools.utilities.typing import LambdaContext class PartialItemFailureResponse(TypedDict): batchItemFailures: List[PartialItemFailures] The provided code snippet includes necessary dependencies for implementing the `process_partial_response` function. Write a Python function `def process_partial_response( event: Dict, record_handler: Callable, processor: BasePartialBatchProcessor, context: LambdaContext | None = None, ) -> PartialItemFailureResponse` to solve the following problem: Higher level function to handle batch event processing. Parameters ---------- event: Dict Lambda's original event record_handler: Callable Callable to process each record from the batch processor: BasePartialBatchProcessor Batch Processor to handle partial failure cases context: LambdaContext Lambda's context, used to optionally inject in record handler Returns ------- result: PartialItemFailureResponse Lambda Partial Batch Response Examples -------- **Processes Lambda's SQS event** ```python from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType, process_partial_response from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord processor = BatchProcessor(EventType.SQS) def record_handler(record: SQSRecord): return record.body def handler(event, context): return process_partial_response( event=event, record_handler=record_handler, processor=processor, context=context ) ``` Limitations ----------- * Async batch processors. Use `async_process_partial_response` instead. Here is the function: def process_partial_response( event: Dict, record_handler: Callable, processor: BasePartialBatchProcessor, context: LambdaContext | None = None, ) -> PartialItemFailureResponse: """ Higher level function to handle batch event processing. Parameters ---------- event: Dict Lambda's original event record_handler: Callable Callable to process each record from the batch processor: BasePartialBatchProcessor Batch Processor to handle partial failure cases context: LambdaContext Lambda's context, used to optionally inject in record handler Returns ------- result: PartialItemFailureResponse Lambda Partial Batch Response Examples -------- **Processes Lambda's SQS event** ```python from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType, process_partial_response from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord processor = BatchProcessor(EventType.SQS) def record_handler(record: SQSRecord): return record.body def handler(event, context): return process_partial_response( event=event, record_handler=record_handler, processor=processor, context=context ) ``` Limitations ----------- * Async batch processors. Use `async_process_partial_response` instead. """ try: records: List[Dict] = event.get("Records", []) except AttributeError: event_types = ", ".join(list(EventType.__members__)) docs = "https://docs.powertools.aws.dev/lambda/python/latest/utilities/batch/#processing-messages-from-sqs" # noqa: E501 # long-line raise ValueError( f"Invalid event format. Please ensure batch event is a valid {processor.event_type.value} event. \n" f"See sample events in our documentation for either {event_types}: \n {docs}", ) with processor(records, record_handler, context): processor.process() return processor.response()
Higher level function to handle batch event processing. Parameters ---------- event: Dict Lambda's original event record_handler: Callable Callable to process each record from the batch processor: BasePartialBatchProcessor Batch Processor to handle partial failure cases context: LambdaContext Lambda's context, used to optionally inject in record handler Returns ------- result: PartialItemFailureResponse Lambda Partial Batch Response Examples -------- **Processes Lambda's SQS event** ```python from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType, process_partial_response from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord processor = BatchProcessor(EventType.SQS) def record_handler(record: SQSRecord): return record.body def handler(event, context): return process_partial_response( event=event, record_handler=record_handler, processor=processor, context=context ) ``` Limitations ----------- * Async batch processors. Use `async_process_partial_response` instead.
5,029
from __future__ import annotations from typing import Any, Awaitable, Callable, Dict, List from aws_lambda_powertools.middleware_factory import lambda_handler_decorator from aws_lambda_powertools.utilities.batch import ( AsyncBatchProcessor, BasePartialBatchProcessor, BatchProcessor, EventType, ) from aws_lambda_powertools.utilities.batch.types import PartialItemFailureResponse from aws_lambda_powertools.utilities.typing import LambdaContext class PartialItemFailureResponse(TypedDict): batchItemFailures: List[PartialItemFailures] The provided code snippet includes necessary dependencies for implementing the `async_process_partial_response` function. Write a Python function `def async_process_partial_response( event: Dict, record_handler: Callable, processor: AsyncBatchProcessor, context: LambdaContext | None = None, ) -> PartialItemFailureResponse` to solve the following problem: Higher level function to handle batch event processing asynchronously. Parameters ---------- event: Dict Lambda's original event record_handler: Callable Callable to process each record from the batch processor: AsyncBatchProcessor Batch Processor to handle partial failure cases context: LambdaContext Lambda's context, used to optionally inject in record handler Returns ------- result: PartialItemFailureResponse Lambda Partial Batch Response Examples -------- **Processes Lambda's SQS event** ```python from aws_lambda_powertools.utilities.batch import AsyncBatchProcessor, EventType, process_partial_response from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord processor = BatchProcessor(EventType.SQS) async def record_handler(record: SQSRecord): return record.body def handler(event, context): return async_process_partial_response( event=event, record_handler=record_handler, processor=processor, context=context ) ``` Limitations ----------- * Sync batch processors. Use `process_partial_response` instead. Here is the function: def async_process_partial_response( event: Dict, record_handler: Callable, processor: AsyncBatchProcessor, context: LambdaContext | None = None, ) -> PartialItemFailureResponse: """ Higher level function to handle batch event processing asynchronously. Parameters ---------- event: Dict Lambda's original event record_handler: Callable Callable to process each record from the batch processor: AsyncBatchProcessor Batch Processor to handle partial failure cases context: LambdaContext Lambda's context, used to optionally inject in record handler Returns ------- result: PartialItemFailureResponse Lambda Partial Batch Response Examples -------- **Processes Lambda's SQS event** ```python from aws_lambda_powertools.utilities.batch import AsyncBatchProcessor, EventType, process_partial_response from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord processor = BatchProcessor(EventType.SQS) async def record_handler(record: SQSRecord): return record.body def handler(event, context): return async_process_partial_response( event=event, record_handler=record_handler, processor=processor, context=context ) ``` Limitations ----------- * Sync batch processors. Use `process_partial_response` instead. """ try: records: List[Dict] = event.get("Records", []) except AttributeError: event_types = ", ".join(list(EventType.__members__)) docs = "https://docs.powertools.aws.dev/lambda/python/latest/utilities/batch/#processing-messages-from-sqs" # noqa: E501 # long-line raise ValueError( f"Invalid event format. Please ensure batch event is a valid {processor.event_type.value} event. \n" f"See sample events in our documentation for either {event_types}: \n {docs}", ) with processor(records, record_handler, context): processor.async_process() return processor.response()
Higher level function to handle batch event processing asynchronously. Parameters ---------- event: Dict Lambda's original event record_handler: Callable Callable to process each record from the batch processor: AsyncBatchProcessor Batch Processor to handle partial failure cases context: LambdaContext Lambda's context, used to optionally inject in record handler Returns ------- result: PartialItemFailureResponse Lambda Partial Batch Response Examples -------- **Processes Lambda's SQS event** ```python from aws_lambda_powertools.utilities.batch import AsyncBatchProcessor, EventType, process_partial_response from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord processor = BatchProcessor(EventType.SQS) async def record_handler(record: SQSRecord): return record.body def handler(event, context): return async_process_partial_response( event=event, record_handler=record_handler, processor=processor, context=context ) ``` Limitations ----------- * Sync batch processors. Use `process_partial_response` instead.
5,030
import enum import re from typing import Any, Dict, List, Optional, overload from aws_lambda_powertools.utilities.data_classes.common import ( BaseRequestContext, BaseRequestContextV2, DictWrapper, ) from aws_lambda_powertools.utilities.data_classes.shared_functions import ( get_header_value, ) class APIGatewayRouteArn: """A parsed route arn""" def __init__( self, region: str, aws_account_id: str, api_id: str, stage: str, http_method: str, resource: str, partition: str = "aws", ): self.partition = partition self.region = region self.aws_account_id = aws_account_id self.api_id = api_id self.stage = stage self.http_method = http_method # Remove matching "/" from `resource`. self.resource = resource.lstrip("/") def arn(self) -> str: """Build an arn from its parts eg: arn:aws:execute-api:us-east-1:123456789012:abcdef123/test/GET/request""" return ( f"arn:{self.partition}:execute-api:{self.region}:{self.aws_account_id}:{self.api_id}/{self.stage}/" f"{self.http_method}/{self.resource}" ) The provided code snippet includes necessary dependencies for implementing the `parse_api_gateway_arn` function. Write a Python function `def parse_api_gateway_arn(arn: str) -> APIGatewayRouteArn` to solve the following problem: Parses a gateway route arn as a APIGatewayRouteArn class Parameters ---------- arn : str ARN string for a methodArn or a routeArn Returns ------- APIGatewayRouteArn Here is the function: def parse_api_gateway_arn(arn: str) -> APIGatewayRouteArn: """Parses a gateway route arn as a APIGatewayRouteArn class Parameters ---------- arn : str ARN string for a methodArn or a routeArn Returns ------- APIGatewayRouteArn """ arn_parts = arn.split(":") api_gateway_arn_parts = arn_parts[5].split("/") return APIGatewayRouteArn( partition=arn_parts[1], region=arn_parts[3], aws_account_id=arn_parts[4], api_id=api_gateway_arn_parts[0], stage=api_gateway_arn_parts[1], http_method=api_gateway_arn_parts[2], # conditional allow us to handle /path/{proxy+} resources, as their length changes. resource="/".join(api_gateway_arn_parts[3:]) if len(api_gateway_arn_parts) >= 4 else "", )
Parses a gateway route arn as a APIGatewayRouteArn class Parameters ---------- arn : str ARN string for a methodArn or a routeArn Returns ------- APIGatewayRouteArn
5,031
import datetime import time import uuid def _formatted_time(now: datetime.date, fmt: str, timezone_offset: int) -> str: """String formatted time with optional timezone offset Parameters ---------- now : datetime.date Current datetime with zero timezone offset fmt : str Data format before adding timezone offset timezone_offset : int Timezone offset in hours, defaults to 0 Returns ------- str Returns string formatted time with optional timezone offset """ if timezone_offset != 0: now = now + datetime.timedelta(hours=timezone_offset) datetime_str = now.strftime(fmt) if fmt.endswith(".%f"): datetime_str = datetime_str[:-3] if timezone_offset == 0: postfix = "Z" else: postfix = "+" if timezone_offset > 0 else "-" postfix += str(abs(timezone_offset)).zfill(2) postfix += ":00:00" return datetime_str + postfix The provided code snippet includes necessary dependencies for implementing the `aws_date` function. Write a Python function `def aws_date(timezone_offset: int = 0) -> str` to solve the following problem: AWSDate - An extended ISO 8601 date string in the format YYYY-MM-DD. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSDate scalar string with optional timezone offset Here is the function: def aws_date(timezone_offset: int = 0) -> str: """AWSDate - An extended ISO 8601 date string in the format YYYY-MM-DD. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSDate scalar string with optional timezone offset """ return _formatted_time(datetime.datetime.utcnow(), "%Y-%m-%d", timezone_offset)
AWSDate - An extended ISO 8601 date string in the format YYYY-MM-DD. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSDate scalar string with optional timezone offset
5,032
import datetime import time import uuid def _formatted_time(now: datetime.date, fmt: str, timezone_offset: int) -> str: """String formatted time with optional timezone offset Parameters ---------- now : datetime.date Current datetime with zero timezone offset fmt : str Data format before adding timezone offset timezone_offset : int Timezone offset in hours, defaults to 0 Returns ------- str Returns string formatted time with optional timezone offset """ if timezone_offset != 0: now = now + datetime.timedelta(hours=timezone_offset) datetime_str = now.strftime(fmt) if fmt.endswith(".%f"): datetime_str = datetime_str[:-3] if timezone_offset == 0: postfix = "Z" else: postfix = "+" if timezone_offset > 0 else "-" postfix += str(abs(timezone_offset)).zfill(2) postfix += ":00:00" return datetime_str + postfix The provided code snippet includes necessary dependencies for implementing the `aws_time` function. Write a Python function `def aws_time(timezone_offset: int = 0) -> str` to solve the following problem: AWSTime - An extended ISO 8601 time string in the format hh:mm:ss.sss. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSTime scalar string with optional timezone offset Here is the function: def aws_time(timezone_offset: int = 0) -> str: """AWSTime - An extended ISO 8601 time string in the format hh:mm:ss.sss. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSTime scalar string with optional timezone offset """ return _formatted_time(datetime.datetime.utcnow(), "%H:%M:%S.%f", timezone_offset)
AWSTime - An extended ISO 8601 time string in the format hh:mm:ss.sss. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSTime scalar string with optional timezone offset
5,033
import datetime import time import uuid def _formatted_time(now: datetime.date, fmt: str, timezone_offset: int) -> str: """String formatted time with optional timezone offset Parameters ---------- now : datetime.date Current datetime with zero timezone offset fmt : str Data format before adding timezone offset timezone_offset : int Timezone offset in hours, defaults to 0 Returns ------- str Returns string formatted time with optional timezone offset """ if timezone_offset != 0: now = now + datetime.timedelta(hours=timezone_offset) datetime_str = now.strftime(fmt) if fmt.endswith(".%f"): datetime_str = datetime_str[:-3] if timezone_offset == 0: postfix = "Z" else: postfix = "+" if timezone_offset > 0 else "-" postfix += str(abs(timezone_offset)).zfill(2) postfix += ":00:00" return datetime_str + postfix The provided code snippet includes necessary dependencies for implementing the `aws_datetime` function. Write a Python function `def aws_datetime(timezone_offset: int = 0) -> str` to solve the following problem: AWSDateTime - An extended ISO 8601 date and time string in the format YYYY-MM-DDThh:mm:ss.sssZ. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSDateTime scalar string with optional timezone offset Here is the function: def aws_datetime(timezone_offset: int = 0) -> str: """AWSDateTime - An extended ISO 8601 date and time string in the format YYYY-MM-DDThh:mm:ss.sssZ. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSDateTime scalar string with optional timezone offset """ return _formatted_time(datetime.datetime.utcnow(), "%Y-%m-%dT%H:%M:%S.%f", timezone_offset)
AWSDateTime - An extended ISO 8601 date and time string in the format YYYY-MM-DDThh:mm:ss.sssZ. Parameters ---------- timezone_offset : int Timezone offset, defaults to 0 Returns ------- str Returns current time as AWSDateTime scalar string with optional timezone offset
5,034
import datetime import time import uuid The provided code snippet includes necessary dependencies for implementing the `aws_timestamp` function. Write a Python function `def aws_timestamp() -> int` to solve the following problem: AWSTimestamp - An integer value representing the number of seconds before or after 1970-01-01-T00:00Z. Here is the function: def aws_timestamp() -> int: """AWSTimestamp - An integer value representing the number of seconds before or after 1970-01-01-T00:00Z.""" return int(time.time())
AWSTimestamp - An integer value representing the number of seconds before or after 1970-01-01-T00:00Z.
5,035
from typing import Any, Dict, List, Optional, Union from aws_lambda_powertools.utilities.data_classes.common import DictWrapper from aws_lambda_powertools.utilities.data_classes.shared_functions import ( get_header_value, ) class AppSyncIdentityIAM(DictWrapper): """AWS_IAM authorization""" def source_ip(self) -> List[str]: """The source IP address of the caller received by AWS AppSync.""" return self["sourceIp"] def username(self) -> str: """The username of the authenticated user. IAM user principal""" return self["username"] def account_id(self) -> str: """The AWS account ID of the caller.""" return self["accountId"] def cognito_identity_pool_id(self) -> str: """The Amazon Cognito identity pool ID associated with the caller.""" return self["cognitoIdentityPoolId"] def cognito_identity_id(self) -> str: """The Amazon Cognito identity ID of the caller.""" return self["cognitoIdentityId"] def user_arn(self) -> str: """The ARN of the IAM user.""" return self["userArn"] def cognito_identity_auth_type(self) -> str: """Either authenticated or unauthenticated based on the identity type.""" return self["cognitoIdentityAuthType"] def cognito_identity_auth_provider(self) -> str: """A comma separated list of external identity provider information used in obtaining the credentials used to sign the request.""" return self["cognitoIdentityAuthProvider"] class AppSyncIdentityCognito(DictWrapper): """AMAZON_COGNITO_USER_POOLS authorization""" def source_ip(self) -> List[str]: """The source IP address of the caller received by AWS AppSync.""" return self["sourceIp"] def username(self) -> str: """The username of the authenticated user.""" return self["username"] def sub(self) -> str: """The UUID of the authenticated user.""" return self["sub"] def claims(self) -> Dict[str, str]: """The claims that the user has.""" return self["claims"] def default_auth_strategy(self) -> str: """The default authorization strategy for this caller (ALLOW or DENY).""" return self["defaultAuthStrategy"] def groups(self) -> List[str]: """List of OIDC groups""" return self["groups"] def issuer(self) -> str: """The token issuer.""" return self["issuer"] The provided code snippet includes necessary dependencies for implementing the `get_identity_object` function. Write a Python function `def get_identity_object(identity: Optional[dict]) -> Any` to solve the following problem: Get the identity object based on the best detected type Here is the function: def get_identity_object(identity: Optional[dict]) -> Any: """Get the identity object based on the best detected type""" # API_KEY authorization if identity is None: return None # AMAZON_COGNITO_USER_POOLS authorization if "sub" in identity: return AppSyncIdentityCognito(identity) # AWS_IAM authorization return AppSyncIdentityIAM(identity)
Get the identity object based on the best detected type
5,036
from typing import Any, Callable, Dict, Type from aws_lambda_powertools.middleware_factory import lambda_handler_decorator from aws_lambda_powertools.utilities.data_classes.common import DictWrapper from aws_lambda_powertools.utilities.typing import LambdaContext class DictWrapper(Mapping): """Provides a single read only access to a wrapper dict""" def __init__(self, data: Dict[str, Any], json_deserializer: Optional[Callable] = None): """ Parameters ---------- data : Dict[str, Any] Lambda Event Source Event payload json_deserializer : Callable, optional function to deserialize `str`, `bytes`, `bytearray` containing a JSON document to a Python `obj`, by default json.loads """ self._data = data self._json_deserializer = json_deserializer or json.loads def __getitem__(self, key: str) -> Any: return self._data[key] def __eq__(self, other: object) -> bool: if not isinstance(other, DictWrapper): return False return self._data == other._data def __iter__(self) -> Iterator: return iter(self._data) def __len__(self) -> int: return len(self._data) def __str__(self) -> str: return str(self._str_helper()) def _str_helper(self) -> Dict[str, Any]: """ Recursively get a Dictionary of DictWrapper properties primarily for use by __str__ for debugging purposes. Will remove "raw_event" properties, and any defined by the Data Class `_sensitive_properties` list field. This should be used in case where secrets, such as access keys, are stored in the Data Class but should not be logged out. """ properties = self._properties() sensitive_properties = ["raw_event"] if hasattr(self, "_sensitive_properties"): sensitive_properties.extend(self._sensitive_properties) # pyright: ignore result: Dict[str, Any] = {} for property_key in properties: if property_key in sensitive_properties: result[property_key] = "[SENSITIVE]" else: try: property_value = getattr(self, property_key) result[property_key] = property_value # Checks whether the class is a subclass of the parent class to perform a recursive operation. if issubclass(property_value.__class__, DictWrapper): result[property_key] = property_value._str_helper() # Checks if the key is a list and if it is a subclass of the parent class elif isinstance(property_value, list): for seq, item in enumerate(property_value): if issubclass(item.__class__, DictWrapper): result[property_key][seq] = item._str_helper() except Exception: result[property_key] = "[Cannot be deserialized]" return result def _properties(self) -> List[str]: return [p for p in dir(self.__class__) if isinstance(getattr(self.__class__, p), property)] def get(self, key: str, default: Optional[Any] = None) -> Optional[Any]: return self._data.get(key, default) def raw_event(self) -> Dict[str, Any]: """The original raw event dict""" return self._data The provided code snippet includes necessary dependencies for implementing the `event_source` function. Write a Python function `def event_source( handler: Callable[[Any, LambdaContext], Any], event: Dict[str, Any], context: LambdaContext, data_class: Type[DictWrapper], )` to solve the following problem: Middleware to create an instance of the passed in event source data class Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: Dict Lambda's Context data_class: Type[DictWrapper] Data class type to instantiate Example -------- **Sample usage** from aws_lambda_powertools.utilities.data_classes import S3Event, event_source @event_source(data_class=S3Event) def handler(event: S3Event, context): return {"key": event.object_key} Here is the function: def event_source( handler: Callable[[Any, LambdaContext], Any], event: Dict[str, Any], context: LambdaContext, data_class: Type[DictWrapper], ): """Middleware to create an instance of the passed in event source data class Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: Dict Lambda's Context data_class: Type[DictWrapper] Data class type to instantiate Example -------- **Sample usage** from aws_lambda_powertools.utilities.data_classes import S3Event, event_source @event_source(data_class=S3Event) def handler(event: S3Event, context): return {"key": event.object_key} """ return handler(data_class(event), context)
Middleware to create an instance of the passed in event source data class Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: Dict Lambda's Context data_class: Type[DictWrapper] Data class type to instantiate Example -------- **Sample usage** from aws_lambda_powertools.utilities.data_classes import S3Event, event_source @event_source(data_class=S3Event) def handler(event: S3Event, context): return {"key": event.object_key}
5,037
import base64 import json import zlib from typing import Iterator, List from aws_lambda_powertools.utilities.data_classes.cloud_watch_logs_event import ( CloudWatchLogsDecodedData, ) from aws_lambda_powertools.utilities.data_classes.common import DictWrapper class KinesisStreamEvent(DictWrapper): """Kinesis stream event Documentation: -------------- - https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html """ def records(self) -> Iterator[KinesisStreamRecord]: for record in self["Records"]: yield KinesisStreamRecord(record) class CloudWatchLogsDecodedData(DictWrapper): def owner(self) -> str: """The AWS Account ID of the originating log data.""" return self["owner"] def log_group(self) -> str: """The log group name of the originating log data.""" return self["logGroup"] def log_stream(self) -> str: """The log stream name of the originating log data.""" return self["logStream"] def subscription_filters(self) -> List[str]: """The list of subscription filter names that matched with the originating log data.""" return self["subscriptionFilters"] def message_type(self) -> str: """Data messages will use the "DATA_MESSAGE" type. Sometimes CloudWatch Logs may emit Kinesis records with a "CONTROL_MESSAGE" type, mainly for checking if the destination is reachable. """ return self["messageType"] def policy_level(self) -> Optional[str]: """The level at which the policy was enforced.""" return self.get("policyLevel") def log_events(self) -> List[CloudWatchLogsLogEvent]: """The actual log data, represented as an array of log event records. The ID property is a unique identifier for every log event. """ return [CloudWatchLogsLogEvent(i) for i in self["logEvents"]] def extract_cloudwatch_logs_from_event(event: KinesisStreamEvent) -> List[CloudWatchLogsDecodedData]: return [CloudWatchLogsDecodedData(record.kinesis.data_zlib_compressed_as_json()) for record in event.records]
null
5,038
import base64 import json import zlib from typing import Iterator, List from aws_lambda_powertools.utilities.data_classes.cloud_watch_logs_event import ( CloudWatchLogsDecodedData, ) from aws_lambda_powertools.utilities.data_classes.common import DictWrapper class KinesisStreamRecord(DictWrapper): def aws_region(self) -> str: def event_id(self) -> str: def event_name(self) -> str: def event_source(self) -> str: def event_source_arn(self) -> str: def event_version(self) -> str: def invoke_identity_arn(self) -> str: def kinesis(self) -> KinesisStreamRecordPayload: class CloudWatchLogsDecodedData(DictWrapper): def owner(self) -> str: def log_group(self) -> str: def log_stream(self) -> str: def subscription_filters(self) -> List[str]: def message_type(self) -> str: def policy_level(self) -> Optional[str]: def log_events(self) -> List[CloudWatchLogsLogEvent]: def extract_cloudwatch_logs_from_record(record: KinesisStreamRecord) -> CloudWatchLogsDecodedData: return CloudWatchLogsDecodedData(data=record.kinesis.data_zlib_compressed_as_json())
null
5,039
from __future__ import annotations import base64 from typing import Any, Dict The provided code snippet includes necessary dependencies for implementing the `base64_decode` function. Write a Python function `def base64_decode(value: str) -> str` to solve the following problem: Decodes a Base64-encoded string and returns the decoded value. Parameters ---------- value: str The Base64-encoded string to decode. Returns ------- str The decoded string value. Here is the function: def base64_decode(value: str) -> str: """ Decodes a Base64-encoded string and returns the decoded value. Parameters ---------- value: str The Base64-encoded string to decode. Returns ------- str The decoded string value. """ return base64.b64decode(value).decode("UTF-8")
Decodes a Base64-encoded string and returns the decoded value. Parameters ---------- value: str The Base64-encoded string to decode. Returns ------- str The decoded string value.
5,040
from __future__ import annotations import base64 from typing import Any, Dict The provided code snippet includes necessary dependencies for implementing the `get_header_value` function. Write a Python function `def get_header_value( headers: dict[str, Any], name: str, default_value: str | None, case_sensitive: bool | None, ) -> str | None` to solve the following problem: Get the value of a header by its name. Parameters ---------- headers: Dict[str, str] The dictionary of headers. name: str The name of the header to retrieve. default_value: str, optional The default value to return if the header is not found. Default is None. case_sensitive: bool, optional Indicates whether the header name should be case-sensitive. Default is None. Returns ------- str, optional The value of the header if found, otherwise the default value or None. Here is the function: def get_header_value( headers: dict[str, Any], name: str, default_value: str | None, case_sensitive: bool | None, ) -> str | None: """ Get the value of a header by its name. Parameters ---------- headers: Dict[str, str] The dictionary of headers. name: str The name of the header to retrieve. default_value: str, optional The default value to return if the header is not found. Default is None. case_sensitive: bool, optional Indicates whether the header name should be case-sensitive. Default is None. Returns ------- str, optional The value of the header if found, otherwise the default value or None. """ # If headers is NoneType, return default value if not headers: return default_value if case_sensitive: return headers.get(name, default_value) name_lower = name.lower() return next( # Iterate over the dict and do a case-insensitive key comparison (value for key, value in headers.items() if key.lower() == name_lower), # Default value is returned if no matches was found default_value, )
Get the value of a header by its name. Parameters ---------- headers: Dict[str, str] The dictionary of headers. name: str The name of the header to retrieve. default_value: str, optional The default value to return if the header is not found. Default is None. case_sensitive: bool, optional Indicates whether the header name should be case-sensitive. Default is None. Returns ------- str, optional The value of the header if found, otherwise the default value or None.
5,041
from __future__ import annotations import base64 from typing import Any, Dict The provided code snippet includes necessary dependencies for implementing the `get_query_string_value` function. Write a Python function `def get_query_string_value( query_string_parameters: Dict[str, str] | None, name: str, default_value: str | None = None, ) -> str | None` to solve the following problem: Retrieves the value of a query string parameter specified by the given name. Parameters ---------- name: str The name of the query string parameter to retrieve. default_value: str, optional The default value to return if the parameter is not found. Defaults to None. Returns ------- str. optional The value of the query string parameter if found, or the default value if not found. Here is the function: def get_query_string_value( query_string_parameters: Dict[str, str] | None, name: str, default_value: str | None = None, ) -> str | None: """ Retrieves the value of a query string parameter specified by the given name. Parameters ---------- name: str The name of the query string parameter to retrieve. default_value: str, optional The default value to return if the parameter is not found. Defaults to None. Returns ------- str. optional The value of the query string parameter if found, or the default value if not found. """ params = query_string_parameters return default_value if params is None else params.get(name, default_value)
Retrieves the value of a query string parameter specified by the given name. Parameters ---------- name: str The name of the query string parameter to retrieve. default_value: str, optional The default value to return if the parameter is not found. Defaults to None. Returns ------- str. optional The value of the query string parameter if found, or the default value if not found.
5,042
from __future__ import annotations import base64 from typing import Any, Dict The provided code snippet includes necessary dependencies for implementing the `get_multi_value_query_string_values` function. Write a Python function `def get_multi_value_query_string_values( multi_value_query_string_parameters: Dict[str, list[str]] | None, name: str, default_values: list[str] | None = None, ) -> list[str]` to solve the following problem: Retrieves the values of a multi-value string parameters specified by the given name. Parameters ---------- name: str The name of the query string parameter to retrieve. default_value: list[str], optional The default value to return if the parameter is not found. Defaults to None. Returns ------- List[str]. optional The values of the query string parameter if found, or the default values if not found. Here is the function: def get_multi_value_query_string_values( multi_value_query_string_parameters: Dict[str, list[str]] | None, name: str, default_values: list[str] | None = None, ) -> list[str]: """ Retrieves the values of a multi-value string parameters specified by the given name. Parameters ---------- name: str The name of the query string parameter to retrieve. default_value: list[str], optional The default value to return if the parameter is not found. Defaults to None. Returns ------- List[str]. optional The values of the query string parameter if found, or the default values if not found. """ default = default_values or [] params = multi_value_query_string_parameters or {} return params.get(name) or default
Retrieves the values of a multi-value string parameters specified by the given name. Parameters ---------- name: str The name of the query string parameter to retrieve. default_value: list[str], optional The default value to return if the parameter is not found. Defaults to None. Returns ------- List[str]. optional The values of the query string parameter if found, or the default values if not found.
5,043
from __future__ import annotations from typing import Any, Dict, List, Optional from aws_lambda_powertools.utilities.data_classes.common import DictWrapper class AWSConfigConfigurationChanged(DictWrapper): def configuration_item_diff(self) -> Dict: """The configuration item diff of the ConfigurationItemChangeNotification event.""" return self["configurationItemDiff"] def configuration_item(self) -> AWSConfigConfigurationItemChanged: """The configuration item of the ConfigurationItemChangeNotification event.""" return AWSConfigConfigurationItemChanged(self["configurationItem"]) def raw_configuration_item(self) -> Dict: """The raw configuration item of the ConfigurationItemChangeNotification event.""" return self["configurationItem"] def record_version(self) -> str: """The record version of the ConfigurationItemChangeNotification event.""" return self["recordVersion"] def message_type(self) -> str: """The message type of the ConfigurationItemChangeNotification event.""" return self["messageType"] def notification_creation_time(self) -> str: """The notification creation time of the ConfigurationItemChangeNotification event.""" return self["notificationCreationTime"] class AWSConfigScheduledNotification(DictWrapper): def accountid(self) -> str: """The accountid of the ScheduledNotification event.""" return self["awsAccountId"] def notification_creation_time(self) -> str: """The notification creation time of the ScheduledNotification event.""" return self["notificationCreationTime"] def record_version(self) -> str: """The record version of the ScheduledNotification event.""" return self["recordVersion"] def message_type(self) -> str: """The message type of the ScheduledNotification event.""" return self["messageType"] class AWSConfigOversizedConfiguration(DictWrapper): def configuration_item_summary(self) -> AWSConfigOversizedConfigurationItemSummary: """The configuration item summary of the OversizedConfiguration event.""" return AWSConfigOversizedConfigurationItemSummary(self["configurationItemSummary"]) def raw_configuration_item_summary(self) -> str: """The raw configuration item summary of the OversizedConfiguration event.""" return self["configurationItemSummary"] def message_type(self) -> str: """The message type of the OversizedConfiguration event.""" return self["messageType"] def notification_creation_time(self) -> str: """The notification creation time of the OversizedConfiguration event.""" return self["notificationCreationTime"] def record_version(self) -> str: """The record version of the OversizedConfiguration event.""" return self["recordVersion"] The provided code snippet includes necessary dependencies for implementing the `get_invoke_event` function. Write a Python function `def get_invoke_event( invoking_event: dict, ) -> AWSConfigConfigurationChanged | AWSConfigScheduledNotification | AWSConfigOversizedConfiguration` to solve the following problem: Returns the corresponding event object based on the messageType in the invoking event. Parameters ---------- invoking_event: dict The invoking event received. Returns ------- AWSConfigConfigurationChanged | AWSConfigScheduledNotification | AWSConfigOversizedConfiguration: The event object based on the messageType in the invoking event. Here is the function: def get_invoke_event( invoking_event: dict, ) -> AWSConfigConfigurationChanged | AWSConfigScheduledNotification | AWSConfigOversizedConfiguration: """ Returns the corresponding event object based on the messageType in the invoking event. Parameters ---------- invoking_event: dict The invoking event received. Returns ------- AWSConfigConfigurationChanged | AWSConfigScheduledNotification | AWSConfigOversizedConfiguration: The event object based on the messageType in the invoking event. """ message_type = invoking_event.get("messageType") if message_type == "ScheduledNotification": return AWSConfigScheduledNotification(invoking_event) if message_type == "OversizedConfigurationItemChangeNotification": return AWSConfigOversizedConfiguration(invoking_event) # Default return is AWSConfigConfigurationChanged event return AWSConfigConfigurationChanged(invoking_event)
Returns the corresponding event object based on the messageType in the invoking event. Parameters ---------- invoking_event: dict The invoking event received. Returns ------- AWSConfigConfigurationChanged | AWSConfigScheduledNotification | AWSConfigOversizedConfiguration: The event object based on the messageType in the invoking event.
5,044
import base64 import json from typing import Any, Callable The provided code snippet includes necessary dependencies for implementing the `base64_encode` function. Write a Python function `def base64_encode(data: str) -> str` to solve the following problem: Encode a string and returns Base64-encoded encoded value. Parameters ---------- data: str The string to encode. Returns ------- str The Base64-encoded encoded value. Here is the function: def base64_encode(data: str) -> str: """Encode a string and returns Base64-encoded encoded value. Parameters ---------- data: str The string to encode. Returns ------- str The Base64-encoded encoded value. """ return base64.b64encode(data.encode()).decode("utf-8")
Encode a string and returns Base64-encoded encoded value. Parameters ---------- data: str The string to encode. Returns ------- str The Base64-encoded encoded value.
5,045
import base64 import json from typing import Any, Callable The provided code snippet includes necessary dependencies for implementing the `base64_decode` function. Write a Python function `def base64_decode(data: str) -> str` to solve the following problem: Decodes a Base64-encoded string and returns the decoded value. Parameters ---------- data: str The Base64-encoded string to decode. Returns ------- str The decoded string value. Here is the function: def base64_decode(data: str) -> str: """Decodes a Base64-encoded string and returns the decoded value. Parameters ---------- data: str The Base64-encoded string to decode. Returns ------- str The decoded string value. """ return base64.b64decode(data).decode("utf-8")
Decodes a Base64-encoded string and returns the decoded value. Parameters ---------- data: str The Base64-encoded string to decode. Returns ------- str The decoded string value.
5,046
import os from typing import TYPE_CHECKING, Any, Dict, Optional, Union import boto3 from botocore.config import Config from aws_lambda_powertools.utilities.parameters.types import TransformOptions from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_env_var_choice, resolve_max_age, ) from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider class AppConfigProvider(BaseProvider): """ AWS App Config Provider Parameters ---------- environment: str Environment of the configuration to pass during client initialization application: str, optional Application of the configuration to pass during client initialization config: botocore.config.Config, optional Botocore configuration to pass during client initialization boto3_session : boto3.session.Session, optional Boto3 session to create a boto3_client from boto3_client: AppConfigDataClient, optional Boto3 AppConfigData Client to use, boto3_session will be ignored if both are provided Example ------- **Retrieves the latest configuration value from App Config** >>> from aws_lambda_powertools.utilities import parameters >>> >>> appconf_provider = parameters.AppConfigProvider(environment="my_env", application="my_app") >>> >>> value : bytes = appconf_provider.get("my_conf") >>> >>> print(value) My configuration value **Retrieves a configuration value from App Config in another AWS region** >>> from botocore.config import Config >>> from aws_lambda_powertools.utilities import parameters >>> >>> config = Config(region_name="us-west-1") >>> appconf_provider = parameters.AppConfigProvider(environment="my_env", application="my_app", config=config) >>> >>> value : bytes = appconf_provider.get("my_conf") >>> >>> print(value) My configuration value """ client: Any = None def __init__( self, environment: str, application: Optional[str] = None, config: Optional[Config] = None, boto3_session: Optional[boto3.session.Session] = None, boto3_client: Optional["AppConfigDataClient"] = None, ): """ Initialize the App Config client """ super().__init__() self.client: "AppConfigDataClient" = self._build_boto3_client( service_name="appconfigdata", client=boto3_client, session=boto3_session, config=config, ) self.application = resolve_env_var_choice( choice=application, env=os.getenv(constants.SERVICE_NAME_ENV, "service_undefined"), ) self.environment = environment self.current_version = "" self._next_token: Dict[str, str] = {} # nosec - token for get_latest_configuration executions # Dict to store the recently retrieved value for a specific configuration. self.last_returned_value: Dict[str, str] = {} def _get(self, name: str, **sdk_options) -> str: """ Retrieve a parameter value from AWS App config. Parameters ---------- name: str Name of the configuration sdk_options: dict, optional SDK options to propagate to `start_configuration_session` API call """ if name not in self._next_token: sdk_options["ConfigurationProfileIdentifier"] = name sdk_options["ApplicationIdentifier"] = self.application sdk_options["EnvironmentIdentifier"] = self.environment response_configuration = self.client.start_configuration_session(**sdk_options) self._next_token[name] = response_configuration["InitialConfigurationToken"] # The new AppConfig APIs require two API calls to return the configuration # First we start the session and after that we retrieve the configuration # We need to store the token to use in the next execution response = self.client.get_latest_configuration(ConfigurationToken=self._next_token[name]) return_value = response["Configuration"].read() self._next_token[name] = response["NextPollConfigurationToken"] # The return of get_latest_configuration can be null because this value is supposed to be cached # on the customer side. # We created a dictionary that stores the most recently retrieved value for a specific configuration. # See https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/appconfigdata/client/get_latest_configuration.html if return_value: self.last_returned_value[name] = return_value return self.last_returned_value[name] def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]: """ Retrieving multiple parameter values is not supported with AWS App Config Provider """ raise NotImplementedError() TransformOptions = Literal["json", "binary", "auto", None] def resolve_max_age(env: str, choice: Optional[int]) -> int: """Resolve max age value""" return choice if choice is not None else int(env) DEFAULT_MAX_AGE_SECS = "5" DEFAULT_PROVIDERS: Dict[str, Any] = {} The provided code snippet includes necessary dependencies for implementing the `get_app_config` function. Write a Python function `def get_app_config( name: str, environment: str, application: Optional[str] = None, transform: TransformOptions = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> Union[str, list, dict, bytes]` to solve the following problem: Retrieve a configuration value from AWS App Config. Parameters ---------- name: str Name of the configuration environment: str Environment of the configuration application: str Application of the configuration transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value sdk_options: dict, optional SDK options to propagate to `start_configuration_session` API call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves the latest version of configuration value from App Config** >>> from aws_lambda_powertools.utilities.parameters import get_app_config >>> >>> value = get_app_config("my_config", environment="my_env", application="my_env") >>> >>> print(value) My configuration value **Retrieves a configuration value and decodes it using a JSON decoder** >>> from aws_lambda_powertools.utilities.parameters import get_app_config >>> >>> value = get_app_config("my_config", environment="my_env", application="my_env", transform='json') >>> >>> print(value) My configuration's JSON value Here is the function: def get_app_config( name: str, environment: str, application: Optional[str] = None, transform: TransformOptions = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> Union[str, list, dict, bytes]: """ Retrieve a configuration value from AWS App Config. Parameters ---------- name: str Name of the configuration environment: str Environment of the configuration application: str Application of the configuration transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value sdk_options: dict, optional SDK options to propagate to `start_configuration_session` API call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves the latest version of configuration value from App Config** >>> from aws_lambda_powertools.utilities.parameters import get_app_config >>> >>> value = get_app_config("my_config", environment="my_env", application="my_env") >>> >>> print(value) My configuration value **Retrieves a configuration value and decodes it using a JSON decoder** >>> from aws_lambda_powertools.utilities.parameters import get_app_config >>> >>> value = get_app_config("my_config", environment="my_env", application="my_env", transform='json') >>> >>> print(value) My configuration's JSON value """ # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age) # Only create the provider if this function is called at least once if "appconfig" not in DEFAULT_PROVIDERS: DEFAULT_PROVIDERS["appconfig"] = AppConfigProvider(environment=environment, application=application) return DEFAULT_PROVIDERS["appconfig"].get( name, max_age=max_age, transform=transform, force_fetch=force_fetch, **sdk_options, )
Retrieve a configuration value from AWS App Config. Parameters ---------- name: str Name of the configuration environment: str Environment of the configuration application: str Application of the configuration transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value sdk_options: dict, optional SDK options to propagate to `start_configuration_session` API call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves the latest version of configuration value from App Config** >>> from aws_lambda_powertools.utilities.parameters import get_app_config >>> >>> value = get_app_config("my_config", environment="my_env", application="my_env") >>> >>> print(value) My configuration value **Retrieves a configuration value and decodes it using a JSON decoder** >>> from aws_lambda_powertools.utilities.parameters import get_app_config >>> >>> value = get_app_config("my_config", environment="my_env", application="my_env", transform='json') >>> >>> print(value) My configuration's JSON value
5,047
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions def get_parameter( name: str, transform: None = None, decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> str: ...
null
5,048
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions def get_parameter( name: str, transform: Literal["json"], decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> dict: ...
null
5,049
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions def get_parameter( name: str, transform: Literal["binary"], decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> Union[str, dict, bytes]: ...
null
5,050
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions def get_parameter( name: str, transform: Literal["auto"], decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> bytes: ...
null
5,051
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions class SSMProvider(BaseProvider): """ AWS Systems Manager Parameter Store Provider Parameters ---------- config: botocore.config.Config, optional Botocore configuration to pass during client initialization boto3_session : boto3.session.Session, optional Boto3 session to create a boto3_client from boto3_client: SSMClient, optional Boto3 SSM Client to use, boto3_session will be ignored if both are provided Example ------- **Retrieves a parameter value from Systems Manager Parameter Store** >>> from aws_lambda_powertools.utilities.parameters import SSMProvider >>> ssm_provider = SSMProvider() >>> >>> value = ssm_provider.get("/my/parameter") >>> >>> print(value) My parameter value **Retrieves a parameter value from Systems Manager Parameter Store in another AWS region** >>> from botocore.config import Config >>> from aws_lambda_powertools.utilities.parameters import SSMProvider >>> >>> config = Config(region_name="us-west-1") >>> ssm_provider = SSMProvider(config=config) >>> >>> value = ssm_provider.get("/my/parameter") >>> >>> print(value) My parameter value **Retrieves multiple parameter values from Systems Manager Parameter Store using a path prefix** >>> from aws_lambda_powertools.utilities.parameters import SSMProvider >>> ssm_provider = SSMProvider() >>> >>> values = ssm_provider.get_multiple("/my/path/prefix") >>> >>> for key, value in values.items(): ... print(key, value) /my/path/prefix/a Parameter value a /my/path/prefix/b Parameter value b /my/path/prefix/c Parameter value c **Retrieves multiple parameter values from Systems Manager Parameter Store passing options to the SDK call** >>> from aws_lambda_powertools.utilities.parameters import SSMProvider >>> ssm_provider = SSMProvider() >>> >>> values = ssm_provider.get_multiple("/my/path/prefix", MaxResults=10) >>> >>> for key, value in values.items(): ... print(key, value) /my/path/prefix/a Parameter value a /my/path/prefix/b Parameter value b /my/path/prefix/c Parameter value c """ client: Any = None _MAX_GET_PARAMETERS_ITEM = 10 _ERRORS_KEY = "_errors" def __init__( self, config: Optional[Config] = None, boto3_session: Optional[boto3.session.Session] = None, boto3_client: Optional["SSMClient"] = None, ): """ Initialize the SSM Parameter Store client """ super().__init__() self.client: "SSMClient" = self._build_boto3_client( service_name="ssm", client=boto3_client, session=boto3_session, config=config, ) # We break Liskov substitution principle due to differences in signatures of this method and superclass get method # We ignore mypy error, as changes to the signature here or in a superclass is a breaking change to users def get( # type: ignore[override] self, name: str, max_age: Optional[int] = None, transform: TransformOptions = None, decrypt: Optional[bool] = None, force_fetch: bool = False, **sdk_options, ) -> Optional[Union[str, dict, bytes]]: """ Retrieve a parameter value or return the cached value Parameters ---------- name: str Parameter name max_age: int, optional Maximum age of the cached value transform: str Optional transformation of the parameter value. Supported values are "json" for JSON strings and "binary" for base 64 encoded values. decrypt: bool, optional If the parameter value should be decrypted force_fetch: bool, optional Force update even before a cached item has expired, defaults to False sdk_options: dict, optional Arguments that will be passed directly to the underlying API call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. """ # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age) # If decrypt is not set, resolve it from the environment variable, defaulting to False decrypt = resolve_truthy_env_var_choice( env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"), choice=decrypt, ) # Add to `decrypt` sdk_options to we can have an explicit option for this sdk_options["decrypt"] = decrypt return super().get(name, max_age, transform, force_fetch, **sdk_options) def _get(self, name: str, decrypt: bool = False, **sdk_options) -> str: """ Retrieve a parameter value from AWS Systems Manager Parameter Store Parameters ---------- name: str Parameter name decrypt: bool, optional If the parameter value should be decrypted sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameter API call """ # Explicit arguments will take precedence over keyword arguments sdk_options["Name"] = name sdk_options["WithDecryption"] = decrypt return self.client.get_parameter(**sdk_options)["Parameter"]["Value"] def _get_multiple( self, path: str, decrypt: Optional[bool] = None, recursive: bool = False, **sdk_options, ) -> Dict[str, str]: """ Retrieve multiple parameter values from AWS Systems Manager Parameter Store Parameters ---------- path: str Path to retrieve the parameters decrypt: bool, optional If the parameter values should be decrypted recursive: bool, optional If this should retrieve the parameter values recursively or not sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameters_by_path API call """ # If decrypt is not set, resolve it from the environment variable, defaulting to False decrypt = resolve_truthy_env_var_choice( env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"), choice=decrypt, ) # Explicit arguments will take precedence over keyword arguments sdk_options["Path"] = path sdk_options["WithDecryption"] = decrypt sdk_options["Recursive"] = recursive parameters = {} for page in self.client.get_paginator("get_parameters_by_path").paginate(**sdk_options): for parameter in page.get("Parameters", []): # Standardize the parameter name # The parameter name returned by SSM will contain the full path. # However, for readability, we should return only the part after # the path. name = parameter["Name"] if name.startswith(path): name = name[len(path) :] name = name.lstrip("/") parameters[name] = parameter["Value"] return parameters # NOTE: When bandwidth permits, allocate a week to refactor to lower cognitive load def get_parameters_by_name( self, parameters: Dict[str, Dict], transform: TransformOptions = None, decrypt: Optional[bool] = None, max_age: Optional[int] = None, raise_on_error: bool = True, ) -> Dict[str, str] | Dict[str, bytes] | Dict[str, dict]: """ Retrieve multiple parameter values by name from SSM or cache. Raise_on_error decides on error handling strategy: - A) Default to fail-fast. Raises GetParameterError upon any error - B) Gracefully aggregate all parameters that failed under "_errors" key It transparently uses GetParameter and/or GetParameters depending on decryption requirements. ┌────────────────────────┐ ┌───▶ Decrypt entire batch │─────┐ │ └────────────────────────┘ │ ┌────────────────────┐ │ ├─────▶ GetParameters API │ ┌──────────────────┐ │ ┌────────────────────────┐ │ └────────────────────┘ │ Split batch │─── ┼──▶│ No decryption required │─────┘ └──────────────────┘ │ └────────────────────────┘ │ ┌────────────────────┐ │ ┌────────────────────────┐ │ GetParameter API │ └──▶│Decrypt some but not all│───────────▶────────────────────┤ └────────────────────────┘ │ GetParameters API │ └────────────────────┘ Parameters ---------- parameters: List[Dict[str, Dict]] List of parameter names, and any optional overrides transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') decrypt: bool, optional If the parameter values should be decrypted max_age: int, optional Maximum age of the cached value raise_on_error: bool Whether to fail-fast or fail gracefully by including "_errors" key in the response, by default True Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. When "_errors" reserved key is in parameters to be fetched from SSM. """ # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age) # If decrypt is not set, resolve it from the environment variable, defaulting to False decrypt = resolve_truthy_env_var_choice( env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"), choice=decrypt, ) # Init potential batch/decrypt batch responses and errors batch_ret: Dict[str, Any] = {} decrypt_ret: Dict[str, Any] = {} batch_err: List[str] = [] decrypt_err: List[str] = [] response: Dict[str, Any] = {} # NOTE: We fail early to avoid unintended graceful errors being replaced with their '_errors' param values self._raise_if_errors_key_is_present(parameters, self._ERRORS_KEY, raise_on_error) batch_params, decrypt_params = self._split_batch_and_decrypt_parameters(parameters, transform, max_age, decrypt) # NOTE: We need to find out whether all parameters must be decrypted or not to know which API to use ## Logic: ## ## GetParameters API -> When decrypt is used for all parameters in the the batch ## GetParameter API -> When decrypt is used for one or more in the batch if len(decrypt_params) != len(parameters): decrypt_ret, decrypt_err = self._get_parameters_by_name_with_decrypt_option(decrypt_params, raise_on_error) batch_ret, batch_err = self._get_parameters_batch_by_name(batch_params, raise_on_error, decrypt=False) else: batch_ret, batch_err = self._get_parameters_batch_by_name(decrypt_params, raise_on_error, decrypt=True) # Fail-fast disabled, let's aggregate errors under "_errors" key so they can handle gracefully if not raise_on_error: response[self._ERRORS_KEY] = [*decrypt_err, *batch_err] return {**response, **batch_ret, **decrypt_ret} def _get_parameters_by_name_with_decrypt_option( self, batch: Dict[str, Dict], raise_on_error: bool, ) -> Tuple[Dict, List]: response: Dict[str, Any] = {} errors: List[str] = [] # Decided for single-thread as it outperforms in 128M and 1G + reduce timeout risk # see: https://github.com/aws-powertools/powertools-lambda-python/issues/1040#issuecomment-1299954613 for parameter, options in batch.items(): try: response[parameter] = self.get(parameter, options["max_age"], options["transform"], options["decrypt"]) except GetParameterError: if raise_on_error: raise errors.append(parameter) continue return response, errors def _get_parameters_batch_by_name( self, batch: Dict[str, Dict], raise_on_error: bool = True, decrypt: bool = False, ) -> Tuple[Dict, List]: """Slice batch and fetch parameters using GetParameters by max permitted""" errors: List[str] = [] # Fetch each possible batch param from cache and return if entire batch is cached cached_params = self._get_parameters_by_name_from_cache(batch) if len(cached_params) == len(batch): return cached_params, errors # Slice batch by max permitted GetParameters call batch_ret, errors = self._get_parameters_by_name_in_chunks(batch, cached_params, raise_on_error, decrypt) return {**cached_params, **batch_ret}, errors def _get_parameters_by_name_from_cache(self, batch: Dict[str, Dict]) -> Dict[str, Any]: """Fetch each parameter from batch that hasn't been expired""" cache = {} for name, options in batch.items(): cache_key = (name, options["transform"]) if self.has_not_expired_in_cache(cache_key): cache[name] = self.store[cache_key].value return cache def _get_parameters_by_name_in_chunks( self, batch: Dict[str, Dict], cache: Dict[str, Any], raise_on_error: bool, decrypt: bool = False, ) -> Tuple[Dict, List]: """Take out differences from cache and batch, slice it and fetch from SSM""" response: Dict[str, Any] = {} errors: List[str] = [] diff = {key: value for key, value in batch.items() if key not in cache} for chunk in slice_dictionary(data=diff, chunk_size=self._MAX_GET_PARAMETERS_ITEM): response, possible_errors = self._get_parameters_by_name( parameters=chunk, raise_on_error=raise_on_error, decrypt=decrypt, ) response.update(response) errors.extend(possible_errors) return response, errors def _get_parameters_by_name( self, parameters: Dict[str, Dict], raise_on_error: bool = True, decrypt: bool = False, ) -> Tuple[Dict[str, Any], List[str]]: """Use SSM GetParameters to fetch parameters, hydrate cache, and handle partial failure Parameters ---------- parameters : Dict[str, Dict] Parameters to fetch raise_on_error : bool, optional Whether to fail-fast or fail gracefully by including "_errors" key in the response, by default True Returns ------- Dict[str, Any] Retrieved parameters as key names and their values Raises ------ GetParameterError When one or more parameters failed on fetching, and raise_on_error is enabled """ ret: Dict[str, Any] = {} batch_errors: List[str] = [] parameter_names = list(parameters.keys()) # All params in the batch must be decrypted # we return early if we hit an unrecoverable exception like InvalidKeyId/InternalServerError # everything else should technically be recoverable as GetParameters is non-atomic try: if decrypt: response = self.client.get_parameters(Names=parameter_names, WithDecryption=True) else: response = self.client.get_parameters(Names=parameter_names) except (self.client.exceptions.InvalidKeyId, self.client.exceptions.InternalServerError): return ret, parameter_names batch_errors = self._handle_any_invalid_get_parameter_errors(response, raise_on_error) transformed_params = self._transform_and_cache_get_parameters_response(response, parameters, raise_on_error) return transformed_params, batch_errors def _transform_and_cache_get_parameters_response( self, api_response: GetParametersResultTypeDef, parameters: Dict[str, Any], raise_on_error: bool = True, ) -> Dict[str, Any]: response: Dict[str, Any] = {} for parameter in api_response["Parameters"]: name = parameter["Name"] value = parameter["Value"] options = parameters[name] transform = options.get("transform") # NOTE: If transform is set, we do it before caching to reduce number of operations if transform: value = transform_value(name, value, transform, raise_on_error) # type: ignore _cache_key = (name, options["transform"]) self.add_to_cache(key=_cache_key, value=value, max_age=options["max_age"]) response[name] = value return response def _handle_any_invalid_get_parameter_errors( api_response: GetParametersResultTypeDef, raise_on_error: bool = True, ) -> List[str]: """GetParameters is non-atomic. Failures don't always reflect in exceptions so we need to collect.""" failed_parameters = api_response["InvalidParameters"] if failed_parameters: if raise_on_error: raise GetParameterError(f"Failed to fetch parameters: {failed_parameters}") return failed_parameters return [] def _split_batch_and_decrypt_parameters( parameters: Dict[str, Dict], transform: TransformOptions, max_age: int, decrypt: bool, ) -> Tuple[Dict[str, Dict], Dict[str, Dict]]: """Split parameters that can be fetched by GetParameters vs GetParameter Parameters ---------- parameters : Dict[str, Dict] Parameters containing names as key and optional config override as value transform : TransformOptions Transform configuration max_age : int How long to cache a parameter for decrypt : bool Whether to use KMS to decrypt a parameter Returns ------- Tuple[Dict[str, Dict], Dict[str, Dict]] GetParameters and GetParameter parameters dict along with their overrides/globals merged """ batch_parameters: Dict[str, Dict] = {} decrypt_parameters: Dict[str, Any] = {} for parameter, options in parameters.items(): # NOTE: TypeDict later _overrides = options or {} _overrides["transform"] = _overrides.get("transform") or transform # These values can be falsy (False, 0) if "decrypt" not in _overrides: _overrides["decrypt"] = decrypt if "max_age" not in _overrides: _overrides["max_age"] = max_age # NOTE: Split parameters who have decrypt OR have it global if _overrides["decrypt"]: decrypt_parameters[parameter] = _overrides else: batch_parameters[parameter] = _overrides return batch_parameters, decrypt_parameters def _raise_if_errors_key_is_present(parameters: Dict, reserved_parameter: str, raise_on_error: bool): """Raise GetParameterError if fail-fast is disabled and '_errors' key is in parameters batch""" if not raise_on_error and reserved_parameter in parameters: raise GetParameterError( f"You cannot fetch a parameter named '{reserved_parameter}' in graceful error mode.", ) def resolve_truthy_env_var_choice(env: str, choice: Optional[bool] = None) -> bool: """Pick explicit choice over truthy env value, if available, otherwise return truthy env value NOTE: Environment variable should be resolved by the caller. Parameters ---------- env : str environment variable actual value choice : bool explicit choice Returns ------- choice : str resolved choice as either bool or environment value """ return choice if choice is not None else strtobool(env) def resolve_max_age(env: str, choice: Optional[int]) -> int: """Resolve max age value""" return choice if choice is not None else int(env) DEFAULT_MAX_AGE_SECS = "5" DEFAULT_PROVIDERS: Dict[str, Any] = {} TransformOptions = Literal["json", "binary", "auto", None] The provided code snippet includes necessary dependencies for implementing the `get_parameter` function. Write a Python function `def get_parameter( name: str, transform: TransformOptions = None, decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> Union[str, dict, bytes]` to solve the following problem: Retrieve a parameter value from AWS Systems Manager (SSM) Parameter Store Parameters ---------- name: str Name of the parameter transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') decrypt: bool, optional If the parameter values should be decrypted force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameter API call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves a parameter value from Systems Manager Parameter Store** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> value = get_parameter("/my/parameter") >>> >>> print(value) My parameter value **Retrieves a parameter value and decodes it using a Base64 decoder** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> value = get_parameter("/my/parameter", transform='binary') >>> >>> print(value) My parameter value Here is the function: def get_parameter( name: str, transform: TransformOptions = None, decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> Union[str, dict, bytes]: """ Retrieve a parameter value from AWS Systems Manager (SSM) Parameter Store Parameters ---------- name: str Name of the parameter transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') decrypt: bool, optional If the parameter values should be decrypted force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameter API call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves a parameter value from Systems Manager Parameter Store** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> value = get_parameter("/my/parameter") >>> >>> print(value) My parameter value **Retrieves a parameter value and decodes it using a Base64 decoder** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> value = get_parameter("/my/parameter", transform='binary') >>> >>> print(value) My parameter value """ # Only create the provider if this function is called at least once if "ssm" not in DEFAULT_PROVIDERS: DEFAULT_PROVIDERS["ssm"] = SSMProvider() # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age) # If decrypt is not set, resolve it from the environment variable, defaulting to False decrypt = resolve_truthy_env_var_choice( env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"), choice=decrypt, ) # Add to `decrypt` sdk_options to we can have an explicit option for this sdk_options["decrypt"] = decrypt return DEFAULT_PROVIDERS["ssm"].get( name, max_age=max_age, transform=transform, force_fetch=force_fetch, **sdk_options, )
Retrieve a parameter value from AWS Systems Manager (SSM) Parameter Store Parameters ---------- name: str Name of the parameter transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') decrypt: bool, optional If the parameter values should be decrypted force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameter API call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves a parameter value from Systems Manager Parameter Store** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> value = get_parameter("/my/parameter") >>> >>> print(value) My parameter value **Retrieves a parameter value and decodes it using a Base64 decoder** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> value = get_parameter("/my/parameter", transform='binary') >>> >>> print(value) My parameter value
5,052
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions def get_parameters( path: str, transform: None = None, recursive: bool = True, decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, raise_on_transform_error: bool = False, **sdk_options, ) -> Dict[str, str]: ...
null
5,053
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions def get_parameters( path: str, transform: Literal["json"], recursive: bool = True, decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, raise_on_transform_error: bool = False, **sdk_options, ) -> Dict[str, dict]: ...
null
5,054
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions def get_parameters( path: str, transform: Literal["binary"], recursive: bool = True, decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, raise_on_transform_error: bool = False, **sdk_options, ) -> Dict[str, bytes]: ...
null
5,055
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions def get_parameters( path: str, transform: Literal["auto"], recursive: bool = True, decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, raise_on_transform_error: bool = False, **sdk_options, ) -> Union[Dict[str, bytes], Dict[str, dict], Dict[str, str]]: ...
null
5,056
from __future__ import annotations import os from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import ( resolve_max_age, resolve_truthy_env_var_choice, slice_dictionary, ) from aws_lambda_powertools.shared.types import Literal from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider, transform_value from .exceptions import GetParameterError from .types import TransformOptions class SSMProvider(BaseProvider): """ AWS Systems Manager Parameter Store Provider Parameters ---------- config: botocore.config.Config, optional Botocore configuration to pass during client initialization boto3_session : boto3.session.Session, optional Boto3 session to create a boto3_client from boto3_client: SSMClient, optional Boto3 SSM Client to use, boto3_session will be ignored if both are provided Example ------- **Retrieves a parameter value from Systems Manager Parameter Store** >>> from aws_lambda_powertools.utilities.parameters import SSMProvider >>> ssm_provider = SSMProvider() >>> >>> value = ssm_provider.get("/my/parameter") >>> >>> print(value) My parameter value **Retrieves a parameter value from Systems Manager Parameter Store in another AWS region** >>> from botocore.config import Config >>> from aws_lambda_powertools.utilities.parameters import SSMProvider >>> >>> config = Config(region_name="us-west-1") >>> ssm_provider = SSMProvider(config=config) >>> >>> value = ssm_provider.get("/my/parameter") >>> >>> print(value) My parameter value **Retrieves multiple parameter values from Systems Manager Parameter Store using a path prefix** >>> from aws_lambda_powertools.utilities.parameters import SSMProvider >>> ssm_provider = SSMProvider() >>> >>> values = ssm_provider.get_multiple("/my/path/prefix") >>> >>> for key, value in values.items(): ... print(key, value) /my/path/prefix/a Parameter value a /my/path/prefix/b Parameter value b /my/path/prefix/c Parameter value c **Retrieves multiple parameter values from Systems Manager Parameter Store passing options to the SDK call** >>> from aws_lambda_powertools.utilities.parameters import SSMProvider >>> ssm_provider = SSMProvider() >>> >>> values = ssm_provider.get_multiple("/my/path/prefix", MaxResults=10) >>> >>> for key, value in values.items(): ... print(key, value) /my/path/prefix/a Parameter value a /my/path/prefix/b Parameter value b /my/path/prefix/c Parameter value c """ client: Any = None _MAX_GET_PARAMETERS_ITEM = 10 _ERRORS_KEY = "_errors" def __init__( self, config: Optional[Config] = None, boto3_session: Optional[boto3.session.Session] = None, boto3_client: Optional["SSMClient"] = None, ): """ Initialize the SSM Parameter Store client """ super().__init__() self.client: "SSMClient" = self._build_boto3_client( service_name="ssm", client=boto3_client, session=boto3_session, config=config, ) # We break Liskov substitution principle due to differences in signatures of this method and superclass get method # We ignore mypy error, as changes to the signature here or in a superclass is a breaking change to users def get( # type: ignore[override] self, name: str, max_age: Optional[int] = None, transform: TransformOptions = None, decrypt: Optional[bool] = None, force_fetch: bool = False, **sdk_options, ) -> Optional[Union[str, dict, bytes]]: """ Retrieve a parameter value or return the cached value Parameters ---------- name: str Parameter name max_age: int, optional Maximum age of the cached value transform: str Optional transformation of the parameter value. Supported values are "json" for JSON strings and "binary" for base 64 encoded values. decrypt: bool, optional If the parameter value should be decrypted force_fetch: bool, optional Force update even before a cached item has expired, defaults to False sdk_options: dict, optional Arguments that will be passed directly to the underlying API call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. """ # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age) # If decrypt is not set, resolve it from the environment variable, defaulting to False decrypt = resolve_truthy_env_var_choice( env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"), choice=decrypt, ) # Add to `decrypt` sdk_options to we can have an explicit option for this sdk_options["decrypt"] = decrypt return super().get(name, max_age, transform, force_fetch, **sdk_options) def _get(self, name: str, decrypt: bool = False, **sdk_options) -> str: """ Retrieve a parameter value from AWS Systems Manager Parameter Store Parameters ---------- name: str Parameter name decrypt: bool, optional If the parameter value should be decrypted sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameter API call """ # Explicit arguments will take precedence over keyword arguments sdk_options["Name"] = name sdk_options["WithDecryption"] = decrypt return self.client.get_parameter(**sdk_options)["Parameter"]["Value"] def _get_multiple( self, path: str, decrypt: Optional[bool] = None, recursive: bool = False, **sdk_options, ) -> Dict[str, str]: """ Retrieve multiple parameter values from AWS Systems Manager Parameter Store Parameters ---------- path: str Path to retrieve the parameters decrypt: bool, optional If the parameter values should be decrypted recursive: bool, optional If this should retrieve the parameter values recursively or not sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameters_by_path API call """ # If decrypt is not set, resolve it from the environment variable, defaulting to False decrypt = resolve_truthy_env_var_choice( env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"), choice=decrypt, ) # Explicit arguments will take precedence over keyword arguments sdk_options["Path"] = path sdk_options["WithDecryption"] = decrypt sdk_options["Recursive"] = recursive parameters = {} for page in self.client.get_paginator("get_parameters_by_path").paginate(**sdk_options): for parameter in page.get("Parameters", []): # Standardize the parameter name # The parameter name returned by SSM will contain the full path. # However, for readability, we should return only the part after # the path. name = parameter["Name"] if name.startswith(path): name = name[len(path) :] name = name.lstrip("/") parameters[name] = parameter["Value"] return parameters # NOTE: When bandwidth permits, allocate a week to refactor to lower cognitive load def get_parameters_by_name( self, parameters: Dict[str, Dict], transform: TransformOptions = None, decrypt: Optional[bool] = None, max_age: Optional[int] = None, raise_on_error: bool = True, ) -> Dict[str, str] | Dict[str, bytes] | Dict[str, dict]: """ Retrieve multiple parameter values by name from SSM or cache. Raise_on_error decides on error handling strategy: - A) Default to fail-fast. Raises GetParameterError upon any error - B) Gracefully aggregate all parameters that failed under "_errors" key It transparently uses GetParameter and/or GetParameters depending on decryption requirements. ┌────────────────────────┐ ┌───▶ Decrypt entire batch │─────┐ │ └────────────────────────┘ │ ┌────────────────────┐ │ ├─────▶ GetParameters API │ ┌──────────────────┐ │ ┌────────────────────────┐ │ └────────────────────┘ │ Split batch │─── ┼──▶│ No decryption required │─────┘ └──────────────────┘ │ └────────────────────────┘ │ ┌────────────────────┐ │ ┌────────────────────────┐ │ GetParameter API │ └──▶│Decrypt some but not all│───────────▶────────────────────┤ └────────────────────────┘ │ GetParameters API │ └────────────────────┘ Parameters ---------- parameters: List[Dict[str, Dict]] List of parameter names, and any optional overrides transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') decrypt: bool, optional If the parameter values should be decrypted max_age: int, optional Maximum age of the cached value raise_on_error: bool Whether to fail-fast or fail gracefully by including "_errors" key in the response, by default True Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. When "_errors" reserved key is in parameters to be fetched from SSM. """ # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age) # If decrypt is not set, resolve it from the environment variable, defaulting to False decrypt = resolve_truthy_env_var_choice( env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"), choice=decrypt, ) # Init potential batch/decrypt batch responses and errors batch_ret: Dict[str, Any] = {} decrypt_ret: Dict[str, Any] = {} batch_err: List[str] = [] decrypt_err: List[str] = [] response: Dict[str, Any] = {} # NOTE: We fail early to avoid unintended graceful errors being replaced with their '_errors' param values self._raise_if_errors_key_is_present(parameters, self._ERRORS_KEY, raise_on_error) batch_params, decrypt_params = self._split_batch_and_decrypt_parameters(parameters, transform, max_age, decrypt) # NOTE: We need to find out whether all parameters must be decrypted or not to know which API to use ## Logic: ## ## GetParameters API -> When decrypt is used for all parameters in the the batch ## GetParameter API -> When decrypt is used for one or more in the batch if len(decrypt_params) != len(parameters): decrypt_ret, decrypt_err = self._get_parameters_by_name_with_decrypt_option(decrypt_params, raise_on_error) batch_ret, batch_err = self._get_parameters_batch_by_name(batch_params, raise_on_error, decrypt=False) else: batch_ret, batch_err = self._get_parameters_batch_by_name(decrypt_params, raise_on_error, decrypt=True) # Fail-fast disabled, let's aggregate errors under "_errors" key so they can handle gracefully if not raise_on_error: response[self._ERRORS_KEY] = [*decrypt_err, *batch_err] return {**response, **batch_ret, **decrypt_ret} def _get_parameters_by_name_with_decrypt_option( self, batch: Dict[str, Dict], raise_on_error: bool, ) -> Tuple[Dict, List]: response: Dict[str, Any] = {} errors: List[str] = [] # Decided for single-thread as it outperforms in 128M and 1G + reduce timeout risk # see: https://github.com/aws-powertools/powertools-lambda-python/issues/1040#issuecomment-1299954613 for parameter, options in batch.items(): try: response[parameter] = self.get(parameter, options["max_age"], options["transform"], options["decrypt"]) except GetParameterError: if raise_on_error: raise errors.append(parameter) continue return response, errors def _get_parameters_batch_by_name( self, batch: Dict[str, Dict], raise_on_error: bool = True, decrypt: bool = False, ) -> Tuple[Dict, List]: """Slice batch and fetch parameters using GetParameters by max permitted""" errors: List[str] = [] # Fetch each possible batch param from cache and return if entire batch is cached cached_params = self._get_parameters_by_name_from_cache(batch) if len(cached_params) == len(batch): return cached_params, errors # Slice batch by max permitted GetParameters call batch_ret, errors = self._get_parameters_by_name_in_chunks(batch, cached_params, raise_on_error, decrypt) return {**cached_params, **batch_ret}, errors def _get_parameters_by_name_from_cache(self, batch: Dict[str, Dict]) -> Dict[str, Any]: """Fetch each parameter from batch that hasn't been expired""" cache = {} for name, options in batch.items(): cache_key = (name, options["transform"]) if self.has_not_expired_in_cache(cache_key): cache[name] = self.store[cache_key].value return cache def _get_parameters_by_name_in_chunks( self, batch: Dict[str, Dict], cache: Dict[str, Any], raise_on_error: bool, decrypt: bool = False, ) -> Tuple[Dict, List]: """Take out differences from cache and batch, slice it and fetch from SSM""" response: Dict[str, Any] = {} errors: List[str] = [] diff = {key: value for key, value in batch.items() if key not in cache} for chunk in slice_dictionary(data=diff, chunk_size=self._MAX_GET_PARAMETERS_ITEM): response, possible_errors = self._get_parameters_by_name( parameters=chunk, raise_on_error=raise_on_error, decrypt=decrypt, ) response.update(response) errors.extend(possible_errors) return response, errors def _get_parameters_by_name( self, parameters: Dict[str, Dict], raise_on_error: bool = True, decrypt: bool = False, ) -> Tuple[Dict[str, Any], List[str]]: """Use SSM GetParameters to fetch parameters, hydrate cache, and handle partial failure Parameters ---------- parameters : Dict[str, Dict] Parameters to fetch raise_on_error : bool, optional Whether to fail-fast or fail gracefully by including "_errors" key in the response, by default True Returns ------- Dict[str, Any] Retrieved parameters as key names and their values Raises ------ GetParameterError When one or more parameters failed on fetching, and raise_on_error is enabled """ ret: Dict[str, Any] = {} batch_errors: List[str] = [] parameter_names = list(parameters.keys()) # All params in the batch must be decrypted # we return early if we hit an unrecoverable exception like InvalidKeyId/InternalServerError # everything else should technically be recoverable as GetParameters is non-atomic try: if decrypt: response = self.client.get_parameters(Names=parameter_names, WithDecryption=True) else: response = self.client.get_parameters(Names=parameter_names) except (self.client.exceptions.InvalidKeyId, self.client.exceptions.InternalServerError): return ret, parameter_names batch_errors = self._handle_any_invalid_get_parameter_errors(response, raise_on_error) transformed_params = self._transform_and_cache_get_parameters_response(response, parameters, raise_on_error) return transformed_params, batch_errors def _transform_and_cache_get_parameters_response( self, api_response: GetParametersResultTypeDef, parameters: Dict[str, Any], raise_on_error: bool = True, ) -> Dict[str, Any]: response: Dict[str, Any] = {} for parameter in api_response["Parameters"]: name = parameter["Name"] value = parameter["Value"] options = parameters[name] transform = options.get("transform") # NOTE: If transform is set, we do it before caching to reduce number of operations if transform: value = transform_value(name, value, transform, raise_on_error) # type: ignore _cache_key = (name, options["transform"]) self.add_to_cache(key=_cache_key, value=value, max_age=options["max_age"]) response[name] = value return response def _handle_any_invalid_get_parameter_errors( api_response: GetParametersResultTypeDef, raise_on_error: bool = True, ) -> List[str]: """GetParameters is non-atomic. Failures don't always reflect in exceptions so we need to collect.""" failed_parameters = api_response["InvalidParameters"] if failed_parameters: if raise_on_error: raise GetParameterError(f"Failed to fetch parameters: {failed_parameters}") return failed_parameters return [] def _split_batch_and_decrypt_parameters( parameters: Dict[str, Dict], transform: TransformOptions, max_age: int, decrypt: bool, ) -> Tuple[Dict[str, Dict], Dict[str, Dict]]: """Split parameters that can be fetched by GetParameters vs GetParameter Parameters ---------- parameters : Dict[str, Dict] Parameters containing names as key and optional config override as value transform : TransformOptions Transform configuration max_age : int How long to cache a parameter for decrypt : bool Whether to use KMS to decrypt a parameter Returns ------- Tuple[Dict[str, Dict], Dict[str, Dict]] GetParameters and GetParameter parameters dict along with their overrides/globals merged """ batch_parameters: Dict[str, Dict] = {} decrypt_parameters: Dict[str, Any] = {} for parameter, options in parameters.items(): # NOTE: TypeDict later _overrides = options or {} _overrides["transform"] = _overrides.get("transform") or transform # These values can be falsy (False, 0) if "decrypt" not in _overrides: _overrides["decrypt"] = decrypt if "max_age" not in _overrides: _overrides["max_age"] = max_age # NOTE: Split parameters who have decrypt OR have it global if _overrides["decrypt"]: decrypt_parameters[parameter] = _overrides else: batch_parameters[parameter] = _overrides return batch_parameters, decrypt_parameters def _raise_if_errors_key_is_present(parameters: Dict, reserved_parameter: str, raise_on_error: bool): """Raise GetParameterError if fail-fast is disabled and '_errors' key is in parameters batch""" if not raise_on_error and reserved_parameter in parameters: raise GetParameterError( f"You cannot fetch a parameter named '{reserved_parameter}' in graceful error mode.", ) def resolve_truthy_env_var_choice(env: str, choice: Optional[bool] = None) -> bool: """Pick explicit choice over truthy env value, if available, otherwise return truthy env value NOTE: Environment variable should be resolved by the caller. Parameters ---------- env : str environment variable actual value choice : bool explicit choice Returns ------- choice : str resolved choice as either bool or environment value """ return choice if choice is not None else strtobool(env) def resolve_max_age(env: str, choice: Optional[int]) -> int: """Resolve max age value""" return choice if choice is not None else int(env) DEFAULT_MAX_AGE_SECS = "5" DEFAULT_PROVIDERS: Dict[str, Any] = {} TransformOptions = Literal["json", "binary", "auto", None] The provided code snippet includes necessary dependencies for implementing the `get_parameters` function. Write a Python function `def get_parameters( path: str, transform: TransformOptions = None, recursive: bool = True, decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, raise_on_transform_error: bool = False, **sdk_options, ) -> Union[Dict[str, str], Dict[str, dict], Dict[str, bytes]]` to solve the following problem: Retrieve multiple parameter values from AWS Systems Manager (SSM) Parameter Store For readability, we strip the path prefix name in the response. Parameters ---------- path: str Path to retrieve the parameters transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') recursive: bool, optional If this should retrieve the parameter values recursively or not, defaults to True decrypt: bool, optional If the parameter values should be decrypted force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value raise_on_transform_error: bool, optional Raises an exception if any transform fails, otherwise this will return a None value for each transform that failed sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameters_by_path API call Raises ------ GetParameterError When the parameter provider fails to retrieve parameter values for a given path. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves parameter values from Systems Manager Parameter Store** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> values = get_parameters("/my/path/prefix") >>> >>> for key, value in values.items(): ... print(key, value) config Parameter value (/my/path/prefix/config) webhook/config Parameter value (/my/path/prefix/webhook/config) **Retrieves parameter values and decodes them using a Base64 decoder** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> values = get_parameters("/my/path/prefix", transform='binary') Here is the function: def get_parameters( path: str, transform: TransformOptions = None, recursive: bool = True, decrypt: Optional[bool] = None, force_fetch: bool = False, max_age: Optional[int] = None, raise_on_transform_error: bool = False, **sdk_options, ) -> Union[Dict[str, str], Dict[str, dict], Dict[str, bytes]]: """ Retrieve multiple parameter values from AWS Systems Manager (SSM) Parameter Store For readability, we strip the path prefix name in the response. Parameters ---------- path: str Path to retrieve the parameters transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') recursive: bool, optional If this should retrieve the parameter values recursively or not, defaults to True decrypt: bool, optional If the parameter values should be decrypted force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value raise_on_transform_error: bool, optional Raises an exception if any transform fails, otherwise this will return a None value for each transform that failed sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameters_by_path API call Raises ------ GetParameterError When the parameter provider fails to retrieve parameter values for a given path. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves parameter values from Systems Manager Parameter Store** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> values = get_parameters("/my/path/prefix") >>> >>> for key, value in values.items(): ... print(key, value) config Parameter value (/my/path/prefix/config) webhook/config Parameter value (/my/path/prefix/webhook/config) **Retrieves parameter values and decodes them using a Base64 decoder** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> values = get_parameters("/my/path/prefix", transform='binary') """ # Only create the provider if this function is called at least once if "ssm" not in DEFAULT_PROVIDERS: DEFAULT_PROVIDERS["ssm"] = SSMProvider() # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age) # If decrypt is not set, resolve it from the environment variable, defaulting to False decrypt = resolve_truthy_env_var_choice( env=os.getenv(constants.PARAMETERS_SSM_DECRYPT_ENV, "false"), choice=decrypt, ) sdk_options["recursive"] = recursive sdk_options["decrypt"] = decrypt return DEFAULT_PROVIDERS["ssm"].get_multiple( path, max_age=max_age, transform=transform, raise_on_transform_error=raise_on_transform_error, force_fetch=force_fetch, **sdk_options, )
Retrieve multiple parameter values from AWS Systems Manager (SSM) Parameter Store For readability, we strip the path prefix name in the response. Parameters ---------- path: str Path to retrieve the parameters transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') recursive: bool, optional If this should retrieve the parameter values recursively or not, defaults to True decrypt: bool, optional If the parameter values should be decrypted force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value raise_on_transform_error: bool, optional Raises an exception if any transform fails, otherwise this will return a None value for each transform that failed sdk_options: dict, optional Dictionary of options that will be passed to the Parameter Store get_parameters_by_path API call Raises ------ GetParameterError When the parameter provider fails to retrieve parameter values for a given path. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves parameter values from Systems Manager Parameter Store** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> values = get_parameters("/my/path/prefix") >>> >>> for key, value in values.items(): ... print(key, value) config Parameter value (/my/path/prefix/config) webhook/config Parameter value (/my/path/prefix/webhook/config) **Retrieves parameter values and decodes them using a Base64 decoder** >>> from aws_lambda_powertools.utilities.parameters import get_parameter >>> >>> values = get_parameters("/my/path/prefix", transform='binary')
5,057
from __future__ import annotations import base64 import json import os from abc import ABC, abstractmethod from datetime import datetime, timedelta from typing import ( TYPE_CHECKING, Any, Callable, Dict, NamedTuple, Optional, Tuple, Type, Union, cast, overload, ) import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants, user_agent from aws_lambda_powertools.shared.functions import resolve_max_age from aws_lambda_powertools.utilities.parameters.types import TransformOptions from .exceptions import GetParameterError, TransformParameterError TransformOptions = Literal["json", "binary", "auto", None] def transform_value( value: Dict[str, Any], transform: TransformOptions, raise_on_transform_error: bool = False, key: str = "", ) -> Dict[str, Any]: ...
null
5,058
from __future__ import annotations import base64 import json import os from abc import ABC, abstractmethod from datetime import datetime, timedelta from typing import ( TYPE_CHECKING, Any, Callable, Dict, NamedTuple, Optional, Tuple, Type, Union, cast, overload, ) import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants, user_agent from aws_lambda_powertools.shared.functions import resolve_max_age from aws_lambda_powertools.utilities.parameters.types import TransformOptions from .exceptions import GetParameterError, TransformParameterError TransformOptions = Literal["json", "binary", "auto", None] def transform_value( value: Union[str, bytes, Dict[str, Any]], transform: TransformOptions, raise_on_transform_error: bool = False, key: str = "", ) -> Optional[Union[str, bytes, Dict[str, Any]]]: ...
null
5,059
from __future__ import annotations import base64 import json import os from abc import ABC, abstractmethod from datetime import datetime, timedelta from typing import ( TYPE_CHECKING, Any, Callable, Dict, NamedTuple, Optional, Tuple, Type, Union, cast, overload, ) import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants, user_agent from aws_lambda_powertools.shared.functions import resolve_max_age from aws_lambda_powertools.utilities.parameters.types import TransformOptions from .exceptions import GetParameterError, TransformParameterError def get_transform_method(value: str, transform: TransformOptions = None) -> Callable[..., Any]: """ Determine the transform method Examples ------- >>> get_transform_method("key","any_other_value") 'any_other_value' >>> get_transform_method("key.json","auto") 'json' >>> get_transform_method("key.binary","auto") 'binary' >>> get_transform_method("key","auto") None >>> get_transform_method("key",None) None Parameters --------- value: str Only used when the transform is "auto". transform: str, optional Original transform method, only "auto" will try to detect the transform method by the key Returns ------ Callable: Transform function could be json.loads, base64.b64decode, or a lambda that echo the str value """ transform_method = TRANSFORM_METHOD_MAPPING.get(transform) if transform == "auto": key_suffix = value.rsplit(".")[-1] transform_method = TRANSFORM_METHOD_MAPPING.get(key_suffix, TRANSFORM_METHOD_MAPPING[None]) return cast(Callable, transform_method) # https://github.com/python/mypy/issues/10740 TransformOptions = Literal["json", "binary", "auto", None] class TransformParameterError(Exception): """When a provider fails to transform a parameter value""" The provided code snippet includes necessary dependencies for implementing the `transform_value` function. Write a Python function `def transform_value( value: Union[str, bytes, Dict[str, Any]], transform: TransformOptions, raise_on_transform_error: bool = True, key: str = "", ) -> Optional[Union[str, bytes, Dict[str, Any]]]` to solve the following problem: Transform a value using one of the available options. Parameters --------- value: str Parameter value to transform transform: str Type of transform, supported values are "json", "binary", and "auto" based on suffix (.json, .binary) key: str Parameter key when transform is auto to infer its transform method raise_on_transform_error: bool, optional Raises an exception if any transform fails, otherwise this will return a None value for each transform that failed Raises ------ TransformParameterError: When the parameter value could not be transformed Here is the function: def transform_value( value: Union[str, bytes, Dict[str, Any]], transform: TransformOptions, raise_on_transform_error: bool = True, key: str = "", ) -> Optional[Union[str, bytes, Dict[str, Any]]]: """ Transform a value using one of the available options. Parameters --------- value: str Parameter value to transform transform: str Type of transform, supported values are "json", "binary", and "auto" based on suffix (.json, .binary) key: str Parameter key when transform is auto to infer its transform method raise_on_transform_error: bool, optional Raises an exception if any transform fails, otherwise this will return a None value for each transform that failed Raises ------ TransformParameterError: When the parameter value could not be transformed """ # Maintenance: For v3, we should consider returning the original value for soft transform failures. err_msg = "Unable to transform value using '{transform}' transform: {exc}" if isinstance(value, bytes): value = value.decode("utf-8") if isinstance(value, dict): # NOTE: We must handle partial failures when receiving multiple values # where one of the keys might fail during transform, e.g. `{"a": "valid", "b": "{"}` # expected: `{"a": "valid", "b": None}` transformed_values: Dict[str, Any] = {} for dict_key, dict_value in value.items(): transform_method = get_transform_method(value=dict_key, transform=transform) try: transformed_values[dict_key] = transform_method(dict_value) except Exception as exc: if raise_on_transform_error: raise TransformParameterError(err_msg.format(transform=transform, exc=exc)) from exc transformed_values[dict_key] = None return transformed_values if transform == "auto": # key="a.json", value='{"a": "b"}', or key="a.binary", value="b64_encoded" transform_method = get_transform_method(value=key, transform=transform) else: # value='{"key": "value"} transform_method = get_transform_method(value=value, transform=transform) try: return transform_method(value) except Exception as exc: if raise_on_transform_error: raise TransformParameterError(err_msg.format(transform=transform, exc=exc)) from exc return None
Transform a value using one of the available options. Parameters --------- value: str Parameter value to transform transform: str Type of transform, supported values are "json", "binary", and "auto" based on suffix (.json, .binary) key: str Parameter key when transform is auto to infer its transform method raise_on_transform_error: bool, optional Raises an exception if any transform fails, otherwise this will return a None value for each transform that failed Raises ------ TransformParameterError: When the parameter value could not be transformed
5,060
from __future__ import annotations import base64 import json import os from abc import ABC, abstractmethod from datetime import datetime, timedelta from typing import ( TYPE_CHECKING, Any, Callable, Dict, NamedTuple, Optional, Tuple, Type, Union, cast, overload, ) import boto3 from botocore.config import Config from aws_lambda_powertools.shared import constants, user_agent from aws_lambda_powertools.shared.functions import resolve_max_age from aws_lambda_powertools.utilities.parameters.types import TransformOptions from .exceptions import GetParameterError, TransformParameterError DEFAULT_PROVIDERS: Dict[str, Any] = {} The provided code snippet includes necessary dependencies for implementing the `clear_caches` function. Write a Python function `def clear_caches()` to solve the following problem: Clear cached parameter values from all providers Here is the function: def clear_caches(): """Clear cached parameter values from all providers""" DEFAULT_PROVIDERS.clear()
Clear cached parameter values from all providers
5,061
import os from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.utilities.parameters.types import TransformOptions from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import resolve_max_age from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider def get_secret( name: str, transform: None = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> str: ...
null
5,062
import os from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.utilities.parameters.types import TransformOptions from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import resolve_max_age from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider def get_secret( name: str, transform: Literal["json"], force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> dict: ...
null
5,063
import os from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.utilities.parameters.types import TransformOptions from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import resolve_max_age from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider def get_secret( name: str, transform: Literal["binary"], force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> Union[str, dict, bytes]: ...
null
5,064
import os from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.utilities.parameters.types import TransformOptions from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import resolve_max_age from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider def get_secret( name: str, transform: Literal["auto"], force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> bytes: ...
null
5,065
import os from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union, overload import boto3 from botocore.config import Config from aws_lambda_powertools.utilities.parameters.types import TransformOptions from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.functions import resolve_max_age from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider class SecretsProvider(BaseProvider): """ AWS Secrets Manager Parameter Provider Parameters ---------- config: botocore.config.Config, optional Botocore configuration to pass during client initialization boto3_session : boto3.session.Session, optional Boto3 session to create a boto3_client from boto3_client: SecretsManagerClient, optional Boto3 SecretsManager Client to use, boto3_session will be ignored if both are provided Example ------- **Retrieves a parameter value from Secrets Manager** >>> from aws_lambda_powertools.utilities.parameters import SecretsProvider >>> secrets_provider = SecretsProvider() >>> >>> value = secrets_provider.get("my-parameter") >>> >>> print(value) My parameter value **Retrieves a parameter value from Secrets Manager in another AWS region** >>> from botocore.config import Config >>> from aws_lambda_powertools.utilities.parameters import SecretsProvider >>> >>> config = Config(region_name="us-west-1") >>> secrets_provider = SecretsProvider(config=config) >>> >>> value = secrets_provider.get("my-parameter") >>> >>> print(value) My parameter value **Retrieves a parameter value from Secrets Manager passing options to the SDK call** >>> from aws_lambda_powertools.utilities.parameters import SecretsProvider >>> secrets_provider = SecretsProvider() >>> >>> value = secrets_provider.get("my-parameter", VersionId="f658cac0-98a5-41d9-b993-8a76a7799194") >>> >>> print(value) My parameter value """ client: Any = None def __init__( self, config: Optional[Config] = None, boto3_session: Optional[boto3.session.Session] = None, boto3_client: Optional["SecretsManagerClient"] = None, ): """ Initialize the Secrets Manager client """ super().__init__() self.client: "SecretsManagerClient" = self._build_boto3_client( service_name="secretsmanager", client=boto3_client, session=boto3_session, config=config, ) def _get(self, name: str, **sdk_options) -> str: """ Retrieve a parameter value from AWS Systems Manager Parameter Store Parameters ---------- name: str Name of the parameter sdk_options: dict, optional Dictionary of options that will be passed to the Secrets Manager get_secret_value API call """ # Explicit arguments will take precedence over keyword arguments sdk_options["SecretId"] = name secret_value = self.client.get_secret_value(**sdk_options) if "SecretString" in secret_value: return secret_value["SecretString"] return secret_value["SecretBinary"] def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]: """ Retrieving multiple parameter values is not supported with AWS Secrets Manager """ raise NotImplementedError() TransformOptions = Literal["json", "binary", "auto", None] def resolve_max_age(env: str, choice: Optional[int]) -> int: """Resolve max age value""" return choice if choice is not None else int(env) DEFAULT_MAX_AGE_SECS = "5" DEFAULT_PROVIDERS: Dict[str, Any] = {} The provided code snippet includes necessary dependencies for implementing the `get_secret` function. Write a Python function `def get_secret( name: str, transform: TransformOptions = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> Union[str, dict, bytes]` to solve the following problem: Retrieve a parameter value from AWS Secrets Manager Parameters ---------- name: str Name of the parameter transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value sdk_options: dict, optional Dictionary of options that will be passed to the get_secret_value call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves a secret*** >>> from aws_lambda_powertools.utilities.parameters import get_secret >>> >>> get_secret("my-secret") **Retrieves a secret and transforms using a JSON deserializer*** >>> from aws_lambda_powertools.utilities.parameters import get_secret >>> >>> get_secret("my-secret", transform="json") **Retrieves a secret and passes custom arguments to the SDK** >>> from aws_lambda_powertools.utilities.parameters import get_secret >>> >>> get_secret("my-secret", VersionId="f658cac0-98a5-41d9-b993-8a76a7799194") Here is the function: def get_secret( name: str, transform: TransformOptions = None, force_fetch: bool = False, max_age: Optional[int] = None, **sdk_options, ) -> Union[str, dict, bytes]: """ Retrieve a parameter value from AWS Secrets Manager Parameters ---------- name: str Name of the parameter transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value sdk_options: dict, optional Dictionary of options that will be passed to the get_secret_value call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves a secret*** >>> from aws_lambda_powertools.utilities.parameters import get_secret >>> >>> get_secret("my-secret") **Retrieves a secret and transforms using a JSON deserializer*** >>> from aws_lambda_powertools.utilities.parameters import get_secret >>> >>> get_secret("my-secret", transform="json") **Retrieves a secret and passes custom arguments to the SDK** >>> from aws_lambda_powertools.utilities.parameters import get_secret >>> >>> get_secret("my-secret", VersionId="f658cac0-98a5-41d9-b993-8a76a7799194") """ # If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS max_age = resolve_max_age(env=os.getenv(constants.PARAMETERS_MAX_AGE_ENV, DEFAULT_MAX_AGE_SECS), choice=max_age) # Only create the provider if this function is called at least once if "secrets" not in DEFAULT_PROVIDERS: DEFAULT_PROVIDERS["secrets"] = SecretsProvider() return DEFAULT_PROVIDERS["secrets"].get( name, max_age=max_age, transform=transform, force_fetch=force_fetch, **sdk_options, )
Retrieve a parameter value from AWS Secrets Manager Parameters ---------- name: str Name of the parameter transform: str, optional Transforms the content from a JSON object ('json') or base64 binary string ('binary') force_fetch: bool, optional Force update even before a cached item has expired, defaults to False max_age: int, optional Maximum age of the cached value sdk_options: dict, optional Dictionary of options that will be passed to the get_secret_value call Raises ------ GetParameterError When the parameter provider fails to retrieve a parameter value for a given name. TransformParameterError When the parameter provider fails to transform a parameter value. Example ------- **Retrieves a secret*** >>> from aws_lambda_powertools.utilities.parameters import get_secret >>> >>> get_secret("my-secret") **Retrieves a secret and transforms using a JSON deserializer*** >>> from aws_lambda_powertools.utilities.parameters import get_secret >>> >>> get_secret("my-secret", transform="json") **Retrieves a secret and passes custom arguments to the SDK** >>> from aws_lambda_powertools.utilities.parameters import get_secret >>> >>> get_secret("my-secret", VersionId="f658cac0-98a5-41d9-b993-8a76a7799194")
5,066
from __future__ import annotations from datetime import datetime, tzinfo from typing import Any, Dict, Optional from dateutil.tz import gettz from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues def _get_now_from_timezone(timezone: Optional[tzinfo]) -> datetime: """ Returns now in the specified timezone. Defaults to UTC if not present. At this stage, we already validated that the passed timezone string is valid, so we assume that gettz() will return a tzinfo object. """ timezone = gettz("UTC") if timezone is None else timezone return datetime.now(timezone) class TimeValues(Enum): """ Possible values when using time rules """ START = "START" END = "END" TIMEZONE = "TIMEZONE" DAYS = "DAYS" SUNDAY = "SUNDAY" MONDAY = "MONDAY" TUESDAY = "TUESDAY" WEDNESDAY = "WEDNESDAY" THURSDAY = "THURSDAY" FRIDAY = "FRIDAY" SATURDAY = "SATURDAY" def days(cls) -> list[str]: return [day.value for day in cls if day.value not in ["START", "END", "TIMEZONE"]] def compare_days_of_week(context_value: Any, condition_value: Dict) -> bool: timezone_name = condition_value.get(TimeValues.TIMEZONE.value, "UTC") # %A = Weekday as locale’s full name. current_day = _get_now_from_timezone(gettz(timezone_name)).strftime("%A").upper() days = condition_value.get(TimeValues.DAYS.value, []) return current_day in days
null
5,067
from __future__ import annotations from datetime import datetime, tzinfo from typing import Any, Dict, Optional from dateutil.tz import gettz from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues def _get_now_from_timezone(timezone: Optional[tzinfo]) -> datetime: """ Returns now in the specified timezone. Defaults to UTC if not present. At this stage, we already validated that the passed timezone string is valid, so we assume that gettz() will return a tzinfo object. """ timezone = gettz("UTC") if timezone is None else timezone return datetime.now(timezone) class TimeValues(Enum): """ Possible values when using time rules """ START = "START" END = "END" TIMEZONE = "TIMEZONE" DAYS = "DAYS" SUNDAY = "SUNDAY" MONDAY = "MONDAY" TUESDAY = "TUESDAY" WEDNESDAY = "WEDNESDAY" THURSDAY = "THURSDAY" FRIDAY = "FRIDAY" SATURDAY = "SATURDAY" def days(cls) -> list[str]: return [day.value for day in cls if day.value not in ["START", "END", "TIMEZONE"]] def compare_datetime_range(context_value: Any, condition_value: Dict) -> bool: timezone_name = condition_value.get(TimeValues.TIMEZONE.value, "UTC") timezone = gettz(timezone_name) current_time: datetime = _get_now_from_timezone(timezone) start_date_str = condition_value.get(TimeValues.START.value, "") end_date_str = condition_value.get(TimeValues.END.value, "") # Since start_date and end_date doesn't include timezone information, we mark the timestamp # with the same timezone as the current_time. This way all the 3 timestamps will be on # the same timezone. start_date = datetime.fromisoformat(start_date_str).replace(tzinfo=timezone) end_date = datetime.fromisoformat(end_date_str).replace(tzinfo=timezone) return start_date <= current_time <= end_date
null
5,068
from __future__ import annotations from datetime import datetime, tzinfo from typing import Any, Dict, Optional from dateutil.tz import gettz from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues def _get_now_from_timezone(timezone: Optional[tzinfo]) -> datetime: HOUR_MIN_SEPARATOR = ":" class TimeValues(Enum): def days(cls) -> list[str]: def compare_time_range(context_value: Any, condition_value: Dict) -> bool: timezone_name = condition_value.get(TimeValues.TIMEZONE.value, "UTC") current_time: datetime = _get_now_from_timezone(gettz(timezone_name)) start_hour, start_min = condition_value.get(TimeValues.START.value, "").split(HOUR_MIN_SEPARATOR) end_hour, end_min = condition_value.get(TimeValues.END.value, "").split(HOUR_MIN_SEPARATOR) start_time = current_time.replace(hour=int(start_hour), minute=int(start_min)) end_time = current_time.replace(hour=int(end_hour), minute=int(end_min)) if int(end_hour) < int(start_hour): # When the end hour is smaller than start hour, it means we are crossing a day's boundary. # In this case we need to assert that current_time is **either** on one side or the other side of the boundary # # ┌─────┐ ┌─────┐ ┌─────┐ # │20.00│ │00.00│ │04.00│ # └─────┘ └─────┘ └─────┘ # ───────────────────────────────────────────┬─────────────────────────────────────────▶ # ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ # │ │ │ # │ either this area │ │ or this area # │ │ │ # └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ # │ return (start_time <= current_time) or (current_time <= end_time) else: # In normal circumstances, we need to assert **both** conditions return start_time <= current_time <= end_time
null
5,069
from __future__ import annotations from datetime import datetime, tzinfo from typing import Any, Dict, Optional from dateutil.tz import gettz from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues class ModuloRangeValues(Enum): """ Possible values when using modulo range rule """ BASE = "BASE" START = "START" END = "END" The provided code snippet includes necessary dependencies for implementing the `compare_modulo_range` function. Write a Python function `def compare_modulo_range(context_value: int, condition_value: Dict) -> bool` to solve the following problem: Returns for a given context 'a' and modulo condition 'b' -> b.start <= a % b.base <= b.end Here is the function: def compare_modulo_range(context_value: int, condition_value: Dict) -> bool: """ Returns for a given context 'a' and modulo condition 'b' -> b.start <= a % b.base <= b.end """ base = condition_value.get(ModuloRangeValues.BASE.value, 1) start = condition_value.get(ModuloRangeValues.START.value, 1) end = condition_value.get(ModuloRangeValues.END.value, 1) return start <= context_value % base <= end
Returns for a given context 'a' and modulo condition 'b' -> b.start <= a % b.base <= b.end
5,070
from __future__ import annotations from datetime import datetime, tzinfo from typing import Any, Dict, Optional from dateutil.tz import gettz from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues The provided code snippet includes necessary dependencies for implementing the `compare_any_in_list` function. Write a Python function `def compare_any_in_list(context_value: list, condition_value: list) -> bool` to solve the following problem: Comparator for ANY_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether any list item in context_value is available in condition_value Here is the function: def compare_any_in_list(context_value: list, condition_value: list) -> bool: """Comparator for ANY_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether any list item in context_value is available in condition_value """ if not isinstance(context_value, list): raise ValueError("Context provided must be a list. Unable to compare ANY_IN_VALUE action.") return any(key in condition_value for key in context_value)
Comparator for ANY_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether any list item in context_value is available in condition_value
5,071
from __future__ import annotations from datetime import datetime, tzinfo from typing import Any, Dict, Optional from dateutil.tz import gettz from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues The provided code snippet includes necessary dependencies for implementing the `compare_all_in_list` function. Write a Python function `def compare_all_in_list(context_value: list, condition_value: list) -> bool` to solve the following problem: Comparator for ALL_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether all list items in context_value are available in condition_value Here is the function: def compare_all_in_list(context_value: list, condition_value: list) -> bool: """Comparator for ALL_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether all list items in context_value are available in condition_value """ if not isinstance(context_value, list): raise ValueError("Context provided must be a list. Unable to compare ALL_IN_VALUE action.") return all(key in condition_value for key in context_value)
Comparator for ALL_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether all list items in context_value are available in condition_value
5,072
from __future__ import annotations from datetime import datetime, tzinfo from typing import Any, Dict, Optional from dateutil.tz import gettz from .schema import HOUR_MIN_SEPARATOR, ModuloRangeValues, TimeValues The provided code snippet includes necessary dependencies for implementing the `compare_none_in_list` function. Write a Python function `def compare_none_in_list(context_value: list, condition_value: list) -> bool` to solve the following problem: Comparator for NONE_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether list items in context_value are **not** available in condition_value Here is the function: def compare_none_in_list(context_value: list, condition_value: list) -> bool: """Comparator for NONE_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether list items in context_value are **not** available in condition_value """ if not isinstance(context_value, list): raise ValueError("Context provided must be a list. Unable to compare NONE_IN_VALUE action.") return all(key not in condition_value for key in context_value)
Comparator for NONE_IN_VALUE action Parameters ---------- context_value : list user-defined context for flag evaluation condition_value : list schema value available for condition being evaluated Returns ------- bool Whether list items in context_value are **not** available in condition_value
5,073
import logging from typing import Any, Callable, Dict, Optional, Union from aws_lambda_powertools.utilities import jmespath_utils from ...middleware_factory import lambda_handler_decorator from .base import validate_data_against_schema logger = logging.getLogger(__name__) def validate_data_against_schema(data: Union[Dict, str], schema: Dict, formats: Optional[Dict] = None): """Validate dict data against given JSON Schema Parameters ---------- data : Dict Data set to be validated schema : Dict JSON Schema to validate against formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool Raises ------ SchemaValidationError When schema validation fails against data set InvalidSchemaFormatError When JSON schema provided is invalid """ try: formats = formats or {} fastjsonschema.validate(definition=schema, data=data, formats=formats) except (TypeError, AttributeError, fastjsonschema.JsonSchemaDefinitionException) as e: raise InvalidSchemaFormatError(f"Schema received: {schema}, Formats: {formats}. Error: {e}") except fastjsonschema.JsonSchemaValueException as e: message = f"Failed schema validation. Error: {e.message}, Path: {e.path}, Data: {e.value}" # noqa: B306 raise SchemaValidationError( message, validation_message=e.message, # noqa: B306 name=e.name, path=e.path, value=e.value, definition=e.definition, rule=e.rule, rule_definition=e.rule_definition, ) The provided code snippet includes necessary dependencies for implementing the `validator` function. Write a Python function `def validator( handler: Callable, event: Union[Dict, str], context: Any, inbound_schema: Optional[Dict] = None, inbound_formats: Optional[Dict] = None, outbound_schema: Optional[Dict] = None, outbound_formats: Optional[Dict] = None, envelope: str = "", jmespath_options: Optional[Dict] = None, **kwargs: Any, ) -> Any` to solve the following problem: Lambda handler decorator to validate incoming/outbound data using a JSON Schema Parameters ---------- handler : Callable Method to annotate on event : Dict Lambda event to be validated context : Any Lambda context object inbound_schema : Dict JSON Schema to validate incoming event outbound_schema : Dict JSON Schema to validate outbound event envelope : Dict JMESPath expression to filter data against jmespath_options : Dict Alternative JMESPath options to be included when filtering expr inbound_formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool outbound_formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool Example ------- **Validate incoming event** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict) def handler(event, context): return event **Validate incoming and outgoing event** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, outbound_schema=response_json_schema_dict) def handler(event, context): return event **Unwrap event before validating against actual payload - using built-in envelopes** from aws_lambda_powertools.utilities.validation import validator, envelopes @validator(inbound_schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST) def handler(event, context): return event **Unwrap event before validating against actual payload - using custom JMESPath expression** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="payload[*].my_data") def handler(event, context): return event **Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="Records[*].powertools_json(body)") def handler(event, context): return event **Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))") def handler(event, context): return event **Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]") def handler(event, context): return event Returns ------- Any Lambda handler response Raises ------ SchemaValidationError When schema validation fails against data set InvalidSchemaFormatError When JSON schema provided is invalid InvalidEnvelopeExpressionError When JMESPath expression to unwrap event is invalid Here is the function: def validator( handler: Callable, event: Union[Dict, str], context: Any, inbound_schema: Optional[Dict] = None, inbound_formats: Optional[Dict] = None, outbound_schema: Optional[Dict] = None, outbound_formats: Optional[Dict] = None, envelope: str = "", jmespath_options: Optional[Dict] = None, **kwargs: Any, ) -> Any: """Lambda handler decorator to validate incoming/outbound data using a JSON Schema Parameters ---------- handler : Callable Method to annotate on event : Dict Lambda event to be validated context : Any Lambda context object inbound_schema : Dict JSON Schema to validate incoming event outbound_schema : Dict JSON Schema to validate outbound event envelope : Dict JMESPath expression to filter data against jmespath_options : Dict Alternative JMESPath options to be included when filtering expr inbound_formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool outbound_formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool Example ------- **Validate incoming event** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict) def handler(event, context): return event **Validate incoming and outgoing event** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, outbound_schema=response_json_schema_dict) def handler(event, context): return event **Unwrap event before validating against actual payload - using built-in envelopes** from aws_lambda_powertools.utilities.validation import validator, envelopes @validator(inbound_schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST) def handler(event, context): return event **Unwrap event before validating against actual payload - using custom JMESPath expression** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="payload[*].my_data") def handler(event, context): return event **Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="Records[*].powertools_json(body)") def handler(event, context): return event **Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))") def handler(event, context): return event **Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]") def handler(event, context): return event Returns ------- Any Lambda handler response Raises ------ SchemaValidationError When schema validation fails against data set InvalidSchemaFormatError When JSON schema provided is invalid InvalidEnvelopeExpressionError When JMESPath expression to unwrap event is invalid """ # noqa: E501 if envelope: event = jmespath_utils.extract_data_from_envelope( data=event, envelope=envelope, jmespath_options=jmespath_options, ) if inbound_schema: logger.debug("Validating inbound event") validate_data_against_schema(data=event, schema=inbound_schema, formats=inbound_formats) response = handler(event, context, **kwargs) if outbound_schema: logger.debug("Validating outbound event") validate_data_against_schema(data=response, schema=outbound_schema, formats=outbound_formats) return response
Lambda handler decorator to validate incoming/outbound data using a JSON Schema Parameters ---------- handler : Callable Method to annotate on event : Dict Lambda event to be validated context : Any Lambda context object inbound_schema : Dict JSON Schema to validate incoming event outbound_schema : Dict JSON Schema to validate outbound event envelope : Dict JMESPath expression to filter data against jmespath_options : Dict Alternative JMESPath options to be included when filtering expr inbound_formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool outbound_formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool Example ------- **Validate incoming event** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict) def handler(event, context): return event **Validate incoming and outgoing event** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, outbound_schema=response_json_schema_dict) def handler(event, context): return event **Unwrap event before validating against actual payload - using built-in envelopes** from aws_lambda_powertools.utilities.validation import validator, envelopes @validator(inbound_schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST) def handler(event, context): return event **Unwrap event before validating against actual payload - using custom JMESPath expression** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="payload[*].my_data") def handler(event, context): return event **Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="Records[*].powertools_json(body)") def handler(event, context): return event **Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))") def handler(event, context): return event **Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validator @validator(inbound_schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]") def handler(event, context): return event Returns ------- Any Lambda handler response Raises ------ SchemaValidationError When schema validation fails against data set InvalidSchemaFormatError When JSON schema provided is invalid InvalidEnvelopeExpressionError When JMESPath expression to unwrap event is invalid
5,074
import logging from typing import Any, Callable, Dict, Optional, Union from aws_lambda_powertools.utilities import jmespath_utils from ...middleware_factory import lambda_handler_decorator from .base import validate_data_against_schema def validate_data_against_schema(data: Union[Dict, str], schema: Dict, formats: Optional[Dict] = None): """Validate dict data against given JSON Schema Parameters ---------- data : Dict Data set to be validated schema : Dict JSON Schema to validate against formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool Raises ------ SchemaValidationError When schema validation fails against data set InvalidSchemaFormatError When JSON schema provided is invalid """ try: formats = formats or {} fastjsonschema.validate(definition=schema, data=data, formats=formats) except (TypeError, AttributeError, fastjsonschema.JsonSchemaDefinitionException) as e: raise InvalidSchemaFormatError(f"Schema received: {schema}, Formats: {formats}. Error: {e}") except fastjsonschema.JsonSchemaValueException as e: message = f"Failed schema validation. Error: {e.message}, Path: {e.path}, Data: {e.value}" # noqa: B306 raise SchemaValidationError( message, validation_message=e.message, # noqa: B306 name=e.name, path=e.path, value=e.value, definition=e.definition, rule=e.rule, rule_definition=e.rule_definition, ) The provided code snippet includes necessary dependencies for implementing the `validate` function. Write a Python function `def validate( event: Any, schema: Dict, formats: Optional[Dict] = None, envelope: Optional[str] = None, jmespath_options: Optional[Dict] = None, )` to solve the following problem: Standalone function to validate event data using a JSON Schema Typically used when you need more control over the validation process. Parameters ---------- event : Dict Lambda event to be validated schema : Dict JSON Schema to validate incoming event envelope : Dict JMESPath expression to filter data against jmespath_options : Dict Alternative JMESPath options to be included when filtering expr formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool Example ------- **Validate event** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict) return event **Unwrap event before validating against actual payload - using built-in envelopes** from aws_lambda_powertools.utilities.validation import validate, envelopes def handler(event, context): validate(event=event, schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST) return event **Unwrap event before validating against actual payload - using custom JMESPath expression** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="payload[*].my_data") return event **Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="Records[*].powertools_json(body)") return event **Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))") return event **Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]") return event Raises ------ SchemaValidationError When schema validation fails against data set InvalidSchemaFormatError When JSON schema provided is invalid InvalidEnvelopeExpressionError When JMESPath expression to unwrap event is invalid Here is the function: def validate( event: Any, schema: Dict, formats: Optional[Dict] = None, envelope: Optional[str] = None, jmespath_options: Optional[Dict] = None, ): """Standalone function to validate event data using a JSON Schema Typically used when you need more control over the validation process. Parameters ---------- event : Dict Lambda event to be validated schema : Dict JSON Schema to validate incoming event envelope : Dict JMESPath expression to filter data against jmespath_options : Dict Alternative JMESPath options to be included when filtering expr formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool Example ------- **Validate event** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict) return event **Unwrap event before validating against actual payload - using built-in envelopes** from aws_lambda_powertools.utilities.validation import validate, envelopes def handler(event, context): validate(event=event, schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST) return event **Unwrap event before validating against actual payload - using custom JMESPath expression** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="payload[*].my_data") return event **Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="Records[*].powertools_json(body)") return event **Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))") return event **Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]") return event Raises ------ SchemaValidationError When schema validation fails against data set InvalidSchemaFormatError When JSON schema provided is invalid InvalidEnvelopeExpressionError When JMESPath expression to unwrap event is invalid """ # noqa: E501 if envelope: event = jmespath_utils.extract_data_from_envelope( data=event, envelope=envelope, jmespath_options=jmespath_options, ) validate_data_against_schema(data=event, schema=schema, formats=formats)
Standalone function to validate event data using a JSON Schema Typically used when you need more control over the validation process. Parameters ---------- event : Dict Lambda event to be validated schema : Dict JSON Schema to validate incoming event envelope : Dict JMESPath expression to filter data against jmespath_options : Dict Alternative JMESPath options to be included when filtering expr formats: Dict Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool Example ------- **Validate event** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict) return event **Unwrap event before validating against actual payload - using built-in envelopes** from aws_lambda_powertools.utilities.validation import validate, envelopes def handler(event, context): validate(event=event, schema=json_schema_dict, envelope=envelopes.API_GATEWAY_REST) return event **Unwrap event before validating against actual payload - using custom JMESPath expression** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="payload[*].my_data") return event **Unwrap and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="Records[*].powertools_json(body)") return event **Unwrap, decode base64 and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="Records[*].kinesis.powertools_json(powertools_base64(data))") return event **Unwrap, decompress ZIP archive and deserialize JSON string event before validating against actual payload - using built-in functions** from aws_lambda_powertools.utilities.validation import validate def handler(event, context): validate(event=event, schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]") return event Raises ------ SchemaValidationError When schema validation fails against data set InvalidSchemaFormatError When JSON schema provided is invalid InvalidEnvelopeExpressionError When JMESPath expression to unwrap event is invalid
5,075
import logging import typing from typing import Any, Callable, Dict, Optional, Type, overload from aws_lambda_powertools.utilities.parser.compat import disable_pydantic_v2_warning from aws_lambda_powertools.utilities.parser.types import EventParserReturnType, Model from ...middleware_factory import lambda_handler_decorator from ..typing import LambdaContext from .envelopes.base import Envelope from .exceptions import InvalidEnvelopeError, InvalidModelTypeError logger = logging.getLogger(__name__) def parse(event: Dict[str, Any], model: Type[Model]) -> Model: ... # pragma: no cover def parse(event: Dict[str, Any], model: Type[Model], envelope: Type[Envelope]) -> Model: ... # pragma: no cover def parse(event: Dict[str, Any], model: Type[Model], envelope: Optional[Type[Envelope]] = None): """Standalone function to parse & validate events using Pydantic models Typically used when you need fine-grained control over error handling compared to event_parser decorator. Example ------- **Lambda handler decorator to parse & validate event** from aws_lambda_powertools.utilities.parser import ValidationError class Order(BaseModel): id: int description: str ... def handler(event: Order, context: LambdaContext): try: parse(model=Order) except ValidationError: ... **Lambda handler decorator to parse & validate event - using built-in envelope** class Order(BaseModel): id: int description: str ... def handler(event: Order, context: LambdaContext): try: parse(model=Order, envelope=envelopes.EVENTBRIDGE) except ValidationError: ... Parameters ---------- event: Dict Lambda event to be parsed & validated model: Model Your data model that will replace the event envelope: Envelope Optional envelope to extract the model from Raises ------ ValidationError When input event does not conform with model provided InvalidModelTypeError When model given does not implement BaseModel InvalidEnvelopeError When envelope given does not implement BaseEnvelope """ if envelope and callable(envelope): try: logger.debug(f"Parsing and validating event model with envelope={envelope}") return envelope().parse(data=event, model=model) except AttributeError as exc: raise InvalidEnvelopeError( f"Error: {str(exc)}. Please ensure that both the Input model and the Envelope inherits from BaseModel,\n" # noqa E501 "and your payload adheres to the specified Input model structure.\n" f"Envelope={envelope}\nModel={model}", ) try: disable_pydantic_v2_warning() logger.debug("Parsing and validating event model; no envelope used") if isinstance(event, str): return model.parse_raw(event) return model.parse_obj(event) except AttributeError as exc: raise InvalidModelTypeError( f"Error: {str(exc)}. Please ensure the Input model inherits from BaseModel,\n" "and your payload adheres to the specified Input model structure.\n" f"Model={model}", ) Model = TypeVar("Model", bound=BaseModel) EventParserReturnType = TypeVar("EventParserReturnType") Envelope = TypeVar("Envelope", bound=BaseEnvelope) class InvalidModelTypeError(Exception): """Input data model does not implement BaseModel""" The provided code snippet includes necessary dependencies for implementing the `event_parser` function. Write a Python function `def event_parser( handler: Callable[..., EventParserReturnType], event: Dict[str, Any], context: LambdaContext, model: Optional[Type[Model]] = None, envelope: Optional[Type[Envelope]] = None, **kwargs: Any, ) -> EventParserReturnType` to solve the following problem: Lambda handler decorator to parse & validate events using Pydantic models It requires a model that implements Pydantic BaseModel to parse & validate the event. When an envelope is given, it'll use the following logic: 1. Parse the event against the envelope model first e.g. EnvelopeModel(**event) 2. Envelope will extract a given key to be parsed against the model e.g. event.detail This is useful when you need to confirm event wrapper structure, and b) selectively extract a portion of your payload for parsing & validation. NOTE: If envelope is omitted, the complete event is parsed to match the model parameter BaseModel definition. Example ------- **Lambda handler decorator to parse & validate event** class Order(BaseModel): id: int description: str ... @event_parser(model=Order) def handler(event: Order, context: LambdaContext): ... **Lambda handler decorator to parse & validate event - using built-in envelope** class Order(BaseModel): id: int description: str ... @event_parser(model=Order, envelope=envelopes.EVENTBRIDGE) def handler(event: Order, context: LambdaContext): ... Parameters ---------- handler: Callable Method to annotate on event: Dict Lambda event to be parsed & validated context: LambdaContext Lambda context object model: Model Your data model that will replace the event. envelope: Envelope Optional envelope to extract the model from Raises ------ ValidationError When input event does not conform with model provided InvalidModelTypeError When model given does not implement BaseModel or is not provided InvalidEnvelopeError When envelope given does not implement BaseEnvelope Here is the function: def event_parser( handler: Callable[..., EventParserReturnType], event: Dict[str, Any], context: LambdaContext, model: Optional[Type[Model]] = None, envelope: Optional[Type[Envelope]] = None, **kwargs: Any, ) -> EventParserReturnType: """Lambda handler decorator to parse & validate events using Pydantic models It requires a model that implements Pydantic BaseModel to parse & validate the event. When an envelope is given, it'll use the following logic: 1. Parse the event against the envelope model first e.g. EnvelopeModel(**event) 2. Envelope will extract a given key to be parsed against the model e.g. event.detail This is useful when you need to confirm event wrapper structure, and b) selectively extract a portion of your payload for parsing & validation. NOTE: If envelope is omitted, the complete event is parsed to match the model parameter BaseModel definition. Example ------- **Lambda handler decorator to parse & validate event** class Order(BaseModel): id: int description: str ... @event_parser(model=Order) def handler(event: Order, context: LambdaContext): ... **Lambda handler decorator to parse & validate event - using built-in envelope** class Order(BaseModel): id: int description: str ... @event_parser(model=Order, envelope=envelopes.EVENTBRIDGE) def handler(event: Order, context: LambdaContext): ... Parameters ---------- handler: Callable Method to annotate on event: Dict Lambda event to be parsed & validated context: LambdaContext Lambda context object model: Model Your data model that will replace the event. envelope: Envelope Optional envelope to extract the model from Raises ------ ValidationError When input event does not conform with model provided InvalidModelTypeError When model given does not implement BaseModel or is not provided InvalidEnvelopeError When envelope given does not implement BaseEnvelope """ # The first parameter of a Lambda function is always the event # This line get the model informed in the event_parser function # or the first parameter of the function by using typing.get_type_hints type_hints = typing.get_type_hints(handler) model = model or (list(type_hints.values())[0] if type_hints else None) if model is None: raise InvalidModelTypeError( "The model must be provided either as the `model` argument to `event_parser`" "or as the type hint of `event` in the handler that it wraps", ) if envelope: parsed_event = parse(event=event, model=model, envelope=envelope) else: parsed_event = parse(event=event, model=model) logger.debug(f"Calling handler {handler.__name__}") return handler(parsed_event, context, **kwargs)
Lambda handler decorator to parse & validate events using Pydantic models It requires a model that implements Pydantic BaseModel to parse & validate the event. When an envelope is given, it'll use the following logic: 1. Parse the event against the envelope model first e.g. EnvelopeModel(**event) 2. Envelope will extract a given key to be parsed against the model e.g. event.detail This is useful when you need to confirm event wrapper structure, and b) selectively extract a portion of your payload for parsing & validation. NOTE: If envelope is omitted, the complete event is parsed to match the model parameter BaseModel definition. Example ------- **Lambda handler decorator to parse & validate event** class Order(BaseModel): id: int description: str ... @event_parser(model=Order) def handler(event: Order, context: LambdaContext): ... **Lambda handler decorator to parse & validate event - using built-in envelope** class Order(BaseModel): id: int description: str ... @event_parser(model=Order, envelope=envelopes.EVENTBRIDGE) def handler(event: Order, context: LambdaContext): ... Parameters ---------- handler: Callable Method to annotate on event: Dict Lambda event to be parsed & validated context: LambdaContext Lambda context object model: Model Your data model that will replace the event. envelope: Envelope Optional envelope to extract the model from Raises ------ ValidationError When input event does not conform with model provided InvalidModelTypeError When model given does not implement BaseModel or is not provided InvalidEnvelopeError When envelope given does not implement BaseEnvelope
5,076
import json import zlib from typing import Dict, List, Type, Union from pydantic import BaseModel, validator from aws_lambda_powertools.shared.functions import base64_decode from aws_lambda_powertools.utilities.parser.models.cloudwatch import ( CloudWatchLogsDecode, ) from aws_lambda_powertools.utilities.parser.types import Literal class KinesisDataStreamModel(BaseModel): class CloudWatchLogsDecode(BaseModel): def extract_cloudwatch_logs_from_event(event: KinesisDataStreamModel) -> List[CloudWatchLogsDecode]: return [CloudWatchLogsDecode(**record.decompress_zlib_record_data_as_json()) for record in event.Records]
null
5,077
import json import zlib from typing import Dict, List, Type, Union from pydantic import BaseModel, validator from aws_lambda_powertools.shared.functions import base64_decode from aws_lambda_powertools.utilities.parser.models.cloudwatch import ( CloudWatchLogsDecode, ) from aws_lambda_powertools.utilities.parser.types import Literal class KinesisDataStreamRecord(BaseModel): eventSource: Literal["aws:kinesis"] eventVersion: str eventID: str eventName: Literal["aws:kinesis:record"] invokeIdentityArn: str awsRegion: str eventSourceARN: str kinesis: KinesisDataStreamRecordPayload def decompress_zlib_record_data_as_json(self) -> Dict: """Decompress Kinesis Record bytes data zlib compressed to JSON""" if not isinstance(self.kinesis.data, bytes): raise ValueError("We can only decompress bytes data, not custom models.") return json.loads(zlib.decompress(self.kinesis.data, zlib.MAX_WBITS | 32)) class CloudWatchLogsDecode(BaseModel): messageType: str owner: str logGroup: str logStream: str subscriptionFilters: List[str] logEvents: List[CloudWatchLogsLogEvent] policyLevel: Optional[str] = None def extract_cloudwatch_logs_from_record(record: KinesisDataStreamRecord) -> CloudWatchLogsDecode: return CloudWatchLogsDecode(**record.decompress_zlib_record_data_as_json())
null
5,078
import functools import logging import os from inspect import isclass from typing import Any, Callable, Dict, Optional, Type, Union, cast from aws_lambda_powertools.middleware_factory import lambda_handler_decorator from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.types import AnyCallableT from aws_lambda_powertools.utilities.idempotency.base import IdempotencyHandler from aws_lambda_powertools.utilities.idempotency.config import IdempotencyConfig from aws_lambda_powertools.utilities.idempotency.persistence.base import ( BasePersistenceLayer, ) from aws_lambda_powertools.utilities.idempotency.serialization.base import ( BaseIdempotencyModelSerializer, BaseIdempotencySerializer, ) from aws_lambda_powertools.utilities.typing import LambdaContext class IdempotencyHandler: """ Base class to orchestrate calls to persistence layer. """ def __init__( self, function: Callable, function_payload: Any, config: IdempotencyConfig, persistence_store: BasePersistenceLayer, output_serializer: Optional[BaseIdempotencySerializer] = None, function_args: Optional[Tuple] = None, function_kwargs: Optional[Dict] = None, ): """ Initialize the IdempotencyHandler Parameters ---------- function_payload: Any JSON Serializable payload to be hashed config: IdempotencyConfig Idempotency Configuration persistence_store : BasePersistenceLayer Instance of persistence layer to store idempotency records output_serializer: Optional[BaseIdempotencySerializer] Serializer to transform the data to and from a dictionary. If not supplied, no serialization is done via the NoOpSerializer function_args: Optional[Tuple] Function arguments function_kwargs: Optional[Dict] Function keyword arguments """ self.function = function self.output_serializer = output_serializer or NoOpSerializer() self.data = deepcopy(_prepare_data(function_payload)) self.fn_args = function_args self.fn_kwargs = function_kwargs self.config = config persistence_store.configure(config, f"{self.function.__module__}.{self.function.__qualname__}") self.persistence_store = persistence_store def handle(self) -> Any: """ Main entry point for handling idempotent execution of a function. Returns ------- Any Function response """ # IdempotencyInconsistentStateError can happen under rare but expected cases # when persistent state changes in the small time between put & get requests. # In most cases we can retry successfully on this exception. for i in range(MAX_RETRIES + 1): # pragma: no cover try: return self._process_idempotency() except IdempotencyInconsistentStateError: if i == MAX_RETRIES: raise # Bubble up when exceeded max tries def _process_idempotency(self): try: # We call save_inprogress first as an optimization for the most common case where no idempotent record # already exists. If it succeeds, there's no need to call get_record. self.persistence_store.save_inprogress( data=self.data, remaining_time_in_millis=self._get_remaining_time_in_millis(), ) except (IdempotencyKeyError, IdempotencyValidationError): raise except IdempotencyItemAlreadyExistsError as exc: # Attempt to retrieve the existing record, either from the exception ReturnValuesOnConditionCheckFailure # or perform a GET operation if the information is not available. # We give preference to ReturnValuesOnConditionCheckFailure because it is a faster and more cost-effective # way of retrieving the existing record after a failed conditional write operation. record = exc.old_data_record or self._get_idempotency_record() # If a record is found, handle it for status if record: return self._handle_for_status(record) except Exception as exc: raise IdempotencyPersistenceLayerError( "Failed to save in progress record to idempotency store", exc, ) from exc return self._get_function_response() def _get_remaining_time_in_millis(self) -> Optional[int]: """ Tries to determine the remaining time available for the current lambda invocation. This only works if the idempotent handler decorator is used, since we need to access the lambda context. However, this could be improved if we start storing the lambda context globally during the invocation. One way to do this is to register the lambda context when configuring the IdempotencyConfig object. Returns ------- Optional[int] Remaining time in millis, or None if the remaining time cannot be determined. """ if self.config.lambda_context is not None: return self.config.lambda_context.get_remaining_time_in_millis() return None def _get_idempotency_record(self) -> Optional[DataRecord]: """ Retrieve the idempotency record from the persistence layer. Raises ---------- IdempotencyInconsistentStateError """ try: data_record = self.persistence_store.get_record(data=self.data) except IdempotencyItemNotFoundError: # This code path will only be triggered if the record is removed between save_inprogress and get_record. logger.debug( f"An existing idempotency record was deleted before we could fetch it. Proceeding with {self.function}", ) raise IdempotencyInconsistentStateError("save_inprogress and get_record return inconsistent results.") # Allow this exception to bubble up except IdempotencyValidationError: raise # Wrap remaining unhandled exceptions with IdempotencyPersistenceLayerError to ease exception handling for # clients except Exception as exc: raise IdempotencyPersistenceLayerError("Failed to get record from idempotency store", exc) from exc return data_record def _handle_for_status(self, data_record: DataRecord) -> Optional[Any]: """ Take appropriate action based on data_record's status Parameters ---------- data_record: DataRecord Returns ------- Optional[Any] Function's response previously used for this idempotency key, if it has successfully executed already. In case an output serializer is configured, the response is deserialized. Raises ------ AlreadyInProgressError A function execution is already in progress IdempotencyInconsistentStateError The persistence store reports inconsistent states across different requests. Retryable. """ # This code path will only be triggered if the record becomes expired between the save_inprogress call and here if data_record.status == STATUS_CONSTANTS["EXPIRED"]: raise IdempotencyInconsistentStateError("save_inprogress and get_record return inconsistent results.") if data_record.status == STATUS_CONSTANTS["INPROGRESS"]: if data_record.in_progress_expiry_timestamp is not None and data_record.in_progress_expiry_timestamp < int( datetime.datetime.now().timestamp() * 1000, ): raise IdempotencyInconsistentStateError( "item should have been expired in-progress because it already time-outed.", ) raise IdempotencyAlreadyInProgressError( f"Execution already in progress with idempotency key: " f"{self.persistence_store.event_key_jmespath}={data_record.idempotency_key}", ) response_dict: Optional[dict] = data_record.response_json_as_dict() if response_dict is not None: return self.output_serializer.from_dict(response_dict) return None def _get_function_response(self): try: response = self.function(*self.fn_args, **self.fn_kwargs) except Exception as handler_exception: # We need these nested blocks to preserve function's exception in case the persistence store operation # also raises an exception try: self.persistence_store.delete_record(data=self.data, exception=handler_exception) except Exception as delete_exception: raise IdempotencyPersistenceLayerError( "Failed to delete record from idempotency store", delete_exception, ) from delete_exception raise else: try: serialized_response: dict = self.output_serializer.to_dict(response) if response else None self.persistence_store.save_success(data=self.data, result=serialized_response) except Exception as save_exception: raise IdempotencyPersistenceLayerError( "Failed to update record state to success in idempotency store", save_exception, ) from save_exception return response class IdempotencyConfig: def __init__( self, event_key_jmespath: str = "", payload_validation_jmespath: str = "", jmespath_options: Optional[Dict] = None, raise_on_no_idempotency_key: bool = False, expires_after_seconds: int = 60 * 60, # 1 hour default use_local_cache: bool = False, local_cache_max_items: int = 256, hash_function: str = "md5", lambda_context: Optional[LambdaContext] = None, ): """ Initialize the base persistence layer Parameters ---------- event_key_jmespath: str A jmespath expression to extract the idempotency key from the event record payload_validation_jmespath: str A jmespath expression to extract the payload to be validated from the event record raise_on_no_idempotency_key: bool, optional Raise exception if no idempotency key was found in the request, by default False expires_after_seconds: int The number of seconds to wait before a record is expired use_local_cache: bool, optional Whether to locally cache idempotency results, by default False local_cache_max_items: int, optional Max number of items to store in local cache, by default 1024 hash_function: str, optional Function to use for calculating hashes, by default md5. lambda_context: LambdaContext, optional Lambda Context containing information about the invocation, function and execution environment. """ self.event_key_jmespath = event_key_jmespath self.payload_validation_jmespath = payload_validation_jmespath self.jmespath_options = jmespath_options self.raise_on_no_idempotency_key = raise_on_no_idempotency_key self.expires_after_seconds = expires_after_seconds self.use_local_cache = use_local_cache self.local_cache_max_items = local_cache_max_items self.hash_function = hash_function self.lambda_context: Optional[LambdaContext] = lambda_context def register_lambda_context(self, lambda_context: LambdaContext): """Captures the Lambda context, to calculate the remaining time before the invocation times out""" self.lambda_context = lambda_context class BasePersistenceLayer(ABC): """ Abstract Base Class for Idempotency persistence layer. """ def __init__(self): """Initialize the defaults""" self.function_name = "" self.configured = False self.event_key_jmespath: str = "" self.event_key_compiled_jmespath = None self.jmespath_options: Optional[dict] = None self.payload_validation_enabled = False self.validation_key_jmespath = None self.raise_on_no_idempotency_key = False self.expires_after_seconds: int = 60 * 60 # 1 hour default self.use_local_cache = False self.hash_function = hashlib.md5 def configure(self, config: IdempotencyConfig, function_name: Optional[str] = None) -> None: """ Initialize the base persistence layer from the configuration settings Parameters ---------- config: IdempotencyConfig Idempotency configuration settings function_name: str, Optional The name of the function being decorated """ self.function_name = f"{os.getenv(constants.LAMBDA_FUNCTION_NAME_ENV, 'test-func')}.{function_name or ''}" if self.configured: # Prevent being reconfigured multiple times return self.configured = True self.event_key_jmespath = config.event_key_jmespath if config.event_key_jmespath: self.event_key_compiled_jmespath = jmespath.compile(config.event_key_jmespath) self.jmespath_options = config.jmespath_options if not self.jmespath_options: self.jmespath_options = {"custom_functions": PowertoolsFunctions()} if config.payload_validation_jmespath: self.validation_key_jmespath = jmespath.compile(config.payload_validation_jmespath) self.payload_validation_enabled = True self.raise_on_no_idempotency_key = config.raise_on_no_idempotency_key self.expires_after_seconds = config.expires_after_seconds self.use_local_cache = config.use_local_cache if self.use_local_cache: self._cache = LRUDict(max_items=config.local_cache_max_items) self.hash_function = getattr(hashlib, config.hash_function) def _get_hashed_idempotency_key(self, data: Dict[str, Any]) -> Optional[str]: """ Extract idempotency key and return a hashed representation Parameters ---------- data: Dict[str, Any] Incoming data Returns ------- str Hashed representation of the data extracted by the jmespath expression """ if self.event_key_jmespath: data = self.event_key_compiled_jmespath.search(data, options=jmespath.Options(**self.jmespath_options)) if self.is_missing_idempotency_key(data=data): if self.raise_on_no_idempotency_key: raise IdempotencyKeyError("No data found to create a hashed idempotency_key") warnings.warn( f"No idempotency key value found. Skipping persistence layer and validation operations. jmespath: {self.event_key_jmespath}", # noqa: E501 stacklevel=2, ) return None generated_hash = self._generate_hash(data=data) return f"{self.function_name}#{generated_hash}" def is_missing_idempotency_key(data) -> bool: if isinstance(data, (tuple, list, dict)): return all(x is None for x in data) elif isinstance(data, (int, float, bool)): return False return not data def _get_hashed_payload(self, data: Dict[str, Any]) -> str: """ Extract payload using validation key jmespath and return a hashed representation Parameters ---------- data: Dict[str, Any] Payload Returns ------- str Hashed representation of the data extracted by the jmespath expression """ if not self.payload_validation_enabled: return "" data = self.validation_key_jmespath.search(data) return self._generate_hash(data=data) def _generate_hash(self, data: Any) -> str: """ Generate a hash value from the provided data Parameters ---------- data: Any The data to hash Returns ------- str Hashed representation of the provided data """ hashed_data = self.hash_function(json.dumps(data, cls=Encoder, sort_keys=True).encode()) return hashed_data.hexdigest() def _validate_payload( self, data_payload: Union[Dict[str, Any], DataRecord], stored_data_record: DataRecord, ) -> None: """ Validate that the hashed payload matches data provided and stored data record Parameters ---------- data_payload: Union[Dict[str, Any], DataRecord] Payload stored_data_record: DataRecord DataRecord fetched from Dynamo or cache Raises ---------- IdempotencyValidationError Payload doesn't match the stored record for the given idempotency key """ if self.payload_validation_enabled: if isinstance(data_payload, DataRecord): data_hash = data_payload.payload_hash else: data_hash = self._get_hashed_payload(data=data_payload) if stored_data_record.payload_hash != data_hash: raise IdempotencyValidationError("Payload does not match stored record for this event key") def _get_expiry_timestamp(self) -> int: """ Returns ------- int unix timestamp of expiry date for idempotency record """ now = datetime.datetime.now() period = datetime.timedelta(seconds=self.expires_after_seconds) return int((now + period).timestamp()) def _save_to_cache(self, data_record: DataRecord): """ Save data_record to local cache except when status is "INPROGRESS" NOTE: We can't cache "INPROGRESS" records as we have no way to reflect updates that can happen outside of the execution environment Parameters ---------- data_record: DataRecord DataRecord instance Returns ------- """ if not self.use_local_cache: return if data_record.status == STATUS_CONSTANTS["INPROGRESS"]: return self._cache[data_record.idempotency_key] = data_record def _retrieve_from_cache(self, idempotency_key: str): if not self.use_local_cache: return cached_record = self._cache.get(key=idempotency_key) if cached_record: if not cached_record.is_expired: return cached_record logger.debug(f"Removing expired local cache record for idempotency key: {idempotency_key}") self._delete_from_cache(idempotency_key=idempotency_key) def _delete_from_cache(self, idempotency_key: str): if not self.use_local_cache: return if idempotency_key in self._cache: del self._cache[idempotency_key] def save_success(self, data: Dict[str, Any], result: dict) -> None: """ Save record of function's execution completing successfully Parameters ---------- data: Dict[str, Any] Payload result: dict The response from function """ idempotency_key = self._get_hashed_idempotency_key(data=data) if idempotency_key is None: # If the idempotency key is None, no data will be saved in the Persistence Layer. # See: https://github.com/aws-powertools/powertools-lambda-python/issues/2465 return None response_data = json.dumps(result, cls=Encoder, sort_keys=True) data_record = DataRecord( idempotency_key=idempotency_key, status=STATUS_CONSTANTS["COMPLETED"], expiry_timestamp=self._get_expiry_timestamp(), response_data=response_data, payload_hash=self._get_hashed_payload(data=data), ) logger.debug( f"Function successfully executed. Saving record to persistence store with " f"idempotency key: {data_record.idempotency_key}", ) self._update_record(data_record=data_record) self._save_to_cache(data_record=data_record) def save_inprogress(self, data: Dict[str, Any], remaining_time_in_millis: Optional[int] = None) -> None: """ Save record of function's execution being in progress Parameters ---------- data: Dict[str, Any] Payload remaining_time_in_millis: Optional[int] If expiry of in-progress invocations is enabled, this will contain the remaining time available in millis """ idempotency_key = self._get_hashed_idempotency_key(data=data) if idempotency_key is None: # If the idempotency key is None, no data will be saved in the Persistence Layer. # See: https://github.com/aws-powertools/powertools-lambda-python/issues/2465 return None data_record = DataRecord( idempotency_key=idempotency_key, status=STATUS_CONSTANTS["INPROGRESS"], expiry_timestamp=self._get_expiry_timestamp(), payload_hash=self._get_hashed_payload(data=data), ) if remaining_time_in_millis: now = datetime.datetime.now() period = datetime.timedelta(milliseconds=remaining_time_in_millis) timestamp = (now + period).timestamp() data_record.in_progress_expiry_timestamp = int(timestamp * 1000) else: warnings.warn( "Couldn't determine the remaining time left. " "Did you call register_lambda_context on IdempotencyConfig?", stacklevel=2, ) logger.debug(f"Saving in progress record for idempotency key: {data_record.idempotency_key}") if self._retrieve_from_cache(idempotency_key=data_record.idempotency_key): raise IdempotencyItemAlreadyExistsError self._put_record(data_record=data_record) def delete_record(self, data: Dict[str, Any], exception: Exception): """ Delete record from the persistence store Parameters ---------- data: Dict[str, Any] Payload exception The exception raised by the function """ idempotency_key = self._get_hashed_idempotency_key(data=data) if idempotency_key is None: # If the idempotency key is None, no data will be saved in the Persistence Layer. # See: https://github.com/aws-powertools/powertools-lambda-python/issues/2465 return None data_record = DataRecord(idempotency_key=idempotency_key) logger.debug( f"Function raised an exception ({type(exception).__name__}). Clearing in progress record in persistence " f"store for idempotency key: {data_record.idempotency_key}", ) self._delete_record(data_record=data_record) self._delete_from_cache(idempotency_key=data_record.idempotency_key) def get_record(self, data: Dict[str, Any]) -> Optional[DataRecord]: """ Retrieve idempotency key for data provided, fetch from persistence store, and convert to DataRecord. Parameters ---------- data: Dict[str, Any] Payload Returns ------- DataRecord DataRecord representation of existing record found in persistence store Raises ------ IdempotencyItemNotFoundError Exception raised if no record exists in persistence store with the idempotency key IdempotencyValidationError Payload doesn't match the stored record for the given idempotency key """ idempotency_key = self._get_hashed_idempotency_key(data=data) if idempotency_key is None: # If the idempotency key is None, no data will be saved in the Persistence Layer. # See: https://github.com/aws-powertools/powertools-lambda-python/issues/2465 return None cached_record = self._retrieve_from_cache(idempotency_key=idempotency_key) if cached_record: logger.debug(f"Idempotency record found in cache with idempotency key: {idempotency_key}") self._validate_payload(data_payload=data, stored_data_record=cached_record) return cached_record record = self._get_record(idempotency_key=idempotency_key) self._validate_payload(data_payload=data, stored_data_record=record) self._save_to_cache(data_record=record) return record def _get_record(self, idempotency_key) -> DataRecord: """ Retrieve item from persistence store using idempotency key and return it as a DataRecord instance. Parameters ---------- idempotency_key Returns ------- DataRecord DataRecord representation of existing record found in persistence store Raises ------ IdempotencyItemNotFoundError Exception raised if no record exists in persistence store with the idempotency key """ raise NotImplementedError def _put_record(self, data_record: DataRecord) -> None: """ Add a DataRecord to persistence store if it does not already exist with that key. Raise ItemAlreadyExists if a non-expired entry already exists. Parameters ---------- data_record: DataRecord DataRecord instance """ raise NotImplementedError def _update_record(self, data_record: DataRecord) -> None: """ Update item in persistence store Parameters ---------- data_record: DataRecord DataRecord instance """ raise NotImplementedError def _delete_record(self, data_record: DataRecord) -> None: """ Remove item from persistence store Parameters ---------- data_record: DataRecord DataRecord instance """ raise NotImplementedError The provided code snippet includes necessary dependencies for implementing the `idempotent` function. Write a Python function `def idempotent( handler: Callable[[Any, LambdaContext], Any], event: Dict[str, Any], context: LambdaContext, persistence_store: BasePersistenceLayer, config: Optional[IdempotencyConfig] = None, **kwargs, ) -> Any` to solve the following problem: Decorator to handle idempotency Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: Dict Lambda's Context persistence_store: BasePersistenceLayer Instance of BasePersistenceLayer to store data config: IdempotencyConfig Configuration Examples -------- **Processes Lambda's event in an idempotent manner** >>> from aws_lambda_powertools.utilities.idempotency import ( >>> idempotent, DynamoDBPersistenceLayer, IdempotencyConfig >>> ) >>> >>> idem_config=IdempotencyConfig(event_key_jmespath="body") >>> persistence_layer = DynamoDBPersistenceLayer(table_name="idempotency_store") >>> >>> @idempotent(config=idem_config, persistence_store=persistence_layer) >>> def handler(event, context): >>> return {"StatusCode": 200} Here is the function: def idempotent( handler: Callable[[Any, LambdaContext], Any], event: Dict[str, Any], context: LambdaContext, persistence_store: BasePersistenceLayer, config: Optional[IdempotencyConfig] = None, **kwargs, ) -> Any: """ Decorator to handle idempotency Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: Dict Lambda's Context persistence_store: BasePersistenceLayer Instance of BasePersistenceLayer to store data config: IdempotencyConfig Configuration Examples -------- **Processes Lambda's event in an idempotent manner** >>> from aws_lambda_powertools.utilities.idempotency import ( >>> idempotent, DynamoDBPersistenceLayer, IdempotencyConfig >>> ) >>> >>> idem_config=IdempotencyConfig(event_key_jmespath="body") >>> persistence_layer = DynamoDBPersistenceLayer(table_name="idempotency_store") >>> >>> @idempotent(config=idem_config, persistence_store=persistence_layer) >>> def handler(event, context): >>> return {"StatusCode": 200} """ if os.getenv(constants.IDEMPOTENCY_DISABLED_ENV): return handler(event, context, **kwargs) config = config or IdempotencyConfig() config.register_lambda_context(context) args = event, context idempotency_handler = IdempotencyHandler( function=handler, function_payload=event, config=config, persistence_store=persistence_store, function_args=args, function_kwargs=kwargs, ) return idempotency_handler.handle()
Decorator to handle idempotency Parameters ---------- handler: Callable Lambda's handler event: Dict Lambda's Event context: Dict Lambda's Context persistence_store: BasePersistenceLayer Instance of BasePersistenceLayer to store data config: IdempotencyConfig Configuration Examples -------- **Processes Lambda's event in an idempotent manner** >>> from aws_lambda_powertools.utilities.idempotency import ( >>> idempotent, DynamoDBPersistenceLayer, IdempotencyConfig >>> ) >>> >>> idem_config=IdempotencyConfig(event_key_jmespath="body") >>> persistence_layer = DynamoDBPersistenceLayer(table_name="idempotency_store") >>> >>> @idempotent(config=idem_config, persistence_store=persistence_layer) >>> def handler(event, context): >>> return {"StatusCode": 200}
5,079
import functools import logging import os from inspect import isclass from typing import Any, Callable, Dict, Optional, Type, Union, cast from aws_lambda_powertools.middleware_factory import lambda_handler_decorator from aws_lambda_powertools.shared import constants from aws_lambda_powertools.shared.types import AnyCallableT from aws_lambda_powertools.utilities.idempotency.base import IdempotencyHandler from aws_lambda_powertools.utilities.idempotency.config import IdempotencyConfig from aws_lambda_powertools.utilities.idempotency.persistence.base import ( BasePersistenceLayer, ) from aws_lambda_powertools.utilities.idempotency.serialization.base import ( BaseIdempotencyModelSerializer, BaseIdempotencySerializer, ) from aws_lambda_powertools.utilities.typing import LambdaContext AnyCallableT = TypeVar("AnyCallableT", bound=Callable[..., Any]) class IdempotencyHandler: """ Base class to orchestrate calls to persistence layer. """ def __init__( self, function: Callable, function_payload: Any, config: IdempotencyConfig, persistence_store: BasePersistenceLayer, output_serializer: Optional[BaseIdempotencySerializer] = None, function_args: Optional[Tuple] = None, function_kwargs: Optional[Dict] = None, ): """ Initialize the IdempotencyHandler Parameters ---------- function_payload: Any JSON Serializable payload to be hashed config: IdempotencyConfig Idempotency Configuration persistence_store : BasePersistenceLayer Instance of persistence layer to store idempotency records output_serializer: Optional[BaseIdempotencySerializer] Serializer to transform the data to and from a dictionary. If not supplied, no serialization is done via the NoOpSerializer function_args: Optional[Tuple] Function arguments function_kwargs: Optional[Dict] Function keyword arguments """ self.function = function self.output_serializer = output_serializer or NoOpSerializer() self.data = deepcopy(_prepare_data(function_payload)) self.fn_args = function_args self.fn_kwargs = function_kwargs self.config = config persistence_store.configure(config, f"{self.function.__module__}.{self.function.__qualname__}") self.persistence_store = persistence_store def handle(self) -> Any: """ Main entry point for handling idempotent execution of a function. Returns ------- Any Function response """ # IdempotencyInconsistentStateError can happen under rare but expected cases # when persistent state changes in the small time between put & get requests. # In most cases we can retry successfully on this exception. for i in range(MAX_RETRIES + 1): # pragma: no cover try: return self._process_idempotency() except IdempotencyInconsistentStateError: if i == MAX_RETRIES: raise # Bubble up when exceeded max tries def _process_idempotency(self): try: # We call save_inprogress first as an optimization for the most common case where no idempotent record # already exists. If it succeeds, there's no need to call get_record. self.persistence_store.save_inprogress( data=self.data, remaining_time_in_millis=self._get_remaining_time_in_millis(), ) except (IdempotencyKeyError, IdempotencyValidationError): raise except IdempotencyItemAlreadyExistsError as exc: # Attempt to retrieve the existing record, either from the exception ReturnValuesOnConditionCheckFailure # or perform a GET operation if the information is not available. # We give preference to ReturnValuesOnConditionCheckFailure because it is a faster and more cost-effective # way of retrieving the existing record after a failed conditional write operation. record = exc.old_data_record or self._get_idempotency_record() # If a record is found, handle it for status if record: return self._handle_for_status(record) except Exception as exc: raise IdempotencyPersistenceLayerError( "Failed to save in progress record to idempotency store", exc, ) from exc return self._get_function_response() def _get_remaining_time_in_millis(self) -> Optional[int]: """ Tries to determine the remaining time available for the current lambda invocation. This only works if the idempotent handler decorator is used, since we need to access the lambda context. However, this could be improved if we start storing the lambda context globally during the invocation. One way to do this is to register the lambda context when configuring the IdempotencyConfig object. Returns ------- Optional[int] Remaining time in millis, or None if the remaining time cannot be determined. """ if self.config.lambda_context is not None: return self.config.lambda_context.get_remaining_time_in_millis() return None def _get_idempotency_record(self) -> Optional[DataRecord]: """ Retrieve the idempotency record from the persistence layer. Raises ---------- IdempotencyInconsistentStateError """ try: data_record = self.persistence_store.get_record(data=self.data) except IdempotencyItemNotFoundError: # This code path will only be triggered if the record is removed between save_inprogress and get_record. logger.debug( f"An existing idempotency record was deleted before we could fetch it. Proceeding with {self.function}", ) raise IdempotencyInconsistentStateError("save_inprogress and get_record return inconsistent results.") # Allow this exception to bubble up except IdempotencyValidationError: raise # Wrap remaining unhandled exceptions with IdempotencyPersistenceLayerError to ease exception handling for # clients except Exception as exc: raise IdempotencyPersistenceLayerError("Failed to get record from idempotency store", exc) from exc return data_record def _handle_for_status(self, data_record: DataRecord) -> Optional[Any]: """ Take appropriate action based on data_record's status Parameters ---------- data_record: DataRecord Returns ------- Optional[Any] Function's response previously used for this idempotency key, if it has successfully executed already. In case an output serializer is configured, the response is deserialized. Raises ------ AlreadyInProgressError A function execution is already in progress IdempotencyInconsistentStateError The persistence store reports inconsistent states across different requests. Retryable. """ # This code path will only be triggered if the record becomes expired between the save_inprogress call and here if data_record.status == STATUS_CONSTANTS["EXPIRED"]: raise IdempotencyInconsistentStateError("save_inprogress and get_record return inconsistent results.") if data_record.status == STATUS_CONSTANTS["INPROGRESS"]: if data_record.in_progress_expiry_timestamp is not None and data_record.in_progress_expiry_timestamp < int( datetime.datetime.now().timestamp() * 1000, ): raise IdempotencyInconsistentStateError( "item should have been expired in-progress because it already time-outed.", ) raise IdempotencyAlreadyInProgressError( f"Execution already in progress with idempotency key: " f"{self.persistence_store.event_key_jmespath}={data_record.idempotency_key}", ) response_dict: Optional[dict] = data_record.response_json_as_dict() if response_dict is not None: return self.output_serializer.from_dict(response_dict) return None def _get_function_response(self): try: response = self.function(*self.fn_args, **self.fn_kwargs) except Exception as handler_exception: # We need these nested blocks to preserve function's exception in case the persistence store operation # also raises an exception try: self.persistence_store.delete_record(data=self.data, exception=handler_exception) except Exception as delete_exception: raise IdempotencyPersistenceLayerError( "Failed to delete record from idempotency store", delete_exception, ) from delete_exception raise else: try: serialized_response: dict = self.output_serializer.to_dict(response) if response else None self.persistence_store.save_success(data=self.data, result=serialized_response) except Exception as save_exception: raise IdempotencyPersistenceLayerError( "Failed to update record state to success in idempotency store", save_exception, ) from save_exception return response class IdempotencyConfig: def __init__( self, event_key_jmespath: str = "", payload_validation_jmespath: str = "", jmespath_options: Optional[Dict] = None, raise_on_no_idempotency_key: bool = False, expires_after_seconds: int = 60 * 60, # 1 hour default use_local_cache: bool = False, local_cache_max_items: int = 256, hash_function: str = "md5", lambda_context: Optional[LambdaContext] = None, ): """ Initialize the base persistence layer Parameters ---------- event_key_jmespath: str A jmespath expression to extract the idempotency key from the event record payload_validation_jmespath: str A jmespath expression to extract the payload to be validated from the event record raise_on_no_idempotency_key: bool, optional Raise exception if no idempotency key was found in the request, by default False expires_after_seconds: int The number of seconds to wait before a record is expired use_local_cache: bool, optional Whether to locally cache idempotency results, by default False local_cache_max_items: int, optional Max number of items to store in local cache, by default 1024 hash_function: str, optional Function to use for calculating hashes, by default md5. lambda_context: LambdaContext, optional Lambda Context containing information about the invocation, function and execution environment. """ self.event_key_jmespath = event_key_jmespath self.payload_validation_jmespath = payload_validation_jmespath self.jmespath_options = jmespath_options self.raise_on_no_idempotency_key = raise_on_no_idempotency_key self.expires_after_seconds = expires_after_seconds self.use_local_cache = use_local_cache self.local_cache_max_items = local_cache_max_items self.hash_function = hash_function self.lambda_context: Optional[LambdaContext] = lambda_context def register_lambda_context(self, lambda_context: LambdaContext): """Captures the Lambda context, to calculate the remaining time before the invocation times out""" self.lambda_context = lambda_context class BasePersistenceLayer(ABC): """ Abstract Base Class for Idempotency persistence layer. """ def __init__(self): """Initialize the defaults""" self.function_name = "" self.configured = False self.event_key_jmespath: str = "" self.event_key_compiled_jmespath = None self.jmespath_options: Optional[dict] = None self.payload_validation_enabled = False self.validation_key_jmespath = None self.raise_on_no_idempotency_key = False self.expires_after_seconds: int = 60 * 60 # 1 hour default self.use_local_cache = False self.hash_function = hashlib.md5 def configure(self, config: IdempotencyConfig, function_name: Optional[str] = None) -> None: """ Initialize the base persistence layer from the configuration settings Parameters ---------- config: IdempotencyConfig Idempotency configuration settings function_name: str, Optional The name of the function being decorated """ self.function_name = f"{os.getenv(constants.LAMBDA_FUNCTION_NAME_ENV, 'test-func')}.{function_name or ''}" if self.configured: # Prevent being reconfigured multiple times return self.configured = True self.event_key_jmespath = config.event_key_jmespath if config.event_key_jmespath: self.event_key_compiled_jmespath = jmespath.compile(config.event_key_jmespath) self.jmespath_options = config.jmespath_options if not self.jmespath_options: self.jmespath_options = {"custom_functions": PowertoolsFunctions()} if config.payload_validation_jmespath: self.validation_key_jmespath = jmespath.compile(config.payload_validation_jmespath) self.payload_validation_enabled = True self.raise_on_no_idempotency_key = config.raise_on_no_idempotency_key self.expires_after_seconds = config.expires_after_seconds self.use_local_cache = config.use_local_cache if self.use_local_cache: self._cache = LRUDict(max_items=config.local_cache_max_items) self.hash_function = getattr(hashlib, config.hash_function) def _get_hashed_idempotency_key(self, data: Dict[str, Any]) -> Optional[str]: """ Extract idempotency key and return a hashed representation Parameters ---------- data: Dict[str, Any] Incoming data Returns ------- str Hashed representation of the data extracted by the jmespath expression """ if self.event_key_jmespath: data = self.event_key_compiled_jmespath.search(data, options=jmespath.Options(**self.jmespath_options)) if self.is_missing_idempotency_key(data=data): if self.raise_on_no_idempotency_key: raise IdempotencyKeyError("No data found to create a hashed idempotency_key") warnings.warn( f"No idempotency key value found. Skipping persistence layer and validation operations. jmespath: {self.event_key_jmespath}", # noqa: E501 stacklevel=2, ) return None generated_hash = self._generate_hash(data=data) return f"{self.function_name}#{generated_hash}" def is_missing_idempotency_key(data) -> bool: if isinstance(data, (tuple, list, dict)): return all(x is None for x in data) elif isinstance(data, (int, float, bool)): return False return not data def _get_hashed_payload(self, data: Dict[str, Any]) -> str: """ Extract payload using validation key jmespath and return a hashed representation Parameters ---------- data: Dict[str, Any] Payload Returns ------- str Hashed representation of the data extracted by the jmespath expression """ if not self.payload_validation_enabled: return "" data = self.validation_key_jmespath.search(data) return self._generate_hash(data=data) def _generate_hash(self, data: Any) -> str: """ Generate a hash value from the provided data Parameters ---------- data: Any The data to hash Returns ------- str Hashed representation of the provided data """ hashed_data = self.hash_function(json.dumps(data, cls=Encoder, sort_keys=True).encode()) return hashed_data.hexdigest() def _validate_payload( self, data_payload: Union[Dict[str, Any], DataRecord], stored_data_record: DataRecord, ) -> None: """ Validate that the hashed payload matches data provided and stored data record Parameters ---------- data_payload: Union[Dict[str, Any], DataRecord] Payload stored_data_record: DataRecord DataRecord fetched from Dynamo or cache Raises ---------- IdempotencyValidationError Payload doesn't match the stored record for the given idempotency key """ if self.payload_validation_enabled: if isinstance(data_payload, DataRecord): data_hash = data_payload.payload_hash else: data_hash = self._get_hashed_payload(data=data_payload) if stored_data_record.payload_hash != data_hash: raise IdempotencyValidationError("Payload does not match stored record for this event key") def _get_expiry_timestamp(self) -> int: """ Returns ------- int unix timestamp of expiry date for idempotency record """ now = datetime.datetime.now() period = datetime.timedelta(seconds=self.expires_after_seconds) return int((now + period).timestamp()) def _save_to_cache(self, data_record: DataRecord): """ Save data_record to local cache except when status is "INPROGRESS" NOTE: We can't cache "INPROGRESS" records as we have no way to reflect updates that can happen outside of the execution environment Parameters ---------- data_record: DataRecord DataRecord instance Returns ------- """ if not self.use_local_cache: return if data_record.status == STATUS_CONSTANTS["INPROGRESS"]: return self._cache[data_record.idempotency_key] = data_record def _retrieve_from_cache(self, idempotency_key: str): if not self.use_local_cache: return cached_record = self._cache.get(key=idempotency_key) if cached_record: if not cached_record.is_expired: return cached_record logger.debug(f"Removing expired local cache record for idempotency key: {idempotency_key}") self._delete_from_cache(idempotency_key=idempotency_key) def _delete_from_cache(self, idempotency_key: str): if not self.use_local_cache: return if idempotency_key in self._cache: del self._cache[idempotency_key] def save_success(self, data: Dict[str, Any], result: dict) -> None: """ Save record of function's execution completing successfully Parameters ---------- data: Dict[str, Any] Payload result: dict The response from function """ idempotency_key = self._get_hashed_idempotency_key(data=data) if idempotency_key is None: # If the idempotency key is None, no data will be saved in the Persistence Layer. # See: https://github.com/aws-powertools/powertools-lambda-python/issues/2465 return None response_data = json.dumps(result, cls=Encoder, sort_keys=True) data_record = DataRecord( idempotency_key=idempotency_key, status=STATUS_CONSTANTS["COMPLETED"], expiry_timestamp=self._get_expiry_timestamp(), response_data=response_data, payload_hash=self._get_hashed_payload(data=data), ) logger.debug( f"Function successfully executed. Saving record to persistence store with " f"idempotency key: {data_record.idempotency_key}", ) self._update_record(data_record=data_record) self._save_to_cache(data_record=data_record) def save_inprogress(self, data: Dict[str, Any], remaining_time_in_millis: Optional[int] = None) -> None: """ Save record of function's execution being in progress Parameters ---------- data: Dict[str, Any] Payload remaining_time_in_millis: Optional[int] If expiry of in-progress invocations is enabled, this will contain the remaining time available in millis """ idempotency_key = self._get_hashed_idempotency_key(data=data) if idempotency_key is None: # If the idempotency key is None, no data will be saved in the Persistence Layer. # See: https://github.com/aws-powertools/powertools-lambda-python/issues/2465 return None data_record = DataRecord( idempotency_key=idempotency_key, status=STATUS_CONSTANTS["INPROGRESS"], expiry_timestamp=self._get_expiry_timestamp(), payload_hash=self._get_hashed_payload(data=data), ) if remaining_time_in_millis: now = datetime.datetime.now() period = datetime.timedelta(milliseconds=remaining_time_in_millis) timestamp = (now + period).timestamp() data_record.in_progress_expiry_timestamp = int(timestamp * 1000) else: warnings.warn( "Couldn't determine the remaining time left. " "Did you call register_lambda_context on IdempotencyConfig?", stacklevel=2, ) logger.debug(f"Saving in progress record for idempotency key: {data_record.idempotency_key}") if self._retrieve_from_cache(idempotency_key=data_record.idempotency_key): raise IdempotencyItemAlreadyExistsError self._put_record(data_record=data_record) def delete_record(self, data: Dict[str, Any], exception: Exception): """ Delete record from the persistence store Parameters ---------- data: Dict[str, Any] Payload exception The exception raised by the function """ idempotency_key = self._get_hashed_idempotency_key(data=data) if idempotency_key is None: # If the idempotency key is None, no data will be saved in the Persistence Layer. # See: https://github.com/aws-powertools/powertools-lambda-python/issues/2465 return None data_record = DataRecord(idempotency_key=idempotency_key) logger.debug( f"Function raised an exception ({type(exception).__name__}). Clearing in progress record in persistence " f"store for idempotency key: {data_record.idempotency_key}", ) self._delete_record(data_record=data_record) self._delete_from_cache(idempotency_key=data_record.idempotency_key) def get_record(self, data: Dict[str, Any]) -> Optional[DataRecord]: """ Retrieve idempotency key for data provided, fetch from persistence store, and convert to DataRecord. Parameters ---------- data: Dict[str, Any] Payload Returns ------- DataRecord DataRecord representation of existing record found in persistence store Raises ------ IdempotencyItemNotFoundError Exception raised if no record exists in persistence store with the idempotency key IdempotencyValidationError Payload doesn't match the stored record for the given idempotency key """ idempotency_key = self._get_hashed_idempotency_key(data=data) if idempotency_key is None: # If the idempotency key is None, no data will be saved in the Persistence Layer. # See: https://github.com/aws-powertools/powertools-lambda-python/issues/2465 return None cached_record = self._retrieve_from_cache(idempotency_key=idempotency_key) if cached_record: logger.debug(f"Idempotency record found in cache with idempotency key: {idempotency_key}") self._validate_payload(data_payload=data, stored_data_record=cached_record) return cached_record record = self._get_record(idempotency_key=idempotency_key) self._validate_payload(data_payload=data, stored_data_record=record) self._save_to_cache(data_record=record) return record def _get_record(self, idempotency_key) -> DataRecord: """ Retrieve item from persistence store using idempotency key and return it as a DataRecord instance. Parameters ---------- idempotency_key Returns ------- DataRecord DataRecord representation of existing record found in persistence store Raises ------ IdempotencyItemNotFoundError Exception raised if no record exists in persistence store with the idempotency key """ raise NotImplementedError def _put_record(self, data_record: DataRecord) -> None: """ Add a DataRecord to persistence store if it does not already exist with that key. Raise ItemAlreadyExists if a non-expired entry already exists. Parameters ---------- data_record: DataRecord DataRecord instance """ raise NotImplementedError def _update_record(self, data_record: DataRecord) -> None: """ Update item in persistence store Parameters ---------- data_record: DataRecord DataRecord instance """ raise NotImplementedError def _delete_record(self, data_record: DataRecord) -> None: """ Remove item from persistence store Parameters ---------- data_record: DataRecord DataRecord instance """ raise NotImplementedError class BaseIdempotencySerializer(ABC): """ Abstract Base Class for Idempotency serialization layer, supporting dict operations. """ def to_dict(self, data: Any) -> Dict: raise NotImplementedError("Implementation of to_dict is required") def from_dict(self, data: Dict) -> Any: raise NotImplementedError("Implementation of from_dict is required") class BaseIdempotencyModelSerializer(BaseIdempotencySerializer): """ Abstract Base Class for Idempotency serialization layer, for using a model as data object representation. """ def instantiate(cls, model_type: Any) -> BaseIdempotencySerializer: """ Creates an instance of a serializer based on a provided model type. In case the model_type is unknown, None will be sent as `model_type`. It's on the implementer to verify that: - None is handled correctly - A model type not matching the expected types is handled Parameters ---------- model_type: Any The model type to instantiate the class for Returns ------- BaseIdempotencySerializer Instance of the serializer class """ pass The provided code snippet includes necessary dependencies for implementing the `idempotent_function` function. Write a Python function `def idempotent_function( function: Optional[AnyCallableT] = None, *, data_keyword_argument: str, persistence_store: BasePersistenceLayer, config: Optional[IdempotencyConfig] = None, output_serializer: Optional[Union[BaseIdempotencySerializer, Type[BaseIdempotencyModelSerializer]]] = None, **kwargs: Any, ) -> Any` to solve the following problem: Decorator to handle idempotency of any function Parameters ---------- function: Callable Function to be decorated data_keyword_argument: str Keyword parameter name in function's signature that we should hash as idempotency key, e.g. "order" persistence_store: BasePersistenceLayer Instance of BasePersistenceLayer to store data config: IdempotencyConfig Configuration output_serializer: Optional[Union[BaseIdempotencySerializer, Type[BaseIdempotencyModelSerializer]]] Serializer to transform the data to and from a dictionary. If not supplied, no serialization is done via the NoOpSerializer. In case a serializer of type inheriting BaseIdempotencyModelSerializer is given, the serializer is derived from the function return type. Examples -------- **Processes an order in an idempotent manner** from aws_lambda_powertools.utilities.idempotency import ( idempotent_function, DynamoDBPersistenceLayer, IdempotencyConfig ) idem_config=IdempotencyConfig(event_key_jmespath="order_id") persistence_layer = DynamoDBPersistenceLayer(table_name="idempotency_store") @idempotent_function(data_keyword_argument="order", config=idem_config, persistence_store=persistence_layer) def process_order(customer_id: str, order: dict, **kwargs): return {"StatusCode": 200} Here is the function: def idempotent_function( function: Optional[AnyCallableT] = None, *, data_keyword_argument: str, persistence_store: BasePersistenceLayer, config: Optional[IdempotencyConfig] = None, output_serializer: Optional[Union[BaseIdempotencySerializer, Type[BaseIdempotencyModelSerializer]]] = None, **kwargs: Any, ) -> Any: """ Decorator to handle idempotency of any function Parameters ---------- function: Callable Function to be decorated data_keyword_argument: str Keyword parameter name in function's signature that we should hash as idempotency key, e.g. "order" persistence_store: BasePersistenceLayer Instance of BasePersistenceLayer to store data config: IdempotencyConfig Configuration output_serializer: Optional[Union[BaseIdempotencySerializer, Type[BaseIdempotencyModelSerializer]]] Serializer to transform the data to and from a dictionary. If not supplied, no serialization is done via the NoOpSerializer. In case a serializer of type inheriting BaseIdempotencyModelSerializer is given, the serializer is derived from the function return type. Examples -------- **Processes an order in an idempotent manner** from aws_lambda_powertools.utilities.idempotency import ( idempotent_function, DynamoDBPersistenceLayer, IdempotencyConfig ) idem_config=IdempotencyConfig(event_key_jmespath="order_id") persistence_layer = DynamoDBPersistenceLayer(table_name="idempotency_store") @idempotent_function(data_keyword_argument="order", config=idem_config, persistence_store=persistence_layer) def process_order(customer_id: str, order: dict, **kwargs): return {"StatusCode": 200} """ if not function: return cast( AnyCallableT, functools.partial( idempotent_function, data_keyword_argument=data_keyword_argument, persistence_store=persistence_store, config=config, output_serializer=output_serializer, **kwargs, ), ) if isclass(output_serializer) and issubclass(output_serializer, BaseIdempotencyModelSerializer): # instantiate an instance of the serializer class output_serializer = output_serializer.instantiate(function.__annotations__.get("return", None)) config = config or IdempotencyConfig() @functools.wraps(function) def decorate(*args, **kwargs): if os.getenv(constants.IDEMPOTENCY_DISABLED_ENV): return function(*args, **kwargs) if data_keyword_argument not in kwargs: raise RuntimeError( f"Unable to extract '{data_keyword_argument}' from keyword arguments." f" Ensure this exists in your function's signature as well as the caller used it as a keyword argument", ) payload = kwargs.get(data_keyword_argument) idempotency_handler = IdempotencyHandler( function=function, function_payload=payload, config=config, persistence_store=persistence_store, output_serializer=output_serializer, function_args=args, function_kwargs=kwargs, ) return idempotency_handler.handle() return cast(AnyCallableT, decorate)
Decorator to handle idempotency of any function Parameters ---------- function: Callable Function to be decorated data_keyword_argument: str Keyword parameter name in function's signature that we should hash as idempotency key, e.g. "order" persistence_store: BasePersistenceLayer Instance of BasePersistenceLayer to store data config: IdempotencyConfig Configuration output_serializer: Optional[Union[BaseIdempotencySerializer, Type[BaseIdempotencyModelSerializer]]] Serializer to transform the data to and from a dictionary. If not supplied, no serialization is done via the NoOpSerializer. In case a serializer of type inheriting BaseIdempotencyModelSerializer is given, the serializer is derived from the function return type. Examples -------- **Processes an order in an idempotent manner** from aws_lambda_powertools.utilities.idempotency import ( idempotent_function, DynamoDBPersistenceLayer, IdempotencyConfig ) idem_config=IdempotencyConfig(event_key_jmespath="order_id") persistence_layer = DynamoDBPersistenceLayer(table_name="idempotency_store") @idempotent_function(data_keyword_argument="order", config=idem_config, persistence_store=persistence_layer) def process_order(customer_id: str, order: dict, **kwargs): return {"StatusCode": 200}