You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by GitBox <gi...@apache.org> on 2022/11/10 06:03:09 UTC

[GitHub] [beam] damondouglas opened a new pull request, #24081: Implement embedded wasm example

damondouglas opened a new pull request, #24081:
URL: https://github.com/apache/beam/pull/24081

   This is a simple example of loading and executing a [WebAssembly](https://webassembly.org/) compiled function written in Rust within a Beam Go SDK DoFn.  Many Beam users express interest in running simple functions in their favorite language embedded within a Beam execution workload.  This example provides preliminary results that perhaps this is possible using [wazero](https://github.com/tetratelabs/wazero).
   
   Running this example was tested on the Direct Runner, Flink Portable Runner, and Dataflow Runner documented in the example's README.
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/workflows/Build%20python%20source%20distribution%20and%20wheels/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/workflows/Python%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/workflows/Java%20Tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/workflows/Go%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] codecov[bot] commented on pull request #24081: Implement embedded wasm example

Posted by GitBox <gi...@apache.org>.
codecov[bot] commented on PR #24081:
URL: https://github.com/apache/beam/pull/24081#issuecomment-1309819712

   # [Codecov](https://codecov.io/gh/apache/beam/pull/24081?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#24081](https://codecov.io/gh/apache/beam/pull/24081?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (61cdcbc) into [master](https://codecov.io/gh/apache/beam/commit/4522f4ce916223afb3c4edd02a7be6018d0ce5a4?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (4522f4c) will **decrease** coverage by `0.00%`.
   > The diff coverage is `n/a`.
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #24081      +/-   ##
   ==========================================
   - Coverage   73.31%   73.30%   -0.01%     
   ==========================================
     Files         714      714              
     Lines       96403    96403              
   ==========================================
   - Hits        70676    70673       -3     
   - Misses      24407    24409       +2     
   - Partials     1320     1321       +1     
   ```
   
   | Flag | Coverage Δ | |
   |---|---|---|
   | go | `50.94% <ø> (-0.02%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Impacted Files](https://codecov.io/gh/apache/beam/pull/24081?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [sdks/go/pkg/beam/core/metrics/dumper.go](https://codecov.io/gh/apache/beam/pull/24081/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9nby9wa2cvYmVhbS9jb3JlL21ldHJpY3MvZHVtcGVyLmdv) | `49.20% <0.00%> (-4.77%)` | :arrow_down: |
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] damondouglas commented on a diff in pull request #24081: Implement embedded WebAssembly example

Posted by GitBox <gi...@apache.org>.
damondouglas commented on code in PR #24081:
URL: https://github.com/apache/beam/pull/24081#discussion_r1020789962


