|
| 1 | +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 2 | +// or more contributor license agreements. Licensed under the Elastic License; |
| 3 | +// you may not use this file except in compliance with the Elastic License. |
| 4 | + |
| 5 | +package main |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "syscall/js" |
| 10 | + |
| 11 | + "github.com/elastic/package-spec/code/go/pkg/validator" |
| 12 | +) |
| 13 | + |
| 14 | +const moduleName = "elasticPackageSpec" |
| 15 | + |
| 16 | +// asyncFunc helps creating functions that return a promise. |
| 17 | +// |
| 18 | +// Calling async JavaScript APIs causes deadlocks in the JS event loop. Not sure |
| 19 | +// how to find if a Go code does it, but for example ValidateFromZip does, so |
| 20 | +// we need to run this code in a goroutine and return the result as a promise. |
| 21 | +// Related: https://github.com/golang/go/issues/41310 |
| 22 | +func asyncFunc(fn func(this js.Value, args []js.Value) interface{}) js.Func { |
| 23 | + return js.FuncOf(func(this js.Value, args []js.Value) interface{} { |
| 24 | + handler := js.FuncOf(func(_ js.Value, handlerArgs []js.Value) interface{} { |
| 25 | + resolve := handlerArgs[0] |
| 26 | + reject := handlerArgs[1] |
| 27 | + |
| 28 | + go func() { |
| 29 | + result := fn(this, args) |
| 30 | + if err, ok := result.(error); ok { |
| 31 | + reject.Invoke(err.Error()) |
| 32 | + return |
| 33 | + } |
| 34 | + resolve.Invoke(result) |
| 35 | + }() |
| 36 | + |
| 37 | + return nil |
| 38 | + }) |
| 39 | + |
| 40 | + return js.Global().Get("Promise").New(handler) |
| 41 | + }) |
| 42 | +} |
| 43 | + |
| 44 | +func main() { |
| 45 | + // It doesn't seem to be possible yet to export values as part of the compiled instance. |
| 46 | + // So we have to expose it by setting a global value. It may worth to explore tinygo for this. |
| 47 | + // Related: https://github.com/golang/go/issues/42372 |
| 48 | + js.Global().Set(moduleName, make(map[string]interface{})) |
| 49 | + module := js.Global().Get(moduleName) |
| 50 | + module.Set("validateFromZip", asyncFunc( |
| 51 | + func(this js.Value, args []js.Value) interface{} { |
| 52 | + if len(args) == 0 || args[0].IsNull() || args[0].IsUndefined() { |
| 53 | + return fmt.Errorf("package path expected") |
| 54 | + } |
| 55 | + |
| 56 | + pkgPath := args[0].String() |
| 57 | + return validator.ValidateFromZip(pkgPath) |
| 58 | + }, |
| 59 | + )) |
| 60 | + |
| 61 | + // Go runtime must be always available at any moment where exported functionality |
| 62 | + // can be executed, so keep it running till done. |
| 63 | + done := make(chan struct{}) |
| 64 | + module.Set("stop", js.FuncOf(func(_ js.Value, _ []js.Value) interface{} { |
| 65 | + close(done) |
| 66 | + return nil |
| 67 | + })) |
| 68 | + <-done |
| 69 | +} |
0 commit comments