wasmo 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wasmo/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Stateful in-process AWS mock for boto3, powered by a single WebAssembly module."""
2
+
3
+ from wasmo._function import FunctionContext
4
+ from wasmo._mock import ENDPOINT, REGION, Mock, Response, mock_aws
5
+
6
+ __all__ = ["ENDPOINT", "REGION", "FunctionContext", "Mock", "Response", "mock_aws"]
wasmo/_function.py ADDED
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import threading
5
+ import time
6
+ import traceback
7
+ from collections.abc import Callable
8
+ from typing import Any
9
+
10
+ Handler = Callable[[Any, "FunctionContext"], Any]
11
+
12
+
13
+ class FunctionContext:
14
+ """The invocation a registered handler runs, as the Lambda context object describes it."""
15
+
16
+ def __init__(self, meta: dict[str, Any]) -> None:
17
+ self.function_name: str = meta["functionName"]
18
+ self.function_version: str = meta["functionVersion"]
19
+ self.invoked_function_arn: str = meta["invokedFunctionArn"]
20
+ self.memory_limit_in_mb: int = meta["memoryLimitInMB"]
21
+ self.aws_request_id: str = meta["awsRequestId"]
22
+ self.log_group_name: str = meta["logGroupName"]
23
+ self.log_stream_name: str = meta["logStreamName"]
24
+ self.invocation_type: str = meta["invocationType"]
25
+ self.client_context: str | None = meta.get("clientContext")
26
+ self.environment: dict[str, str] = dict(meta["environment"])
27
+ self._deadline_ms: float = meta["deadlineMs"]
28
+ self._lines: list[str] = []
29
+ self._lock = threading.Lock()
30
+
31
+ def get_remaining_time_in_millis(self) -> int:
32
+ return max(0, int(self._deadline_ms - time.time() * 1000))
33
+
34
+ def log(self, message: str) -> None:
35
+ """Append a line to the invocation log that Invoke returns with LogType Tail."""
36
+ with self._lock:
37
+ self._lines.append(message if message.endswith("\n") else message + "\n")
38
+
39
+ def _log_text(self) -> str:
40
+ with self._lock:
41
+ return "".join(self._lines)
42
+
43
+
44
+ def run(handlers: dict[str, Handler], meta_bytes: bytes, payload: bytes) -> tuple[bytes, bytes]:
45
+ """Run one invocation and encode the result meta and payload for wasmo_complete."""
46
+ meta = json.loads(meta_bytes)
47
+ handler = handlers.get(meta["functionName"])
48
+ if handler is None:
49
+ return json.dumps({"id": meta["id"], "registered": False}).encode(), b""
50
+ context = FunctionContext(meta)
51
+ result: dict[str, Any] = {"id": meta["id"]}
52
+ body = b""
53
+ try:
54
+ body = json.dumps(handler(json.loads(payload), context)).encode()
55
+ except Exception as e:
56
+ result["error"] = {
57
+ "type": type(e).__name__,
58
+ "message": str(e),
59
+ "stackTrace": [line.rstrip("\n") for line in traceback.format_tb(e.__traceback__)],
60
+ }
61
+ result["log"] = context._log_text()
62
+ return json.dumps(result).encode(), body
wasmo/_mock.py ADDED
@@ -0,0 +1,267 @@
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import inspect
5
+ import io
6
+ import json
7
+ import os
8
+ import struct
9
+ import threading
10
+ from collections.abc import Callable, Iterable, Iterator
11
+ from dataclasses import dataclass
12
+ from typing import Any, TypeVar, overload
13
+ from urllib.parse import urlsplit
14
+
15
+ import boto3
16
+ import botocore.loaders
17
+ import botocore.session
18
+ from botocore.awsrequest import AWSPreparedRequest, AWSResponse
19
+
20
+ from wasmo._function import Handler, run
21
+ from wasmo._runtime import Instance
22
+
23
+ ENDPOINT = "http://wasmo.local"
24
+ REGION = "us-east-1"
25
+ ACCESS_KEY_ID = "test"
26
+ SECRET_ACCESS_KEY = "test"
27
+
28
+ _ENV = {
29
+ "AWS_ACCESS_KEY_ID": ACCESS_KEY_ID,
30
+ "AWS_SECRET_ACCESS_KEY": SECRET_ACCESS_KEY,
31
+ "AWS_SESSION_TOKEN": None,
32
+ "AWS_SECURITY_TOKEN": None,
33
+ "AWS_DEFAULT_REGION": REGION,
34
+ "AWS_REGION": REGION,
35
+ }
36
+
37
+ _loader = botocore.loaders.create_loader()
38
+ _create_client = botocore.session.Session.create_client
39
+ _create_client_signature = inspect.signature(_create_client)
40
+
41
+ F = TypeVar("F", bound=Callable[..., Any])
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Response:
46
+ status: int
47
+ headers: dict[str, str]
48
+ body: bytes
49
+
50
+
51
+ class _RawResponse(io.BytesIO):
52
+ def stream(self, amt: int = 65536, decode_content: bool | None = None) -> Iterator[bytes]:
53
+ while chunk := self.read(amt):
54
+ yield chunk
55
+
56
+
57
+ def _bytes(body: Any) -> bytes:
58
+ if body is None:
59
+ return b""
60
+ if isinstance(body, (bytes, bytearray, memoryview)):
61
+ return bytes(body)
62
+ if isinstance(body, str):
63
+ return body.encode()
64
+ if hasattr(body, "read"):
65
+ return _bytes(body.read())
66
+ if isinstance(body, Iterable):
67
+ return b"".join(_bytes(chunk) for chunk in body)
68
+ raise TypeError(f"wasmo: unsupported request body {type(body).__name__}")
69
+
70
+
71
+ def _header(value: str | bytes) -> str:
72
+ return value.decode() if isinstance(value, bytes) else value
73
+
74
+
75
+ class Mock:
76
+ """An isolated in-process AWS backed by its own WebAssembly instance."""
77
+
78
+ def __init__(self) -> None:
79
+ self._lock = threading.Lock()
80
+ self._instance: Instance | None = None
81
+ self._closed = False
82
+ self._functions: dict[str, Handler] = {}
83
+
84
+ def register_function(self, name: str, handler: Handler) -> Handler:
85
+ """Bind ``handler(event, context)`` to every invocation of the Lambda function ``name``.
86
+
87
+ The handler gets the decoded event and returns a JSON-serializable response; an exception
88
+ becomes a function error. It runs outside the mock's lock, so it may call AWS through the
89
+ same mock.
90
+ """
91
+ self._functions[name] = handler
92
+ return handler
93
+
94
+ def fetch(
95
+ self,
96
+ url: str,
97
+ *,
98
+ method: str = "GET",
99
+ headers: dict[str, str] | None = None,
100
+ body: bytes = b"",
101
+ ) -> Response:
102
+ """Send a raw HTTP request, such as a presigned URL, to this mock."""
103
+ pairs = [(k.lower(), v) for k, v in (headers or {}).items()]
104
+ if not any(k == "host" for k, _ in pairs):
105
+ pairs.append(("host", urlsplit(url).netloc))
106
+ meta = json.dumps({"method": method, "url": url, "headers": pairs}).encode()
107
+ pending: list[tuple[bytes, bytes]] = []
108
+ with self._lock:
109
+ if self._closed:
110
+ raise RuntimeError("wasmo: mock is closed")
111
+ if self._instance is None:
112
+ self._instance = Instance()
113
+ instance = self._instance
114
+ frame = instance.handle(meta, body, pending)
115
+ while pending:
116
+ result, payload = run(self._functions, *pending.pop(0))
117
+ with self._lock:
118
+ answer = instance.complete(result, payload, pending)
119
+ frame = answer or frame
120
+ (meta_len,) = struct.unpack_from(">I", frame)
121
+ res = json.loads(frame[4 : 4 + meta_len])
122
+ if "await" in res:
123
+ raise RuntimeError(f"wasmo: invocation {res['await']} was never answered")
124
+ out: dict[str, str] = {}
125
+ for name, value in res["headers"]:
126
+ out[name] = f"{out[name]}, {value}" if name in out else value
127
+ return Response(res["status"], out, frame[4 + meta_len :])
128
+
129
+ def _send(self, request: AWSPreparedRequest, **_: Any) -> AWSResponse:
130
+ headers = {k: _header(v) for k, v in request.headers.items()}
131
+ res = self.fetch(
132
+ request.url, method=request.method, headers=headers, body=_bytes(request.body)
133
+ )
134
+ return AWSResponse(request.url, res.status, res.headers, _RawResponse(res.body))
135
+
136
+ def _bind(self, client: Any) -> Any:
137
+ client.meta.events.register("before-send", self._send, unique_id=f"wasmo-{id(self)}")
138
+ return client
139
+
140
+ def session(self, **kwargs: Any) -> boto3.Session:
141
+ """A boto3 session whose clients and resources talk to this mock."""
142
+ kwargs.setdefault("region_name", REGION)
143
+ if "aws_access_key_id" not in kwargs:
144
+ kwargs["aws_access_key_id"] = ACCESS_KEY_ID
145
+ kwargs["aws_secret_access_key"] = SECRET_ACCESS_KEY
146
+ return boto3.Session(botocore_session=_Session(self), **kwargs)
147
+
148
+ def client(self, service_name: str, **kwargs: Any) -> Any:
149
+ return self.session().client(service_name, **kwargs)
150
+
151
+ def resource(self, service_name: str, **kwargs: Any) -> Any:
152
+ return self.session().resource(service_name, **kwargs)
153
+
154
+ def reset(self) -> None:
155
+ """Drop all state. Existing clients keep working against the empty state."""
156
+ with self._lock:
157
+ if self._closed:
158
+ raise RuntimeError("wasmo: mock is closed")
159
+ self._instance = None
160
+
161
+ def close(self) -> None:
162
+ with self._lock:
163
+ self._closed = True
164
+ self._instance = None
165
+
166
+ def start(self) -> None:
167
+ """Route every botocore client created from now on to this mock."""
168
+ _activate(self)
169
+
170
+ def stop(self) -> None:
171
+ _deactivate(self)
172
+
173
+ def __enter__(self) -> Mock:
174
+ self.start()
175
+ return self
176
+
177
+ def __exit__(self, *_: object) -> None:
178
+ self.stop()
179
+ self.close()
180
+
181
+ def __call__(self, func: F) -> F:
182
+ return mock_aws(func)
183
+
184
+
185
+ class _Session(botocore.session.Session):
186
+ def __init__(self, mock: Mock) -> None:
187
+ super().__init__()
188
+ self.register_component("data_loader", _loader)
189
+ self._wasmo = mock
190
+
191
+ def create_client(self, *args: Any, **kwargs: Any) -> Any:
192
+ bound = _create_client_signature.bind(self, *args, **kwargs)
193
+ if bound.arguments.get("endpoint_url") is None:
194
+ bound.arguments["endpoint_url"] = ENDPOINT
195
+ return self._wasmo._bind(_create_client(*bound.args, **bound.kwargs))
196
+
197
+
198
+ _active: list[Mock] = []
199
+ _active_lock = threading.Lock()
200
+ _saved_env: dict[str, str | None] = {}
201
+
202
+
203
+ def _patched_create_client(session: botocore.session.Session, *args: Any, **kwargs: Any) -> Any:
204
+ with _active_lock:
205
+ mock = _active[-1] if _active else None
206
+ bound = _create_client_signature.bind(session, *args, **kwargs)
207
+ if mock is None:
208
+ return _create_client(*bound.args, **bound.kwargs)
209
+ arguments = bound.arguments
210
+ if arguments.get("endpoint_url") is None:
211
+ arguments["endpoint_url"] = ENDPOINT
212
+ if arguments.get("aws_access_key_id") is None:
213
+ arguments["aws_access_key_id"] = ACCESS_KEY_ID
214
+ arguments["aws_secret_access_key"] = SECRET_ACCESS_KEY
215
+ arguments["aws_session_token"] = None
216
+ return mock._bind(_create_client(*bound.args, **bound.kwargs))
217
+
218
+
219
+ def _activate(mock: Mock) -> None:
220
+ with _active_lock:
221
+ if mock in _active:
222
+ raise RuntimeError("wasmo: mock is already started")
223
+ if not _active:
224
+ for name, value in _ENV.items():
225
+ _saved_env[name] = os.environ.get(name)
226
+ if value is None:
227
+ os.environ.pop(name, None)
228
+ else:
229
+ os.environ[name] = value
230
+ botocore.session.Session.create_client = _patched_create_client # type: ignore[method-assign]
231
+ _active.append(mock)
232
+
233
+
234
+ def _deactivate(mock: Mock) -> None:
235
+ with _active_lock:
236
+ if mock not in _active:
237
+ raise RuntimeError("wasmo: mock is not started")
238
+ _active.remove(mock)
239
+ if not _active:
240
+ botocore.session.Session.create_client = _create_client # type: ignore[method-assign]
241
+ for name, value in _saved_env.items():
242
+ if value is None:
243
+ os.environ.pop(name, None)
244
+ else:
245
+ os.environ[name] = value
246
+ _saved_env.clear()
247
+
248
+
249
+ @overload
250
+ def mock_aws() -> Mock: ...
251
+
252
+
253
+ @overload
254
+ def mock_aws(func: F) -> F: ...
255
+
256
+
257
+ def mock_aws(func: F | None = None) -> Mock | F:
258
+ """Return a Mock for ``with``, or wrap ``func`` so each call runs in a fresh Mock."""
259
+ if func is None:
260
+ return Mock()
261
+
262
+ @functools.wraps(func)
263
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
264
+ with Mock():
265
+ return func(*args, **kwargs)
266
+
267
+ return wrapper # type: ignore[return-value]
wasmo/_runtime.py ADDED
@@ -0,0 +1,123 @@
1
+ from __future__ import annotations
2
+
3
+ import ctypes
4
+ import os
5
+ import threading
6
+ import time
7
+ from importlib.resources import files
8
+
9
+ import wasmtime
10
+
11
+ _compile_lock = threading.Lock()
12
+ _compiled: tuple[wasmtime.Engine, wasmtime.Module] | None = None
13
+
14
+
15
+ def _module() -> tuple[wasmtime.Engine, wasmtime.Module]:
16
+ global _compiled
17
+ with _compile_lock:
18
+ if _compiled is None:
19
+ engine = wasmtime.Engine()
20
+ binary = files(__package__).joinpath("wasmo.wasm").read_bytes()
21
+ _compiled = (engine, wasmtime.Module(engine, binary))
22
+ return _compiled
23
+
24
+
25
+ def _now_ms() -> float:
26
+ return time.time() * 1000
27
+
28
+
29
+ def _random_fill(caller: wasmtime.Caller, ptr: int, length: int) -> None:
30
+ memory = caller["memory"]
31
+ assert isinstance(memory, wasmtime.Memory)
32
+ memory.write(caller, os.urandom(length & 0xFFFFFFFF), ptr & 0xFFFFFFFF)
33
+
34
+
35
+ def _read(caller: wasmtime.Caller, ptr: int, length: int) -> bytes:
36
+ memory = caller["memory"]
37
+ assert isinstance(memory, wasmtime.Memory)
38
+ ptr, length = ptr & 0xFFFFFFFF, length & 0xFFFFFFFF
39
+ return bytes(memory.read(caller, ptr, ptr + length))
40
+
41
+
42
+ class Instance:
43
+ def __init__(self) -> None:
44
+ engine, module = _module()
45
+ self._store = wasmtime.Store(engine)
46
+ self._pending: list[tuple[bytes, bytes]] | None = None
47
+ linker = wasmtime.Linker(engine)
48
+ linker.define_func(
49
+ "wasmo", "now_ms", wasmtime.FuncType([], [wasmtime.ValType.f64()]), _now_ms
50
+ )
51
+ linker.define_func(
52
+ "wasmo",
53
+ "random_fill",
54
+ wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i32()], []),
55
+ _random_fill,
56
+ access_caller=True,
57
+ )
58
+ i32 = wasmtime.ValType.i32()
59
+ linker.define_func(
60
+ "wasmo",
61
+ "invoke",
62
+ wasmtime.FuncType([i32, i32, i32, i32], []),
63
+ self._invoke,
64
+ access_caller=True,
65
+ )
66
+ exports = linker.instantiate(self._store, module).exports(self._store)
67
+ self._memory = exports["memory"]
68
+ self._alloc = exports["wasmo_alloc"]
69
+ self._free = exports["wasmo_free"]
70
+ self._handle = exports["wasmo_handle"]
71
+ self._complete = exports["wasmo_complete"]
72
+
73
+ def _invoke(
74
+ self,
75
+ caller: wasmtime.Caller,
76
+ meta_ptr: int,
77
+ meta_len: int,
78
+ payload_ptr: int,
79
+ payload_len: int,
80
+ ) -> None:
81
+ if self._pending is None:
82
+ raise RuntimeError("wasmo: invoke outside a request")
83
+ self._pending.append(
84
+ (_read(caller, meta_ptr, meta_len), _read(caller, payload_ptr, payload_len))
85
+ )
86
+
87
+ def _span(self, ptr: int, length: int) -> int:
88
+ if ptr + length > self._memory.data_len(self._store):
89
+ raise RuntimeError("wasmo: memory access out of range")
90
+ return ctypes.addressof(self._memory.data_ptr(self._store).contents) + ptr
91
+
92
+ def _put(self, data: bytes) -> int:
93
+ ptr = self._alloc(self._store, len(data)) & 0xFFFFFFFF
94
+ if data:
95
+ ctypes.memmove(self._span(ptr, len(data)), data, len(data))
96
+ return ptr
97
+
98
+ def handle(self, meta: bytes, body: bytes, pending: list[tuple[bytes, bytes]]) -> bytes:
99
+ frame = self._call(self._handle, meta, body, pending)
100
+ assert frame is not None
101
+ return frame
102
+
103
+ def complete(
104
+ self, meta: bytes, payload: bytes, pending: list[tuple[bytes, bytes]]
105
+ ) -> bytes | None:
106
+ return self._call(self._complete, meta, payload, pending)
107
+
108
+ def _call(
109
+ self, fn: wasmtime.Func, meta: bytes, body: bytes, pending: list[tuple[bytes, bytes]]
110
+ ) -> bytes | None:
111
+ meta_ptr = self._put(meta)
112
+ body_ptr = self._put(body)
113
+ self._pending = pending
114
+ try:
115
+ res = fn(self._store, meta_ptr, len(meta), body_ptr, len(body))
116
+ finally:
117
+ self._pending = None
118
+ if res == 0:
119
+ return None
120
+ ptr, length = (res >> 32) & 0xFFFFFFFF, res & 0xFFFFFFFF
121
+ frame = ctypes.string_at(self._span(ptr, length), length)
122
+ self._free(self._store, ptr, length)
123
+ return frame
wasmo/py.typed ADDED
File without changes
wasmo/wasmo.wasm ADDED
Binary file
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: wasmo
3
+ Version: 0.1.0
4
+ Summary: Stateful in-process AWS mock for boto3, powered by a single WebAssembly module
5
+ Project-URL: Homepage, https://github.com/conao3/wasm-wasmo
6
+ Project-URL: Documentation, https://github.com/conao3/wasm-wasmo/tree/main/python#readme
7
+ Project-URL: Source, https://github.com/conao3/wasm-wasmo/tree/main/python
8
+ Project-URL: Issues, https://github.com/conao3/wasm-wasmo/issues
9
+ Project-URL: Changelog, https://github.com/conao3/wasm-wasmo/blob/main/CHANGELOG.md
10
+ Author: conao3
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Keywords: aws,boto3,botocore,mock,testing,webassembly
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Framework :: Pytest
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: MacOS
19
+ Classifier: Operating System :: POSIX :: Linux
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Classifier: Programming Language :: Python :: 3.14
27
+ Classifier: Topic :: Software Development :: Testing
28
+ Classifier: Topic :: Software Development :: Testing :: Mocking
29
+ Classifier: Typing :: Typed
30
+ Requires-Python: >=3.10
31
+ Requires-Dist: boto3>=1.36
32
+ Requires-Dist: botocore>=1.36
33
+ Requires-Dist: wasmtime>=50
34
+ Description-Content-Type: text/markdown
35
+
36
+ # wasmo
37
+
38
+ A stateful AWS mock that runs inside your test process. Write a value to DynamoDB and the next `get_item` returns it; put an object in S3 and `list_objects_v2` shows it. No Docker, no ports, no sidecar process: the AWS emulator is a single WebAssembly module that wasmo hooks into botocore's HTTP layer, so request signing, retries, checksums, and response parsing are boto3's own.
39
+
40
+ Emulated services: STS, SQS, DynamoDB, S3, SNS, EventBridge, Secrets Manager, SSM Parameter Store, KMS. The same module also backs wasmo's Go, JavaScript, and JVM adapters, so every language sees the same behaviour. Source and service coverage: <https://github.com/conao3/wasm-wasmo>.
41
+
42
+ Requires Python 3.10+. The WebAssembly module ships inside the package and runs on [wasmtime](https://pypi.org/project/wasmtime/). It is compiled once per process; each mock gets its own instance.
43
+
44
+ ```python
45
+ import boto3
46
+ import wasmo
47
+
48
+ with wasmo.mock_aws() as aws:
49
+ s3 = boto3.client("s3")
50
+ s3.create_bucket(Bucket="assets")
51
+ s3.put_object(Bucket="assets", Key="hello.txt", Body=b"hi")
52
+ assert s3.get_object(Bucket="assets", Key="hello.txt")["Body"].read() == b"hi"
53
+
54
+ aws.reset() # drop all state
55
+ ```
56
+
57
+ Inside `mock_aws()`, every botocore client and boto3 resource created from any session talks to that mock. A client stays bound to the mock it was created in. Unless you pass them explicitly, wasmo sets the endpoint to `http://wasmo.local` and the credentials to `test` / `test`, and the environment gets `AWS_DEFAULT_REGION=us-east-1` and the same dummy credentials for the duration of the block. Leaving the block closes the mock; its clients then raise.
58
+
59
+ As a decorator, each call runs in a fresh mock:
60
+
61
+ ```python
62
+ @wasmo.mock_aws
63
+ def test_enqueue():
64
+ sqs = boto3.client("sqs")
65
+ url = sqs.create_queue(QueueName="jobs")["QueueUrl"]
66
+ sqs.send_message(QueueUrl=url, MessageBody="hi")
67
+ assert sqs.receive_message(QueueUrl=url)["Messages"][0]["Body"] == "hi"
68
+ ```
69
+
70
+ A pytest fixture:
71
+
72
+ ```python
73
+ import pytest
74
+ import wasmo
75
+
76
+
77
+ @pytest.fixture
78
+ def aws():
79
+ with wasmo.mock_aws() as aws:
80
+ yield aws
81
+
82
+
83
+ def test_rejects_a_duplicate(aws):
84
+ table = boto3.resource("dynamodb").Table("users") # create the table first
85
+ put = dict(Item={"id": "1"}, ConditionExpression="attribute_not_exists(id)")
86
+ table.put_item(**put)
87
+ with pytest.raises(table.meta.client.exceptions.ConditionalCheckFailedException):
88
+ table.put_item(**put)
89
+ ```
90
+
91
+ Without patching botocore, `wasmo.Mock()` hands out bound clients directly:
92
+
93
+ ```python
94
+ aws = wasmo.Mock()
95
+ ddb = aws.resource("dynamodb")
96
+ sqs = aws.client("sqs", region_name="eu-west-1")
97
+ session = aws.session() # a boto3.Session bound to this mock
98
+ aws.close()
99
+ ```
100
+
101
+ `aws.fetch(url, method="GET", headers=None, body=b"")` sends a raw HTTP request to the mock and returns a `Response(status, headers, body)`, for example to fetch a presigned URL.
102
+
103
+ S3 works with virtual-hosted (`<bucket>.wasmo.local`, the default) and path-style addressing, `GetObject` returns a botocore `StreamingBody`, and `boto3.s3.transfer` multipart uploads and ranged downloads work as against AWS. Clients created with an `https://` endpoint send `aws-chunked` bodies with trailing checksums, which wasmo decodes.
104
+
105
+ A `Mock` is safe to use from several threads; calls into one instance are serialized.
106
+
107
+ Lambda functions created with `create_function` run handlers registered by name, on every invocation path (Invoke, SNS, EventBridge, S3 notifications, event source mappings, async destinations). A handler takes the decoded event and a `wasmo.FunctionContext` (`function_name`, `aws_request_id`, `environment`, `log()`, ...), returns a JSON-serializable value, and may call the same mock; an exception becomes a function error.
108
+
109
+ ```python
110
+ def resize(event, context):
111
+ context.log(f"request {context.aws_request_id}")
112
+ return {"ok": True}
113
+
114
+
115
+ aws.register_function("resize", resize)
116
+ ```
@@ -0,0 +1,11 @@
1
+ wasmo/__init__.py,sha256=5GxunszA0u7jx3R0juKaO6JkOwh5aw59MhEsfztfXRw,283
2
+ wasmo/_function.py,sha256=HJiyJ9-djeuJjotMYZthV2Bj6vo27_hoeNg5aO3jg84,2452
3
+ wasmo/_mock.py,sha256=ZHYXxLhq5Xi3BU5vhZ2F_xQoYXEJmk9C7dnFKSUI1Pk,9049
4
+ wasmo/_runtime.py,sha256=8DCinGj4SRA-vHp3fqedVegCh8rBy2P9ZLQnv6EShDk,4153
5
+ wasmo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ wasmo/wasmo.wasm,sha256=R_HtwFh1NzCopHcdtJEKFldXRo6THHkdakfM7JOOGmo,6102833
7
+ wasmo-0.1.0.dist-info/METADATA,sha256=FIEOFF0twveKxitSyDO6QLLx8q3Aw2L87y-eOskZTak,5428
8
+ wasmo-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
9
+ wasmo-0.1.0.dist-info/licenses/LICENSE,sha256=6zZvFtCkbukgN_CvKkzxYE-gsSuowrp4Cr8nINmh7Kk,11336
10
+ wasmo-0.1.0.dist-info/licenses/NOTICE,sha256=ParzYf-1setILaRsZshtIbE655pAQK3SoaTVRSN0NFc,366
11
+ wasmo-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work, excluding
103
+ those notices that do not pertain to any part of the Derivative
104
+ Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one of
111
+ the following places: within a NOTICE text file distributed as
112
+ part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions for
125
+ use, reproduction, or distribution of Your modifications, or for any
126
+ such Derivative Works as a whole, provided Your use, reproduction,
127
+ and distribution of the Work otherwise complies with the conditions
128
+ stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed
144
+ to in writing, Licensor provides the Work (and each Contributor
145
+ provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
146
+ OR CONDITIONS OF ANY KIND, either express or implied, including,
147
+ without limitation, any warranties or conditions of TITLE,
148
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
149
+ PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor has
163
+ been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing the
166
+ Work or Derivative Works thereof, You may choose to offer, and charge
167
+ a fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your own
170
+ behalf and on Your sole responsibility, not on behalf of any other
171
+ Contributor, and only if You agree to indemnify, defend, and hold
172
+ each Contributor harmless for any liability incurred by, or claims
173
+ asserted against, such Contributor by reason of your accepting any
174
+ such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 conao3
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,12 @@
1
+ wasmo
2
+ Copyright 2026 conao3
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+
6
+ The WebAssembly module embeds AWS service models from Botocore
7
+ (https://github.com/boto/botocore, Apache-2.0).
8
+
9
+ ------------------------------------------------------------------------
10
+
11
+ Botocore
12
+ Copyright 2012-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.