##########
sdks/go/examples/wasm/wasm.go:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// wasm is an EXPERIMENTAL simple example that loads and executes a wasm file function.
+// greet.wasm, Cargo.toml and greet.rs were copied from the example provided by the wazero library:
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+//
+// New Concepts:
+// 1. Load a wasm file compiled from: cargo build --release --target wasm32-unknown-unknown
+// 2. Execute a wasm function within a DoFn
+package main
+
+import (
+	"context"
+	_ "embed"
+	"flag"
+	"fmt"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/io/textio"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/register"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/x/beamx"
+	"github.com/tetratelabs/wazero"
+	"github.com/tetratelabs/wazero/api"
+	"log"
+)
+
+const (
+	wasmFunctionName           = "greeting"
+	wasmAllocateFunctionName   = "allocate"
+	wasmDeallocateFunctionName = "deallocate"
+)
+
+//go:embed greet.wasm
+var greetWasm []byte
+
+var (
+	output = flag.String("output", "", "Output file (required).")
+)
+
+func init() {
+	// register.DoFnXxY registers a struct DoFn so that it can be correctly
+	// serialized and does some optimization to avoid runtime reflection. Since
+	// embeddedWasmFn's ProcessElement func has 2 inputs (context.Context) and 2 outputs (string, error),
+	// we use register.DoFn2x2 and provide its input and output types as its constraints.
+	// Struct DoFns must be registered for a pipeline to run.
+	register.DoFn2x2[context.Context, string, string, error](&embeddedWasmFn{})
+}
+
+func preRun() error {
+	if *output == "" {
+		return fmt.Errorf("--output is required")
+	}
+	return nil
+}
+
+func main() {
+	flag.Parse()
+	beam.Init()
+	ctx := context.Background()
+	if err := preRun(); err != nil {
+		panic(err)
+	}
+	if err := run(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func run(ctx context.Context) error {
+	p, s := beam.NewPipelineWithRoot()
+
+	in := beam.Create(s, "a", "b", "c", "d", "e", "f", "g", "h")

Review Comment:
   Thank you :-) I replaced with `"Ada", "Lovelace", "World", "Beam", "Senior López"`. The last one is so we can see this with unicode and because Senior López is an important 🐕 member of the Beam community.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] damondouglas commented on a diff in pull request #24081: Implement embedded WebAssembly example

Posted by GitBox <gi...@apache.org>.
damondouglas commented on code in PR #24081:
URL: https://github.com/apache/beam/pull/24081#discussion_r1020790141


##########
sdks/go/examples/wasm/wasm.go:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// wasm is an EXPERIMENTAL simple example that loads and executes a wasm file function.
+// greet.wasm, Cargo.toml and greet.rs were copied from the example provided by the wazero library:
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+//
+// New Concepts:
+// 1. Load a wasm file compiled from: cargo build --release --target wasm32-unknown-unknown
+// 2. Execute a wasm function within a DoFn
+package main
+
+import (
+	"context"
+	_ "embed"
+	"flag"
+	"fmt"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/io/textio"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/register"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/x/beamx"
+	"github.com/tetratelabs/wazero"
+	"github.com/tetratelabs/wazero/api"
+	"log"
+)
+
+const (
+	wasmFunctionName           = "greeting"
+	wasmAllocateFunctionName   = "allocate"
+	wasmDeallocateFunctionName = "deallocate"
+)
+
+//go:embed greet.wasm
+var greetWasm []byte
+
+var (
+	output = flag.String("output", "", "Output file (required).")
+)
+
+func init() {
+	// register.DoFnXxY registers a struct DoFn so that it can be correctly
+	// serialized and does some optimization to avoid runtime reflection. Since
+	// embeddedWasmFn's ProcessElement func has 2 inputs (context.Context) and 2 outputs (string, error),
+	// we use register.DoFn2x2 and provide its input and output types as its constraints.
+	// Struct DoFns must be registered for a pipeline to run.
+	register.DoFn2x2[context.Context, string, string, error](&embeddedWasmFn{})
+}
+
+func preRun() error {
+	if *output == "" {
+		return fmt.Errorf("--output is required")
+	}
+	return nil
+}
+
+func main() {
+	flag.Parse()
+	beam.Init()
+	ctx := context.Background()
+	if err := preRun(); err != nil {
+		panic(err)
+	}
+	if err := run(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func run(ctx context.Context) error {
+	p, s := beam.NewPipelineWithRoot()
+
+	in := beam.Create(s, "a", "b", "c", "d", "e", "f", "g", "h")
+
+	out := beam.ParDo(s.Scope("embeddedWasm"), &embeddedWasmFn{}, in)
+
+	textio.Write(s, *output, out)
+
+	if err := beamx.Run(ctx, p); err != nil {
+		return fmt.Errorf("failed to run pipeline: %v", err)
+	}
+	return nil
+}
+
+// Concept #2 wrap wasm function execution within a DoFn.
+// wasmFn wraps a DoFn to execute a Rust compiled wasm function
+type embeddedWasmFn struct {
+	r                              wazero.Runtime
+	mod                            api.Module
+	greeting, allocate, deallocate api.Function
+}
+
+// Setup loads and initializes the embedded wasm functions
+// Concept #1: Load a compiled wasm file []byte content and function.
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) Setup(ctx context.Context) error {
+	fn.r = wazero.NewRuntime(ctx)
+	_, err := fn.r.NewHostModuleBuilder("env").
+		NewFunctionBuilder().WithFunc(logString).Export("log").
+		Instantiate(ctx, fn.r)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate host module: %w", err)
+	}
+	fn.mod, err = fn.r.InstantiateModuleFromBinary(ctx, greetWasm)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate wasm module: %v", err)
+	}
+	fn.greeting = fn.mod.ExportedFunction(wasmFunctionName)
+	fn.allocate = fn.mod.ExportedFunction(wasmAllocateFunctionName)
+	fn.deallocate = fn.mod.ExportedFunction(wasmDeallocateFunctionName)
+	return nil
+}
+
+// ProcessElement processes a string calling a wasm function written in Rust
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) ProcessElement(ctx context.Context, s string) (string, error) {
+	size := uint64(len(s))
+	results, err := fn.allocate.Call(ctx, size)
+	if err != nil {
+		return "", fmt.Errorf("error calling allocate: %w", err)
+	}
+	ptr := results[0]
+	defer fn.deallocate.Call(ctx, ptr, size)
+	if !fn.mod.Memory().Write(ctx, uint32(ptr), []byte(s)) {
+		return "", fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d",
+			ptr, size, fn.mod.Memory().Size(ctx))
+	}
+
+	ptrSize, err := fn.greeting.Call(ctx, ptr, size)
+	resultPtr := uint32(ptrSize[0] >> 32)
+	resultSize := uint32(ptrSize[0])
+	defer fn.deallocate.Call(ctx, uint64(resultPtr), uint64(resultSize))
+	bytes, ok := fn.mod.Memory().Read(ctx, resultPtr, resultSize)
+	if !ok {
+		return "", fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
+			resultPtr, resultSize, fn.mod.Memory().Size(ctx))
+	}
+	return string(bytes), nil
+}

