|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/sha256" |
| 6 | + "fmt" |
| 7 | + "hash" |
| 8 | + |
| 9 | + "github.com/storacha/go-ucanto/client" |
| 10 | + "github.com/storacha/go-ucanto/core/invocation" |
| 11 | + "github.com/storacha/go-ucanto/core/message" |
| 12 | + "github.com/storacha/go-ucanto/transport" |
| 13 | + "github.com/storacha/go-ucanto/transport/headercar" |
| 14 | + "github.com/storacha/go-ucanto/ucan" |
| 15 | +) |
| 16 | + |
| 17 | +func NewConnection(id ucan.Principal, channel transport.Channel) (*Connection, error) { |
| 18 | + hasher := sha256.New |
| 19 | + codec := headercar.NewOutboundCodec() |
| 20 | + return &Connection{id, codec, channel, hasher}, nil |
| 21 | +} |
| 22 | + |
| 23 | +type Connection struct { |
| 24 | + id ucan.Principal |
| 25 | + codec transport.OutboundCodec |
| 26 | + channel transport.Channel |
| 27 | + hasher func() hash.Hash |
| 28 | +} |
| 29 | + |
| 30 | +var _ client.Connection = (*Connection)(nil) |
| 31 | + |
| 32 | +func (c *Connection) ID() ucan.Principal { |
| 33 | + return c.id |
| 34 | +} |
| 35 | + |
| 36 | +func (c *Connection) Codec() transport.OutboundCodec { |
| 37 | + return c.codec |
| 38 | +} |
| 39 | + |
| 40 | +func (c *Connection) Channel() transport.Channel { |
| 41 | + return c.channel |
| 42 | +} |
| 43 | + |
| 44 | +func (c *Connection) Hasher() hash.Hash { |
| 45 | + return c.hasher() |
| 46 | +} |
| 47 | + |
| 48 | +func Execute(ctx context.Context, invocations []invocation.Invocation, conn client.Connection) (client.ExecutionResponse, error) { |
| 49 | + input, err := message.Build(invocations, nil) |
| 50 | + if err != nil { |
| 51 | + return nil, fmt.Errorf("building message: %w", err) |
| 52 | + } |
| 53 | + |
| 54 | + req, err := conn.Codec().Encode(input) |
| 55 | + if err != nil { |
| 56 | + return nil, fmt.Errorf("encoding message: %w", err) |
| 57 | + } |
| 58 | + |
| 59 | + res, err := conn.Channel().Request(ctx, req) |
| 60 | + if err != nil { |
| 61 | + return nil, fmt.Errorf("sending message: %w", err) |
| 62 | + } |
| 63 | + |
| 64 | + output, err := conn.Codec().Decode(res) |
| 65 | + if err != nil { |
| 66 | + return nil, fmt.Errorf("decoding message: %w", err) |
| 67 | + } |
| 68 | + |
| 69 | + return client.ExecutionResponse(output), nil |
| 70 | +} |
0 commit comments