blob: 4798b0558b43b5c370c93c8a745e5d0cd0020074 [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/x/mongo/driver/topology"
13 "github.com/mongodb/mongo-go-driver/x/network/command"
14 "github.com/mongodb/mongo-go-driver/x/network/description"
15 "github.com/mongodb/mongo-go-driver/x/network/result"
16)
17
18// AbortTransaction handles the full cycle dispatch and execution of abortting a transaction
19// against the provided topology.
20func AbortTransaction(
21 ctx context.Context,
22 cmd command.AbortTransaction,
23 topo *topology.Topology,
24 selector description.ServerSelector,
25) (result.TransactionResult, error) {
26 res, err := abortTransaction(ctx, cmd, topo, selector, nil)
27 if cerr, ok := err.(command.Error); ok && err != nil {
28 // Retry if appropriate
29 if cerr.Retryable() {
30 res, err = abortTransaction(ctx, cmd, topo, selector, cerr)
31 }
32 }
33 return res, err
34}
35
36func abortTransaction(
37 ctx context.Context,
38 cmd command.AbortTransaction,
39 topo *topology.Topology,
40 selector description.ServerSelector,
41 oldErr error,
42) (result.TransactionResult, error) {
43 ss, err := topo.SelectServer(ctx, selector)
44 if err != nil {
45 // If retrying server selection, return the original error if it fails
46 if oldErr != nil {
47 return result.TransactionResult{}, oldErr
48 }
49 return result.TransactionResult{}, err
50 }
51
52 desc := ss.Description()
53
54 if oldErr != nil && (!topo.SupportsSessions() || !description.SessionsSupported(desc.WireVersion)) {
55 // Assuming we are retrying (oldErr != nil),
56 // if server doesn't support retryable writes, return the original error
57 // Conditions for retry write support are the same as that of sessions
58 return result.TransactionResult{}, oldErr
59 }
60
61 conn, err := ss.Connection(ctx)
62 if err != nil {
63 if oldErr != nil {
64 return result.TransactionResult{}, oldErr
65 }
66 return result.TransactionResult{}, err
67 }
68 defer conn.Close()
69
70 return cmd.RoundTrip(ctx, desc, conn)
71}