blob: 6447a49ea4e628fc8b50ac47fc5905e16869137f [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
12 "github.com/mongodb/mongo-go-driver/bson"
13 "github.com/mongodb/mongo-go-driver/mongo/writeconcern"
14 "github.com/mongodb/mongo-go-driver/x/mongo/driver/session"
15 "github.com/mongodb/mongo-go-driver/x/mongo/driver/topology"
16 "github.com/mongodb/mongo-go-driver/x/mongo/driver/uuid"
17 "github.com/mongodb/mongo-go-driver/x/network/command"
18 "github.com/mongodb/mongo-go-driver/x/network/description"
19)
20
21// Write handles the full cycle dispatch and execution of a write command against the provided
22// topology.
23func Write(
24 ctx context.Context,
25 cmd command.Write,
26 topo *topology.Topology,
27 selector description.ServerSelector,
28 clientID uuid.UUID,
29 pool *session.Pool,
30) (bson.Raw, error) {
31
32 ss, err := topo.SelectServer(ctx, selector)
33 if err != nil {
34 return nil, err
35 }
36
37 desc := ss.Description()
38 conn, err := ss.Connection(ctx)
39 if err != nil {
40 return nil, err
41 }
42
43 if !writeconcern.AckWrite(cmd.WriteConcern) {
44 go func() {
45 defer func() { _ = recover() }()
46 defer conn.Close()
47
48 _, _ = cmd.RoundTrip(ctx, desc, conn)
49 }()
50
51 return nil, command.ErrUnacknowledgedWrite
52 }
53 defer conn.Close()
54
55 // If no explicit session and deployment supports sessions, start implicit session.
56 if cmd.Session == nil && topo.SupportsSessions() {
57 cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit)
58 if err != nil {
59 return nil, err
60 }
61 defer cmd.Session.EndSession()
62 }
63
64 return cmd.RoundTrip(ctx, desc, conn)
65}
66
67// Retryable writes are supported if the server supports sessions, the operation is not
68// within a transaction, and the write is acknowledged
69func retrySupported(
70 topo *topology.Topology,
71 desc description.SelectedServer,
72 sess *session.Client,
73 wc *writeconcern.WriteConcern,
74) bool {
75 return topo.SupportsSessions() &&
76 description.SessionsSupported(desc.WireVersion) &&
77 !(sess.TransactionInProgress() || sess.TransactionStarting()) &&
78 writeconcern.AckWrite(wc)
79}