github.com/metacurrency/holochain@v0.1.0-alpha-26.0.20200915073418-5c83169c9b5b/action_send.go (about)

     1  package holochain
     2  
     3  import (
     4  	peer "github.com/libp2p/go-libp2p-peer"
     5  	"reflect"
     6  	"time"
     7  )
     8  
     9  //------------------------------------------------------------
    10  // Send
    11  
    12  type Callback struct {
    13  	Function string
    14  	ID       string
    15  	zomeType string
    16  }
    17  
    18  type SendOptions struct {
    19  	Callback *Callback
    20  	Timeout  int
    21  }
    22  
    23  type ActionSend struct {
    24  	to      peer.ID
    25  	msg     AppMsg
    26  	options *SendOptions
    27  }
    28  
    29  type APIFnSend struct {
    30  	action ActionSend
    31  }
    32  
    33  func (fn *APIFnSend) Name() string {
    34  	return "send"
    35  }
    36  
    37  func (fn *APIFnSend) Args() []Arg {
    38  	return []Arg{{Name: "to", Type: HashArg}, {Name: "msg", Type: MapArg}, {Name: "options", Type: MapArg, MapType: reflect.TypeOf(SendOptions{}), Optional: true}}
    39  }
    40  
    41  func (fn *APIFnSend) Call(h *Holochain) (response interface{}, err error) {
    42  	var r interface{}
    43  	var timeout time.Duration
    44  	a := &fn.action
    45  	if a.options != nil {
    46  		timeout = time.Duration(a.options.Timeout) * time.Millisecond
    47  	}
    48  	msg := h.node.NewMessage(APP_MESSAGE, a.msg)
    49  	if a.options != nil && a.options.Callback != nil {
    50  		err = h.SendAsync(ActionProtocol, a.to, msg, a.options.Callback, timeout)
    51  	} else {
    52  
    53  		r, err = h.Send(h.node.ctx, ActionProtocol, a.to, msg, timeout)
    54  		if err == nil {
    55  			response = r.(AppMsg).Body
    56  		}
    57  	}
    58  	return
    59  }
    60  
    61  func (a *ActionSend) Name() string {
    62  	return "send"
    63  }
    64  
    65  func (a *ActionSend) Receive(dht *DHT, msg *Message) (response interface{}, err error) {
    66  	t := msg.Body.(AppMsg)
    67  	var r Ribosome
    68  	r, _, err = dht.h.MakeRibosome(t.ZomeType)
    69  	if err != nil {
    70  		return
    71  	}
    72  	rsp := AppMsg{ZomeType: t.ZomeType}
    73  	rsp.Body, err = r.Receive(peer.IDB58Encode(msg.From), t.Body)
    74  	if err == nil {
    75  		response = rsp
    76  	}
    77  	return
    78  }