Don Newton | 379ae25 | 2019-04-01 12:17:06 -0400 | [diff] [blame^] | 1 | // Copyright (C) MongoDB, Inc. 2017-present. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | // not use this file except in compliance with the License. You may obtain |
| 5 | // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | |
| 7 | package internal |
| 8 | |
| 9 | import ( |
| 10 | "context" |
| 11 | |
| 12 | "github.com/mongodb/mongo-go-driver/bson" |
| 13 | "github.com/mongodb/mongo-go-driver/x/bsonx" |
| 14 | "github.com/mongodb/mongo-go-driver/x/network/wiremessage" |
| 15 | "errors" |
| 16 | "fmt" |
| 17 | ) |
| 18 | |
| 19 | // Implements the connection.Connection interface by reading and writing wire messages |
| 20 | // to a channel |
| 21 | type ChannelConn struct { |
| 22 | WriteErr error |
| 23 | Written chan wiremessage.WireMessage |
| 24 | ReadResp chan wiremessage.WireMessage |
| 25 | ReadErr chan error |
| 26 | } |
| 27 | |
| 28 | func (c *ChannelConn) WriteWireMessage(ctx context.Context, wm wiremessage.WireMessage) error { |
| 29 | select { |
| 30 | case c.Written <- wm: |
| 31 | default: |
| 32 | c.WriteErr = errors.New("could not write wiremessage to written channel") |
| 33 | } |
| 34 | return c.WriteErr |
| 35 | } |
| 36 | |
| 37 | func (c *ChannelConn) ReadWireMessage(ctx context.Context) (wiremessage.WireMessage, error) { |
| 38 | var wm wiremessage.WireMessage |
| 39 | var err error |
| 40 | select { |
| 41 | case wm = <-c.ReadResp: |
| 42 | case err = <-c.ReadErr: |
| 43 | case <-ctx.Done(): |
| 44 | } |
| 45 | return wm, err |
| 46 | } |
| 47 | |
| 48 | func (c *ChannelConn) Close() error { |
| 49 | return nil |
| 50 | } |
| 51 | |
| 52 | func (c *ChannelConn) Expired() bool { |
| 53 | return false |
| 54 | } |
| 55 | |
| 56 | func (c *ChannelConn) Alive() bool { |
| 57 | return true |
| 58 | } |
| 59 | |
| 60 | func (c *ChannelConn) ID() string { |
| 61 | return "faked" |
| 62 | } |
| 63 | |
| 64 | // Create a OP_REPLY wiremessage from a BSON document |
| 65 | func MakeReply(doc bsonx.Doc) (wiremessage.WireMessage, error) { |
| 66 | rdr, err := doc.MarshalBSON() |
| 67 | if err != nil { |
| 68 | return nil, errors.New(fmt.Sprintf("could not create document: %v", err)) |
| 69 | } |
| 70 | return wiremessage.Reply{ |
| 71 | NumberReturned: 1, |
| 72 | Documents: []bson.Raw{rdr}, |
| 73 | }, nil |
| 74 | } |