Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(lambda): extract layers in warm worker pool (#236)
Stephan Mielke43c9151a54e3
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.pyindex ea7114c7..79c0904b 100644--- a/ministack/core/lambda_runtime.py+++ b/ministack/core/lambda_runtime.py@@ -41,6 +41,11 @@ def run():env = init.get("env", {})os.environ.update(env)sys.path.insert(0, code_dir)+ for _ld in filter(None, os.environ.get("_LAMBDA_LAYERS_DIRS", "").split(os.pathsep)):+ _py = os.path.join(_ld, "python")+ if os.path.isdir(_py):+ sys.path.insert(0, _py)+ sys.path.insert(0, _ld)try:mod = importlib.import_module(module_name)handler_fn = getattr(mod, handler_name)@@ -318,6 +323,42 @@ class Worker:with zipfile.ZipFile(os.path.join(self._tmpdir, "code.zip")) as zf:zf.extractall(code_dir)+ # Extract Lambda Layers and build search paths for the worker process.+ # This mirrors the layer handling in lambda_svc._execute_function_local().+ layers_dirs: list[str] = []+ layer_refs = self.config.get("Layers", [])+ if layer_refs:+ from ministack.services.lambda_svc import _resolve_layer_zip+ for layer_ref in layer_refs:+ layer_arn = layer_ref if isinstance(layer_ref, str) else layer_ref.get("Arn", "")+ if not layer_arn:+ continue+ try:+ layer_data = _resolve_layer_zip(layer_arn)+ if layer_data:+ layer_dir = os.path.join(self._tmpdir, f"layer_{len(layers_dirs)}")+ os.makedirs(layer_dir)+ lzip = os.path.join(self._tmpdir, f"layer_{len(layers_dirs)}.zip")+ try:+ with open(lzip, "wb") as lf:+ lf.write(layer_data)+ with zipfile.ZipFile(lzip) as lzf:+ # Validate paths to prevent zip-slip attacks+ for member in lzf.namelist():+ resolved = os.path.realpath(os.path.join(layer_dir, member))+ if not resolved.startswith(os.path.realpath(layer_dir) + os.sep) and resolved != os.path.realpath(layer_dir):+ raise RuntimeError(f"Zip entry escapes target dir: {member}")+ lzf.extractall(layer_dir)+ except (OSError, zipfile.BadZipFile, zipfile.LargeFileError) as e:+ logger.error("Failed to extract layer %s", layer_arn, exc_info=True)+ raise RuntimeError(f"Failed to extract layer {layer_arn}") from e+ layers_dirs.append(layer_dir)+ except RuntimeError:+ raise+ except Exception as e:+ logger.error("Unexpected error resolving layer %s: %s", layer_arn, e)+ raise RuntimeError(f"Failed to resolve layer {layer_arn}") from e+handler = self.config.get("Handler", "index.handler")module_name, handler_name = handler.rsplit(".", 1)env_vars = self.config.get("Environment", {}).get("Variables", {})@@ -327,6 +368,28 @@ class Worker:spawn_env.setdefault("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", str(self.config.get("MemorySize", 128)))spawn_env.setdefault("_LAMBDA_FUNCTION_ARN", self.config.get("FunctionArn", ""))+ # Set layer paths so worker runtimes can find packages from extracted layers.+ # _LAMBDA_LAYERS_DIRS is consumed by the Python worker; Node.js layer resolution+ # is handled via NODE_PATH populated from each layer's nodejs paths below.+ if layers_dirs:+ spawn_env["_LAMBDA_LAYERS_DIRS"] = os.pathsep.join(layers_dirs)+ # NODE_PATH is needed for Node.js workers, including ESM import() which+ # ignores module.paths. Prepend to any existing NODE_PATH.+ node_paths = []+ for ld in layers_dirs:+ nm = os.path.join(ld, "nodejs", "node_modules")+ if os.path.isdir(nm):+ node_paths.append(nm)+ nj = os.path.join(ld, "nodejs")+ if os.path.isdir(nj):+ node_paths.append(nj)+ if node_paths:+ existing = spawn_env.get("NODE_PATH")+ if existing:+ spawn_env["NODE_PATH"] = os.pathsep.join(node_paths + [existing])+ else:+ spawn_env["NODE_PATH"] = os.pathsep.join(node_paths)+self._proc = subprocess.Popen([binary, worker_path],stdin=subprocess.PIPE,diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex a80f5b41..aa9f48ef 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -1455,6 +1455,94 @@ def test_apigwv2_nodejs_lambda_proxy(lam, apigw):pass+def test_lambda_warm_worker_uses_layer(lam):+ """Warm worker should extract layers and make their code available to the handler."""+ # Create a layer with a Python module+ layer_buf = io.BytesIO()+ with zipfile.ZipFile(layer_buf, "w") as z:+ z.writestr("python/myhelper.py", "LAYER_VALUE = 'from-layer'\n")+ layer_resp = lam.publish_layer_version(+ LayerName="warm-layer-test",+ Content={"ZipFile": layer_buf.getvalue()},+ CompatibleRuntimes=["python3.12"],+ )+ layer_arn = layer_resp["LayerVersionArn"]++ # Create a function that imports from the layer+ func_code = (+ "import myhelper\n"+ "def handler(event, context):\n"+ " return {'value': myhelper.LAYER_VALUE}\n"+ )+ func_buf = io.BytesIO()+ with zipfile.ZipFile(func_buf, "w") as z:+ z.writestr("index.py", func_code)++ fname = f"warm-layer-{_uuid_mod.uuid4().hex[:8]}"+ lam.create_function(+ FunctionName=fname,+ Runtime="python3.12",+ Role="arn:aws:iam::000000000000:role/test",+ Handler="index.handler",+ Code={"ZipFile": func_buf.getvalue()},+ Layers=[layer_arn],+ )++ try:+ resp = lam.invoke(FunctionName=fname, Payload=b"{}")+ assert resp["StatusCode"] == 200+ assert "FunctionError" not in resp, f"Lambda error: {resp.get('FunctionError')}"+ payload = json.loads(resp["Payload"].read())+ assert payload["value"] == "from-layer"+ finally:+ lam.delete_function(FunctionName=fname)+++def test_lambda_warm_worker_nodejs_uses_layer(lam):+ """Warm worker should extract Node.js layers and make packages available via require()."""+ # Create a layer with a Node.js module under nodejs/node_modules/+ layer_buf = io.BytesIO()+ with zipfile.ZipFile(layer_buf, "w") as z:+ z.writestr(+ "nodejs/node_modules/layerhelper/index.js",+ "module.exports.LAYER_VALUE = 'from-node-layer';\n",+ )+ layer_resp = lam.publish_layer_version(+ LayerName="warm-node-layer-test",+ Content={"ZipFile": layer_buf.getvalue()},+ CompatibleRuntimes=["nodejs20.x"],+ )+ layer_arn = layer_resp["LayerVersionArn"]++ # Create a Node.js function that requires the layer package+ handler_code = (+ "const helper = require('layerhelper');\n"+ "exports.handler = async (event) => {\n"+ " return { value: helper.LAYER_VALUE };\n"+ "};\n"+ )+ func_buf = io.BytesIO()+ with zipfile.ZipFile(func_buf, "w") as z:+ z.writestr("index.js", handler_code)++ fname = f"warm-node-layer-{_uuid_mod.uuid4().hex[:8]}"+ lam.create_function(+ FunctionName=fname,+ Runtime="nodejs20.x",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": func_buf.getvalue()},+ Layers=[layer_arn],+ )++ try:+ resp = lam.invoke(FunctionName=fname, Payload=b"{}")+ assert resp["StatusCode"] == 200+ assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"+ payload = json.loads(resp["Payload"].read())+ assert payload["value"] == "from-node-layer"+ finally:+ lam.delete_function(FunctionName=fname)# ---------------------------------------------------------------------------# Terraform compatibility tests# ---------------------------------------------------------------------------