...

Source file src/go.mongodb.org/mongo-driver/x/mongo/driver/session/server_session.go

Documentation: go.mongodb.org/mongo-driver/x/mongo/driver/session

     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 session
     8  
     9  import (
    10  	"time"
    11  
    12  	"go.mongodb.org/mongo-driver/internal/uuid"
    13  	"go.mongodb.org/mongo-driver/mongo/description"
    14  	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
    15  )
    16  
    17  // Server is an open session with the server.
    18  type Server struct {
    19  	SessionID bsoncore.Document
    20  	TxnNumber int64
    21  	LastUsed  time.Time
    22  	Dirty     bool
    23  }
    24  
    25  // returns whether or not a session has expired given a timeout in minutes
    26  // a session is considered expired if it has less than 1 minute left before becoming stale
    27  func (ss *Server) expired(topoDesc topologyDescription) bool {
    28  	// There is no server monitoring in LB mode, so we do not track session timeout minutes from server hello responses
    29  	// and never consider sessions to be expired.
    30  	if topoDesc.kind == description.LoadBalanced {
    31  		return false
    32  	}
    33  
    34  	if topoDesc.timeoutMinutes == nil || *topoDesc.timeoutMinutes <= 0 {
    35  		return true
    36  	}
    37  	timeUnused := time.Since(ss.LastUsed).Minutes()
    38  	return timeUnused > float64(*topoDesc.timeoutMinutes-1)
    39  }
    40  
    41  // update the last used time for this session.
    42  // must be called whenever this server session is used to send a command to the server.
    43  func (ss *Server) updateUseTime() {
    44  	ss.LastUsed = time.Now()
    45  }
    46  
    47  func newServerSession() (*Server, error) {
    48  	id, err := uuid.New()
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	idx, idDoc := bsoncore.AppendDocumentStart(nil)
    54  	idDoc = bsoncore.AppendBinaryElement(idDoc, "id", UUIDSubtype, id[:])
    55  	idDoc, _ = bsoncore.AppendDocumentEnd(idDoc, idx)
    56  
    57  	return &Server{
    58  		SessionID: idDoc,
    59  		LastUsed:  time.Now(),
    60  	}, nil
    61  }
    62  
    63  // IncrementTxnNumber increments the transaction number.
    64  func (ss *Server) IncrementTxnNumber() {
    65  	ss.TxnNumber++
    66  }
    67  
    68  // MarkDirty marks the session as dirty.
    69  func (ss *Server) MarkDirty() {
    70  	ss.Dirty = true
    71  }
    72  
    73  // UUIDSubtype is the BSON binary subtype that a UUID should be encoded as
    74  const UUIDSubtype byte = 4
    75  

View as plain text