github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/state/backend.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package state 5 6 import ( 7 "time" 8 9 "github.com/juju/clock" 10 "github.com/juju/errors" 11 12 "github.com/juju/juju/state/watcher" 13 ) 14 15 //go:generate go run go.uber.org/mock/mockgen -package mocks -destination mocks/watcher_mock.go github.com/juju/juju/state/watcher BaseWatcher 16 17 // modelBackend collects together some useful internal state methods for 18 // accessing mongo and mapping local and global ids to one another. 19 type modelBackend interface { 20 ModelUUID() string 21 IsController() bool 22 23 // docID generates a globally unique ID value 24 // where the model UUID is prefixed to the 25 // localID. 26 docID(string) string 27 28 // localID returns the local ID value by stripping 29 // off the model UUID prefix if it is there. 30 localID(string) string 31 32 // strictLocalID returns the local ID value by removing the 33 // model UUID prefix. If there is no prefix matching the 34 // State's model, an error is returned. 35 strictLocalID(string) (string, error) 36 37 // nowToTheSecond returns the current time in UTC to the nearest second. We use 38 // this for a time source that is not more precise than we can handle. When 39 // serializing time in and out of mongo, we lose enough precision that it's 40 // misleading to store any more than precision to the second. 41 nowToTheSecond() time.Time 42 43 clock() clock.Clock 44 db() Database 45 modelName() (string, error) 46 txnLogWatcher() watcher.BaseWatcher 47 } 48 49 func (st *State) docID(localID string) string { 50 return ensureModelUUID(st.ModelUUID(), localID) 51 } 52 53 func (st *State) localID(id string) string { 54 modelUUID, localID, ok := splitDocID(id) 55 if !ok || modelUUID != st.ModelUUID() { 56 return id 57 } 58 return localID 59 } 60 61 func (st *State) strictLocalID(id string) (string, error) { 62 modelUUID, localID, ok := splitDocID(id) 63 if !ok || modelUUID != st.ModelUUID() { 64 return "", errors.Errorf("unexpected id: %#v", id) 65 } 66 return localID, nil 67 } 68 69 func (st *State) clock() clock.Clock { 70 return st.stateClock 71 } 72 73 func (st *State) modelName() (string, error) { 74 m, err := st.Model() 75 if err != nil { 76 return "", errors.Trace(err) 77 } 78 return m.Name(), nil 79 } 80 81 func (st *State) nowToTheSecond() time.Time { 82 return st.clock().Now().Round(time.Second).UTC() 83 }