github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/model/model.go (about) 1 package model 2 3 import ( 4 "fmt" 5 6 sm "github.com/grafana/synthetic-monitoring-agent/pkg/pb/synthetic_monitoring" 7 ) 8 9 type GlobalID int64 10 11 type Check struct { 12 sm.Check 13 RegionId int `json:"regionId"` 14 } 15 16 func (c *Check) FromSM(check sm.Check) error { 17 // This implementation is a bit wasteful, but it ensures that it 18 // remains in sync with the protobuf definition. 19 data, err := check.Marshal() 20 if err != nil { 21 return fmt.Errorf("failed to marshal check %d tenant %d: %w", check.Id, check.TenantId, err) 22 } 23 24 if err := c.Unmarshal(data); err != nil { 25 return fmt.Errorf("failed to unmarshal data for check %d tenant %d: %w", check.Id, check.TenantId, err) 26 } 27 28 // Note that in some cases (e.g. check delete operations) we receive a 29 // check that only contains the check ID and nothing else, not even the 30 // tenant ID. We obtain the region ID from the check ID, and ignore the 31 // value that comes with the tenant ID. 32 c.Id, c.RegionId = GetLocalAndRegionIDs(GlobalID(check.Id)) 33 if c.TenantId != 0 { 34 c.TenantId, _ = GetLocalAndRegionIDs(GlobalID(check.TenantId)) 35 } 36 37 return nil 38 } 39 40 func (c *Check) GlobalID() GlobalID { 41 id, err := sm.LocalIDToGlobalID(c.Id, c.RegionId) 42 if err != nil { 43 return GlobalID(c.Id) 44 } 45 46 return GlobalID(id) 47 } 48 49 func (c *Check) GlobalTenantID() GlobalID { 50 id, err := sm.LocalIDToGlobalID(c.TenantId, c.RegionId) 51 if err != nil { 52 return GlobalID(c.TenantId) 53 } 54 55 return GlobalID(id) 56 } 57 58 // GetLocalAndRegionIDs takes a Global ID as specified in the sm data 59 // structures and returns a pair of ids corresponding to the local ID and the 60 // region ID. If the provided id is already a local one, it's returned without 61 // modification with the region set to 0. 62 func GetLocalAndRegionIDs(id GlobalID) (localID int64, regionID int) { 63 localID, regionID, err := sm.GlobalIDToLocalID(int64(id)) 64 if err != nil { 65 // Id is already local, use region 0. 66 return int64(id), 0 67 } 68 69 return localID, regionID 70 }