Skip to content

Commit

Permalink
Add plugin.CallWithContext method (#60)
Browse files Browse the repository at this point in the history
This PR adds a new method that allows calling plugin functions with a
custom context.

This will allow developers to call extism plugins with custom timeouts
and cancellation.
  • Loading branch information
Marton6 authored Mar 6, 2024
1 parent a6257ad commit c982866
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ $ go run main.go

All exports have a simple interface of optional bytes in, and optional bytes out. This plug-in happens to take a string and return a JSON encoded string with a report of results.

> **Note**: If you want to pass a custom `context.Context` when calling a plugin function, you can use the [extism.Plugin.CallWithContext](https://pkg.go.dev/github.com/extism/go-sdk#Plugin.CallWithContext) method instead.

### Plug-in State

Plug-ins may be stateful or stateless. Plug-ins can maintain state between calls by the use of variables. Our count vowels plug-in remembers the total number of vowels it's ever counted in the "total" key in the result. You can see this by making subsequent calls to the export:
Expand Down
7 changes: 5 additions & 2 deletions extism.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,11 +518,14 @@ func (plugin *Plugin) FunctionExists(name string) bool {

// Call a function by name with the given input, returning the output
func (plugin *Plugin) Call(name string, data []byte) (uint32, []byte, error) {
ctx := plugin.Runtime.ctx
return plugin.CallWithContext(plugin.Runtime.ctx, name, data)
}

// Call a function by name with the given input and context, returning the output
func (plugin *Plugin) CallWithContext(ctx context.Context, name string, data []byte) (uint32, []byte, error) {
if plugin.Timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(plugin.Runtime.ctx, plugin.Timeout)
ctx, cancel = context.WithTimeout(ctx, plugin.Timeout)
defer cancel()
}

Expand Down

0 comments on commit c982866

Please sign in to comment.