Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(glue): GetUserDefinedFunctions accepts java.util.regex \Q...\E patterns (#936)
Jonathan Meersonccc57c9169b2
diff --git a/ministack/services/glue.py b/ministack/services/glue.pyindex 35ea595f..20a16483 100644--- a/ministack/services/glue.py+++ b/ministack/services/glue.py@@ -1885,6 +1885,36 @@ def _get_user_defined_function(data):return json_response({"UserDefinedFunction": udf})+def _translate_java_regex_quote(pattern):+ r"""Translate java.util.regex `\Q...\E` literal-quote spans into their+ RE2/Python-`re` equivalent.++ Real AWS Glue compiles `Pattern` with java.util.regex, which supports `\Q`+ (begin literal quote) and `\E` (end literal quote): everything between them+ is matched literally regardless of regex metacharacters. Trino's Hive/Glue+ connector relies on this — it resolves a UDF with a pattern like+ `trino__\Qdw_clean_text\E__.*`. Python's `re` (like Go's RE2) does not+ understand `\Q...\E` and raises `bad escape \Q`, so we rewrite each span by+ `re.escape()`-ing the literal between `\Q` and `\E` before compiling. Per+ Java semantics a trailing `\Q` with no closing `\E` quotes to end-of-string.+ """+ out = []+ i = 0+ while True:+ start = pattern.find(r"\Q", i)+ if start == -1:+ out.append(pattern[i:])+ break+ out.append(pattern[i:start])+ end = pattern.find(r"\E", start + 2)+ if end == -1:+ out.append(re.escape(pattern[start + 2:]))+ break+ out.append(re.escape(pattern[start + 2:end]))+ i = end + 2+ return "".join(out)++def _get_user_defined_functions(data):db_name = data.get("DatabaseName")pattern = data.get("Pattern") or ""@@ -1897,10 +1927,12 @@ def _get_user_defined_functions(data):if pattern:# Real AWS Glue treats Pattern as a regular expression matched against the# function name (not a glob). e.g. Trino's Glue connector resolves a UDF- # with a regex like `trino__<name>__.*`. An invalid regex (e.g. a bare+ # with a regex like `trino__<name>__.*`. Glue compiles it with+ # java.util.regex, so translate `\Q...\E` literal-quote spans (which RE2+ # / Python `re` reject) before compiling. An invalid regex (e.g. a bare# `*`) raises InvalidInputException, mirroring Glue's RE2 parse error.try:- compiled = re.compile(pattern)+ compiled = re.compile(_translate_java_regex_quote(pattern))except re.error as exc:return error_response_json("InvalidInputException",diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex f662daba..d243f524 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -4458,6 +4458,7 @@ def _create_esm(data: dict):}if ":sqs:" not in event_source_arn:esm["StartingPosition"] = data.get("StartingPosition", "LATEST")+ _init_stream_position(esm_id, event_source_arn, esm["StartingPosition"])if data.get("FilterCriteria"):esm["FilterCriteria"] = data.get("FilterCriteria")# #442: Tags are accepted on CreateEventSourceMapping. Stored inline on@@ -4562,6 +4563,27 @@ _dynamodb_stream_positions = AccountScopedDict()_dynamodb_stream_positions_lock = threading.Lock()+def _init_stream_position(esm_id, source_arn, starting):+ """Anchor a DynamoDB-stream ESM's read position at subscription time so+ LATEST does not depend on when the poller thread first ticks. No-op if the+ position was already set."""+ if ":dynamodb:" not in source_arn or "/stream/" not in source_arn:+ return+ from ministack.services import dynamodb as _ddb++ stream_records = getattr(_ddb, "_stream_records", None)+ if stream_records is None:+ return+ table_name = source_arn.split("/stream/")[0].split("/")[-1]+ with _dynamodb_stream_positions_lock:+ if esm_id in _dynamodb_stream_positions:+ return+ if starting == "TRIM_HORIZON":+ _dynamodb_stream_positions[esm_id] = 0+ else:+ _dynamodb_stream_positions[esm_id] = len(stream_records.get(table_name, []))++def _ensure_poller():global _poller_startedwith _poller_lock:diff --git a/tests/test_glue.py b/tests/test_glue.pyindex d2ca88cb..4756fec8 100644--- a/tests/test_glue.py+++ b/tests/test_glue.py@@ -1244,6 +1244,39 @@ def test_glue_get_user_defined_functions_pattern_is_regex(glue):assert func_name in names(Pattern="trino__.*")+def test_glue_get_user_defined_functions_pattern_java_quote(glue):+ r"""GetUserDefinedFunctions accepts java.util.regex `\Q...\E` literal-quote+ spans, matching real AWS Glue (which compiles Pattern with java.util.regex).+ Trino's Hive/Glue connector resolves a UDF with a pattern like+ `trino__\Qdw_clean_text\E__.*`; Python `re` / Go RE2 reject `\Q` outright, so+ ministack must translate the span before compiling."""+ glue.create_database(DatabaseInput={"Name": "pq"})+ func_name = "trino__dw_clean_text__abc"+ glue.create_user_defined_function(+ DatabaseName="pq",+ FunctionInput={"FunctionName": func_name, "ClassName": "TrinoFunction"},+ )++ def names(**kwargs):+ return [u["FunctionName"] for u in glue.get_user_defined_functions(**kwargs)["UserDefinedFunctions"]]++ # The exact pattern Trino's Glue connector emits — must resolve the function,+ # not raise `bad escape \Q`.+ assert func_name in names(DatabaseName="pq", Pattern=r"trino__\Qdw_clean_text\E__.*")+ # `.*` still matches everything (regex semantics unaffected).+ assert func_name in names(DatabaseName="pq", Pattern=".*")+ # The literal between \Q...\E is matched literally: regex metachars inside it+ # do not apply, so a `.` in the quoted span only matches a literal dot.+ glue.create_user_defined_function(+ DatabaseName="pq",+ FunctionInput={"FunctionName": "a.b", "ClassName": "TrinoFunction"},+ )+ assert names(DatabaseName="pq", Pattern=r"^\Qa.b\E$") == ["a.b"]+ assert names(DatabaseName="pq", Pattern=r"^\Qaxb\E$") == []+ # A trailing \Q with no closing \E quotes to end-of-string (Java semantics).+ assert func_name in names(DatabaseName="pq", Pattern=r"trino__\Qdw_clean_text__abc")++def test_glue_resolve_script_account_scoped(tmp_path, monkeypatch):"""_resolve_script finds an s3:// script persisted under the account-scopedon-disk layout DATA_DIR/<account>/<bucket>/<key> (#827).