Review Comment:
   I added back the original helpful comments from the wazero example with some edits to reflect the Beam context within which the DoFn invokes these methods.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lostluck merged pull request #24081: Implement embedded WebAssembly example

Posted by GitBox <gi...@apache.org>.
lostluck merged PR #24081:
URL: https://github.com/apache/beam/pull/24081


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lostluck commented on a diff in pull request #24081: Implement embedded WebAssembly example

Posted by GitBox <gi...@apache.org>.
lostluck commented on code in PR #24081:
URL: https://github.com/apache/beam/pull/24081#discussion_r1022228345


##########
sdks/go/examples/wasm/wasm.go:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// wasm is an EXPERIMENTAL simple example that loads and executes a wasm file function.
+// greet.wasm, Cargo.toml and greet.rs were copied from the example provided by the wazero library:
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+//
+// New Concepts:
+// 1. Load a wasm file compiled from: cargo build --release --target wasm32-unknown-unknown
+// 2. Execute a wasm function within a DoFn
+package main
+
+import (
+	"context"
+	_ "embed"
+	"flag"
+	"fmt"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/io/textio"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/register"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/x/beamx"
+	"github.com/tetratelabs/wazero"
+	"github.com/tetratelabs/wazero/api"
+	"log"
+)
+
+const (
+	wasmFunctionName           = "greeting"
+	wasmAllocateFunctionName   = "allocate"
+	wasmDeallocateFunctionName = "deallocate"
+)
+
+//go:embed greet.wasm
+var greetWasm []byte
+
+var (
+	output = flag.String("output", "", "Output file (required).")
+)
+
+func init() {
+	// register.DoFnXxY registers a struct DoFn so that it can be correctly
+	// serialized and does some optimization to avoid runtime reflection. Since
+	// embeddedWasmFn's ProcessElement func has 2 inputs (context.Context) and 2 outputs (string, error),
+	// we use register.DoFn2x2 and provide its input and output types as its constraints.
+	// Struct DoFns must be registered for a pipeline to run.
+	register.DoFn2x2[context.Context, string, string, error](&embeddedWasmFn{})
+}
+
+func preRun() error {
+	if *output == "" {
+		return fmt.Errorf("--output is required")
+	}
+	return nil
+}
+
+func main() {
+	flag.Parse()
+	beam.Init()
+	ctx := context.Background()
+	if err := preRun(); err != nil {
+		panic(err)
+	}
+	if err := run(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func run(ctx context.Context) error {
+	p, s := beam.NewPipelineWithRoot()
+
+	in := beam.Create(s, "a", "b", "c", "d", "e", "f", "g", "h")
+
+	out := beam.ParDo(s.Scope("embeddedWasm"), &embeddedWasmFn{}, in)
+
+	textio.Write(s, *output, out)
+
+	if err := beamx.Run(ctx, p); err != nil {
+		return fmt.Errorf("failed to run pipeline: %v", err)
+	}
+	return nil
+}
+
+// Concept #2 wrap wasm function execution within a DoFn.
+// wasmFn wraps a DoFn to execute a Rust compiled wasm function
+type embeddedWasmFn struct {
+	r                              wazero.Runtime
+	mod                            api.Module
+	greeting, allocate, deallocate api.Function
+}
+
+// Setup loads and initializes the embedded wasm functions
+// Concept #1: Load a compiled wasm file []byte content and function.
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) Setup(ctx context.Context) error {
+	fn.r = wazero.NewRuntime(ctx)
+	_, err := fn.r.NewHostModuleBuilder("env").
+		NewFunctionBuilder().WithFunc(logString).Export("log").
+		Instantiate(ctx, fn.r)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate host module: %w", err)
+	}
+	fn.mod, err = fn.r.InstantiateModuleFromBinary(ctx, greetWasm)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate wasm module: %v", err)
+	}
+	fn.greeting = fn.mod.ExportedFunction(wasmFunctionName)
+	fn.allocate = fn.mod.ExportedFunction(wasmAllocateFunctionName)
+	fn.deallocate = fn.mod.ExportedFunction(wasmDeallocateFunctionName)
+	return nil
+}
+
+// ProcessElement processes a string calling a wasm function written in Rust
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) ProcessElement(ctx context.Context, s string) (string, error) {
+	size := uint64(len(s))
+	results, err := fn.allocate.Call(ctx, size)
+	if err != nil {
+		return "", fmt.Errorf("error calling allocate: %w", err)
+	}
+	ptr := results[0]
+	defer fn.deallocate.Call(ctx, ptr, size)
+	if !fn.mod.Memory().Write(ctx, uint32(ptr), []byte(s)) {
+		return "", fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d",
+			ptr, size, fn.mod.Memory().Size(ctx))
+	}
+
+	ptrSize, err := fn.greeting.Call(ctx, ptr, size)
+	resultPtr := uint32(ptrSize[0] >> 32)
+	resultSize := uint32(ptrSize[0])
+	defer fn.deallocate.Call(ctx, uint64(resultPtr), uint64(resultSize))
+	bytes, ok := fn.mod.Memory().Read(ctx, resultPtr, resultSize)
+	if !ok {
+		return "", fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
+			resultPtr, resultSize, fn.mod.Memory().Size(ctx))
+	}
+	return string(bytes), nil
+}

