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 7package readpref 8 9import ( 10 "errors" 11 "time" 12 13 "go.mongodb.org/mongo-driver/tag" 14) 15 16// ErrInvalidTagSet indicates that an invalid set of tags was specified. 17var ErrInvalidTagSet = errors.New("an even number of tags must be specified") 18 19// Option configures a read preference 20type Option func(*ReadPref) error 21 22// WithMaxStaleness sets the maximum staleness a 23// server is allowed. 24func WithMaxStaleness(ms time.Duration) Option { 25 return func(rp *ReadPref) error { 26 rp.maxStaleness = ms 27 rp.maxStalenessSet = true 28 return nil 29 } 30} 31 32// WithTags sets a single tag set used to match 33// a server. The last call to WithTags or WithTagSets 34// overrides all previous calls to either method. 35func WithTags(tags ...string) Option { 36 return func(rp *ReadPref) error { 37 length := len(tags) 38 if length < 2 || length%2 != 0 { 39 return ErrInvalidTagSet 40 } 41 42 tagset := make(tag.Set, 0, length/2) 43 44 for i := 1; i < length; i += 2 { 45 tagset = append(tagset, tag.Tag{Name: tags[i-1], Value: tags[i]}) 46 } 47 48 return WithTagSets(tagset)(rp) 49 } 50} 51 52// WithTagSets sets the tag sets used to match 53// a server. The last call to WithTags or WithTagSets 54// overrides all previous calls to either method. 55func WithTagSets(tagSets ...tag.Set) Option { 56 return func(rp *ReadPref) error { 57 rp.tagSets = tagSets 58 return nil 59 } 60} 61