github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/graph/link.go (about)

     1  package graph
     2  
     3  import (
     4  	"github.com/15mga/kiwi/ds"
     5  	"github.com/15mga/kiwi/util"
     6  )
     7  
     8  type ILink interface {
     9  	IGraphElem
    10  	In() IIn
    11  	Out() IOut
    12  	Transfer(msg IMsg) *util.Err
    13  	AddFilter(fn func(IMsg) *util.Err)
    14  }
    15  
    16  func newLink(g IGraph, name string, out IOut, in IIn) ILink {
    17  	return &link{
    18  		IGraphElem: newGraphElem(g, name),
    19  		out:        out,
    20  		in:         in,
    21  	}
    22  }
    23  
    24  type link struct {
    25  	IGraphElem
    26  	in     IIn
    27  	out    IOut
    28  	filter *ds.FnErrLink1[IMsg]
    29  }
    30  
    31  func (l *link) In() IIn {
    32  	return l.in
    33  }
    34  
    35  func (l *link) Out() IOut {
    36  	return l.out
    37  }
    38  
    39  func (l *link) Transfer(msg IMsg) *util.Err {
    40  	if !l.Enabled() {
    41  		return nil
    42  	}
    43  	if l.filter != nil {
    44  		err := l.filter.Invoke(msg)
    45  		if err != nil {
    46  			err.AddParam("link", l.Path())
    47  			return err
    48  		}
    49  	}
    50  	return l.in.Receive(msg)
    51  }
    52  
    53  func (l *link) AddFilter(fn func(IMsg) *util.Err) {
    54  	if l.filter == nil {
    55  		l.filter = ds.NewFnErrLink1[IMsg]()
    56  	}
    57  	l.filter.Push(fn)
    58  }