Review Comment:
   Agreed there's a fine line in what to strip out when the crux of the example is "putting chocolate into my peanut butter". 
   In this case, wasm is just complicated, so it should be commented appropriately in any of it's contexts, if only because it makes it easier for someone else to get started in the *other* direction. (eg. "I know beam, but would like to learn how to put wasm stuff into my DoFns"). Afterall, by the time you're considering using wasm with beam, you're already familiar enough with Beam.
   
   Anything more complicated than this example is all up to the WASM/Wasmer/Wazero communities ;).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] lostluck commented on a diff in pull request #24081: Implement embedded WebAssembly example

Posted by GitBox <gi...@apache.org>.
lostluck commented on code in PR #24081:
URL: https://github.com/apache/beam/pull/24081#discussion_r1020614296


##########
sdks/go/examples/wasm/wasm.go:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// wasm is an EXPERIMENTAL simple example that loads and executes a wasm file function.
+// greet.wasm, Cargo.toml and greet.rs were copied from the example provided by the wazero library:
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+//
+// New Concepts:
+// 1. Load a wasm file compiled from: cargo build --release --target wasm32-unknown-unknown
+// 2. Execute a wasm function within a DoFn
+package main
+
+import (
+	"context"
+	_ "embed"
+	"flag"
+	"fmt"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/io/textio"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/register"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/x/beamx"
+	"github.com/tetratelabs/wazero"
+	"github.com/tetratelabs/wazero/api"
+	"log"
+)
+
+const (
+	wasmFunctionName           = "greeting"
+	wasmAllocateFunctionName   = "allocate"
+	wasmDeallocateFunctionName = "deallocate"
+)
+
+//go:embed greet.wasm
+var greetWasm []byte
+
+var (
+	output = flag.String("output", "", "Output file (required).")
+)
+
+func init() {
+	// register.DoFnXxY registers a struct DoFn so that it can be correctly
+	// serialized and does some optimization to avoid runtime reflection. Since
+	// embeddedWasmFn's ProcessElement func has 2 inputs (context.Context) and 2 outputs (string, error),
+	// we use register.DoFn2x2 and provide its input and output types as its constraints.
+	// Struct DoFns must be registered for a pipeline to run.
+	register.DoFn2x2[context.Context, string, string, error](&embeddedWasmFn{})
+}
+
+func preRun() error {
+	if *output == "" {
+		return fmt.Errorf("--output is required")
+	}
+	return nil
+}
+
+func main() {
+	flag.Parse()
+	beam.Init()
+	ctx := context.Background()
+	if err := preRun(); err != nil {
+		panic(err)
+	}
+	if err := run(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func run(ctx context.Context) error {
+	p, s := beam.NewPipelineWithRoot()
+
+	in := beam.Create(s, "a", "b", "c", "d", "e", "f", "g", "h")

Review Comment:
   Only one comment: Also include "World" because then there's at least one word that isn't a single character, also, because it's traditional.
   
   Personally, I'd go with "World", "Wasm", "Beam", "Dolly", as it's more interesting to an example runner.  (Hello Dolly is a musical)



##########
sdks/go/examples/wasm/wasm.go:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// wasm is an EXPERIMENTAL simple example that loads and executes a wasm file function.
+// greet.wasm, Cargo.toml and greet.rs were copied from the example provided by the wazero library:
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+//
+// New Concepts:
+// 1. Load a wasm file compiled from: cargo build --release --target wasm32-unknown-unknown
+// 2. Execute a wasm function within a DoFn
+package main
+
+import (
+	"context"
+	_ "embed"
+	"flag"
+	"fmt"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/io/textio"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/register"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/x/beamx"
+	"github.com/tetratelabs/wazero"
+	"github.com/tetratelabs/wazero/api"
+	"log"
+)
+
+const (
+	wasmFunctionName           = "greeting"
+	wasmAllocateFunctionName   = "allocate"
+	wasmDeallocateFunctionName = "deallocate"
+)
+
+//go:embed greet.wasm
+var greetWasm []byte
+
+var (
+	output = flag.String("output", "", "Output file (required).")
+)
+
+func init() {
+	// register.DoFnXxY registers a struct DoFn so that it can be correctly
+	// serialized and does some optimization to avoid runtime reflection. Since
+	// embeddedWasmFn's ProcessElement func has 2 inputs (context.Context) and 2 outputs (string, error),
+	// we use register.DoFn2x2 and provide its input and output types as its constraints.
+	// Struct DoFns must be registered for a pipeline to run.
+	register.DoFn2x2[context.Context, string, string, error](&embeddedWasmFn{})
+}
+
+func preRun() error {
+	if *output == "" {
+		return fmt.Errorf("--output is required")
+	}
+	return nil
+}
+
+func main() {
+	flag.Parse()
+	beam.Init()
+	ctx := context.Background()
+	if err := preRun(); err != nil {
+		panic(err)
+	}
+	if err := run(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func run(ctx context.Context) error {
+	p, s := beam.NewPipelineWithRoot()
+
+	in := beam.Create(s, "a", "b", "c", "d", "e", "f", "g", "h")
+
+	out := beam.ParDo(s.Scope("embeddedWasm"), &embeddedWasmFn{}, in)

Review Comment:
   I'd remove the sub scoping here. It doesn't add anything when it's a single function, and it dilutes the example. Folks may interpret this to mean "we always need to rename scopes for wasm using DoFns".



##########
sdks/go/examples/wasm/wasm.go:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// wasm is an EXPERIMENTAL simple example that loads and executes a wasm file function.
+// greet.wasm, Cargo.toml and greet.rs were copied from the example provided by the wazero library:
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+//
+// New Concepts:
+// 1. Load a wasm file compiled from: cargo build --release --target wasm32-unknown-unknown
+// 2. Execute a wasm function within a DoFn
+package main
+
+import (
+	"context"
+	_ "embed"
+	"flag"
+	"fmt"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/io/textio"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/register"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/x/beamx"
+	"github.com/tetratelabs/wazero"
+	"github.com/tetratelabs/wazero/api"
+	"log"
+)
+
+const (
+	wasmFunctionName           = "greeting"
+	wasmAllocateFunctionName   = "allocate"
+	wasmDeallocateFunctionName = "deallocate"
+)
+
+//go:embed greet.wasm
+var greetWasm []byte
+
+var (
+	output = flag.String("output", "", "Output file (required).")
+)
+
+func init() {
+	// register.DoFnXxY registers a struct DoFn so that it can be correctly
+	// serialized and does some optimization to avoid runtime reflection. Since
+	// embeddedWasmFn's ProcessElement func has 2 inputs (context.Context) and 2 outputs (string, error),
+	// we use register.DoFn2x2 and provide its input and output types as its constraints.
+	// Struct DoFns must be registered for a pipeline to run.
+	register.DoFn2x2[context.Context, string, string, error](&embeddedWasmFn{})
+}
+
+func preRun() error {
+	if *output == "" {
+		return fmt.Errorf("--output is required")
+	}
+	return nil
+}
+
+func main() {
+	flag.Parse()
+	beam.Init()
+	ctx := context.Background()
+	if err := preRun(); err != nil {
+		panic(err)
+	}
+	if err := run(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func run(ctx context.Context) error {
+	p, s := beam.NewPipelineWithRoot()
+
+	in := beam.Create(s, "a", "b", "c", "d", "e", "f", "g", "h")
+
+	out := beam.ParDo(s.Scope("embeddedWasm"), &embeddedWasmFn{}, in)
+
+	textio.Write(s, *output, out)
+
+	if err := beamx.Run(ctx, p); err != nil {
+		return fmt.Errorf("failed to run pipeline: %v", err)
+	}
+	return nil
+}
+
+// Concept #2 wrap wasm function execution within a DoFn.
+// wasmFn wraps a DoFn to execute a Rust compiled wasm function
+type embeddedWasmFn struct {
+	r                              wazero.Runtime
+	mod                            api.Module
+	greeting, allocate, deallocate api.Function
+}
+
+// Setup loads and initializes the embedded wasm functions
+// Concept #1: Load a compiled wasm file []byte content and function.
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) Setup(ctx context.Context) error {
+	fn.r = wazero.NewRuntime(ctx)
+	_, err := fn.r.NewHostModuleBuilder("env").
+		NewFunctionBuilder().WithFunc(logString).Export("log").
+		Instantiate(ctx, fn.r)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate host module: %w", err)
+	}
+	fn.mod, err = fn.r.InstantiateModuleFromBinary(ctx, greetWasm)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate wasm module: %v", err)
+	}
+	fn.greeting = fn.mod.ExportedFunction(wasmFunctionName)
+	fn.allocate = fn.mod.ExportedFunction(wasmAllocateFunctionName)
+	fn.deallocate = fn.mod.ExportedFunction(wasmDeallocateFunctionName)
+	return nil
+}
+
+// ProcessElement processes a string calling a wasm function written in Rust
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) ProcessElement(ctx context.Context, s string) (string, error) {
+	size := uint64(len(s))
+	results, err := fn.allocate.Call(ctx, size)
+	if err != nil {
+		return "", fmt.Errorf("error calling allocate: %w", err)
+	}
+	ptr := results[0]
+	defer fn.deallocate.Call(ctx, ptr, size)
+	if !fn.mod.Memory().Write(ctx, uint32(ptr), []byte(s)) {
+		return "", fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d",
+			ptr, size, fn.mod.Memory().Size(ctx))
+	}
+
+	ptrSize, err := fn.greeting.Call(ctx, ptr, size)
+	resultPtr := uint32(ptrSize[0] >> 32)
+	resultSize := uint32(ptrSize[0])
+	defer fn.deallocate.Call(ctx, uint64(resultPtr), uint64(resultSize))
+	bytes, ok := fn.mod.Memory().Read(ctx, resultPtr, resultSize)
+	if !ok {
+		return "", fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
+			resultPtr, resultSize, fn.mod.Memory().Size(ctx))
+	}
+	return string(bytes), nil
+}
+
+func logString(ctx context.Context, m api.Module, offset, byteCount uint32) {
+	buf, ok := m.Memory().Read(ctx, offset, byteCount)
+	if !ok {
+		log.Panicf("Memory.Read(%d, %d) out of range", offset, byteCount)
+	}
+	fmt.Println(string(buf))

Review Comment:
   I'd use the beam Log package instead of fmt.Println, so they're visible when using portable runners outside of Loopback mode.  Note that this is different from the standard library "log" package.
   
   When the [new structure logging package for Go](https://go.googlesource.com/proposal/+/master/design/56345-structured-logging.md) comes out in ~1.20, we can add a proper "beam" backend to it so we become more compatible with the ecosystem (and deprecate the existing log package/ re-implement it in terms of the new structured logging, because it leaves plenty to be desired at present).



##########
sdks/go/examples/wasm/wasm.go:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// wasm is an EXPERIMENTAL simple example that loads and executes a wasm file function.
+// greet.wasm, Cargo.toml and greet.rs were copied from the example provided by the wazero library:
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+//
+// New Concepts:
+// 1. Load a wasm file compiled from: cargo build --release --target wasm32-unknown-unknown
+// 2. Execute a wasm function within a DoFn
+package main
+
+import (
+	"context"
+	_ "embed"
+	"flag"
+	"fmt"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/io/textio"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/register"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/x/beamx"
+	"github.com/tetratelabs/wazero"
+	"github.com/tetratelabs/wazero/api"
+	"log"
+)
+
+const (
+	wasmFunctionName           = "greeting"
+	wasmAllocateFunctionName   = "allocate"
+	wasmDeallocateFunctionName = "deallocate"
+)
+
+//go:embed greet.wasm
+var greetWasm []byte
+
+var (
+	output = flag.String("output", "", "Output file (required).")
+)
+
+func init() {
+	// register.DoFnXxY registers a struct DoFn so that it can be correctly
+	// serialized and does some optimization to avoid runtime reflection. Since
+	// embeddedWasmFn's ProcessElement func has 2 inputs (context.Context) and 2 outputs (string, error),
+	// we use register.DoFn2x2 and provide its input and output types as its constraints.
+	// Struct DoFns must be registered for a pipeline to run.
+	register.DoFn2x2[context.Context, string, string, error](&embeddedWasmFn{})
+}
+
+func preRun() error {
+	if *output == "" {
+		return fmt.Errorf("--output is required")
+	}
+	return nil
+}
+
+func main() {
+	flag.Parse()
+	beam.Init()
+	ctx := context.Background()
+	if err := preRun(); err != nil {
+		panic(err)
+	}
+	if err := run(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func run(ctx context.Context) error {
+	p, s := beam.NewPipelineWithRoot()
+
+	in := beam.Create(s, "a", "b", "c", "d", "e", "f", "g", "h")
+
+	out := beam.ParDo(s.Scope("embeddedWasm"), &embeddedWasmFn{}, in)
+
+	textio.Write(s, *output, out)
+
+	if err := beamx.Run(ctx, p); err != nil {
+		return fmt.Errorf("failed to run pipeline: %v", err)
+	}
+	return nil
+}
+
+// Concept #2 wrap wasm function execution within a DoFn.
+// wasmFn wraps a DoFn to execute a Rust compiled wasm function
+type embeddedWasmFn struct {
+	r                              wazero.Runtime
+	mod                            api.Module
+	greeting, allocate, deallocate api.Function
+}
+
+// Setup loads and initializes the embedded wasm functions
+// Concept #1: Load a compiled wasm file []byte content and function.
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) Setup(ctx context.Context) error {
+	fn.r = wazero.NewRuntime(ctx)
+	_, err := fn.r.NewHostModuleBuilder("env").
+		NewFunctionBuilder().WithFunc(logString).Export("log").
+		Instantiate(ctx, fn.r)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate host module: %w", err)
+	}
+	fn.mod, err = fn.r.InstantiateModuleFromBinary(ctx, greetWasm)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate wasm module: %v", err)
+	}
+	fn.greeting = fn.mod.ExportedFunction(wasmFunctionName)
+	fn.allocate = fn.mod.ExportedFunction(wasmAllocateFunctionName)
+	fn.deallocate = fn.mod.ExportedFunction(wasmDeallocateFunctionName)
+	return nil
+}
+
+// ProcessElement processes a string calling a wasm function written in Rust
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) ProcessElement(ctx context.Context, s string) (string, error) {
+	size := uint64(len(s))
+	results, err := fn.allocate.Call(ctx, size)
+	if err != nil {
+		return "", fmt.Errorf("error calling allocate: %w", err)
+	}
+	ptr := results[0]
+	defer fn.deallocate.Call(ctx, ptr, size)
+	if !fn.mod.Memory().Write(ctx, uint32(ptr), []byte(s)) {
+		return "", fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d",
+			ptr, size, fn.mod.Memory().Size(ctx))
+	}
+
+	ptrSize, err := fn.greeting.Call(ctx, ptr, size)
+	resultPtr := uint32(ptrSize[0] >> 32)
+	resultSize := uint32(ptrSize[0])
+	defer fn.deallocate.Call(ctx, uint64(resultPtr), uint64(resultSize))
+	bytes, ok := fn.mod.Memory().Read(ctx, resultPtr, resultSize)
+	if !ok {
+		return "", fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
+			resultPtr, resultSize, fn.mod.Memory().Size(ctx))
+	}
+	return string(bytes), nil
+}

