github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/transporter/proxy/proxy.go (about)

     1  package proxy
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"strings"
     7  
     8  	"github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/httpx"
     9  	"github.com/machinefi/w3bstream/pkg/depends/kit/kit"
    10  	"github.com/machinefi/w3bstream/pkg/depends/kit/logr"
    11  	"github.com/machinefi/w3bstream/pkg/depends/protocol/eventpb"
    12  	"github.com/machinefi/w3bstream/pkg/errors/status"
    13  	"github.com/machinefi/w3bstream/pkg/modules/event"
    14  	"github.com/machinefi/w3bstream/pkg/types"
    15  )
    16  
    17  type ForwardRequest struct {
    18  	httpx.MethodPost
    19  	event.EventReq
    20  }
    21  
    22  func (r *ForwardRequest) Path() string {
    23  	return "/srv-applet-mgr/v0/event/" + r.Channel
    24  }
    25  
    26  func Forward(ctx context.Context, channel string, ev *eventpb.Event) (interface{}, error) {
    27  	ctx, l := logr.Start(ctx, "transporter.proxy.Forward")
    28  	defer l.End()
    29  
    30  	cli := types.MustProxyClientFromContext(ctx)
    31  
    32  	body := event.EventReq{
    33  		Channel:   channel,
    34  		EventType: ev.Header.GetEventType(),
    35  		EventID:   ev.Header.GetEventId(),
    36  		Timestamp: ev.Header.GetPubTime(),
    37  		Payload:   *(bytes.NewBuffer(ev.Payload)),
    38  	}
    39  
    40  	tok := ev.Header.GetToken()
    41  	if tok == "" {
    42  		return nil, status.InvalidEventToken
    43  	}
    44  
    45  	if !strings.HasPrefix(tok, "Bearer") {
    46  		tok = "Bearer " + tok
    47  	}
    48  
    49  	meta := kit.Metadata{
    50  		"Authorization": []string{tok},
    51  	}
    52  
    53  	rsp := &event.EventRsp{}
    54  	req := &ForwardRequest{EventReq: body}
    55  	if _, err := cli.Do(ctx, req, meta).Into(rsp); err != nil {
    56  		return nil, err
    57  	}
    58  	return rsp, nil
    59  }