wasmo 0.1.1

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 19ea9d8889a6aca1fefd124004d973e97a73ccd7428d0dc5870dfe0a2e10d18a
4
+ data.tar.gz: 89e3f684aea9a5f03bfa694f42f3daeaed3e6909c13e0ee261ef2b90fd1eb23e
5
+ SHA512:
6
+ metadata.gz: 754d49a0dd9c1a7bf7bfa60a750cc3f5147d2fafcc37fd80220e4edfd0b00087e20b9c48de37fff9c038d0b15a75a1df5ce89d73bc0c87cbe93d675e3f936efb
7
+ data.tar.gz: e26da18729de67a1633bec0fceacf7b0d768f28212f5707ea014f3819e1b699a58ebcce797ed11dc831d375250ad5ae95a85110561d4e465527f8fb978060119
data/LICENSE ADDED
@@ -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.
data/NOTICE ADDED
@@ -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.
data/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # wasmo
2
+
3
+ A stateful AWS mock that runs inside your test process. Write a value to DynamoDB and the next `GetItem` returns it; put an object in S3 and `ListObjectsV2` shows it. No Docker, no ports, no sidecar process: the AWS emulator is a single WebAssembly module, run by [wasmtime-rb](https://github.com/bytecodealliance/wasmtime-rb), that plugs into the AWS SDK for Ruby v3 as the send handler.
4
+
5
+ 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>.
6
+
7
+ ```ruby
8
+ require "wasmo"
9
+ require "aws-sdk-dynamodb"
10
+ require "aws-sdk-sqs"
11
+
12
+ aws = Wasmo::Mock.new
13
+ ddb = aws.client(Aws::DynamoDB::Client) # or Aws::DynamoDB::Client.new(**aws.config)
14
+ ddb.put_item(table_name: "users", item: { "id" => "1" })
15
+ aws.reset # drop all state
16
+ aws.close # later requests raise Wasmo::ClosedError
17
+
18
+ Wasmo.mock_aws do |mock|
19
+ Aws::SQS::Client.new.create_queue(queue_name: "jobs") # every client built in the block uses the mock
20
+ end
21
+ ```
22
+
23
+ Requests go through the SDK's own signing, retries, checksums, and response parsing; only Net::HTTP is replaced. Each `Wasmo::Mock` owns an isolated WebAssembly instance and serializes calls into it, so one mock can be shared across threads and separate mocks never share state. Clients get `region` `us-east-1`, `endpoint` `http://wasmo.local`, and dummy credentials; S3 works with both virtual-hosted and path-style (`force_path_style: true`) addressing. `aws.request(method, url, headers, body)` sends a raw HTTP request, e.g. to fetch a presigned URL.
24
+
25
+ Lambda functions created with `create_function` run blocks registered by name, on every invocation path (Invoke, SNS, EventBridge, S3 notifications, event source mappings, async destinations): `aws.register_function("resize") { |event, context| { "ok" => true } }`. The block gets 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.
26
+
27
+ The compiled module is cached in `Gem.cache_home/wasmo` (`~/.cache/wasmo`), so only the first run after an upgrade pays for compilation.
28
+
29
+ Ruby 3.3+. wasmtime-rb ships precompiled native gems for Linux and macOS; elsewhere Bundler builds it from source with a Rust toolchain.
30
+
31
+ ## License
32
+
33
+ Apache-2.0. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Wasmo
4
+ # The invocation a registered handler runs, as the Lambda context object
5
+ # describes it.
6
+ class FunctionContext
7
+ FIELDS = {
8
+ function_name: "functionName",
9
+ function_version: "functionVersion",
10
+ invoked_function_arn: "invokedFunctionArn",
11
+ memory_limit_in_mb: "memoryLimitInMB",
12
+ aws_request_id: "awsRequestId",
13
+ log_group_name: "logGroupName",
14
+ log_stream_name: "logStreamName",
15
+ invocation_type: "invocationType",
16
+ client_context: "clientContext"
17
+ }.freeze
18
+
19
+ attr_reader(*FIELDS.keys, :environment)
20
+
21
+ def initialize(meta)
22
+ FIELDS.each { |attr, key| instance_variable_set(:"@#{attr}", meta[key]) }
23
+ @environment = meta["environment"].freeze
24
+ @deadline_ms = meta["deadlineMs"]
25
+ @log = +""
26
+ @log_lock = Mutex.new
27
+ end
28
+
29
+ def get_remaining_time_in_millis # rubocop:disable Naming/AccessorMethodName
30
+ [(@deadline_ms - Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)).to_i, 0].max
31
+ end
32
+
33
+ # Appends a line to the invocation log that Invoke returns with LogType Tail.
34
+ def log(message)
35
+ @log_lock.synchronize do
36
+ @log << message.to_s
37
+ @log << "\n" unless @log.end_with?("\n")
38
+ end
39
+ end
40
+
41
+ def log_text
42
+ @log_lock.synchronize { @log.dup }
43
+ end
44
+ end
45
+
46
+ # Runs the invocations the module announces through its invoke import.
47
+ module Function
48
+ def self.run(functions, meta_json, payload)
49
+ meta = JSON.parse(meta_json)
50
+ handler = functions[meta["functionName"]]
51
+ return [JSON.generate({ id: meta["id"], registered: false }), ""] if handler.nil?
52
+
53
+ context = FunctionContext.new(meta)
54
+ result, body = answer(handler, payload, context)
55
+ [JSON.generate({ id: meta["id"], **result, log: context.log_text }), body]
56
+ end
57
+
58
+ def self.answer(handler, payload, context)
59
+ [{}, JSON.generate(handler.call(JSON.parse(payload), context))]
60
+ rescue StandardError => e
61
+ [{ error: { type: e.class.name, message: e.message, stackTrace: e.backtrace || [] } }, ""]
62
+ end
63
+ end
64
+ end
data/lib/wasmo/mock.rb ADDED
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Wasmo
4
+ # An isolated in-process AWS.
5
+ class Mock
6
+ def initialize
7
+ @instance = Instance.new
8
+ @functions = {}
9
+ end
10
+
11
+ # Binds the block to every invocation of the Lambda function named +name+.
12
+ # It receives the decoded event and a FunctionContext and returns a
13
+ # JSON-serializable response; an exception becomes a function error. It
14
+ # runs outside the mock's lock, so it may call AWS through the same mock.
15
+ def register_function(name, &handler)
16
+ raise ArgumentError, "wasmo: register_function needs a block" unless handler
17
+
18
+ @functions[name] = handler
19
+ end
20
+
21
+ # Client options that send requests to this mock.
22
+ def config
23
+ {
24
+ plugins: [Plugin.new(self)],
25
+ region: REGION,
26
+ endpoint: ENDPOINT,
27
+ credentials: Aws::Credentials.new("test", "test")
28
+ }
29
+ end
30
+
31
+ # Builds an AWS SDK client that talks to this mock.
32
+ def client(klass, **options)
33
+ base = config
34
+ klass.new(**base, **options, plugins: base[:plugins] + Array(options[:plugins]))
35
+ end
36
+
37
+ # Drops all state.
38
+ def reset
39
+ raise ClosedError, "wasmo: mock is closed" if @instance.closed?
40
+
41
+ old = @instance
42
+ @instance = Instance.new
43
+ old.close
44
+ end
45
+
46
+ def close
47
+ @instance.close
48
+ end
49
+
50
+ Response = Struct.new(:status, :headers, :body)
51
+
52
+ # Sends one raw HTTP request to the mock. Response headers are pairs in
53
+ # wire order.
54
+ def request(method, url, headers = [], body = "")
55
+ pairs = headers.map { |k, v| [k.to_s.downcase, v.to_s] }
56
+ pairs << ["host", host(URI(url))] unless pairs.any? { |k, _| k == "host" }
57
+ meta = JSON.generate({ method: method, url: url, headers: pairs })
58
+ res, data = @instance.roundtrip(meta, body.b, @functions)
59
+ Response.new(res["status"], res["headers"], data)
60
+ end
61
+
62
+ private
63
+
64
+ def host(uri)
65
+ uri.port == uri.default_port ? uri.host : "#{uri.host}:#{uri.port}"
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Wasmo
4
+ # A Seahorse plugin whose send handler delivers requests to a Wasmo::Mock
5
+ # instead of Net::HTTP. Signing, retries and response parsing stay in the
6
+ # SDK.
7
+ class Plugin < Seahorse::Client::Plugin
8
+ def initialize(mock)
9
+ super()
10
+ @mock = mock
11
+ end
12
+
13
+ def add_options(config)
14
+ super
15
+ config.add_option(:wasmo_mock, @mock)
16
+ end
17
+
18
+ # The send handler.
19
+ class Handler < Seahorse::Client::Handler
20
+ def call(context)
21
+ transmit(context)
22
+ Seahorse::Client::Response.new(context: context)
23
+ end
24
+
25
+ private
26
+
27
+ def transmit(context)
28
+ res = send_request(context.config.wasmo_mock, context.http_request)
29
+ resp = context.http_response
30
+ resp.signal_headers(res.status, response_headers(res.headers))
31
+ resp.signal_data(res.body) unless res.body.empty?
32
+ resp.signal_done
33
+ rescue StandardError => e
34
+ context.http_response.signal_error(e)
35
+ end
36
+
37
+ def send_request(mock, req)
38
+ mock.request(req.http_method, req.endpoint.to_s, req.headers.to_h, read(req.body))
39
+ end
40
+
41
+ def read(body)
42
+ return +"" if body.nil?
43
+
44
+ body.rewind if body.respond_to?(:rewind)
45
+ data = body.read || +""
46
+ body.rewind if body.respond_to?(:rewind)
47
+ data
48
+ end
49
+
50
+ def response_headers(pairs)
51
+ pairs.each_with_object({}) do |(k, v), out|
52
+ name = k.downcase
53
+ out[name] = out.key?(name) ? "#{out[name]}, #{v}" : v
54
+ end
55
+ end
56
+ end
57
+
58
+ handler(Handler, step: :send)
59
+ end
60
+ end
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "json"
6
+ require "securerandom"
7
+ require "uri"
8
+ require "wasmtime"
9
+
10
+ module Wasmo
11
+ # The compiled module and host imports, shared by every mock in the process.
12
+ # The machine code is cached under Gem.cache_home/wasmo, so only the first
13
+ # process after an upgrade pays for compilation.
14
+ module Runtime
15
+ WASM_PATH = File.expand_path("wasmo.wasm", __dir__)
16
+ LOAD_LOCK = Mutex.new
17
+
18
+ class << self
19
+ def instantiate
20
+ engine, linker, mod = load
21
+ store = Wasmtime::Store.new(engine)
22
+ [store, linker.instantiate(store, mod)]
23
+ end
24
+
25
+ private
26
+
27
+ def load
28
+ LOAD_LOCK.synchronize do
29
+ @load ||= begin
30
+ engine = Wasmtime::Engine.new
31
+ [engine, linker(engine), compile(engine)]
32
+ end
33
+ end
34
+ end
35
+
36
+ def compile(engine)
37
+ bytes = File.binread(WASM_PATH)
38
+ key = Digest::SHA256.hexdigest([bytes, engine.precompile_compatibility_key, Wasmtime::VERSION].join("\0"))
39
+ path = File.join(Gem.cache_home, "wasmo", "#{key}.cwasm")
40
+ return Wasmtime::Module.deserialize_file(engine, path) if File.exist?(path)
41
+
42
+ mod = Wasmtime::Module.new(engine, bytes)
43
+ store_cache(path, mod.serialize)
44
+ mod
45
+ end
46
+
47
+ def store_cache(path, data)
48
+ dir = File.dirname(path)
49
+ FileUtils.mkdir_p(dir)
50
+ tmp = "#{path}.#{Process.pid}.#{SecureRandom.hex(4)}"
51
+ File.binwrite(tmp, data)
52
+ File.rename(tmp, path)
53
+ FileUtils.rm_f(Dir[File.join(dir, "*.cwasm")] - [path])
54
+ end
55
+
56
+ def linker(engine)
57
+ linker = Wasmtime::Linker.new(engine)
58
+ linker.func_new("wasmo", "now_ms", [], [:f64]) do |_caller|
59
+ Process.clock_gettime(Process::CLOCK_REALTIME, :float_millisecond)
60
+ end
61
+ linker.func_new("wasmo", "random_fill", %i[i32 i32], []) do |caller, ptr, len|
62
+ caller.export("memory").to_memory.write(ptr & 0xffff_ffff, SecureRandom.bytes(len & 0xffff_ffff))
63
+ nil
64
+ end
65
+ define_invoke(linker)
66
+ end
67
+
68
+ def define_invoke(linker)
69
+ linker.func_new("wasmo", "invoke", %i[i32 i32 i32 i32],
70
+ []) do |caller, meta_ptr, meta_len, payload_ptr, payload_len|
71
+ pending = Thread.current[:wasmo_pending] or raise Error, "wasmo: invoke outside a request"
72
+ memory = caller.export("memory").to_memory
73
+ pending << [memory.read(meta_ptr & 0xffff_ffff, meta_len),
74
+ memory.read(payload_ptr & 0xffff_ffff, payload_len)]
75
+ nil
76
+ end
77
+ linker
78
+ end
79
+ end
80
+ end
81
+
82
+ # One WebAssembly instance. Calls are serialized because a wasm instance is
83
+ # not reentrant.
84
+ class Instance
85
+ def initialize
86
+ @lock = Mutex.new
87
+ @store, instance = Runtime.instantiate
88
+ @memory = instance.export("memory").to_memory
89
+ @alloc = instance.export("wasmo_alloc").to_func
90
+ @free = instance.export("wasmo_free").to_func
91
+ @handle = instance.export("wasmo_handle").to_func
92
+ @complete = instance.export("wasmo_complete").to_func
93
+ end
94
+
95
+ # Sends a request and runs the Lambda invocations it starts outside the
96
+ # lock, answering each with wasmo_complete.
97
+ def roundtrip(meta, body, functions)
98
+ pending = []
99
+ frame = @lock.synchronize { call(@handle, meta, body, pending) }
100
+ until pending.empty?
101
+ result, payload = Function.run(functions, *pending.shift)
102
+ answer = @lock.synchronize { call(@complete, result, payload.b, pending) }
103
+ frame = answer if answer
104
+ end
105
+ decode(frame)
106
+ end
107
+
108
+ def closed?
109
+ @lock.synchronize { @store.nil? }
110
+ end
111
+
112
+ def close
113
+ @lock.synchronize do
114
+ @store&.close
115
+ @store = nil
116
+ end
117
+ end
118
+
119
+ private
120
+
121
+ def decode(frame)
122
+ meta_len = frame.unpack1("N")
123
+ res = JSON.parse(frame.byteslice(4, meta_len))
124
+ raise Error, "wasmo: invocation #{res['await']} was never answered" if res.key?("await")
125
+
126
+ [res, frame.byteslice((4 + meta_len)..)]
127
+ end
128
+
129
+ def call(func, meta, body, pending)
130
+ raise ClosedError, "wasmo: mock is closed" if @store.nil?
131
+
132
+ res = with_pending(pending) do
133
+ func.call(put(meta), meta.bytesize, put(body), body.bytesize)
134
+ end & 0xffff_ffff_ffff_ffff
135
+ return nil if res.zero?
136
+
137
+ ptr = res >> 32
138
+ len = res & 0xffff_ffff
139
+ frame = @memory.read(ptr, len)
140
+ @free.call(ptr, len)
141
+ frame
142
+ end
143
+
144
+ def with_pending(pending)
145
+ Thread.current[:wasmo_pending] = pending
146
+ yield
147
+ ensure
148
+ Thread.current[:wasmo_pending] = nil
149
+ end
150
+
151
+ def put(data)
152
+ ptr = @alloc.call(data.bytesize) & 0xffff_ffff
153
+ @memory.write(ptr, data) unless data.empty?
154
+ ptr
155
+ end
156
+ end
157
+ end
Binary file
data/lib/wasmo.rb ADDED
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "aws-sdk-core"
4
+ require_relative "wasmo/runtime"
5
+ require_relative "wasmo/function"
6
+ require_relative "wasmo/plugin"
7
+ require_relative "wasmo/mock"
8
+
9
+ # A stateful AWS mock that runs inside the Ruby process. Each Wasmo::Mock owns
10
+ # an isolated WebAssembly instance, so state never leaks between mocks.
11
+ module Wasmo
12
+ ENDPOINT = "http://wasmo.local"
13
+ REGION = "us-east-1"
14
+
15
+ class Error < StandardError; end
16
+
17
+ class ClosedError < Error; end
18
+
19
+ CONFIG_LOCK = Mutex.new
20
+
21
+ # Starts a mock, points every AWS client built inside the block at it
22
+ # through Aws.config, and closes it when the block returns.
23
+ def self.mock_aws
24
+ mock = Mock.new
25
+ saved = swap_aws_config { |config| config.merge(mock.config) { |key, old, new| key == :plugins ? old + new : new } }
26
+ begin
27
+ yield mock
28
+ ensure
29
+ swap_aws_config { saved }
30
+ mock.close
31
+ end
32
+ end
33
+
34
+ def self.swap_aws_config
35
+ CONFIG_LOCK.synchronize do
36
+ saved = Aws.config
37
+ Aws.config = yield saved
38
+ saved
39
+ end
40
+ end
41
+ private_class_method :swap_aws_config
42
+ end
metadata ADDED
@@ -0,0 +1,106 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: wasmo
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - conao3
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-01 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: aws-sdk-core
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '3.200'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '3.200'
26
+ - !ruby/object:Gem::Dependency
27
+ name: fiddle
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '1.1'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '1.1'
40
+ - !ruby/object:Gem::Dependency
41
+ name: wasmtime
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '50'
47
+ - - "<"
48
+ - !ruby/object:Gem::Version
49
+ version: '60'
50
+ type: :runtime
51
+ prerelease: false
52
+ version_requirements: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '50'
57
+ - - "<"
58
+ - !ruby/object:Gem::Version
59
+ version: '60'
60
+ description: |
61
+ wasmo runs a stateful AWS mock inside the test process. A Seahorse plugin replaces the HTTP send
62
+ handler of the AWS SDK for Ruby v3 and answers every request from a WebAssembly module run with
63
+ wasmtime-rb, so signing, retries, checksums, and response parsing stay in the SDK. Each mock owns
64
+ an isolated instance, with no Docker, ports, or sidecar process.
65
+ executables: []
66
+ extensions: []
67
+ extra_rdoc_files: []
68
+ files:
69
+ - LICENSE
70
+ - NOTICE
71
+ - README.md
72
+ - lib/wasmo.rb
73
+ - lib/wasmo/function.rb
74
+ - lib/wasmo/mock.rb
75
+ - lib/wasmo/plugin.rb
76
+ - lib/wasmo/runtime.rb
77
+ - lib/wasmo/wasmo.wasm
78
+ homepage: https://github.com/conao3/wasm-wasmo
79
+ licenses:
80
+ - Apache-2.0
81
+ metadata:
82
+ homepage_uri: https://github.com/conao3/wasm-wasmo
83
+ source_code_uri: https://github.com/conao3/wasm-wasmo/tree/main/ruby
84
+ documentation_uri: https://github.com/conao3/wasm-wasmo/tree/main/ruby#readme
85
+ changelog_uri: https://github.com/conao3/wasm-wasmo/blob/main/CHANGELOG.md
86
+ bug_tracker_uri: https://github.com/conao3/wasm-wasmo/issues
87
+ rubygems_mfa_required: 'true'
88
+ rdoc_options: []
89
+ require_paths:
90
+ - lib
91
+ required_ruby_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '3.3'
96
+ required_rubygems_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ requirements: []
102
+ rubygems_version: 3.7.2
103
+ specification_version: 4
104
+ summary: Stateful in-process AWS mock for the AWS SDK for Ruby v3, powered by a single
105
+ WebAssembly module
106
+ test_files: []