blob: 06aa51fe559d708de741c55f7c478e04c3f0a5ad [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 session
8
9import (
10 "time"
11
12 "crypto/rand"
13
14 "github.com/mongodb/mongo-go-driver/x/bsonx"
15 "github.com/mongodb/mongo-go-driver/x/mongo/driver/uuid"
16)
17
18var rander = rand.Reader
19
20// Server is an open session with the server.
21type Server struct {
22 SessionID bsonx.Doc
23 TxnNumber int64
24 LastUsed time.Time
25}
26
27// returns whether or not a session has expired given a timeout in minutes
28// a session is considered expired if it has less than 1 minute left before becoming stale
29func (ss *Server) expired(timeoutMinutes uint32) bool {
30 if timeoutMinutes <= 0 {
31 return true
32 }
33 timeUnused := time.Since(ss.LastUsed).Minutes()
34 return timeUnused > float64(timeoutMinutes-1)
35}
36
37// update the last used time for this session.
38// must be called whenever this server session is used to send a command to the server.
39func (ss *Server) updateUseTime() {
40 ss.LastUsed = time.Now()
41}
42
43func newServerSession() (*Server, error) {
44 id, err := uuid.New()
45 if err != nil {
46 return nil, err
47 }
48
49 idDoc := bsonx.Doc{{"id", bsonx.Binary(UUIDSubtype, id[:])}}
50
51 return &Server{
52 SessionID: idDoc,
53 LastUsed: time.Now(),
54 }, nil
55}
56
57// IncrementTxnNumber increments the transaction number.
58func (ss *Server) IncrementTxnNumber() {
59 ss.TxnNumber++
60}
61
62// UUIDSubtype is the BSON binary subtype that a UUID should be encoded as
63const UUIDSubtype byte = 4