Review Comment:
   Given the direct pointer/offset + size uses, it would be good to add comments. I tried just wraping in methods, but that didn't help very much, so I propose doing something like...
   
   ```suggestion
   func (fn *embeddedWasmFn) ProcessElement(ctx context.Context, s string) (string, error) {
   	// Write the string to wasm
   	size := uint64(len(s))
   	results, err := fn.allocate.Call(ctx, size)
   	if err != nil {
   		return "", fmt.Errorf("error calling allocate: %w", err)
   	}
   	ptr := results[0]
   	defer fn.deallocate.Call(ctx, ptr, size)
   	if !fn.mod.Memory().Write(ctx, uint32(ptr), []byte(s)) {
   		return "", fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d",
   			ptr, size, fn.mod.Memory().Size(ctx))
   	}
   
   	// Call the wasm function and read the updated string
   	ptrSize, err := fn.greeting.Call(ctx, ptr, size)
   	resultPtr := uint32(ptrSize[0] >> 32)
   	resultSize := uint32(ptrSize[0])
   	defer fn.deallocate.Call(ctx, uint64(resultPtr), uint64(resultSize))
   	bytes, ok := fn.mod.Memory().Read(ctx, resultPtr, resultSize)
   	if !ok {
   		return "", fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
   			resultPtr, resultSize, fn.mod.Memory().Size(ctx))
   	}
   	return string(bytes), nil
   }
   ```



