github.com/awesome-flow/flow@v0.0.3-0.20190918184116-508d75d68a2c/pkg/corev1alpha1/x/decoder_base64.go (about)

     1  package x
     2  
     3  import (
     4  	"encoding/base64"
     5  	"sync"
     6  
     7  	core "github.com/awesome-flow/flow/pkg/corev1alpha1"
     8  )
     9  
    10  type DecoderBase64 struct {
    11  	name     string
    12  	ctx      *core.Context
    13  	queue    chan *core.Message
    14  	wg       sync.WaitGroup
    15  	encoding *base64.Encoding
    16  }
    17  
    18  var _ core.Actor = (*DecoderBase64)(nil)
    19  
    20  func NewDecoderBase64(name string, ctx *core.Context, params core.Params) (core.Actor, error) {
    21  	return &DecoderBase64{
    22  		name:     name,
    23  		ctx:      ctx,
    24  		queue:    make(chan *core.Message, 1),
    25  		encoding: base64.StdEncoding,
    26  	}, nil
    27  }
    28  
    29  func (d *DecoderBase64) Name() string {
    30  	return d.name
    31  }
    32  
    33  func (d *DecoderBase64) Start() error {
    34  	return nil
    35  }
    36  
    37  func (d *DecoderBase64) Stop() error {
    38  	close(d.queue)
    39  	d.wg.Wait()
    40  	return nil
    41  }
    42  
    43  func (d *DecoderBase64) Connect(nthreads int, peer core.Receiver) error {
    44  	for i := 0; i < nthreads; i++ {
    45  		d.wg.Add(1)
    46  		go func() {
    47  			for msg := range d.queue {
    48  				if err := peer.Receive(msg); err != nil {
    49  					d.ctx.Logger().Error("base64 decoder %q failed to send message to receiver: %s", d.name, err)
    50  				}
    51  			}
    52  			d.wg.Done()
    53  		}()
    54  	}
    55  	return nil
    56  }
    57  
    58  func (d *DecoderBase64) Receive(msg *core.Message) error {
    59  	decbody, err := d.decodeBase64(msg.Body())
    60  	if err != nil {
    61  		return err
    62  	}
    63  	msg.SetBody(decbody)
    64  	d.queue <- msg
    65  	return nil
    66  }
    67  
    68  func (d *DecoderBase64) decodeBase64(data []byte) ([]byte, error) {
    69  	newlen := d.encoding.DecodedLen(len(data))
    70  	out := make([]byte, newlen)
    71  	n, err := d.encoding.Decode(out, data)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  	return out[:n], nil
    76  }