github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/vendor_skip/go.mongodb.org/mongo-driver/mongo/description/topology_version.go (about)

     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 description
     8  
     9  import (
    10  	"fmt"
    11  
    12  	"go.mongodb.org/mongo-driver/bson"
    13  	"go.mongodb.org/mongo-driver/bson/primitive"
    14  )
    15  
    16  // TopologyVersion represents a software version.
    17  type TopologyVersion struct {
    18  	ProcessID primitive.ObjectID
    19  	Counter   int64
    20  }
    21  
    22  // NewTopologyVersion creates a TopologyVersion based on doc
    23  func NewTopologyVersion(doc bson.Raw) (*TopologyVersion, error) {
    24  	elements, err := doc.Elements()
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	var tv TopologyVersion
    29  	var ok bool
    30  	for _, element := range elements {
    31  		switch element.Key() {
    32  		case "processId":
    33  			tv.ProcessID, ok = element.Value().ObjectIDOK()
    34  			if !ok {
    35  				return nil, fmt.Errorf("expected 'processId' to be a objectID but it's a BSON %s", element.Value().Type)
    36  			}
    37  		case "counter":
    38  			tv.Counter, ok = element.Value().Int64OK()
    39  			if !ok {
    40  				return nil, fmt.Errorf("expected 'counter' to be an int64 but it's a BSON %s", element.Value().Type)
    41  			}
    42  		}
    43  	}
    44  	return &tv, nil
    45  }
    46  
    47  // CompareToIncoming compares the receiver, which represents the currently known TopologyVersion for a server, to an
    48  // incoming TopologyVersion extracted from a server command response.
    49  //
    50  // This returns -1 if the receiver version is less than the response, 0 if the versions are equal, and 1 if the
    51  // receiver version is greater than the response. This comparison is not commutative.
    52  func (tv *TopologyVersion) CompareToIncoming(responseTV *TopologyVersion) int {
    53  	if tv == nil || responseTV == nil {
    54  		return -1
    55  	}
    56  	if tv.ProcessID != responseTV.ProcessID {
    57  		return -1
    58  	}
    59  	if tv.Counter == responseTV.Counter {
    60  		return 0
    61  	}
    62  	if tv.Counter < responseTV.Counter {
    63  		return -1
    64  	}
    65  	return 1
    66  }