|
| 1 | +// Copyright 2023 Blink Labs, LLC. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package embedded |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + |
| 20 | + "github.com/blinklabs-io/snek/event" |
| 21 | +) |
| 22 | + |
| 23 | +type CallbackFunc func(event.Event) error |
| 24 | + |
| 25 | +type EmbeddedOutput struct { |
| 26 | + errorChan chan error |
| 27 | + eventChan chan event.Event |
| 28 | + callbackFunc CallbackFunc |
| 29 | + outputChan chan event.Event |
| 30 | +} |
| 31 | + |
| 32 | +func New(options ...EmbeddedOptionFunc) *EmbeddedOutput { |
| 33 | + e := &EmbeddedOutput{ |
| 34 | + errorChan: make(chan error), |
| 35 | + eventChan: make(chan event.Event, 10), |
| 36 | + } |
| 37 | + for _, option := range options { |
| 38 | + option(e) |
| 39 | + } |
| 40 | + return e |
| 41 | +} |
| 42 | + |
| 43 | +// Start the embedded output |
| 44 | +func (e *EmbeddedOutput) Start() error { |
| 45 | + go func() { |
| 46 | + for { |
| 47 | + evt, ok := <-e.eventChan |
| 48 | + // Channel has been closed, which means we're shutting down |
| 49 | + if !ok { |
| 50 | + return |
| 51 | + } |
| 52 | + if e.callbackFunc != nil { |
| 53 | + if err := e.callbackFunc(evt); err != nil { |
| 54 | + e.errorChan <- fmt.Errorf("callback function error: %s", err) |
| 55 | + return |
| 56 | + } |
| 57 | + } |
| 58 | + if e.outputChan != nil { |
| 59 | + e.outputChan <- evt |
| 60 | + } |
| 61 | + } |
| 62 | + }() |
| 63 | + return nil |
| 64 | +} |
| 65 | + |
| 66 | +// Stop the embedded output |
| 67 | +func (e *EmbeddedOutput) Stop() error { |
| 68 | + close(e.eventChan) |
| 69 | + close(e.errorChan) |
| 70 | + if e.outputChan != nil { |
| 71 | + close(e.outputChan) |
| 72 | + } |
| 73 | + return nil |
| 74 | +} |
| 75 | + |
| 76 | +// ErrorChan returns the input error channel |
| 77 | +func (e *EmbeddedOutput) ErrorChan() chan error { |
| 78 | + return e.errorChan |
| 79 | +} |
| 80 | + |
| 81 | +// InputChan returns the input event channel |
| 82 | +func (e *EmbeddedOutput) InputChan() chan<- event.Event { |
| 83 | + return e.eventChan |
| 84 | +} |
| 85 | + |
| 86 | +// OutputChan always returns nil |
| 87 | +func (e *EmbeddedOutput) OutputChan() <-chan event.Event { |
| 88 | + return nil |
| 89 | +} |
0 commit comments