diff --git a/app/cli/cmd/attestation_event.go b/app/cli/cmd/attestation_event.go index ba67890a8..6a15d90f9 100644 --- a/app/cli/cmd/attestation_event.go +++ b/app/cli/cmd/attestation_event.go @@ -16,15 +16,18 @@ package cmd import ( + "errors" "fmt" + "strconv" "strings" "github.com/chainloop-dev/chainloop/app/cli/pkg/action" + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" "github.com/spf13/cobra" ) func newAttestationEventCmd() *cobra.Command { - var step, status, message string + var step, status, message, current, total string cmd := &cobra.Command{ Use: "event", @@ -35,12 +38,17 @@ The step shows in "chainloop workflow run describe" while the attestation is in Events are progress information only. They are not part of the signed attestation. The step uses letters, digits, "_" and "-", up to 64 characters. Events with the same step are one step of the timeline. To show a material in the step that adds it, use the same step in "chainloop attestation add --step". +A long step can report its progress with --current and --total, for example 240 of 500 commits, in repeated started events. If the event cannot be recorded, the command shows a warning and exits with success, so it never breaks the pipeline.`, Example: ` # Record the start and the end of a step chainloop attestation event --step sast-scan --status started --message "Semgrep, ruleset p/ci" chainloop attestation add --name sast-report --value report.sarif --step sast-scan chainloop attestation event --step sast-scan --status succeeded + # Report the progress of a long step with repeated started events + chainloop attestation event --step classify-commits --status started --current 0 --total 500 + chainloop attestation event --step classify-commits --status started --current 240 --total 500 + # Record a step that did not run chainloop attestation event --step dast-scan --status skipped --message "no web target"`, // the arguments are checked in RunE, so that a wrong call is a warning too @@ -69,8 +77,14 @@ If the event cannot be recorded, the command shows a warning and exits with succ return nil } + progress, err := parseRunEventProgress(cmd.Flags().Changed("current"), cmd.Flags().Changed("total"), current, total) + if err != nil { + logger.Warn().Err(err).Msg("the event was not recorded") + return nil + } + a := action.NewAttestationEvent(&action.AttestationEventOpts{ActionsOpts: ActionOpts, LocalStatePath: attestationLocalStatePath}) - recorded, err := a.Run(cmd.Context(), attestationID, step, st, message) + recorded, err := a.Run(cmd.Context(), attestationID, step, st, message, progress) switch { case err != nil: logger.Warn().Err(err).Msg("the event was not recorded") @@ -87,7 +101,33 @@ If the event cannot be recorded, the command shows a warning and exits with succ cmd.Flags().StringVar(&step, "step", "", "key of the step (required), with letters, digits, _ and -, up to 64 characters") cmd.Flags().StringVar(&status, "status", "", fmt.Sprintf("status of the step (required), valid options are %s", strings.Join(action.RunEventStatuses, ", "))) cmd.Flags().StringVar(&message, "message", "", "message of the event, up to 1 KB") + // string flags, so that a value that is not a number is a warning and not a failure + cmd.Flags().StringVar(¤t, "current", "", "progress of the step: the work done so far, from 0 to --total. Requires --total") + cmd.Flags().StringVar(&total, "total", "", "progress of the step: the total work, more than 0. Requires --current") flagAttestationID(cmd) return cmd } + +// parseRunEventProgress returns the progress of the flags, or nil when neither is set. A flag +// that is set with an empty value is set, so its value is wrong. The action checks the values +// with the rules of the control plane. +func parseRunEventProgress(currentSet, totalSet bool, current, total string) (*pb.WorkflowRunEvent_Progress, error) { + if !currentSet && !totalSet { + return nil, nil + } + if !currentSet || !totalSet { + return nil, errors.New("set both --current and --total, or neither") + } + + c, err := strconv.ParseInt(current, 10, 64) + if err != nil { + return nil, fmt.Errorf("invalid --current %q: %w", current, err) + } + t, err := strconv.ParseInt(total, 10, 64) + if err != nil { + return nil, fmt.Errorf("invalid --total %q: %w", total, err) + } + + return &pb.WorkflowRunEvent_Progress{Current: c, Total: t}, nil +} diff --git a/app/cli/cmd/attestation_event_test.go b/app/cli/cmd/attestation_event_test.go index 13272ef46..2d4883e46 100644 --- a/app/cli/cmd/attestation_event_test.go +++ b/app/cli/cmd/attestation_event_test.go @@ -70,6 +70,9 @@ func TestAttestationEventCmd(t *testing.T) { statusFlag = "--status" started = "started" sastScan = "sast-scan" + currentFlag = "--current" + totalFlag = "--total" + bothFlags = "set both --current and --total, or neither" ) // remote selects remote state, so no local state is needed remote := func(args ...string) []string { return append(args, "--attestation-id", runID) } @@ -80,9 +83,11 @@ func TestAttestationEventCmd(t *testing.T) { cpErr error wantSent bool wantKey string - wantWarn string - wantInfo string - wantErr string + // wantProgress is the current and total of the sent event, nil for no progress + wantProgress []int64 + wantWarn string + wantInfo string + wantErr string }{ { name: "recorded", args: remote(stepFlag, sastScan, statusFlag, started, "--message", "Semgrep"), @@ -102,6 +107,22 @@ func TestAttestationEventCmd(t *testing.T) { {name: "missing step", args: remote(statusFlag, started), wantWarn: "--step is required"}, {name: "the removed --name flag", args: remote("--name", sastScan, statusFlag, started), wantErr: "unknown flag: --name"}, {name: "positional argument", args: remote(sastScan, statusFlag, started), wantWarn: "unexpected arguments"}, + { + name: "progress", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "240", totalFlag, "500"), + wantSent: true, wantKey: sastScan, wantProgress: []int64{240, 500}, wantInfo: "event recorded", + }, + { + name: "progress at zero", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "0", totalFlag, "500"), + wantSent: true, wantKey: sastScan, wantProgress: []int64{0, 500}, wantInfo: "event recorded", + }, + {name: "empty current and total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag+"=", totalFlag+"="), wantWarn: "invalid --current"}, + {name: "current with no total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "240"), wantWarn: bothFlags}, + {name: "total with no current", args: remote(stepFlag, sastScan, statusFlag, started, totalFlag, "500"), wantWarn: bothFlags}, + {name: "current that is not a number", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "many", totalFlag, "500"), wantWarn: "invalid --current"}, + {name: "total that is not a number", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "1", totalFlag, "1.5"), wantWarn: "invalid --total"}, + {name: "current over total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "501", totalFlag, "500"), wantWarn: "current must not be greater than total"}, + {name: "zero total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "0", totalFlag, "0"), wantWarn: "invalid progress"}, + {name: "negative current", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "-1", totalFlag, "500"), wantWarn: "invalid progress"}, } for _, tc := range testCases { @@ -129,6 +150,14 @@ func TestAttestationEventCmd(t *testing.T) { assert.Equal(t, runID, got[0].GetWorkflowRunId()) assert.Equal(t, pb.WorkflowRunEvent_TYPE_CUSTOM, got[0].GetEvent().GetType()) assert.Equal(t, tc.wantKey, got[0].GetEvent().GetKey()) + assert.Nil(t, got[0].GetEvent().GetAttributes()) + if tc.wantProgress == nil { + assert.Nil(t, got[0].GetEvent().GetProgress()) + } else { + p := got[0].GetEvent().GetProgress() + require.NotNil(t, p) + assert.Equal(t, tc.wantProgress, []int64{p.GetCurrent(), p.GetTotal()}) + } } if tc.wantWarn != "" { diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go index 0e6446808..ee3f67560 100644 --- a/app/cli/cmd/workflow_run_timeline.go +++ b/app/cli/cmd/workflow_run_timeline.go @@ -339,6 +339,11 @@ func timelineCustomStep(key string, evs []*action.RunEvent, materials []timedNod node.details = append(node.details, "took "+timelineDuration(*first.CreatedAt, *last.CreatedAt)) } + if p := timelineProgress(last); p != "" { + node.details = append(node.details, p) + } + + evs = timelineFoldProgressUpdates(evs) if len(materials) == 0 { timelineFoldEvents(node, evs) return node @@ -378,9 +383,49 @@ func timelineFoldEvents(node *timelineNode, evs []*action.RunEvent) { } } -// timelineEventNode is the line of one event of a step +// timelineEventNode is the line of one event of a step: its message and its progress, or its +// status when it has neither func timelineEventNode(e *action.RunEvent) *timelineNode { - return &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: timelineMessage(e)} + var parts []string + if e.Message != "" { + parts = append(parts, timelineMessage(e)) + } + if p := timelineProgress(e); p != "" { + parts = append(parts, p) + } + if len(parts) == 0 { + parts = append(parts, e.Status) + } + + return &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: strings.Join(parts, " · ")} +} + +// timelineProgress is the progress of an event as "current/total", or empty +func timelineProgress(e *action.RunEvent) string { + if e.Progress == nil { + return "" + } + + return fmt.Sprintf("%d/%d", e.Progress.Current, e.Progress.Total) +} + +// timelineFoldProgressUpdates keeps the last of each series of progress updates of a step. +// A progress update is a started event with progress that is not the first event of the step. +// A long step sends one every few seconds, so a step can have hundreds of them. +func timelineFoldProgressUpdates(evs []*action.RunEvent) []*action.RunEvent { + isUpdate := func(i int) bool { + return i > 0 && evs[i].Status == timelineStarted && evs[i].Progress != nil + } + + out := make([]*action.RunEvent, 0, len(evs)) + for i, e := range evs { + if isUpdate(i) && i+1 < len(evs) && isUpdate(i+1) { + continue + } + out = append(out, e) + } + + return out } func timelineDuration(from, to time.Time) string { diff --git a/app/cli/cmd/workflow_run_timeline_test.go b/app/cli/cmd/workflow_run_timeline_test.go index 3f5edc33f..3e45623a5 100644 --- a/app/cli/cmd/workflow_run_timeline_test.go +++ b/app/cli/cmd/workflow_run_timeline_test.go @@ -47,6 +47,10 @@ func TestRenderRunTimeline(t *testing.T) { e.Material.Step = step return e } + withProgress := func(e *action.RunEvent, current, total int64) *action.RunEvent { + e.Progress = &action.RunEventProgress{Current: current, Total: total} + return e + } testCases := []struct { name string @@ -185,6 +189,33 @@ func TestRenderRunTimeline(t *testing.T) { "├─ 10:01:22 ✓ added evidence `sbom`\n" + "└─ 10:02:02 ✓ pushed and stored\n", }, + { + // spec issue-3825 R-015: the step row shows the progress of its last event, and the + // progress updates in a row fold into the last one + name: "run in progress, with progress of custom steps", + events: []*action.RunEvent{ + started, + withProgress(custom(60*time.Second, "classify-commits", "started", "Classifying 500 commits"), 0, 500), + withProgress(custom(70*time.Second, "classify-commits", "started", ""), 120, 500), + withProgress(custom(80*time.Second, "classify-commits", "started", ""), 240, 500), + withProgress(custom(90*time.Second, "single", "started", ""), 3, 10), + withProgress(custom(100*time.Second, "analyze", "started", ""), 0, 10), + withProgress(custom(110*time.Second, "analyze", "started", ""), 10, 10), + custom(120*time.Second, "analyze", "succeeded", ""), + }, + progress: &action.RunProgress{}, + want: "Timeline (reported progress) · started 10:00:02 · running for 5m43s · 0 of 0 required provided\n" + + "├─ 10:00:02 ✓ initialized policies: 2 passed\n" + + "├─ 10:01:02 ● step `classify-commits` running for 4m43s · 240/500\n" + + "│ ├─ 10:01:02 ● Classifying 500 commits · 0/500\n" + + "│ └─ 10:01:22 ● 240/500\n" + + "├─ 10:01:32 ● step `single` running for 4m13s · 3/10\n" + + "├─ 10:01:42 ✓ step `analyze` took 20s\n" + + "│ ├─ 10:01:42 ● 0/10\n" + + "│ ├─ 10:01:52 ● 10/10\n" + + "│ └─ 10:02:02 ✓ succeeded\n" + + "└─ ● waiting for push\n", + }, { name: "stored run, with a custom step that never ended", events: []*action.RunEvent{ diff --git a/app/cli/documentation/cli-reference.md b/app/cli/documentation/cli-reference.md index 2ae75d804..a1673edf0 100644 --- a/app/cli/documentation/cli-reference.md +++ b/app/cli/documentation/cli-reference.md @@ -319,6 +319,7 @@ The step shows in "chainloop workflow run describe" while the attestation is in Events are progress information only. They are not part of the signed attestation. The step uses letters, digits, "_" and "-", up to 64 characters. Events with the same step are one step of the timeline. To show a material in the step that adds it, use the same step in "chainloop attestation add --step". +A long step can report its progress with --current and --total, for example 240 of 500 commits, in repeated started events. If the event cannot be recorded, the command shows a warning and exits with success, so it never breaks the pipeline. ``` @@ -333,6 +334,10 @@ chainloop attestation event --step sast-scan --status started --message "Semgrep chainloop attestation add --name sast-report --value report.sarif --step sast-scan chainloop attestation event --step sast-scan --status succeeded +Report the progress of a long step with repeated started events +chainloop attestation event --step classify-commits --status started --current 0 --total 500 +chainloop attestation event --step classify-commits --status started --current 240 --total 500 + Record a step that did not run chainloop attestation event --step dast-scan --status skipped --message "no web target" ``` @@ -341,10 +346,12 @@ Options ``` --attestation-id string Unique identifier of the in-progress attestation +--current string progress of the step: the work done so far, from 0 to --total. Requires --total -h, --help[=true|false] help for event --message string message of the event, up to 1 KB --status string status of the step (required), valid options are started, succeeded, failed, canceled, skipped --step string key of the step (required), with letters, digits, _ and -, up to 64 characters +--total string progress of the step: the total work, more than 0. Requires --current ``` Options inherited from parent commands diff --git a/app/cli/pkg/action/attestation_event.go b/app/cli/pkg/action/attestation_event.go index a21186635..6ff6ab20b 100644 --- a/app/cli/pkg/action/attestation_event.go +++ b/app/cli/pkg/action/attestation_event.go @@ -75,10 +75,24 @@ func NewAttestationEvent(cfg *AttestationEventOpts) *AttestationEvent { return &AttestationEvent{ActionsOpts: cfg.ActionsOpts, localStatePath: cfg.LocalStatePath} } -// Run records the event. It returns false, with no error, when the attestation is a dry run, -// which has no run in the control plane. The event is informational only: the caller must -// not fail the pipeline on its error. -func (action *AttestationEvent) Run(ctx context.Context, attestationID, key string, st pb.WorkflowRunEvent_Status, message string) (bool, error) { +// Run records the event, with the progress of the step when it is not nil. It returns false, +// with no error, when the attestation is a dry run, which has no run in the control plane. +// The event is informational only: the caller must not fail the pipeline on its error. +func (action *AttestationEvent) Run(ctx context.Context, attestationID, key string, st pb.WorkflowRunEvent_Status, message string, progress *pb.WorkflowRunEvent_Progress) (bool, error) { + event := &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_CUSTOM, + Key: key, + Status: st, + Message: message, + } + if progress != nil { + // check the values before anything else, with the rules of the control plane + if err := validateRunEventProgress(progress); err != nil { + return false, err + } + event.Progress = progress + } + // the caller reports the error, so the recorder does not log it again var recorder *runEventRecorder if attestationID != "" { @@ -96,12 +110,7 @@ func (action *AttestationEvent) Run(ctx context.Context, attestationID, key stri recorder = newRunEventRecorderFromState(action.CPConnection, state, zerolog.Nop()) } - if err := recorder.Record(ctx, &pb.WorkflowRunEvent{ - Type: pb.WorkflowRunEvent_TYPE_CUSTOM, - Key: key, - Status: st, - Message: message, - }); err != nil { + if err := recorder.Record(ctx, event); err != nil { return false, err } diff --git a/app/cli/pkg/action/attestation_event_test.go b/app/cli/pkg/action/attestation_event_test.go index 10da26d1e..3617cb90b 100644 --- a/app/cli/pkg/action/attestation_event_test.go +++ b/app/cli/pkg/action/attestation_event_test.go @@ -85,7 +85,7 @@ func TestAttestationEvent(t *testing.T) { st, err := ParseRunEventStatus(tc.status) require.NoError(t, err) - recorded, err := a.Run(context.Background(), tc.attestationID, key, st, message) + recorded, err := a.Run(context.Background(), tc.attestationID, key, st, message, nil) switch { case tc.wantErr != nil: require.ErrorIs(t, err, tc.wantErr) @@ -114,6 +114,55 @@ func TestAttestationEvent(t *testing.T) { } } +// The progress values of a custom step go in the progress of its event. Wrong values are not +// sent (spec issue-3825 R-015). +func TestAttestationEventProgress(t *testing.T) { + testCases := []struct { + name string + progress *pb.WorkflowRunEvent_Progress + wantErr string + }{ + {name: "no progress"}, + {name: "progress", progress: &pb.WorkflowRunEvent_Progress{Current: 240, Total: 500}}, + {name: "progress at zero", progress: &pb.WorkflowRunEvent_Progress{Current: 0, Total: 500}}, + {name: "progress at the total", progress: &pb.WorkflowRunEvent_Progress{Current: 500, Total: 500}}, + {name: "negative current", progress: &pb.WorkflowRunEvent_Progress{Current: -1, Total: 500}, wantErr: "current"}, + {name: "zero total", progress: &pb.WorkflowRunEvent_Progress{Current: 0, Total: 0}, wantErr: "total"}, + {name: "current over total", progress: &pb.WorkflowRunEvent_Progress{Current: 501, Total: 500}, wantErr: "current must not be greater than total"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeEventsControlPlane{} + conn := newFakeEventsConn(t, fake) + a := NewAttestationEvent(&AttestationEventOpts{ActionsOpts: &ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}}) + + // remote state, so no local state is needed + recorded, err := a.Run(context.Background(), testRunID, "classify-commits", pb.WorkflowRunEvent_STATUS_STARTED, "", tc.progress) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + assert.False(t, recorded) + assert.Empty(t, fake.received()) + return + } + + require.NoError(t, err) + assert.True(t, recorded) + got := fake.received() + require.Len(t, got, 1) + assert.Nil(t, got[0].GetEvent().GetAttributes()) + if tc.progress == nil { + assert.Nil(t, got[0].GetEvent().GetProgress()) + return + } + p := got[0].GetEvent().GetProgress() + require.NotNil(t, p) + assert.Equal(t, tc.progress.GetCurrent(), p.GetCurrent()) + assert.Equal(t, tc.progress.GetTotal(), p.GetTotal()) + }) + } +} + // A dry run has no run in the control plane, so nothing is sent func TestAttestationEventDryRun(t *testing.T) { fake := &fakeEventsControlPlane{} @@ -131,7 +180,7 @@ func TestAttestationEventDryRun(t *testing.T) { })) a := NewAttestationEvent(&AttestationEventOpts{ActionsOpts: &ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}, LocalStatePath: statePath}) - recorded, err := a.Run(context.Background(), "", "sast-scan", pb.WorkflowRunEvent_STATUS_STARTED, "") + recorded, err := a.Run(context.Background(), "", "sast-scan", pb.WorkflowRunEvent_STATUS_STARTED, "", nil) require.NoError(t, err) assert.False(t, recorded) assert.Empty(t, fake.received()) diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index ce53b750a..6c5487c60 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -70,6 +70,15 @@ func validateRunEventStepKey(step string) error { return protovalidate.Validate(&pb.WorkflowRunEvent_MaterialAttributes{Step: step}) } +// validateRunEventProgress checks the progress of a custom event with the rules of the control plane +func validateRunEventProgress(p *pb.WorkflowRunEvent_Progress) error { + if err := protovalidate.Validate(p); err != nil { + return fmt.Errorf("invalid progress: %w", err) + } + + return nil +} + // runEventRecorder sends progress events of an attestation to the control plane. // Events are informational only: callers must never stop the attestation on its error. // It turns itself off for the rest of the command when the control plane does not know the call. diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index 91da643da..61208de68 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -536,6 +536,14 @@ type RunEvent struct { Message string `json:"message,omitempty"` Attestation *RunEventAttestation `json:"attestation,omitempty"` Material *RunEventMaterial `json:"material,omitempty"` + // Progress of the step, from repeated started events + Progress *RunEventProgress `json:"progress,omitempty"` +} + +// RunEventProgress is the progress of a step, for example 240 of 500 commits +type RunEventProgress struct { + Current int64 `json:"current"` + Total int64 `json:"total"` } type RunEventAttestation struct { @@ -640,6 +648,10 @@ func pbRunEventToAction(in *pb.WorkflowRunEvent) *RunEvent { } } + if p := in.GetProgress(); p != nil { + out.Progress = &RunEventProgress{Current: p.GetCurrent(), Total: p.GetTotal()} + } + return out } diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index 85fa7e3cb..9e598a9c5 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -253,3 +253,23 @@ func TestWorkflowRunDescribeEvents(t *testing.T) { }) } } + +// The progress of a step reaches the describe output (spec issue-3825 R-015) +func TestPBRunEventToActionProgress(t *testing.T) { + testCases := []struct { + name string + progress *pb.WorkflowRunEvent_Progress + want *RunEventProgress + }{ + {name: "no progress"}, + {name: "progress", progress: &pb.WorkflowRunEvent_Progress{Current: 240, Total: 500}, want: &RunEventProgress{Current: 240, Total: 500}}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + in := &pb.WorkflowRunEvent{Type: pb.WorkflowRunEvent_TYPE_CUSTOM, Key: "classify-commits", Status: pb.WorkflowRunEvent_STATUS_STARTED, Progress: tc.progress} + + assert.Equal(t, tc.want, pbRunEventToAction(in).Progress) + }) + } +} diff --git a/app/controlplane/api/controlplane/v1/workflow_run.pb.go b/app/controlplane/api/controlplane/v1/workflow_run.pb.go index e68422a0f..04386e293 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -144,7 +144,7 @@ const ( WorkflowRunEvent_TYPE_ATTESTATION WorkflowRunEvent_Type = 1 WorkflowRunEvent_TYPE_MATERIAL WorkflowRunEvent_Type = 2 // A step that the pipeline records with chainloop attestation event. It has no attributes, - // and its key has the format of an annotation name, up to 64 characters. + // and it can have a progress. Its key has the format of an annotation name, up to 64 characters. WorkflowRunEvent_TYPE_CUSTOM WorkflowRunEvent_Type = 4 ) @@ -1327,6 +1327,9 @@ type WorkflowRunEvent struct { Key string `protobuf:"bytes,5,opt,name=key,proto3" json:"key,omitempty"` Status WorkflowRunEvent_Status `protobuf:"varint,6,opt,name=status,proto3,enum=controlplane.v1.WorkflowRunEvent_Status" json:"status,omitempty"` Message string `protobuf:"bytes,7,opt,name=message,proto3" json:"message,omitempty"` + // Progress of the step, for example 240 of 500 commits. A step reports its progress with + // repeated started events. Optional. Today only custom events accept it. + Progress *WorkflowRunEvent_Progress `protobuf:"bytes,8,opt,name=progress,proto3" json:"progress,omitempty"` // Types that are valid to be assigned to Attributes: // // *WorkflowRunEvent_Attestation @@ -1415,6 +1418,13 @@ func (x *WorkflowRunEvent) GetMessage() string { return "" } +func (x *WorkflowRunEvent) GetProgress() *WorkflowRunEvent_Progress { + if x != nil { + return x.Progress + } + return nil +} + func (x *WorkflowRunEvent) GetAttributes() isWorkflowRunEvent_Attributes { if x != nil { return x.Attributes @@ -2578,6 +2588,58 @@ func (x *WorkflowRunEvent_MaterialAttributes) GetStep() string { return "" } +type WorkflowRunEvent_Progress struct { + state protoimpl.MessageState `protogen:"open.v1"` + Current int64 `protobuf:"varint,1,opt,name=current,proto3" json:"current,omitempty"` + Total int64 `protobuf:"varint,2,opt,name=total,proto3" json:"total,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunEvent_Progress) Reset() { + *x = WorkflowRunEvent_Progress{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunEvent_Progress) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunEvent_Progress) ProtoMessage() {} + +func (x *WorkflowRunEvent_Progress) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunEvent_Progress.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent_Progress) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 3} +} + +func (x *WorkflowRunEvent_Progress) GetCurrent() int64 { + if x != nil { + return x.Current + } + return 0 +} + +func (x *WorkflowRunEvent_Progress) GetTotal() int64 { + if x != nil { + return x.Total + } + return 0 +} + type WorkflowRunEvent_PolicyCounts struct { state protoimpl.MessageState `protogen:"open.v1"` Evaluated int32 `protobuf:"varint,1,opt,name=evaluated,proto3" json:"evaluated,omitempty"` @@ -2591,7 +2653,7 @@ type WorkflowRunEvent_PolicyCounts struct { func (x *WorkflowRunEvent_PolicyCounts) Reset() { *x = WorkflowRunEvent_PolicyCounts{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2603,7 +2665,7 @@ func (x *WorkflowRunEvent_PolicyCounts) String() string { func (*WorkflowRunEvent_PolicyCounts) ProtoMessage() {} func (x *WorkflowRunEvent_PolicyCounts) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2616,7 +2678,7 @@ func (x *WorkflowRunEvent_PolicyCounts) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunEvent_PolicyCounts.ProtoReflect.Descriptor instead. func (*WorkflowRunEvent_PolicyCounts) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 3} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 4} } func (x *WorkflowRunEvent_PolicyCounts) GetEvaluated() int32 { @@ -2674,7 +2736,7 @@ type WorkflowRunProgress_Material struct { func (x *WorkflowRunProgress_Material) Reset() { *x = WorkflowRunProgress_Material{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2686,7 +2748,7 @@ func (x *WorkflowRunProgress_Material) String() string { func (*WorkflowRunProgress_Material) ProtoMessage() {} func (x *WorkflowRunProgress_Material) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2778,7 +2840,7 @@ type WorkflowRunServiceViewResponse_Result struct { func (x *WorkflowRunServiceViewResponse_Result) Reset() { *x = WorkflowRunServiceViewResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2790,7 +2852,7 @@ func (x *WorkflowRunServiceViewResponse_Result) String() string { func (*WorkflowRunServiceViewResponse_Result) ProtoMessage() {} func (x *WorkflowRunServiceViewResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[37] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2846,7 +2908,7 @@ type WorkflowRunServiceViewResponse_VerificationResult struct { func (x *WorkflowRunServiceViewResponse_VerificationResult) Reset() { *x = WorkflowRunServiceViewResponse_VerificationResult{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[37] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2858,7 +2920,7 @@ func (x *WorkflowRunServiceViewResponse_VerificationResult) String() string { func (*WorkflowRunServiceViewResponse_VerificationResult) ProtoMessage() {} func (x *WorkflowRunServiceViewResponse_VerificationResult) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[37] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[38] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2898,7 +2960,7 @@ type AttestationServiceGetUploadCredsResponse_Result struct { func (x *AttestationServiceGetUploadCredsResponse_Result) Reset() { *x = AttestationServiceGetUploadCredsResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[38] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2910,7 +2972,7 @@ func (x *AttestationServiceGetUploadCredsResponse_Result) String() string { func (*AttestationServiceGetUploadCredsResponse_Result) ProtoMessage() {} func (x *AttestationServiceGetUploadCredsResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[38] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[39] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3029,7 +3091,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "$AttestationServiceRecordEventRequest\x120\n" + "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\x12?\n" + "\x05event\x18\x02 \x01(\v2!.controlplane.v1.WorkflowRunEventB\x06\xbaH\x03\xc8\x01\x01R\x05event\"'\n" + - "%AttestationServiceRecordEventResponse\"\xa3\x10\n" + + "%AttestationServiceRecordEventResponse\"\xa1\x12\n" + "\x10WorkflowRunEvent\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x129\n" + "\n" + @@ -3041,7 +3103,8 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\xbaH\ar\x05\x10\x01\x18\x80\x01R\x03key\x12L\n" + "\x06status\x18\x06 \x01(\x0e2(.controlplane.v1.WorkflowRunEvent.StatusB\n" + "\xbaH\a\x82\x01\x04\x10\x01 \x00R\x06status\x12\"\n" + - "\amessage\x18\a \x01(\tB\b\xbaH\x05r\x03(\x80\bR\amessage\x12[\n" + + "\amessage\x18\a \x01(\tB\b\xbaH\x05r\x03(\x80\bR\amessage\x12F\n" + + "\bprogress\x18\b \x01(\v2*.controlplane.v1.WorkflowRunEvent.ProgressR\bprogress\x12[\n" + "\vattestation\x18\n" + " \x01(\v27.controlplane.v1.WorkflowRunEvent.AttestationAttributesH\x00R\vattestation\x12R\n" + "\bmaterial\x18\v \x01(\v24.controlplane.v1.WorkflowRunEvent.MaterialAttributesH\x00R\bmaterial\x1a\xdf\x03\n" + @@ -3070,7 +3133,11 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "inContract\x12,\n" + "\x12added_by_collector\x18\x06 \x01(\bR\x10addedByCollector\x12J\n" + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x12%\n" + - "\x04step\x18\b \x01(\tB\x11\xbaH\x0er\f\x18@2\b^[\\w-]*$R\x04step\x1a\xb8\x01\n" + + "\x04step\x18\b \x01(\tB\x11\xbaH\x0er\f\x18@2\b^[\\w-]*$R\x04step\x1a\xb3\x01\n" + + "\bProgress\x12!\n" + + "\acurrent\x18\x01 \x01(\x03B\a\xbaH\x04\"\x02(\x00R\acurrent\x12\x1d\n" + + "\x05total\x18\x02 \x01(\x03B\a\xbaH\x04\"\x02 \x00R\x05total:e\xbaHb\x1a`\n" + + "\x1aprogress_current_lte_total\x12¤t must not be greater than total\x1a\x1athis.current <= this.total\x1a\xb8\x01\n" + "\fPolicyCounts\x12\x1c\n" + "\tevaluated\x18\x01 \x01(\x05R\tevaluated\x12\x16\n" + "\x06passed\x18\x02 \x01(\x05R\x06passed\x12\x1a\n" + @@ -3198,7 +3265,7 @@ func file_controlplane_v1_workflow_run_proto_rawDescGZIP() []byte { } var file_controlplane_v1_workflow_run_proto_enumTypes = make([]protoimpl.EnumInfo, 6) -var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 39) +var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 40) var file_controlplane_v1_workflow_run_proto_goTypes = []any{ (AttestationServiceCancelRequest_TriggerType)(0), // 0: controlplane.v1.AttestationServiceCancelRequest.TriggerType (WorkflowRunEvent_Source)(0), // 1: controlplane.v1.WorkflowRunEvent.Source @@ -3240,101 +3307,103 @@ var file_controlplane_v1_workflow_run_proto_goTypes = []any{ (*WorkflowRunEvent_AttestationAttributes)(nil), // 37: controlplane.v1.WorkflowRunEvent.AttestationAttributes (*WorkflowRunEvent_ExpectedMaterial)(nil), // 38: controlplane.v1.WorkflowRunEvent.ExpectedMaterial (*WorkflowRunEvent_MaterialAttributes)(nil), // 39: controlplane.v1.WorkflowRunEvent.MaterialAttributes - (*WorkflowRunEvent_PolicyCounts)(nil), // 40: controlplane.v1.WorkflowRunEvent.PolicyCounts - (*WorkflowRunProgress_Material)(nil), // 41: controlplane.v1.WorkflowRunProgress.Material - (*WorkflowRunServiceViewResponse_Result)(nil), // 42: controlplane.v1.WorkflowRunServiceViewResponse.Result - (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 43: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 44: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - (*WorkflowItem)(nil), // 45: controlplane.v1.WorkflowItem - (*v1.Policy)(nil), // 46: workflowcontract.v1.Policy - (*v1.PolicyGroup)(nil), // 47: workflowcontract.v1.PolicyGroup - (v1.CraftingSchema_Runner_RunnerType)(0), // 48: workflowcontract.v1.CraftingSchema.Runner.RunnerType - (*timestamppb.Timestamp)(nil), // 49: google.protobuf.Timestamp - (RunStatus)(0), // 50: controlplane.v1.RunStatus - (PolicyViolationsFilter)(0), // 51: controlplane.v1.PolicyViolationsFilter - (PolicyStatusFilter)(0), // 52: controlplane.v1.PolicyStatusFilter - (PolicyGatesFilter)(0), // 53: controlplane.v1.PolicyGatesFilter - (*CursorPaginationRequest)(nil), // 54: controlplane.v1.CursorPaginationRequest - (*WorkflowRunItem)(nil), // 55: controlplane.v1.WorkflowRunItem - (*CursorPaginationResponse)(nil), // 56: controlplane.v1.CursorPaginationResponse - (*WorkflowContractVersionItem)(nil), // 57: controlplane.v1.WorkflowContractVersionItem - (*AttestationItem)(nil), // 58: controlplane.v1.AttestationItem - (*CASBackendItem)(nil), // 59: controlplane.v1.CASBackendItem + (*WorkflowRunEvent_Progress)(nil), // 40: controlplane.v1.WorkflowRunEvent.Progress + (*WorkflowRunEvent_PolicyCounts)(nil), // 41: controlplane.v1.WorkflowRunEvent.PolicyCounts + (*WorkflowRunProgress_Material)(nil), // 42: controlplane.v1.WorkflowRunProgress.Material + (*WorkflowRunServiceViewResponse_Result)(nil), // 43: controlplane.v1.WorkflowRunServiceViewResponse.Result + (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 44: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 45: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + (*WorkflowItem)(nil), // 46: controlplane.v1.WorkflowItem + (*v1.Policy)(nil), // 47: workflowcontract.v1.Policy + (*v1.PolicyGroup)(nil), // 48: workflowcontract.v1.PolicyGroup + (v1.CraftingSchema_Runner_RunnerType)(0), // 49: workflowcontract.v1.CraftingSchema.Runner.RunnerType + (*timestamppb.Timestamp)(nil), // 50: google.protobuf.Timestamp + (RunStatus)(0), // 51: controlplane.v1.RunStatus + (PolicyViolationsFilter)(0), // 52: controlplane.v1.PolicyViolationsFilter + (PolicyStatusFilter)(0), // 53: controlplane.v1.PolicyStatusFilter + (PolicyGatesFilter)(0), // 54: controlplane.v1.PolicyGatesFilter + (*CursorPaginationRequest)(nil), // 55: controlplane.v1.CursorPaginationRequest + (*WorkflowRunItem)(nil), // 56: controlplane.v1.WorkflowRunItem + (*CursorPaginationResponse)(nil), // 57: controlplane.v1.CursorPaginationResponse + (*WorkflowContractVersionItem)(nil), // 58: controlplane.v1.WorkflowContractVersionItem + (*AttestationItem)(nil), // 59: controlplane.v1.AttestationItem + (*CASBackendItem)(nil), // 60: controlplane.v1.CASBackendItem } var file_controlplane_v1_workflow_run_proto_depIdxs = []int32{ - 45, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem - 46, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy + 46, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem + 47, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy 10, // 2: controlplane.v1.AttestationServiceGetPolicyResponse.reference:type_name -> controlplane.v1.RemotePolicyReference - 47, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup + 48, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup 10, // 4: controlplane.v1.AttestationServiceGetPolicyGroupResponse.reference:type_name -> controlplane.v1.RemotePolicyReference 33, // 5: controlplane.v1.AttestationServiceGetContractResponse.result:type_name -> controlplane.v1.AttestationServiceGetContractResponse.Result - 48, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType + 49, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType 34, // 7: controlplane.v1.AttestationServiceInitResponse.result:type_name -> controlplane.v1.AttestationServiceInitResponse.Result 36, // 8: controlplane.v1.AttestationServiceStoreResponse.result:type_name -> controlplane.v1.AttestationServiceStoreResponse.Result 0, // 9: controlplane.v1.AttestationServiceCancelRequest.trigger:type_name -> controlplane.v1.AttestationServiceCancelRequest.TriggerType 23, // 10: controlplane.v1.AttestationServiceRecordEventRequest.event:type_name -> controlplane.v1.WorkflowRunEvent - 49, // 11: controlplane.v1.WorkflowRunEvent.created_at:type_name -> google.protobuf.Timestamp + 50, // 11: controlplane.v1.WorkflowRunEvent.created_at:type_name -> google.protobuf.Timestamp 1, // 12: controlplane.v1.WorkflowRunEvent.source:type_name -> controlplane.v1.WorkflowRunEvent.Source 2, // 13: controlplane.v1.WorkflowRunEvent.type:type_name -> controlplane.v1.WorkflowRunEvent.Type 3, // 14: controlplane.v1.WorkflowRunEvent.status:type_name -> controlplane.v1.WorkflowRunEvent.Status - 37, // 15: controlplane.v1.WorkflowRunEvent.attestation:type_name -> controlplane.v1.WorkflowRunEvent.AttestationAttributes - 39, // 16: controlplane.v1.WorkflowRunEvent.material:type_name -> controlplane.v1.WorkflowRunEvent.MaterialAttributes - 50, // 17: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus - 51, // 18: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter - 52, // 19: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter - 53, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter - 54, // 21: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest - 55, // 22: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem - 56, // 23: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse - 29, // 24: controlplane.v1.WorkflowRunServiceGetProgressResponse.progress:type_name -> controlplane.v1.WorkflowRunProgress - 23, // 25: controlplane.v1.WorkflowRunServiceGetProgressResponse.events:type_name -> controlplane.v1.WorkflowRunEvent - 41, // 26: controlplane.v1.WorkflowRunProgress.materials:type_name -> controlplane.v1.WorkflowRunProgress.Material - 40, // 27: controlplane.v1.WorkflowRunProgress.attestation_policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 42, // 28: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result - 44, // 29: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - 45, // 30: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem - 57, // 31: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem - 55, // 32: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 35, // 33: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions - 40, // 34: controlplane.v1.WorkflowRunEvent.AttestationAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 38, // 35: controlplane.v1.WorkflowRunEvent.AttestationAttributes.expected_materials:type_name -> controlplane.v1.WorkflowRunEvent.ExpectedMaterial - 40, // 36: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 4, // 37: controlplane.v1.WorkflowRunProgress.Material.requirement:type_name -> controlplane.v1.WorkflowRunProgress.Requirement - 5, // 38: controlplane.v1.WorkflowRunProgress.Material.status:type_name -> controlplane.v1.WorkflowRunProgress.Status - 40, // 39: controlplane.v1.WorkflowRunProgress.Material.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 55, // 40: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 58, // 41: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem - 43, // 42: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - 59, // 43: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem - 6, // 44: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest - 13, // 45: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest - 15, // 46: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest - 17, // 47: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest - 31, // 48: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest - 19, // 49: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest - 21, // 50: controlplane.v1.AttestationService.RecordEvent:input_type -> controlplane.v1.AttestationServiceRecordEventRequest - 8, // 51: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest - 11, // 52: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest - 24, // 53: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest - 26, // 54: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest - 27, // 55: controlplane.v1.WorkflowRunService.GetProgress:input_type -> controlplane.v1.WorkflowRunServiceGetProgressRequest - 7, // 56: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse - 14, // 57: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse - 16, // 58: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse - 18, // 59: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse - 32, // 60: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse - 20, // 61: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse - 22, // 62: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse - 9, // 63: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse - 12, // 64: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse - 25, // 65: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse - 30, // 66: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse - 28, // 67: controlplane.v1.WorkflowRunService.GetProgress:output_type -> controlplane.v1.WorkflowRunServiceGetProgressResponse - 56, // [56:68] is the sub-list for method output_type - 44, // [44:56] is the sub-list for method input_type - 44, // [44:44] is the sub-list for extension type_name - 44, // [44:44] is the sub-list for extension extendee - 0, // [0:44] is the sub-list for field type_name + 40, // 15: controlplane.v1.WorkflowRunEvent.progress:type_name -> controlplane.v1.WorkflowRunEvent.Progress + 37, // 16: controlplane.v1.WorkflowRunEvent.attestation:type_name -> controlplane.v1.WorkflowRunEvent.AttestationAttributes + 39, // 17: controlplane.v1.WorkflowRunEvent.material:type_name -> controlplane.v1.WorkflowRunEvent.MaterialAttributes + 51, // 18: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus + 52, // 19: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter + 53, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter + 54, // 21: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter + 55, // 22: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest + 56, // 23: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem + 57, // 24: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse + 29, // 25: controlplane.v1.WorkflowRunServiceGetProgressResponse.progress:type_name -> controlplane.v1.WorkflowRunProgress + 23, // 26: controlplane.v1.WorkflowRunServiceGetProgressResponse.events:type_name -> controlplane.v1.WorkflowRunEvent + 42, // 27: controlplane.v1.WorkflowRunProgress.materials:type_name -> controlplane.v1.WorkflowRunProgress.Material + 41, // 28: controlplane.v1.WorkflowRunProgress.attestation_policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 43, // 29: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result + 45, // 30: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + 46, // 31: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem + 58, // 32: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem + 56, // 33: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 35, // 34: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions + 41, // 35: controlplane.v1.WorkflowRunEvent.AttestationAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 38, // 36: controlplane.v1.WorkflowRunEvent.AttestationAttributes.expected_materials:type_name -> controlplane.v1.WorkflowRunEvent.ExpectedMaterial + 41, // 37: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 4, // 38: controlplane.v1.WorkflowRunProgress.Material.requirement:type_name -> controlplane.v1.WorkflowRunProgress.Requirement + 5, // 39: controlplane.v1.WorkflowRunProgress.Material.status:type_name -> controlplane.v1.WorkflowRunProgress.Status + 41, // 40: controlplane.v1.WorkflowRunProgress.Material.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 56, // 41: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 59, // 42: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem + 44, // 43: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + 60, // 44: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem + 6, // 45: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest + 13, // 46: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest + 15, // 47: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest + 17, // 48: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest + 31, // 49: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest + 19, // 50: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest + 21, // 51: controlplane.v1.AttestationService.RecordEvent:input_type -> controlplane.v1.AttestationServiceRecordEventRequest + 8, // 52: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest + 11, // 53: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest + 24, // 54: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest + 26, // 55: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest + 27, // 56: controlplane.v1.WorkflowRunService.GetProgress:input_type -> controlplane.v1.WorkflowRunServiceGetProgressRequest + 7, // 57: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse + 14, // 58: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse + 16, // 59: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse + 18, // 60: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse + 32, // 61: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse + 20, // 62: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse + 22, // 63: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse + 9, // 64: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse + 12, // 65: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse + 25, // 66: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse + 30, // 67: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse + 28, // 68: controlplane.v1.WorkflowRunService.GetProgress:output_type -> controlplane.v1.WorkflowRunServiceGetProgressResponse + 57, // [57:69] is the sub-list for method output_type + 45, // [45:57] is the sub-list for method input_type + 45, // [45:45] is the sub-list for extension type_name + 45, // [45:45] is the sub-list for extension extendee + 0, // [0:45] is the sub-list for field type_name } func init() { file_controlplane_v1_workflow_run_proto_init() } @@ -3360,7 +3429,7 @@ func file_controlplane_v1_workflow_run_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_controlplane_v1_workflow_run_proto_rawDesc), len(file_controlplane_v1_workflow_run_proto_rawDesc)), NumEnums: 6, - NumMessages: 39, + NumMessages: 40, NumExtensions: 0, NumServices: 2, }, diff --git a/app/controlplane/api/controlplane/v1/workflow_run.proto b/app/controlplane/api/controlplane/v1/workflow_run.proto index 2c4ba76bf..8bccf00a3 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -238,6 +238,9 @@ message WorkflowRunEvent { defined_only: true }]; string message = 7 [(buf.validate.field).string.max_bytes = 1024]; + // Progress of the step, for example 240 of 500 commits. A step reports its progress with + // repeated started events. Optional. Today only custom events accept it. + Progress progress = 8; oneof attributes { AttestationAttributes attestation = 10; @@ -259,7 +262,7 @@ message WorkflowRunEvent { reserved 3; reserved "TYPE_PUSH"; // A step that the pipeline records with chainloop attestation event. It has no attributes, - // and its key has the format of an annotation name, up to 64 characters. + // and it can have a progress. Its key has the format of an annotation name, up to 64 characters. TYPE_CUSTOM = 4; } @@ -312,6 +315,17 @@ message WorkflowRunEvent { }]; } + message Progress { + int64 current = 1 [(buf.validate.field).int64.gte = 0]; + int64 total = 2 [(buf.validate.field).int64.gt = 0]; + + option (buf.validate.message).cel = { + id: "progress_current_lte_total" + expression: "this.current <= this.total" + message: "current must not be greater than total" + }; + } + message PolicyCounts { int32 evaluated = 1; int32 passed = 2; diff --git a/app/controlplane/api/controlplane/v1/workflow_run_test.go b/app/controlplane/api/controlplane/v1/workflow_run_test.go index bbf29c860..8be2517f8 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run_test.go +++ b/app/controlplane/api/controlplane/v1/workflow_run_test.go @@ -91,3 +91,43 @@ func TestAttestationServiceRecordEventRequestLimits(t *testing.T) { }) } } + +// The progress values of a custom step (spec issue-3825 R-015) +func TestWorkflowRunEventCustomProgress(t *testing.T) { + progress := func(current, total int64) *v1.WorkflowRunEvent_Progress { + return &v1.WorkflowRunEvent_Progress{Current: current, Total: total} + } + + testCases := []struct { + desc string + progress *v1.WorkflowRunEvent_Progress + wantErr bool + }{ + {desc: "no attributes"}, + {desc: "progress in the middle", progress: progress(240, 500)}, + {desc: "progress at zero", progress: progress(0, 500)}, + {desc: "progress at the total", progress: progress(500, 500)}, + {desc: "negative current", progress: progress(-1, 500), wantErr: true}, + {desc: "zero total", progress: progress(0, 0), wantErr: true}, + {desc: "negative total", progress: progress(0, -1), wantErr: true}, + {desc: "current over total", progress: progress(501, 500), wantErr: true}, + // the control plane checks that only custom events have a progress + } + + validator, err := protovalidate.New() + require.NoError(t, err) + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + ev := &v1.WorkflowRunEvent{Type: v1.WorkflowRunEvent_TYPE_CUSTOM, Key: "classify-commits", Status: v1.WorkflowRunEvent_STATUS_STARTED} + ev.Progress = tc.progress + + err := validator.Validate(ev) + if tc.wantErr { + assert.Error(t, err) + return + } + assert.NoError(t, err) + }) + } +} diff --git a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts index 68eef56d5..08ad66dd7 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts @@ -1,6 +1,7 @@ /* eslint-disable */ import { grpc } from "@improbable-eng/grpc-web"; import { BrowserHeaders } from "browser-headers"; +import Long from "long"; import _m0 from "protobufjs/minimal"; import { Timestamp } from "../../google/protobuf/timestamp"; import { @@ -247,6 +248,11 @@ export interface WorkflowRunEvent { key: string; status: WorkflowRunEvent_Status; message: string; + /** + * Progress of the step, for example 240 of 500 commits. A step reports its progress with + * repeated started events. Optional. Today only custom events accept it. + */ + progress?: WorkflowRunEvent_Progress; attestation?: WorkflowRunEvent_AttestationAttributes | undefined; material?: WorkflowRunEvent_MaterialAttributes | undefined; } @@ -296,7 +302,7 @@ export enum WorkflowRunEvent_Type { TYPE_MATERIAL = 2, /** * TYPE_CUSTOM - A step that the pipeline records with chainloop attestation event. It has no attributes, - * and its key has the format of an annotation name, up to 64 characters. + * and it can have a progress. Its key has the format of an annotation name, up to 64 characters. */ TYPE_CUSTOM = 4, UNRECOGNIZED = -1, @@ -437,6 +443,11 @@ export interface WorkflowRunEvent_MaterialAttributes { step: string; } +export interface WorkflowRunEvent_Progress { + current: number; + total: number; +} + export interface WorkflowRunEvent_PolicyCounts { evaluated: number; passed: number; @@ -2459,6 +2470,7 @@ function createBaseWorkflowRunEvent(): WorkflowRunEvent { key: "", status: 0, message: "", + progress: undefined, attestation: undefined, material: undefined, }; @@ -2487,6 +2499,9 @@ export const WorkflowRunEvent = { if (message.message !== "") { writer.uint32(58).string(message.message); } + if (message.progress !== undefined) { + WorkflowRunEvent_Progress.encode(message.progress, writer.uint32(66).fork()).ldelim(); + } if (message.attestation !== undefined) { WorkflowRunEvent_AttestationAttributes.encode(message.attestation, writer.uint32(82).fork()).ldelim(); } @@ -2552,6 +2567,13 @@ export const WorkflowRunEvent = { message.message = reader.string(); continue; + case 8: + if (tag !== 66) { + break; + } + + message.progress = WorkflowRunEvent_Progress.decode(reader, reader.uint32()); + continue; case 10: if (tag !== 82) { break; @@ -2584,6 +2606,7 @@ export const WorkflowRunEvent = { key: isSet(object.key) ? String(object.key) : "", status: isSet(object.status) ? workflowRunEvent_StatusFromJSON(object.status) : 0, message: isSet(object.message) ? String(object.message) : "", + progress: isSet(object.progress) ? WorkflowRunEvent_Progress.fromJSON(object.progress) : undefined, attestation: isSet(object.attestation) ? WorkflowRunEvent_AttestationAttributes.fromJSON(object.attestation) : undefined, @@ -2600,6 +2623,8 @@ export const WorkflowRunEvent = { message.key !== undefined && (obj.key = message.key); message.status !== undefined && (obj.status = workflowRunEvent_StatusToJSON(message.status)); message.message !== undefined && (obj.message = message.message); + message.progress !== undefined && + (obj.progress = message.progress ? WorkflowRunEvent_Progress.toJSON(message.progress) : undefined); message.attestation !== undefined && (obj.attestation = message.attestation ? WorkflowRunEvent_AttestationAttributes.toJSON(message.attestation) : undefined); @@ -2621,6 +2646,9 @@ export const WorkflowRunEvent = { message.key = object.key ?? ""; message.status = object.status ?? 0; message.message = object.message ?? ""; + message.progress = (object.progress !== undefined && object.progress !== null) + ? WorkflowRunEvent_Progress.fromPartial(object.progress) + : undefined; message.attestation = (object.attestation !== undefined && object.attestation !== null) ? WorkflowRunEvent_AttestationAttributes.fromPartial(object.attestation) : undefined; @@ -3071,6 +3099,77 @@ export const WorkflowRunEvent_MaterialAttributes = { }, }; +function createBaseWorkflowRunEvent_Progress(): WorkflowRunEvent_Progress { + return { current: 0, total: 0 }; +} + +export const WorkflowRunEvent_Progress = { + encode(message: WorkflowRunEvent_Progress, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.current !== 0) { + writer.uint32(8).int64(message.current); + } + if (message.total !== 0) { + writer.uint32(16).int64(message.total); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent_Progress { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunEvent_Progress(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 8) { + break; + } + + message.current = longToNumber(reader.int64() as Long); + continue; + case 2: + if (tag !== 16) { + break; + } + + message.total = longToNumber(reader.int64() as Long); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunEvent_Progress { + return { + current: isSet(object.current) ? Number(object.current) : 0, + total: isSet(object.total) ? Number(object.total) : 0, + }; + }, + + toJSON(message: WorkflowRunEvent_Progress): unknown { + const obj: any = {}; + message.current !== undefined && (obj.current = Math.round(message.current)); + message.total !== undefined && (obj.total = Math.round(message.total)); + return obj; + }, + + create, I>>(base?: I): WorkflowRunEvent_Progress { + return WorkflowRunEvent_Progress.fromPartial(base ?? {}); + }, + + fromPartial, I>>(object: I): WorkflowRunEvent_Progress { + const message = createBaseWorkflowRunEvent_Progress(); + message.current = object.current ?? 0; + message.total = object.total ?? 0; + return message; + }, +}; + function createBaseWorkflowRunEvent_PolicyCounts(): WorkflowRunEvent_PolicyCounts { return { evaluated: 0, passed: 0, violated: 0, skipped: 0, violatedPolicies: [] }; } @@ -5049,6 +5148,18 @@ function fromJsonTimestamp(o: any): Date { } } +function longToNumber(long: Long): number { + if (long.gt(Number.MAX_SAFE_INTEGER)) { + throw new tsProtoGlobalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER"); + } + return long.toNumber(); +} + +if (_m0.util.Long !== Long) { + _m0.util.Long = Long as any; + _m0.configure(); +} + function isSet(value: any): boolean { return value !== null && value !== undefined; } diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.Progress.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.Progress.jsonschema.json new file mode 100644 index 000000000..af73cbf19 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.Progress.jsonschema.json @@ -0,0 +1,35 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.Progress.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "current": { + "anyOf": [ + { + "exclusiveMaximum": 9223372036854775808, + "minimum": 0, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ] + }, + "total": { + "anyOf": [ + { + "exclusiveMaximum": 9223372036854775808, + "exclusiveMinimum": 0, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ] + } + }, + "title": "Progress", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.Progress.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.Progress.schema.json new file mode 100644 index 000000000..da550da8c --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.Progress.schema.json @@ -0,0 +1,35 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.Progress.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "current": { + "anyOf": [ + { + "exclusiveMaximum": 9223372036854775808, + "minimum": 0, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ] + }, + "total": { + "anyOf": [ + { + "exclusiveMaximum": 9223372036854775808, + "exclusiveMinimum": 0, + "type": "integer" + }, + { + "pattern": "^-?[0-9]+$", + "type": "string" + } + ] + } + }, + "title": "Progress", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json index 253ebdd3b..e0cf0f97c 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json @@ -33,6 +33,10 @@ "maxLength": 1024, "type": "string" }, + "progress": { + "$ref": "controlplane.v1.WorkflowRunEvent.Progress.jsonschema.json", + "description": "Progress of the step, for example 240 of 500 commits. A step reports its progress with\n repeated started events. Optional. Today only custom events accept it." + }, "source": { "anyOf": [ { diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json index f02345df7..f7742f0d0 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json @@ -33,6 +33,10 @@ "maxLength": 1024, "type": "string" }, + "progress": { + "$ref": "controlplane.v1.WorkflowRunEvent.Progress.schema.json", + "description": "Progress of the step, for example 240 of 500 commits. A step reports its progress with\n repeated started events. Optional. Today only custom events accept it." + }, "source": { "anyOf": [ { diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 7caa90120..f88aac81d 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -725,6 +725,10 @@ func pbWorkflowRunEventToBiz(in *pb.WorkflowRunEvent) (*biz.WorkflowRunEvent, er }} } + if p := in.GetProgress(); p != nil { + out.Progress = &biz.WorkflowRunEventProgress{Current: p.GetCurrent(), Total: p.GetTotal()} + } + return out, nil } @@ -799,6 +803,10 @@ func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { }} } + if p := in.Progress; p != nil { + out.Progress = &pb.WorkflowRunEvent_Progress{Current: p.Current, Total: p.Total} + } + return out } diff --git a/app/controlplane/internal/service/workflowrunevent_test.go b/app/controlplane/internal/service/workflowrunevent_test.go index 6abfcc8f5..af1f79e51 100644 --- a/app/controlplane/internal/service/workflowrunevent_test.go +++ b/app/controlplane/internal/service/workflowrunevent_test.go @@ -54,3 +54,37 @@ func TestWorkflowRunEventMaterialStepRoundTrip(t *testing.T) { }) } } + +// The progress of an event goes to the control plane and back (spec issue-3825 R-015) +func TestWorkflowRunEventProgressRoundTrip(t *testing.T) { + testCases := []struct { + name string + progress *pb.WorkflowRunEvent_Progress + }{ + {name: "progress", progress: &pb.WorkflowRunEvent_Progress{Current: 240, Total: 500}}, + {name: "progress at zero", progress: &pb.WorkflowRunEvent_Progress{Current: 0, Total: 500}}, + {name: "no progress"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + ev, err := pbWorkflowRunEventToBiz(&pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_CUSTOM, + Key: "classify-commits", + Status: pb.WorkflowRunEvent_STATUS_STARTED, + Progress: tc.progress, + }) + require.NoError(t, err) + + out := bizWorkflowRunEventToPb(ev) + assert.Nil(t, out.GetAttributes()) + if tc.progress == nil { + assert.Nil(t, out.GetProgress()) + return + } + require.NotNil(t, out.GetProgress()) + assert.Equal(t, tc.progress.GetCurrent(), out.GetProgress().GetCurrent()) + assert.Equal(t, tc.progress.GetTotal(), out.GetProgress().GetTotal()) + }) + } +} diff --git a/app/controlplane/pkg/biz/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go index c7afe7fc7..9aa49f8d0 100644 --- a/app/controlplane/pkg/biz/workflowrunevent.go +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -63,7 +63,8 @@ type WorkflowRunEventType string const ( WorkflowRunEventTypeAttestation WorkflowRunEventType = "attestation" WorkflowRunEventTypeMaterial WorkflowRunEventType = "material" - // WorkflowRunEventTypeCustom is a step that the pipeline records. It has no attributes. + // WorkflowRunEventTypeCustom is a step that the pipeline records. It has no attributes, and + // it can have a progress. WorkflowRunEventTypeCustom WorkflowRunEventType = "custom" ) @@ -111,6 +112,8 @@ type WorkflowRunEvent struct { Status WorkflowRunEventStatus Message string Attributes *WorkflowRunEventAttributes + // Progress of the step. Optional. Today only custom events accept it. + Progress *WorkflowRunEventProgress } // WorkflowRunEventAttributes holds the typed attributes of an event. Only the field @@ -120,6 +123,14 @@ type WorkflowRunEventAttributes struct { Material *WorkflowRunEventMaterialAttributes `json:"material,omitempty"` } +// WorkflowRunEventProgress is the progress of a step, for example 240 of 500 commits. A step +// reports its progress with repeated started events. Current is at least 0 and at most Total, +// and Total is more than 0. +type WorkflowRunEventProgress struct { + Current int64 `json:"current"` + Total int64 `json:"total"` +} + type WorkflowRunEventAttestationAttributes struct { ContractName string `json:"contract_name,omitempty"` ContractRevision int32 `json:"contract_revision,omitempty"` @@ -245,6 +256,15 @@ func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { } } + if p := ev.Progress; p != nil { + if ev.Type != WorkflowRunEventTypeCustom { + return NewErrValidationStr("only custom events can have a progress") + } + if p.Current < 0 || p.Total <= 0 || p.Current > p.Total { + return NewErrValidationStr(fmt.Sprintf("invalid progress %d/%d: current must be from 0 to total, and total more than 0", p.Current, p.Total)) + } + } + return nil } diff --git a/app/controlplane/pkg/biz/workflowrunevent_test.go b/app/controlplane/pkg/biz/workflowrunevent_test.go index 72cf5ce0d..54bbc43aa 100644 --- a/app/controlplane/pkg/biz/workflowrunevent_test.go +++ b/app/controlplane/pkg/biz/workflowrunevent_test.go @@ -31,6 +31,8 @@ const ( sbomKey = "chainloop.material.sbom" shortText = "abc" errCustomKey = "custom event key" + classifyKey = "classify-commits" + errProgress = "invalid progress" ) func TestValidateWorkflowRunEvent(t *testing.T) { @@ -39,6 +41,9 @@ func TestValidateWorkflowRunEvent(t *testing.T) { return &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom", Step: step}} } attestation := &WorkflowRunEventAttributes{Attestation: &WorkflowRunEventAttestationAttributes{ContractName: "build"}} + progress := func(current, total int64) *WorkflowRunEventProgress { + return &WorkflowRunEventProgress{Current: current, Total: total} + } testCases := []struct { name string @@ -142,6 +147,43 @@ func TestValidateWorkflowRunEvent(t *testing.T) { event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Message: strings.Repeat("a", MaxWorkflowRunEventMessageBytes+1)}, wantErr: "longer than", }, + { + name: "custom event with progress", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: classifyKey, Progress: progress(240, 500)}, + }, + { + name: "custom event with progress at zero", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: classifyKey, Progress: progress(0, 500)}, + }, + { + name: "custom event with progress at the total", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: classifyKey, Progress: progress(500, 500)}, + }, + { + name: "progress with a negative current", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: classifyKey, Progress: progress(-1, 500)}, + wantErr: errProgress, + }, + { + name: "progress with a zero total", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: classifyKey, Progress: progress(0, 0)}, + wantErr: errProgress, + }, + { + name: "progress with current over total", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: classifyKey, Progress: progress(501, 500)}, + wantErr: errProgress, + }, + { + name: "progress on a material event", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Progress: progress(1, 2)}, + wantErr: "only custom events", + }, + { + name: "progress on an attestation event", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeAttestation, Key: WorkflowRunEventKeyAttestation, Progress: progress(1, 2)}, + wantErr: "only custom events", + }, } for _, tc := range testCases { diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/20261203225510.sql b/app/controlplane/pkg/data/ent/migrate/migrations/20261203225510.sql new file mode 100644 index 000000000..fcb4ee37b --- /dev/null +++ b/app/controlplane/pkg/data/ent/migrate/migrations/20261203225510.sql @@ -0,0 +1,2 @@ +-- Modify "workflow_run_events" table +ALTER TABLE "workflow_run_events" ADD COLUMN "progress" jsonb NULL; diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum index 03ea51b78..f73001d48 100644 --- a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum +++ b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum @@ -1,4 +1,4 @@ -h1:DigGqFAgl0FJLX+iyKT/UPGDFD55/urgtPYLjHSnmug= +h1:5PoGkbvde8KM6bPN4gVMsWC7mKlJDhewbko7CK2QFEk= 20230706165452_init-schema.sql h1:VvqbNFEQnCvUVyj2iDYVQQxDM0+sSXqocpt/5H64k8M= 20230710111950-cas-backend.sql h1:A8iBuSzZIEbdsv9ipBtscZQuaBp3V5/VMw7eZH6GX+g= 20230712094107-cas-backends-workflow-runs.sql h1:a5rzxpVGyd56nLRSsKrmCFc9sebg65RWzLghKHh5xvI= @@ -150,3 +150,4 @@ h1:DigGqFAgl0FJLX+iyKT/UPGDFD55/urgtPYLjHSnmug= 20261123100446.sql h1:m6G8YK7prIatRFKx10ZE1mL3qkL7W1pAcQm3vDwML24= 20261130191056.sql h1:pIT59TQwRU/ZBsSdBJjSEE4dOjbmclXbLWI4Upt7X+0= 20261202203348.sql h1:L/mdfquftw4+wozHjtyycIf9SIrO32gkNaI6dzIsAoM= +20261203225510.sql h1:qd7gMFcF20qPzFqNI3WlY+Ql3AW5zX9Yu3hzUsyHMPo= diff --git a/app/controlplane/pkg/data/ent/migrate/schema.go b/app/controlplane/pkg/data/ent/migrate/schema.go index a31179367..b5986f1b2 100644 --- a/app/controlplane/pkg/data/ent/migrate/schema.go +++ b/app/controlplane/pkg/data/ent/migrate/schema.go @@ -1006,6 +1006,7 @@ var ( {Name: "status", Type: field.TypeEnum, Enums: []string{"started", "succeeded", "failed", "canceled", "skipped"}}, {Name: "message", Type: field.TypeString, Nullable: true, Size: 2147483647}, {Name: "attributes", Type: field.TypeJSON, Nullable: true}, + {Name: "progress", Type: field.TypeJSON, Nullable: true}, {Name: "workflow_run_id", Type: field.TypeUUID}, } // WorkflowRunEventsTable holds the schema information for the "workflow_run_events" table. @@ -1016,7 +1017,7 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "workflow_run_events_workflow_runs_events", - Columns: []*schema.Column{WorkflowRunEventsColumns[8]}, + Columns: []*schema.Column{WorkflowRunEventsColumns[9]}, RefColumns: []*schema.Column{WorkflowRunsColumns[0]}, OnDelete: schema.Cascade, }, @@ -1025,7 +1026,7 @@ var ( { Name: "workflowrunevent_workflow_run_id_created_at", Unique: false, - Columns: []*schema.Column{WorkflowRunEventsColumns[8], WorkflowRunEventsColumns[1]}, + Columns: []*schema.Column{WorkflowRunEventsColumns[9], WorkflowRunEventsColumns[1]}, }, }, } diff --git a/app/controlplane/pkg/data/ent/mutation.go b/app/controlplane/pkg/data/ent/mutation.go index 0e13e5d0d..f180787ab 100644 --- a/app/controlplane/pkg/data/ent/mutation.go +++ b/app/controlplane/pkg/data/ent/mutation.go @@ -22516,6 +22516,7 @@ type WorkflowRunEventMutation struct { status *biz.WorkflowRunEventStatus message *string attributes **biz.WorkflowRunEventAttributes + progress **biz.WorkflowRunEventProgress clearedFields map[string]struct{} workflow_run *uuid.UUID clearedworkflow_run bool @@ -22942,6 +22943,55 @@ func (m *WorkflowRunEventMutation) ResetAttributes() { delete(m.clearedFields, workflowrunevent.FieldAttributes) } +// SetProgress sets the "progress" field. +func (m *WorkflowRunEventMutation) SetProgress(brep *biz.WorkflowRunEventProgress) { + m.progress = &brep +} + +// Progress returns the value of the "progress" field in the mutation. +func (m *WorkflowRunEventMutation) Progress() (r *biz.WorkflowRunEventProgress, exists bool) { + v := m.progress + if v == nil { + return + } + return *v, true +} + +// OldProgress returns the old "progress" field's value of the WorkflowRunEvent entity. +// If the WorkflowRunEvent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WorkflowRunEventMutation) OldProgress(ctx context.Context) (v *biz.WorkflowRunEventProgress, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProgress is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProgress requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProgress: %w", err) + } + return oldValue.Progress, nil +} + +// ClearProgress clears the value of the "progress" field. +func (m *WorkflowRunEventMutation) ClearProgress() { + m.progress = nil + m.clearedFields[workflowrunevent.FieldProgress] = struct{}{} +} + +// ProgressCleared returns if the "progress" field was cleared in this mutation. +func (m *WorkflowRunEventMutation) ProgressCleared() bool { + _, ok := m.clearedFields[workflowrunevent.FieldProgress] + return ok +} + +// ResetProgress resets all changes to the "progress" field. +func (m *WorkflowRunEventMutation) ResetProgress() { + m.progress = nil + delete(m.clearedFields, workflowrunevent.FieldProgress) +} + // ClearWorkflowRun clears the "workflow_run" edge to the WorkflowRun entity. func (m *WorkflowRunEventMutation) ClearWorkflowRun() { m.clearedworkflow_run = true @@ -23003,7 +23053,7 @@ func (m *WorkflowRunEventMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *WorkflowRunEventMutation) Fields() []string { - fields := make([]string, 0, 8) + fields := make([]string, 0, 9) if m.workflow_run != nil { fields = append(fields, workflowrunevent.FieldWorkflowRunID) } @@ -23028,6 +23078,9 @@ func (m *WorkflowRunEventMutation) Fields() []string { if m.attributes != nil { fields = append(fields, workflowrunevent.FieldAttributes) } + if m.progress != nil { + fields = append(fields, workflowrunevent.FieldProgress) + } return fields } @@ -23052,6 +23105,8 @@ func (m *WorkflowRunEventMutation) Field(name string) (ent.Value, bool) { return m.Message() case workflowrunevent.FieldAttributes: return m.Attributes() + case workflowrunevent.FieldProgress: + return m.Progress() } return nil, false } @@ -23077,6 +23132,8 @@ func (m *WorkflowRunEventMutation) OldField(ctx context.Context, name string) (e return m.OldMessage(ctx) case workflowrunevent.FieldAttributes: return m.OldAttributes(ctx) + case workflowrunevent.FieldProgress: + return m.OldProgress(ctx) } return nil, fmt.Errorf("unknown WorkflowRunEvent field %s", name) } @@ -23142,6 +23199,13 @@ func (m *WorkflowRunEventMutation) SetField(name string, value ent.Value) error } m.SetAttributes(v) return nil + case workflowrunevent.FieldProgress: + v, ok := value.(*biz.WorkflowRunEventProgress) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProgress(v) + return nil } return fmt.Errorf("unknown WorkflowRunEvent field %s", name) } @@ -23178,6 +23242,9 @@ func (m *WorkflowRunEventMutation) ClearedFields() []string { if m.FieldCleared(workflowrunevent.FieldAttributes) { fields = append(fields, workflowrunevent.FieldAttributes) } + if m.FieldCleared(workflowrunevent.FieldProgress) { + fields = append(fields, workflowrunevent.FieldProgress) + } return fields } @@ -23198,6 +23265,9 @@ func (m *WorkflowRunEventMutation) ClearField(name string) error { case workflowrunevent.FieldAttributes: m.ClearAttributes() return nil + case workflowrunevent.FieldProgress: + m.ClearProgress() + return nil } return fmt.Errorf("unknown WorkflowRunEvent nullable field %s", name) } @@ -23230,6 +23300,9 @@ func (m *WorkflowRunEventMutation) ResetField(name string) error { case workflowrunevent.FieldAttributes: m.ResetAttributes() return nil + case workflowrunevent.FieldProgress: + m.ResetProgress() + return nil } return fmt.Errorf("unknown WorkflowRunEvent field %s", name) } diff --git a/app/controlplane/pkg/data/ent/schema/workflowrunevent.go b/app/controlplane/pkg/data/ent/schema/workflowrunevent.go index fea2f1ba0..8a2920656 100644 --- a/app/controlplane/pkg/data/ent/schema/workflowrunevent.go +++ b/app/controlplane/pkg/data/ent/schema/workflowrunevent.go @@ -48,6 +48,8 @@ func (WorkflowRunEvent) Fields() []ent.Field { field.Enum("status").GoType(biz.WorkflowRunEventStatus("")).Immutable(), field.Text("message").Optional().Immutable(), field.JSON("attributes", &biz.WorkflowRunEventAttributes{}).Optional().Immutable(), + // Progress of the step, for any event type + field.JSON("progress", &biz.WorkflowRunEventProgress{}).Optional().Immutable(), } } diff --git a/app/controlplane/pkg/data/ent/workflowrunevent.go b/app/controlplane/pkg/data/ent/workflowrunevent.go index 1de2eb8fa..60fa617cd 100644 --- a/app/controlplane/pkg/data/ent/workflowrunevent.go +++ b/app/controlplane/pkg/data/ent/workflowrunevent.go @@ -37,6 +37,8 @@ type WorkflowRunEvent struct { Message string `json:"message,omitempty"` // Attributes holds the value of the "attributes" field. Attributes *biz.WorkflowRunEventAttributes `json:"attributes,omitempty"` + // Progress holds the value of the "progress" field. + Progress *biz.WorkflowRunEventProgress `json:"progress,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the WorkflowRunEventQuery when eager-loading is set. Edges WorkflowRunEventEdges `json:"edges"` @@ -68,7 +70,7 @@ func (*WorkflowRunEvent) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case workflowrunevent.FieldAttributes: + case workflowrunevent.FieldAttributes, workflowrunevent.FieldProgress: values[i] = new([]byte) case workflowrunevent.FieldSource, workflowrunevent.FieldType, workflowrunevent.FieldKey, workflowrunevent.FieldStatus, workflowrunevent.FieldMessage: values[i] = new(sql.NullString) @@ -147,6 +149,14 @@ func (_m *WorkflowRunEvent) assignValues(columns []string, values []any) error { return fmt.Errorf("unmarshal field attributes: %w", err) } } + case workflowrunevent.FieldProgress: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field progress", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Progress); err != nil { + return fmt.Errorf("unmarshal field progress: %w", err) + } + } default: _m.selectValues.Set(columns[i], values[i]) } @@ -211,6 +221,9 @@ func (_m *WorkflowRunEvent) String() string { builder.WriteString(", ") builder.WriteString("attributes=") builder.WriteString(fmt.Sprintf("%v", _m.Attributes)) + builder.WriteString(", ") + builder.WriteString("progress=") + builder.WriteString(fmt.Sprintf("%v", _m.Progress)) builder.WriteByte(')') return builder.String() } diff --git a/app/controlplane/pkg/data/ent/workflowrunevent/where.go b/app/controlplane/pkg/data/ent/workflowrunevent/where.go index 46df94d45..d401f3d8d 100644 --- a/app/controlplane/pkg/data/ent/workflowrunevent/where.go +++ b/app/controlplane/pkg/data/ent/workflowrunevent/where.go @@ -377,6 +377,16 @@ func AttributesNotNil() predicate.WorkflowRunEvent { return predicate.WorkflowRunEvent(sql.FieldNotNull(FieldAttributes)) } +// ProgressIsNil applies the IsNil predicate on the "progress" field. +func ProgressIsNil() predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldIsNull(FieldProgress)) +} + +// ProgressNotNil applies the NotNil predicate on the "progress" field. +func ProgressNotNil() predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNotNull(FieldProgress)) +} + // HasWorkflowRun applies the HasEdge predicate on the "workflow_run" edge. func HasWorkflowRun() predicate.WorkflowRunEvent { return predicate.WorkflowRunEvent(func(s *sql.Selector) { diff --git a/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go index a3d11f23c..0d240705e 100644 --- a/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go +++ b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go @@ -33,6 +33,8 @@ const ( FieldMessage = "message" // FieldAttributes holds the string denoting the attributes field in the database. FieldAttributes = "attributes" + // FieldProgress holds the string denoting the progress field in the database. + FieldProgress = "progress" // EdgeWorkflowRun holds the string denoting the workflow_run edge name in mutations. EdgeWorkflowRun = "workflow_run" // Table holds the table name of the workflowrunevent in the database. @@ -57,6 +59,7 @@ var Columns = []string{ FieldStatus, FieldMessage, FieldAttributes, + FieldProgress, } // ValidColumn reports if the column name is valid (part of the table columns). diff --git a/app/controlplane/pkg/data/ent/workflowrunevent_create.go b/app/controlplane/pkg/data/ent/workflowrunevent_create.go index 40abf1e2f..298386a09 100644 --- a/app/controlplane/pkg/data/ent/workflowrunevent_create.go +++ b/app/controlplane/pkg/data/ent/workflowrunevent_create.go @@ -90,6 +90,12 @@ func (_c *WorkflowRunEventCreate) SetAttributes(v *biz.WorkflowRunEventAttribute return _c } +// SetProgress sets the "progress" field. +func (_c *WorkflowRunEventCreate) SetProgress(v *biz.WorkflowRunEventProgress) *WorkflowRunEventCreate { + _c.mutation.SetProgress(v) + return _c +} + // SetID sets the "id" field. func (_c *WorkflowRunEventCreate) SetID(v uuid.UUID) *WorkflowRunEventCreate { _c.mutation.SetID(v) @@ -256,6 +262,10 @@ func (_c *WorkflowRunEventCreate) createSpec() (*WorkflowRunEvent, *sqlgraph.Cre _spec.SetField(workflowrunevent.FieldAttributes, field.TypeJSON, value) _node.Attributes = value } + if value, ok := _c.mutation.Progress(); ok { + _spec.SetField(workflowrunevent.FieldProgress, field.TypeJSON, value) + _node.Progress = value + } if nodes := _c.mutation.WorkflowRunIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -366,6 +376,9 @@ func (u *WorkflowRunEventUpsertOne) UpdateNewValues() *WorkflowRunEventUpsertOne if _, exists := u.create.mutation.Attributes(); exists { s.SetIgnore(workflowrunevent.FieldAttributes) } + if _, exists := u.create.mutation.Progress(); exists { + s.SetIgnore(workflowrunevent.FieldProgress) + } })) return u } @@ -604,6 +617,9 @@ func (u *WorkflowRunEventUpsertBulk) UpdateNewValues() *WorkflowRunEventUpsertBu if _, exists := b.mutation.Attributes(); exists { s.SetIgnore(workflowrunevent.FieldAttributes) } + if _, exists := b.mutation.Progress(); exists { + s.SetIgnore(workflowrunevent.FieldProgress) + } } })) return u diff --git a/app/controlplane/pkg/data/ent/workflowrunevent_update.go b/app/controlplane/pkg/data/ent/workflowrunevent_update.go index 57abfaf1a..f7ef75f25 100644 --- a/app/controlplane/pkg/data/ent/workflowrunevent_update.go +++ b/app/controlplane/pkg/data/ent/workflowrunevent_update.go @@ -92,6 +92,9 @@ func (_u *WorkflowRunEventUpdate) sqlSave(ctx context.Context) (_node int, err e if _u.mutation.AttributesCleared() { _spec.ClearField(workflowrunevent.FieldAttributes, field.TypeJSON) } + if _u.mutation.ProgressCleared() { + _spec.ClearField(workflowrunevent.FieldProgress, field.TypeJSON) + } _spec.AddModifiers(_u.modifiers...) if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -208,6 +211,9 @@ func (_u *WorkflowRunEventUpdateOne) sqlSave(ctx context.Context) (_node *Workfl if _u.mutation.AttributesCleared() { _spec.ClearField(workflowrunevent.FieldAttributes, field.TypeJSON) } + if _u.mutation.ProgressCleared() { + _spec.ClearField(workflowrunevent.FieldProgress, field.TypeJSON) + } _spec.AddModifiers(_u.modifiers...) _node = &WorkflowRunEvent{config: _u.config} _spec.Assign = _node.assignValues diff --git a/app/controlplane/pkg/data/workflowrunevent.go b/app/controlplane/pkg/data/workflowrunevent.go index cf7491710..ad3a00a11 100644 --- a/app/controlplane/pkg/data/workflowrunevent.go +++ b/app/controlplane/pkg/data/workflowrunevent.go @@ -90,6 +90,9 @@ func createWorkflowRunEvent(ctx context.Context, client *ent.Client, event *biz. if event.Attributes != nil { q.SetAttributes(event.Attributes) } + if event.Progress != nil { + q.SetProgress(event.Progress) + } ev, err := q.Save(ctx) if err != nil { @@ -129,5 +132,6 @@ func entWorkflowRunEventToBiz(e *ent.WorkflowRunEvent) *biz.WorkflowRunEvent { Status: e.Status, Message: e.Message, Attributes: e.Attributes, + Progress: e.Progress, } } diff --git a/app/controlplane/pkg/data/workflowrunevent_integration_test.go b/app/controlplane/pkg/data/workflowrunevent_integration_test.go index 5b0844103..2a76b39f3 100644 --- a/app/controlplane/pkg/data/workflowrunevent_integration_test.go +++ b/app/controlplane/pkg/data/workflowrunevent_integration_test.go @@ -150,6 +150,29 @@ func (s *workflowRunEventIntegrationTestSuite) TestCreate() { } } +// The progress of a custom step is stored in its column and read back +// (spec issue-3825 R-015) +func (s *workflowRunEventIntegrationTestSuite) TestCustomProgressStored() { + ctx := context.Background() + runID := s.newRun() + + _, err := s.Repos.WorkflowRunEvent.Create(ctx, &biz.WorkflowRunEvent{ + WorkflowRunID: runID, + Source: biz.WorkflowRunEventSourceCLI, + Type: biz.WorkflowRunEventTypeCustom, + Key: "classify-commits", + Status: biz.WorkflowRunEventStatusStarted, + Progress: &biz.WorkflowRunEventProgress{Current: 0, Total: 500}, + }, 10) + s.Require().NoError(err) + + got, err := s.Repos.WorkflowRunEvent.List(ctx, runID) + s.Require().NoError(err) + s.Require().Len(got, 1) + s.Equal(&biz.WorkflowRunEventProgress{Current: 0, Total: 500}, got[0].Progress) + s.Nil(got[0].Attributes) +} + func (s *workflowRunEventIntegrationTestSuite) TestList() { ctx := context.Background() repo := s.Repos.WorkflowRunEvent diff --git a/docs/specs/issue-3825-attestation-progress-events.md b/docs/specs/issue-3825-attestation-progress-events.md index 6b42e5a07..c69102750 100644 --- a/docs/specs/issue-3825-attestation-progress-events.md +++ b/docs/specs/issue-3825-attestation-progress-events.md @@ -48,7 +48,7 @@ While an attestation is in progress, the control plane knows only that its workf - Non-goal: an audit-grade record of a run. Run events are unsigned, ~~deletable after the retention period,~~ kept for the life of the run (R-014), and readable by run viewers. The signed attestation and the existing audit log stay the audit record. - Non-goal: send run events to the audit log, the event bus, or a SIEM. The volume is high, and the ticket does not ask for it. - Non-goal: identify the caller on each event. The attestation already records who authenticated, and all events of a run come from the same attestation. -- Non-goal: custom attributes on custom events. A custom event has a key, a status, and a message only. +- ~~Non-goal: custom attributes on custom events. A custom event has a key, a status, and a message only.~~ Superseded by D-015: an event can also have progress values, and today only custom events accept them (R-015). - Non-goal: streaming or push updates. The control plane rejects streaming calls, so clients poll. - In scope: the custom event command (R-009). It can ship after the automatic events, but it uses the same event model. One spec decides that model once, so that the custom events fit it. @@ -129,6 +129,10 @@ Supersedes R-012. `chainloop attestation event --name --status -- Supersedes R-007. The control plane MUST keep the events of a run for as long as it keeps the run. It deletes the events only when it deletes the run. No periodic job deletes events, and the control plane configuration has no retention setting (D-014). A configuration that still sets the removed `workflow_run_events_retention` MUST load, so that an upgrade does not break the control plane. - Done when: the events of a run that finished more than 90 days ago are still returned by the read call (R-011). A control plane with `workflow_run_events_retention` in its configuration starts. +### R-015: Progress values on custom events +A custom event MAY have progress values: a current value and a total, for example 240 of 500 commits. `chainloop attestation event --step --current --total ` MUST record them in the progress of the event (D-015). The command takes the key with `--step`, which replaced `--name` (R-003 of spec issue-3878). The command needs both flags or neither. A flag with an empty value is a wrong value. The control plane and the CLI MUST reject progress values unless the current value is from 0 to the total, and the total is more than 0. Only custom events accept progress values. A long step reports its progress with repeated `started` events of its key. There is no new status. A wrong value is a wrong call: the command shows a warning, sends nothing, and exits with success (R-013). When the last event of a custom step has progress values, `chainloop workflow run describe` MUST show them on the row of the step as `/`. Below the step, it shows only the last of consecutive progress updates. A progress update is a `started` event with progress values that is not the first event of the step. +- Done when: `chainloop attestation event --step classify-commits --status started --current 240 --total 500` shows the step row ``step `classify-commits` running for 1m20s · 240/500`` in `describe`. `--current 501 --total 500`, or `--current 1` with no `--total`, shows a warning, records nothing, and exits with 0. + ## Constraints - Open source: the feature works in the control plane and the CLI alone. It does not need the event bus or any commercial component. @@ -288,6 +292,16 @@ Run events have no retention period. They stay with the run, and they go only wh - A total quota of events, or a policy that deletes old runs: a new mechanism for a growth that runs and attestations already have. The limit for each run (R-008) bounds a run to 1,000 client events, plus the closing event of the control plane (R-006). The events of all runs grow with the number of runs, and this is accepted. - Source: product decision after #3865 +### D-015: Progress is an optional field of every event, and progress updates are `started` events +Supersedes the Non-goal "custom attributes on custom events". A run event has an optional progress, with a current value and a total (R-015). The progress is a field of the event, next to its message, and not one of its typed attributes (D-006). The control plane stores it in its own column. Today only custom events accept a progress. A step reports its progress with repeated `started` events, with no new status. +- Why: some pipeline steps run for minutes to hours, for example a task that classifies thousands of commits. A step with only a start and an end shows no progress between them. Typed values let the CLI and the UI draw a progress bar, and the control plane can check them. A progress is not specific to one event type. As a field of the event, automatic events, for example a large `add`, can get a progress later with no API change. A progress update has the status of the step, which is still running, so `started` is correct. A new status would change the meaning of the status, which describes the step (D-004). +- Alternatives considered: + - Progress in the custom attributes of the event: only custom events could ever have it, because the attributes of an event match its type. + - Progress in the message, for example "240/500": no check, and each client must parse the text. + - A new `progress` status: a second status for a running step, and each client must handle it as `started`. + - A free key-value map on custom events: no check of the content (D-006). +- Source: PFM-8434 + ## Open Questions None. @@ -295,7 +309,7 @@ None. ## Milestones 1. **Automatic progress.** Automatic events (R-001, R-002, R-005, R-006), the read call (R-003), `describe` for runs in progress (R-004), retention (R-007), and limits (R-008). R-010 supersedes R-001, R-011 supersedes R-003, and R-014 supersedes R-007. -2. **Custom events.** `chainloop attestation event` (R-009). R-012 supersedes R-009. +2. **Custom events.** `chainloop attestation event` (R-009). R-012 supersedes R-009. R-015 adds progress values. ## Risks