blob: fd6c949cf74955f628b804077e10638439acbb10 [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// 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
7package driver
8
9import (
10 "context"
11 "fmt"
12
13 "github.com/mongodb/mongo-go-driver/bson"
14 "github.com/mongodb/mongo-go-driver/bson/bsoncodec"
15 "github.com/mongodb/mongo-go-driver/bson/bsontype"
16 "github.com/mongodb/mongo-go-driver/mongo/options"
17 "github.com/mongodb/mongo-go-driver/x/bsonx"
18 "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore"
19
20 "time"
21
22 "github.com/mongodb/mongo-go-driver/x/mongo/driver/session"
23 "github.com/mongodb/mongo-go-driver/x/mongo/driver/topology"
24 "github.com/mongodb/mongo-go-driver/x/mongo/driver/uuid"
25 "github.com/mongodb/mongo-go-driver/x/network/command"
26 "github.com/mongodb/mongo-go-driver/x/network/description"
27)
28
29// Aggregate handles the full cycle dispatch and execution of an aggregate command against the provided
30// topology.
31func Aggregate(
32 ctx context.Context,
33 cmd command.Aggregate,
34 topo *topology.Topology,
35 readSelector, writeSelector description.ServerSelector,
36 clientID uuid.UUID,
37 pool *session.Pool,
38 registry *bsoncodec.Registry,
39 opts ...*options.AggregateOptions,
40) (*BatchCursor, error) {
41
42 dollarOut := cmd.HasDollarOut()
43
44 var ss *topology.SelectedServer
45 var err error
46 switch dollarOut {
47 case true:
48 ss, err = topo.SelectServer(ctx, writeSelector)
49 if err != nil {
50 return nil, err
51 }
52 case false:
53 ss, err = topo.SelectServer(ctx, readSelector)
54 if err != nil {
55 return nil, err
56 }
57 }
58
59 desc := ss.Description()
60 conn, err := ss.Connection(ctx)
61 if err != nil {
62 return nil, err
63 }
64
65 defer conn.Close()
66
67 rp, err := getReadPrefBasedOnTransaction(cmd.ReadPref, cmd.Session)
68 if err != nil {
69 return nil, err
70 }
71 cmd.ReadPref = rp
72
73 // If no explicit session and deployment supports sessions, start implicit session.
74 if cmd.Session == nil && topo.SupportsSessions() {
75 cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit)
76 if err != nil {
77 return nil, err
78 }
79 }
80
81 aggOpts := options.MergeAggregateOptions(opts...)
82
83 if aggOpts.AllowDiskUse != nil {
84 cmd.Opts = append(cmd.Opts, bsonx.Elem{"allowDiskUse", bsonx.Boolean(*aggOpts.AllowDiskUse)})
85 }
86 var batchSize int32
87 if aggOpts.BatchSize != nil {
88 elem := bsonx.Elem{"batchSize", bsonx.Int32(*aggOpts.BatchSize)}
89 cmd.Opts = append(cmd.Opts, elem)
90 cmd.CursorOpts = append(cmd.CursorOpts, elem)
91 batchSize = *aggOpts.BatchSize
92 }
93 if aggOpts.BypassDocumentValidation != nil && desc.WireVersion.Includes(4) {
94 cmd.Opts = append(cmd.Opts, bsonx.Elem{"bypassDocumentValidation", bsonx.Boolean(*aggOpts.BypassDocumentValidation)})
95 }
96 if aggOpts.Collation != nil {
97 if desc.WireVersion.Max < 5 {
98 return nil, ErrCollation
99 }
100 cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(aggOpts.Collation.ToDocument())})
101 }
102 if aggOpts.MaxTime != nil {
103 cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*aggOpts.MaxTime / time.Millisecond))})
104 }
105 if aggOpts.MaxAwaitTime != nil {
106 // specified as maxTimeMS on getMore commands
107 cmd.CursorOpts = append(cmd.CursorOpts, bsonx.Elem{
108 "maxTimeMS", bsonx.Int64(int64(*aggOpts.MaxAwaitTime / time.Millisecond)),
109 })
110 }
111 if aggOpts.Comment != nil {
112 cmd.Opts = append(cmd.Opts, bsonx.Elem{"comment", bsonx.String(*aggOpts.Comment)})
113 }
114 if aggOpts.Hint != nil {
115 hintElem, err := interfaceToElement("hint", aggOpts.Hint, registry)
116 if err != nil {
117 return nil, err
118 }
119
120 cmd.Opts = append(cmd.Opts, hintElem)
121 }
122
123 res, err := cmd.RoundTrip(ctx, desc, conn)
124 if err != nil {
125 closeImplicitSession(cmd.Session)
126 return nil, err
127 }
128
129 if desc.WireVersion.Max < 4 {
130 return buildLegacyCommandBatchCursor(res, batchSize, ss.Server)
131 }
132
133 return NewBatchCursor(bsoncore.Document(res), cmd.Session, cmd.Clock, ss.Server, cmd.CursorOpts...)
134}
135
136func buildLegacyCommandBatchCursor(rdr bson.Raw, batchSize int32, server *topology.Server) (*BatchCursor, error) {
137 firstBatchDocs, ns, cursorID, err := getCursorValues(rdr)
138 if err != nil {
139 return nil, err
140 }
141
142 return NewLegacyBatchCursor(ns, cursorID, firstBatchDocs, 0, batchSize, server)
143}
144
145// get the firstBatch, cursor ID, and namespace from a bson.Raw
146//
147// TODO(GODRIVER-617): Change the documents return value into []bsoncore.Document.
148func getCursorValues(result bson.Raw) ([]bson.Raw, command.Namespace, int64, error) {
149 cur, err := result.LookupErr("cursor")
150 if err != nil {
151 return nil, command.Namespace{}, 0, err
152 }
153 if cur.Type != bson.TypeEmbeddedDocument {
154 return nil, command.Namespace{}, 0, fmt.Errorf("cursor should be an embedded document but it is a BSON %s", cur.Type)
155 }
156
157 elems, err := cur.Document().Elements()
158 if err != nil {
159 return nil, command.Namespace{}, 0, err
160 }
161
162 var ok bool
163 var batch []bson.Raw
164 var namespace command.Namespace
165 var cursorID int64
166
167 for _, elem := range elems {
168 switch elem.Key() {
169 case "firstBatch":
170 arr, ok := elem.Value().ArrayOK()
171 if !ok {
172 return nil, command.Namespace{}, 0, fmt.Errorf("firstBatch should be an array but it is a BSON %s", elem.Value().Type)
173 }
174 if err != nil {
175 return nil, command.Namespace{}, 0, err
176 }
177
178 vals, err := arr.Values()
179 if err != nil {
180 return nil, command.Namespace{}, 0, err
181 }
182
183 for _, val := range vals {
184 if val.Type != bsontype.EmbeddedDocument {
185 return nil, command.Namespace{}, 0, fmt.Errorf("element of cursor batch is not a document, but at %s", val.Type)
186 }
187 batch = append(batch, val.Value)
188 }
189 case "ns":
190 if elem.Value().Type != bson.TypeString {
191 return nil, command.Namespace{}, 0, fmt.Errorf("namespace should be a string but it is a BSON %s", elem.Value().Type)
192 }
193 namespace = command.ParseNamespace(elem.Value().StringValue())
194 err = namespace.Validate()
195 if err != nil {
196 return nil, command.Namespace{}, 0, err
197 }
198 case "id":
199 cursorID, ok = elem.Value().Int64OK()
200 if !ok {
201 return nil, command.Namespace{}, 0, fmt.Errorf("id should be an int64 but it is a BSON %s", elem.Value().Type)
202 }
203 }
204 }
205
206 return batch, namespace, cursorID, nil
207}