##########
sdks/go/examples/wasm/wasm.go:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// wasm is an EXPERIMENTAL simple example that loads and executes a wasm file function.
+// greet.wasm, Cargo.toml and greet.rs were copied from the example provided by the wazero library:
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+//
+// New Concepts:
+// 1. Load a wasm file compiled from: cargo build --release --target wasm32-unknown-unknown
+// 2. Execute a wasm function within a DoFn
+package main
+
+import (
+	"context"
+	_ "embed"
+	"flag"
+	"fmt"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/io/textio"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/register"
+	"github.com/apache/beam/sdks/v2/go/pkg/beam/x/beamx"
+	"github.com/tetratelabs/wazero"
+	"github.com/tetratelabs/wazero/api"
+	"log"
+)
+
+const (
+	wasmFunctionName           = "greeting"
+	wasmAllocateFunctionName   = "allocate"
+	wasmDeallocateFunctionName = "deallocate"
+)
+
+//go:embed greet.wasm
+var greetWasm []byte
+
+var (
+	output = flag.String("output", "", "Output file (required).")
+)
+
+func init() {
+	// register.DoFnXxY registers a struct DoFn so that it can be correctly
+	// serialized and does some optimization to avoid runtime reflection. Since
+	// embeddedWasmFn's ProcessElement func has 2 inputs (context.Context) and 2 outputs (string, error),
+	// we use register.DoFn2x2 and provide its input and output types as its constraints.
+	// Struct DoFns must be registered for a pipeline to run.
+	register.DoFn2x2[context.Context, string, string, error](&embeddedWasmFn{})
+}
+
+func preRun() error {
+	if *output == "" {
+		return fmt.Errorf("--output is required")
+	}
+	return nil
+}
+
+func main() {
+	flag.Parse()
+	beam.Init()
+	ctx := context.Background()
+	if err := preRun(); err != nil {
+		panic(err)
+	}
+	if err := run(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func run(ctx context.Context) error {
+	p, s := beam.NewPipelineWithRoot()
+
+	in := beam.Create(s, "a", "b", "c", "d", "e", "f", "g", "h")
+
+	out := beam.ParDo(s.Scope("embeddedWasm"), &embeddedWasmFn{}, in)
+
+	textio.Write(s, *output, out)
+
+	if err := beamx.Run(ctx, p); err != nil {
+		return fmt.Errorf("failed to run pipeline: %v", err)
+	}
+	return nil
+}
+
+// Concept #2 wrap wasm function execution within a DoFn.
+// wasmFn wraps a DoFn to execute a Rust compiled wasm function
+type embeddedWasmFn struct {
+	r                              wazero.Runtime
+	mod                            api.Module
+	greeting, allocate, deallocate api.Function
+}
+
+// Setup loads and initializes the embedded wasm functions
+// Concept #1: Load a compiled wasm file []byte content and function.
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) Setup(ctx context.Context) error {
+	fn.r = wazero.NewRuntime(ctx)
+	_, err := fn.r.NewHostModuleBuilder("env").
+		NewFunctionBuilder().WithFunc(logString).Export("log").
+		Instantiate(ctx, fn.r)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate host module: %w", err)
+	}
+	fn.mod, err = fn.r.InstantiateModuleFromBinary(ctx, greetWasm)
+	if err != nil {
+		return fmt.Errorf("failed to instantiate wasm module: %v", err)
+	}
+	fn.greeting = fn.mod.ExportedFunction(wasmFunctionName)
+	fn.allocate = fn.mod.ExportedFunction(wasmAllocateFunctionName)
+	fn.deallocate = fn.mod.ExportedFunction(wasmDeallocateFunctionName)
+	return nil
+}
+
+// ProcessElement processes a string calling a wasm function written in Rust
+// This example is derived from
+// https://github.com/tetratelabs/wazero/blob/v1.0.0-pre.3/examples/allocation/rust/greet.go
+func (fn *embeddedWasmFn) ProcessElement(ctx context.Context, s string) (string, error) {
+	size := uint64(len(s))
+	results, err := fn.allocate.Call(ctx, size)
+	if err != nil {
+		return "", fmt.Errorf("error calling allocate: %w", err)
+	}
+	ptr := results[0]
+	defer fn.deallocate.Call(ctx, ptr, size)
+	if !fn.mod.Memory().Write(ctx, uint32(ptr), []byte(s)) {
+		return "", fmt.Errorf("Memory.Write(%d, %d) out of range of memory size %d",
+			ptr, size, fn.mod.Memory().Size(ctx))
+	}
+
+	ptrSize, err := fn.greeting.Call(ctx, ptr, size)
+	resultPtr := uint32(ptrSize[0] >> 32)
+	resultSize := uint32(ptrSize[0])
+	defer fn.deallocate.Call(ctx, uint64(resultPtr), uint64(resultSize))
+	bytes, ok := fn.mod.Memory().Read(ctx, resultPtr, resultSize)
+	if !ok {
+		return "", fmt.Errorf("Memory.Read(%d, %d) out of range of memory size %d",
+			resultPtr, resultSize, fn.mod.Memory().Size(ctx))
+	}
+	return string(bytes), nil
+}
+
+func logString(ctx context.Context, m api.Module, offset, byteCount uint32) {

Review Comment:
   Please add a comment to this saying that it's being used as a foreign function to the wasm code. It's easy to miss that when reading the code, and it's not used elsewhere.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [beam] github-actions[bot] commented on pull request #24081: Implement embedded WebAssembly example

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on PR #24081:
URL: https://github.com/apache/beam/pull/24081#issuecomment-1309840603

   Assigning reviewers. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @lostluck for label go.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org