|
| 1 | +/* |
| 2 | + * Copyright 2024 Function Stream Org. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package gofs |
| 18 | + |
| 19 | +import "C" |
| 20 | +import ( |
| 21 | + "encoding/json" |
| 22 | + "fmt" |
| 23 | + "io" |
| 24 | + "os" |
| 25 | + |
| 26 | + . "github.com/functionstream/function-stream/common/wasm_utils" |
| 27 | + "github.com/wirelessr/avroschema" |
| 28 | +) |
| 29 | + |
| 30 | +var processFile *os.File |
| 31 | + |
| 32 | +func init() { |
| 33 | + processFile, _ = os.Open("/process") |
| 34 | +} |
| 35 | + |
| 36 | +var processFunc func([]byte) []byte |
| 37 | + |
| 38 | +//go:wasmimport fs registerSchema |
| 39 | +func registerSchema(inputSchemaPtrSize, outputSchemaPtrSize uint64) |
| 40 | + |
| 41 | +func Register[I any, O any](process func(*I) *O) error { |
| 42 | + inputSchema, err := avroschema.Reflect(new(I)) |
| 43 | + if err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + outputSchema, err := avroschema.Reflect(new(O)) |
| 47 | + if err != nil { |
| 48 | + return err |
| 49 | + } |
| 50 | + processFunc = func(payload []byte) []byte { |
| 51 | + input := new(I) |
| 52 | + err = json.Unmarshal(payload, input) |
| 53 | + if err != nil { |
| 54 | + fmt.Fprintf(os.Stderr, "Failed to parse JSON: %s %s", err, payload) |
| 55 | + } |
| 56 | + output := process(input) |
| 57 | + outputPayload, _ := json.Marshal(output) |
| 58 | + return outputPayload |
| 59 | + } |
| 60 | + registerSchema(PtrSize(StringToPtr(inputSchema)), PtrSize(StringToPtr(outputSchema))) |
| 61 | + return nil |
| 62 | +} |
| 63 | + |
| 64 | +//export process |
| 65 | +func process() { |
| 66 | + payload, _ := io.ReadAll(processFile) |
| 67 | + outputPayload := processFunc(payload) |
| 68 | + _, _ = processFile.Write(outputPayload) |
| 69 | +} |
0 commit comments