Skip to content

Commit 3b29020

Browse files
Merge branch 'main' into feat/oauth-auth
2 parents 4eb0b7d + da2a46f commit 3b29020

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

pkg/cmd/root/root.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ package root
44

55
import (
66
"context"
7+
"encoding/json"
78
"errors"
89
"fmt"
910
"io"
@@ -13,6 +14,7 @@ import (
1314
"os/exec"
1415
"path/filepath"
1516
"strings"
17+
"time"
1618

1719
"github.com/AlecAivazis/survey/v2/terminal"
1820
"github.com/MakeNowJust/heredoc"
@@ -117,6 +119,56 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command {
117119
return cmd
118120
}
119121

122+
// runSummary is the JSON object written to stderr when observability env vars are set.
123+
type runSummary struct {
124+
Event string `json:"event"`
125+
InvocationID string `json:"invocation_id"`
126+
Command string `json:"command"`
127+
Status string `json:"status"`
128+
DurationMs int64 `json:"duration_ms"`
129+
Error string `json:"error,omitempty"`
130+
}
131+
132+
func shouldEmitRunSummary() bool {
133+
return os.Getenv("ALGOLIA_CLI_NON_INTERACTIVE") == "1" ||
134+
os.Getenv("ALGOLIA_CLI_OBSERVABILITY") == "1"
135+
}
136+
137+
func emitRunSummary(stderr io.Writer, ctx context.Context, cmd *cobra.Command, runErr error, duration time.Duration) {
138+
meta := telemetry.GetEventMetadata(ctx)
139+
invocationID := ""
140+
if meta != nil {
141+
invocationID = meta.InvocationID
142+
}
143+
commandPath := ""
144+
if meta != nil && meta.CommandPath != "" {
145+
commandPath = meta.CommandPath
146+
}
147+
if commandPath == "" && cmd != nil {
148+
commandPath = cmd.CommandPath()
149+
}
150+
status := "ok"
151+
errMsg := ""
152+
if runErr != nil {
153+
status = "error"
154+
errMsg = runErr.Error()
155+
if len(errMsg) > 500 {
156+
errMsg = errMsg[:497] + "..."
157+
}
158+
}
159+
s := runSummary{
160+
Event: "cli_run",
161+
InvocationID: invocationID,
162+
Command: commandPath,
163+
Status: status,
164+
DurationMs: duration.Milliseconds(),
165+
Error: errMsg,
166+
}
167+
enc := json.NewEncoder(stderr)
168+
enc.SetEscapeHTML(false)
169+
_ = enc.Encode(s)
170+
}
171+
120172
func Execute() exitCode {
121173
hasDebug := os.Getenv("DEBUG") != ""
122174
hasTelemetry := os.Getenv("ALGOLIA_CLI_TELEMETRY") != "0"
@@ -202,7 +254,14 @@ func Execute() exitCode {
202254
}
203255

204256
// Run the command.
257+
start := time.Now()
205258
cmd, err := rootCmd.ExecuteContextC(ctx)
259+
duration := time.Since(start)
260+
261+
if shouldEmitRunSummary() {
262+
emitRunSummary(stderr, ctx, cmd, err, duration)
263+
}
264+
206265
// Handle eventual errors.
207266
if err != nil {
208267
if err == cmdutil.ErrSilent {

0 commit comments

Comments
 (0)