Skip to content

Commit 7294d49

Browse files
authored
feat(metric): model trigger counts api (#248)
Because - dashboard needs API for model trigger completed/error counts This commit - add new metrics API ![image](https://github.com/user-attachments/assets/9891351a-692e-4334-b880-bd1a98a497b0)
1 parent 89cce72 commit 7294d49

File tree

6 files changed

+140
-3
lines changed

6 files changed

+140
-3
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ require (
1616
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1
1717
github.com/iancoleman/strcase v0.2.0
1818
github.com/influxdata/influxdb-client-go/v2 v2.12.3
19-
github.com/instill-ai/protogen-go v0.3.3-alpha.0.20241029162707-1398399a24ee
19+
github.com/instill-ai/protogen-go v0.3.3-alpha.0.20241104082233-1b396ff465a7
2020
github.com/instill-ai/usage-client v0.2.4-alpha.0.20240123081026-6c78d9a5197a
2121
github.com/instill-ai/x v0.4.0-alpha
2222
github.com/knadh/koanf v1.5.0

go.sum

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,8 +1090,8 @@ github.com/influxdata/influxdb-client-go/v2 v2.12.3 h1:28nRlNMRIV4QbtIUvxhWqaxn0
10901090
github.com/influxdata/influxdb-client-go/v2 v2.12.3/go.mod h1:IrrLUbCjjfkmRuaCiGQg4m2GbkaeJDcuWoxiWdQEbA0=
10911091
github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839 h1:W9WBk7wlPfJLvMCdtV4zPulc4uCPrlywQOmbFOhgQNU=
10921092
github.com/influxdata/line-protocol v0.0.0-20200327222509-2487e7298839/go.mod h1:xaLFMmpvUxqXtVkUJfg9QmT88cDaCJ3ZKgdZ78oO8Qo=
1093-
github.com/instill-ai/protogen-go v0.3.3-alpha.0.20241029162707-1398399a24ee h1:onnzrn5jabO3jDLPo2193Ql6YMRyDWDx9K834Bfi8V0=
1094-
github.com/instill-ai/protogen-go v0.3.3-alpha.0.20241029162707-1398399a24ee/go.mod h1:rf0UY7VpEgpaLudYEcjx5rnbuwlBaaLyD4FQmWLtgAY=
1093+
github.com/instill-ai/protogen-go v0.3.3-alpha.0.20241104082233-1b396ff465a7 h1:Xxyepd41EX7oDjEhVvAaY5Ofk2gk6Z/D0RO2lUxM200=
1094+
github.com/instill-ai/protogen-go v0.3.3-alpha.0.20241104082233-1b396ff465a7/go.mod h1:rf0UY7VpEgpaLudYEcjx5rnbuwlBaaLyD4FQmWLtgAY=
10951095
github.com/instill-ai/usage-client v0.2.4-alpha.0.20240123081026-6c78d9a5197a h1:gmy8BcCFDZQan40c/D3f62DwTYtlCwi0VrSax+pKffw=
10961096
github.com/instill-ai/usage-client v0.2.4-alpha.0.20240123081026-6c78d9a5197a/go.mod h1:EpX3Yr661uWULtZf5UnJHfr5rw2PDyX8ku4Kx0UtYFw=
10971097
github.com/instill-ai/x v0.4.0-alpha h1:zQV2VLbSHjMv6gyBN/2mwwrvWk0/mJM6ZKS12AzjfQg=

pkg/handler/publichandler.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,39 @@ func (h *PublicHandler) ValidateToken(ctx context.Context, req *mgmtPB.ValidateT
853853
return &mgmtPB.ValidateTokenResponse{UserUid: userUID}, nil
854854
}
855855

856+
// GetModelTriggerCount returns the model trigger count of a given
857+
// requester within a timespan. Results are grouped by trigger status.
858+
func (h *PublicHandler) GetModelTriggerCount(ctx context.Context, req *mgmtPB.GetModelTriggerCountRequest) (*mgmtPB.GetModelTriggerCountResponse, error) {
859+
eventName := "GetModelTriggerCount"
860+
ctx, span := tracer.Start(ctx, eventName,
861+
trace.WithSpanKind(trace.SpanKindServer))
862+
defer span.End()
863+
864+
logUUID, _ := uuid.NewV4()
865+
logger, _ := logger.GetZapLogger(ctx)
866+
867+
ctxUserUID, err := h.Service.ExtractCtxUser(ctx, false)
868+
if err != nil {
869+
span.SetStatus(1, err.Error())
870+
return nil, err
871+
}
872+
873+
resp, err := h.Service.GetModelTriggerCount(ctx, req, ctxUserUID)
874+
if err != nil {
875+
span.SetStatus(1, err.Error())
876+
return nil, fmt.Errorf("fetching credit chart records: %w", err)
877+
}
878+
879+
logger.Info(string(custom_otel.NewLogMessage(
880+
span,
881+
logUUID.String(),
882+
ctxUserUID,
883+
eventName,
884+
)))
885+
886+
return resp, nil
887+
}
888+
856889
func (h *PublicHandler) ListPipelineTriggerRecords(ctx context.Context, req *mgmtPB.ListPipelineTriggerRecordsRequest) (*mgmtPB.ListPipelineTriggerRecordsResponse, error) {
857890
eventName := "ListPipelineTriggerRecords"
858891
ctx, span := tracer.Start(ctx, eventName,

pkg/repository/influx.go

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ type InfluxDB interface {
3535
QueryPipelineTriggerRecords(ctx context.Context, owner string, ownerQueryString string, pageSize int64, pageToken string, filter filtering.Filter) (pipelines []*mgmtpb.PipelineTriggerRecord, totalSize int64, nextPageToken string, err error)
3636
QueryPipelineTriggerTableRecords(ctx context.Context, owner string, ownerQueryString string, pageSize int64, pageToken string, filter filtering.Filter) (records []*mgmtpb.PipelineTriggerTableRecord, totalSize int64, nextPageToken string, err error)
3737
QueryPipelineTriggerChartRecords(ctx context.Context, owner string, ownerQueryString string, aggregationWindow int64, filter filtering.Filter) (records []*mgmtpb.PipelineTriggerChartRecord, err error)
38+
GetModelTriggerCount(ctx context.Context, p GetModelTriggerCountParams) (*mgmtpb.GetModelTriggerCountResponse, error)
3839
ListModelTriggerChartRecords(ctx context.Context, p ListModelTriggerChartRecordsParams) (*mgmtpb.ListModelTriggerChartRecordsResponse, error)
3940

4041
Bucket() string
@@ -450,6 +451,82 @@ func (i *influxDB) QueryPipelineTriggerChartRecords(ctx context.Context, owner s
450451
return records, nil
451452
}
452453

454+
const qModelTriggerCount = `
455+
from(bucket: "%s")
456+
|> range(start: %s, stop: %s)
457+
|> filter(fn: (r) => r._measurement == "model.trigger.v1" and r.requester_uid == "%s")
458+
|> filter(fn: (r) => r._field == "trigger_time")
459+
|> group(columns: ["requester_uid", "status"])
460+
|> count(column: "_value")
461+
`
462+
463+
// GetModelTriggerCountParams contains the required information to
464+
// query the model trigger count of a namespace.
465+
// TODO jvallesm: this should be defined in the service package for better
466+
// decoupling. At the moment this implies breaking an import cycle with many
467+
// dependencies.
468+
type GetModelTriggerCountParams struct {
469+
RequesterUID uuid.UUID
470+
Start time.Time
471+
Stop time.Time
472+
}
473+
474+
func (i *influxDB) GetModelTriggerCount(
475+
ctx context.Context,
476+
p GetModelTriggerCountParams,
477+
) (*mgmtpb.GetModelTriggerCountResponse, error) {
478+
l, _ := logger.GetZapLogger(ctx)
479+
l = l.With(zap.Reflect("triggerCountParams", p))
480+
481+
query := fmt.Sprintf(
482+
qModelTriggerCount,
483+
i.Bucket(),
484+
p.Start.Format(time.RFC3339Nano),
485+
p.Stop.Format(time.RFC3339Nano),
486+
p.RequesterUID.String(),
487+
)
488+
result, err := i.QueryAPI().Query(ctx, query)
489+
if err != nil {
490+
return nil, fmt.Errorf("%w: querying data from InfluxDB: %w", errdomain.ErrInvalidArgument, err)
491+
}
492+
493+
defer result.Close()
494+
495+
// We'll have one record per status.
496+
countRecords := make([]*mgmtpb.TriggerCount, 0, 2)
497+
for result.Next() {
498+
l := l.With(zap.Time("_time", result.Record().Time()))
499+
500+
statusStr := result.Record().ValueByKey("status").(string)
501+
status := mgmtpb.Status(mgmtpb.Status_value[statusStr])
502+
if status == mgmtpb.Status_STATUS_UNSPECIFIED {
503+
l.Error("Missing status on trigger count record.")
504+
}
505+
506+
count, match := result.Record().Value().(int64)
507+
if !match {
508+
l.Error("Missing count on model trigger count record.")
509+
}
510+
511+
countRecords = append(countRecords, &mgmtpb.TriggerCount{
512+
TriggerCount: int32(count),
513+
Status: &status,
514+
})
515+
}
516+
517+
if result.Err() != nil {
518+
return nil, fmt.Errorf("collecting information from model trigger count records: %w", err)
519+
}
520+
521+
if result.Record() == nil {
522+
return nil, nil
523+
}
524+
525+
return &mgmtpb.GetModelTriggerCountResponse{
526+
ModelTriggerCounts: countRecords,
527+
}, nil
528+
}
529+
453530
const qModelTriggerChartRecords = `
454531
from(bucket: "%s")
455532
|> range(start: %s, stop: %s)

pkg/service/metric.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,32 @@ func (s *service) ListPipelineTriggerChartRecords(ctx context.Context, owner *mg
164164
return pipelineTriggerChartRecords, nil
165165
}
166166

167+
func (s *service) GetModelTriggerCount(ctx context.Context, req *mgmtpb.GetModelTriggerCountRequest, ctxUserUID uuid.UUID) (*mgmtpb.GetModelTriggerCountResponse, error) {
168+
requesterUID, err := s.GrantedNamespaceUID(ctx, req.GetRequesterId(), ctxUserUID)
169+
if err != nil {
170+
return nil, fmt.Errorf("checking user permissions: %w", err)
171+
}
172+
173+
now := time.Now().UTC()
174+
p := repository.GetModelTriggerCountParams{
175+
RequesterUID: requesterUID,
176+
177+
// Default values
178+
Start: time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()),
179+
Stop: now,
180+
}
181+
182+
if req.GetStart() != nil {
183+
p.Start = req.GetStart().AsTime()
184+
}
185+
186+
if req.GetStop() != nil {
187+
p.Stop = req.GetStop().AsTime()
188+
}
189+
190+
return s.influxDB.GetModelTriggerCount(ctx, p)
191+
}
192+
167193
func (s *service) ListModelTriggerChartRecords(
168194
ctx context.Context,
169195
req *mgmtpb.ListModelTriggerChartRecordsRequest,

pkg/service/service.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ type Service interface {
7373
ListPipelineTriggerRecords(ctx context.Context, owner *mgmtpb.User, pageSize int64, pageToken string, filter filtering.Filter) ([]*mgmtpb.PipelineTriggerRecord, int64, string, error)
7474
ListPipelineTriggerTableRecords(ctx context.Context, owner *mgmtpb.User, pageSize int64, pageToken string, filter filtering.Filter) ([]*mgmtpb.PipelineTriggerTableRecord, int64, string, error)
7575
ListPipelineTriggerChartRecords(ctx context.Context, owner *mgmtpb.User, aggregationWindow int64, filter filtering.Filter) ([]*mgmtpb.PipelineTriggerChartRecord, error)
76+
GetModelTriggerCount(ctx context.Context, req *mgmtpb.GetModelTriggerCountRequest, ctxUserUID uuid.UUID) (*mgmtpb.GetModelTriggerCountResponse, error)
7677
ListModelTriggerChartRecords(ctx context.Context, req *mgmtpb.ListModelTriggerChartRecordsRequest, ctxUserUID uuid.UUID) (*mgmtpb.ListModelTriggerChartRecordsResponse, error)
7778

7879
DBUser2PBUser(ctx context.Context, dbUser *datamodel.Owner) (*mgmtpb.User, error)

0 commit comments

Comments
 (0)