From 3aedca0a2b07cf75fe0ee04ede671a939108b3a2 Mon Sep 17 00:00:00 2001 From: Lennart Espe <3391295+lnsp@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:09:09 +0100 Subject: [PATCH] Read service logs as records, per deployment or across all deployments service logs --json requests format=json and prints the platform's records unchanged, one per line; keepalives are dropped and a server that answers in plain text yields {"line": ...}. --all and --deployment pick which deployment's log to read, and --timestamps prefixes each line with its time. --- README.md | 4 +- api/client.go | 96 +++++++++++++++++----- api/logstream.go | 186 ++++++++++++++++++++++++++++++++++++++---- api/logstream_test.go | 54 ++++++++++++ api/token_test.go | 4 +- cmd/output.go | 40 ++------- cmd/output_test.go | 16 ++-- cmd/services.go | 52 +++++++++--- cmd/services_test.go | 143 ++++++++++++++++++++++++++++++++ 9 files changed, 500 insertions(+), 95 deletions(-) diff --git a/README.md b/README.md index d4851de..5f1b085 100644 --- a/README.md +++ b/README.md @@ -184,9 +184,11 @@ valar service list #### Show the logs of the latest deployment ```bash -valar service logs [--follow] [--tail] [--skip n] [service] +valar service logs [--follow] [--tail] [--skip n] [--all | --deployment n] [--timestamps] [--service service] ``` +`--all` shows every deployment's log, oldest first, and `--deployment` one deployment's. `--timestamps` prefixes each line with the time it was written. With `--json`, each line is a record such as `{"ts": "...", "deployment": "3", "stream": "output", "line": "..."}`; platform events have `stream: "platform"` with `event` and `attrs`, and further fields may appear. An older platform yields `{"line": "..."}` only. Following records reconnects at the end of the log, so lines written while reconnecting can be missed. + #### Print a service's URLs Linked custom domains come first, then the service's own `-` domains. diff --git a/api/client.go b/api/client.go index 2bf90f3..c5da8f3 100644 --- a/api/client.go +++ b/api/client.go @@ -117,42 +117,94 @@ func (client *Client) ListServices(project, service string) ([]Service, error) { return services, nil } -// StreamServiceLogs streams the logs of the latest service endpoint. A followed -// stream reconnects and resumes if the connection is cut. -func (client *Client) StreamServiceLogs(project, service string, w io.Writer, follow, tail bool, skip int) error { - base := fmt.Sprintf("/projects/%s/services/%s/logs", project, service) - logPath := func(params url.Values) string { - if follow { - params.Set("follow", "true") - params.Set("keepalive", keepaliveInterval.String()) - } - return base + "?" + params.Encode() +// LogOptions selects which service log to read and where to start. +type LogOptions struct { + Follow bool + // Tail starts at the end of the log, Skip that many lines further on. + Tail bool + Skip int + // All reads every deployment's log in version order; Deployment reads one + // deployment's. Neither reads the latest deployment's. + All bool + Deployment int +} + +// logPath builds the request path for a service log with the given query. +func (opts LogOptions) logPath(project, service string, params url.Values) string { + if opts.Deployment > 0 { + params.Set("deployment", strconv.Itoa(opts.Deployment)) + } + if opts.Follow { + params.Set("follow", "true") + params.Set("keepalive", keepaliveInterval.String()) + } + return fmt.Sprintf("/projects/%s/services/%s/logs?%s", project, service, params.Encode()) +} + +// start is the query of the first request. The server refuses all combined +// with seek or skip. +func (opts LogOptions) start() url.Values { + if opts.All { + return url.Values{"all": {"true"}} } seek := "start" - if tail { + if opts.Tail { seek = "end" } - start := url.Values{"seek": {seek}, "skip": {strconv.Itoa(skip)}} - if !follow { - return client.streamOnce(logPath(start), w) + return url.Values{"seek": {seek}, "skip": {strconv.Itoa(opts.Skip)}} +} + +// StreamServiceLogs writes a service log as plain text. A followed stream +// reconnects and resumes if the connection is cut. +func (client *Client) StreamServiceLogs(project, service string, w io.Writer, opts LogOptions) error { + if !opts.Follow { + return client.streamOnce(opts.logPath(project, service, opts.start()), w) } - // A stream that starts at the beginning of the log resumes at an exact byte - // offset. One anchored to the end of the log, or started at a line offset, - // has no absolute position to resume from, so it re-anchors to the current - // end and may miss lines written while reconnecting. - exact := !tail && skip == 0 + // A stream that starts at the beginning of one deployment's log resumes at + // an exact byte offset. One anchored to the end of the log, started at a + // line offset or spanning all deployments has no absolute position to + // resume from, so it re-anchors to the current end and may miss lines + // written while reconnecting. + exact := !opts.Tail && opts.Skip == 0 && !opts.All return client.follow(followOptions{path: func(resumeAfter int) string { switch { case resumeAfter == 0: - return logPath(start) + return opts.logPath(project, service, opts.start()) case exact: - return logPath(url.Values{"seek": {"start"}, "offset": {strconv.Itoa(resumeAfter)}}) + return opts.logPath(project, service, url.Values{"seek": {"start"}, "offset": {strconv.Itoa(resumeAfter)}}) default: - return logPath(url.Values{"seek": {"end"}}) + return opts.logPath(project, service, url.Values{"seek": {"end"}}) } }}, w) } +// StreamServiceLogRecords passes a service log to emit one record at a time. +// Against a server that answers in plain text, each record holds only a line. +func (client *Client) StreamServiceLogRecords(project, service string, opts LogOptions, emit func(LogRecord) error) error { + path := func(params url.Values) string { + params.Set("format", "json") + return opts.logPath(project, service, params) + } + if !opts.Follow { + return client.streamRecordsOnce(path(opts.start()), emit) + } + delivered := 0 + count := func(record LogRecord) error { + delivered++ + return emit(record) + } + started := false + return client.reconnect(func() error { + params := opts.start() + if started { + // Records have no resume cursor yet, so a reconnect re-anchors to the end. + params = url.Values{"seek": {"end"}} + } + started = true + return client.streamRecordsOnce(path(params), count) + }, func() int { return delivered }, false) +} + // SubmitArtifact submits a new build input artifact to the server. func (client *Client) SubmitArtifact(project, service, kind string, archive io.ReadCloser) (*Artifact, error) { var ( diff --git a/api/logstream.go b/api/logstream.go index 63899e6..4b8dd78 100644 --- a/api/logstream.go +++ b/api/logstream.go @@ -2,6 +2,7 @@ package api import ( "bufio" + "bytes" "encoding/json" "errors" "fmt" @@ -63,21 +64,29 @@ type followOptions struct { finite bool } -// follow streams a log, reconnecting when the connection is cut. A follow can -// idle for minutes at a time and intermediaries routinely drop idle -// connections, so a cut is expected rather than fatal. +// follow streams a log, reconnecting when the connection is cut. func (client *Client) follow(opts followOptions, w io.Writer) error { counter := &countingWriter{w: w} + return client.reconnect(func() error { + return client.streamOnce(opts.path(counter.bytes), counter) + }, func() int { return counter.bytes }, opts.finite) +} + +// reconnect runs once again whenever its stream is cut, until the stream ends +// for good. delivered reports how much has come through so far. A follow can +// idle for minutes at a time and intermediaries routinely drop idle +// connections, so a cut is expected rather than fatal. +func (client *Client) reconnect(once func() error, delivered func() int, finite bool) error { for tries := 0; ; { - before := counter.bytes - err := client.streamOnce(opts.path(counter.bytes), counter) - if err == nil && opts.finite { + before := delivered() + err := once() + if err == nil && finite { return nil } if !retryable(err) { return err } - if counter.bytes > before { + if delivered() > before { tries = 0 } else if tries++; tries >= maxReconnectTries { // Nothing is coming through; report it rather than spin or, worse, @@ -106,37 +115,59 @@ func reconnectDelay(tries int) time.Duration { return delay } -// streamOnce runs a single streaming request, decoding framed responses and -// copying raw ones. A nil error means the server closed the stream. -func (client *Client) streamOnce(path string, w io.Writer) error { +// openStream starts a streaming request and reports whether its response is +// framed. A response the server refused becomes an error. +func (client *Client) openStream(path string) (io.ReadCloser, bool, error) { req, err := http.NewRequest(http.MethodGet, client.Endpoint+path, nil) if err != nil { - return fmt.Errorf("client request: %w", err) + return nil, false, fmt.Errorf("client request: %w", err) } req.Header.Add("Authorization", "Bearer "+client.Token) resp, err := client.stream.Do(req) if err != nil { - return fmt.Errorf("submitting request: %w", err) + return nil, false, fmt.Errorf("submitting request: %w", err) } - defer resp.Body.Close() client.noteTokenExpiry(resp.Header) if resp.StatusCode != http.StatusOK { + defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { - return fmt.Errorf("fetching response: %w", err) + return nil, false, fmt.Errorf("fetching response: %w", err) } - return client.responseError(resp, body) + return nil, false, client.responseError(resp, body) } - if contentType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")); err == nil && contentType == logStreamContentType { - return decodeFramedStream(resp.Body, w) + contentType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + return resp.Body, err == nil && contentType == logStreamContentType, nil +} + +// streamOnce runs a single streaming request, decoding framed responses and +// copying raw ones. A nil error means the server closed the stream. +func (client *Client) streamOnce(path string, w io.Writer) error { + body, framed, err := client.openStream(path) + if err != nil { + return err } - if _, err := io.Copy(w, resp.Body); err != nil && err != io.EOF { + defer body.Close() + if framed { + return decodeFramedStream(body, w) + } + if _, err := io.Copy(w, body); err != nil && err != io.EOF { return fmt.Errorf("copying request: %w", err) } return nil } +// streamRecordsOnce runs a single streaming request for log records. +func (client *Client) streamRecordsOnce(path string, emit func(LogRecord) error) error { + body, framed, err := client.openStream(path) + if err != nil { + return err + } + defer body.Close() + return decodeRecords(body, framed, emit) +} + // decodeFramedStream writes framed log payloads to w and drops keepalives. func decodeFramedStream(r io.Reader, w io.Writer) error { scanner := bufio.NewScanner(r) @@ -162,3 +193,122 @@ func decodeFramedStream(r io.Reader, w io.Writer) error { } return nil } + +// LogRecord is one line of a service log. Raw is the record exactly as the +// server sent it, unknown fields included; it is nil for a line the server +// sent as plain text. +type LogRecord struct { + TS string `json:"ts,omitempty"` + Deployment string `json:"deployment,omitempty"` + Stream string `json:"stream,omitempty"` + Line string `json:"line"` + Raw json.RawMessage `json:"-"` +} + +// recordLine is any line of a newline-delimited JSON log response: a record, +// a keepalive or, from a server without records, a frame of text. +type recordLine struct { + TS string `json:"ts"` + Deployment string `json:"deployment"` + Stream string `json:"stream"` + Line *string `json:"line"` + Keepalive bool `json:"keepalive"` + Data []byte `json:"data"` +} + +// decodeRecords passes the records of a log response to emit. A server that +// predates records answers in plain text, or in text frames when framed; +// each line of that text becomes a record holding only the line. An unframed +// response is taken as records if its first non-empty line is one. +func decodeRecords(r io.Reader, framed bool, emit func(LogRecord) error) error { + text := &TextRecords{Emit: emit} + var pending []string + decided := framed + scanner := bufio.NewScanner(r) + scanner.Buffer(make([]byte, 0, bufio.MaxScanTokenSize), maxLogFrameSize) + for scanner.Scan() { + line := scanner.Bytes() + if !decided { + if len(bytes.TrimSpace(line)) == 0 { + pending = append(pending, string(line)) + continue + } + var probe recordLine + framed = json.Unmarshal(line, &probe) == nil && probe.Line != nil + decided = true + if !framed { + for _, blank := range pending { + if _, err := text.Write([]byte(blank + "\n")); err != nil { + return err + } + } + } + } + if !framed { + if _, err := text.Write(append(line, '\n')); err != nil { + return err + } + continue + } + if len(line) == 0 { + continue + } + var decoded recordLine + if err := json.Unmarshal(line, &decoded); err != nil { + return fmt.Errorf("decoding log record: %w", err) + } + switch { + case decoded.Keepalive: + case decoded.Line != nil: + record := LogRecord{ + TS: decoded.TS, + Deployment: decoded.Deployment, + Stream: decoded.Stream, + Line: *decoded.Line, + Raw: bytes.Clone(line), + } + if err := emit(record); err != nil { + return err + } + case decoded.Data != nil: + if _, err := text.Write(decoded.Data); err != nil { + return err + } + } + } + if err := scanner.Err(); err != nil { + return fmt.Errorf("reading log stream: %w", err) + } + return text.Flush() +} + +// TextRecords turns text into one record per line, passed to Emit. Flush +// emits a final line that has no line break. +type TextRecords struct { + Emit func(LogRecord) error + buf []byte +} + +func (tr *TextRecords) Write(b []byte) (int, error) { + tr.buf = append(tr.buf, b...) + for { + i := bytes.IndexByte(tr.buf, '\n') + if i < 0 { + return len(b), nil + } + line := bytes.TrimSuffix(tr.buf[:i], []byte("\r")) + if err := tr.Emit(LogRecord{Line: string(line)}); err != nil { + return 0, err + } + tr.buf = tr.buf[i+1:] + } +} + +func (tr *TextRecords) Flush() error { + if len(tr.buf) == 0 { + return nil + } + line := string(tr.buf) + tr.buf = nil + return tr.Emit(LogRecord{Line: line}) +} diff --git a/api/logstream_test.go b/api/logstream_test.go index 291d916..133aa46 100644 --- a/api/logstream_test.go +++ b/api/logstream_test.go @@ -3,9 +3,12 @@ package api import ( "bytes" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" + "net/url" + "reflect" "strconv" "strings" "sync" @@ -235,6 +238,57 @@ func TestFollow_DecodesFramedResponses(t *testing.T) { } } +// TestStreamServiceLogRecords_FollowReanchors covers the missing resume +// cursor: a cut record stream reconnects at the end of the newest log. +func TestStreamServiceLogRecords_FollowReanchors(t *testing.T) { + var mu sync.Mutex + var queries []url.Values + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + attempt := len(queries) + queries = append(queries, r.URL.Query()) + mu.Unlock() + w.Header().Set("Content-Type", logStreamContentType) + switch attempt { + case 0: + fmt.Fprintln(w, `{"keepalive":true}`) + fmt.Fprintln(w, `{"deployment":"1","stream":"output","line":"first"}`) + w.(http.Flusher).Flush() + cutConnection(t, w) + case 1: + fmt.Fprintln(w, `{"deployment":"2","stream":"output","line":"second"}`) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + var lines []string + client := newTestClient(srv.URL) + err := client.StreamServiceLogRecords("p", "s", LogOptions{Follow: true, All: true}, func(record LogRecord) error { + lines = append(lines, record.Deployment+":"+record.Line) + return nil + }) + var statusErr Error + if !errors.As(err, &statusErr) || statusErr.StatusCode != http.StatusNotFound { + t.Fatalf("got %v, want the 404 that ends the test stream", err) + } + if want := []string{"1:first", "2:second"}; strings.Join(lines, ",") != strings.Join(want, ",") { + t.Errorf("got %v, want %v", lines, want) + } + mu.Lock() + defer mu.Unlock() + for i, want := range []url.Values{ + {"format": {"json"}, "all": {"true"}, "follow": {"true"}, "keepalive": {keepaliveInterval.String()}}, + {"format": {"json"}, "seek": {"end"}, "follow": {"true"}, "keepalive": {keepaliveInterval.String()}}, + } { + if !reflect.DeepEqual(queries[i], want) { + t.Errorf("request %d: got %v, want %v", i, queries[i], want) + } + } +} + func equalInts(a, b []int) bool { if len(a) != len(b) { return false diff --git a/api/token_test.go b/api/token_test.go index d2daee0..695f2ed 100644 --- a/api/token_test.go +++ b/api/token_test.go @@ -44,7 +44,7 @@ func TestTokenExpiry_Reported(t *testing.T) { }{ {"Request", "2027-02-18T10:00:00Z", http.StatusOK, func(c *Client) error { _, err := c.UserInfo(); return err }, true}, {"FailedRequest", "2027-02-18T10:00:00Z", http.StatusNotFound, func(c *Client) error { _, err := c.UserInfo(); return err }, true}, - {"Stream", "2027-02-18T10:00:00Z", http.StatusOK, func(c *Client) error { return c.StreamServiceLogs("p", "s", io.Discard, false, false, 0) }, true}, + {"Stream", "2027-02-18T10:00:00Z", http.StatusOK, func(c *Client) error { return c.StreamServiceLogs("p", "s", io.Discard, LogOptions{}) }, true}, {"NoHeader", "", http.StatusOK, func(c *Client) error { _, err := c.UserInfo(); return err }, false}, {"Malformed", "next week", http.StatusOK, func(c *Client) error { _, err := c.UserInfo(); return err }, false}, } { @@ -101,7 +101,7 @@ func TestTokenRefused(t *testing.T) { }) for name, err := range map[string]error{ "request": func() error { _, err := client.UserInfo(); return err }(), - "stream": client.StreamServiceLogs("p", "s", io.Discard, false, false, 0), + "stream": client.StreamServiceLogs("p", "s", io.Discard, LogOptions{}), } { var apiErr Error if !errors.As(err, &apiErr) || apiErr.StatusCode != tc.Status { diff --git a/cmd/output.go b/cmd/output.go index 6ae0040..b943f31 100644 --- a/cmd/output.go +++ b/cmd/output.go @@ -1,7 +1,6 @@ package cmd import ( - "bytes" "encoding/json" "errors" "fmt" @@ -204,38 +203,17 @@ func writeJSONLine(w io.Writer, v any) error { // logLine is a line of service or batch output in a JSON stream. type logLine struct { - Content string `json:"content"` + Line string `json:"line"` } -// jsonLineWriter turns raw output into one {"content": ...} object per line. -// Flush writes a final line that has no line break. -type jsonLineWriter struct { - w io.Writer - buf []byte -} - -func (lw *jsonLineWriter) Write(b []byte) (int, error) { - lw.buf = append(lw.buf, b...) - for { - i := bytes.IndexByte(lw.buf, '\n') - if i < 0 { - return len(b), nil - } - line := bytes.TrimSuffix(lw.buf[:i], []byte("\r")) - if err := writeJSONLine(lw.w, logLine{Content: string(line)}); err != nil { - return 0, err - } - lw.buf = lw.buf[i+1:] - } -} - -func (lw *jsonLineWriter) Flush() error { - if len(lw.buf) == 0 { - return nil +// writeLogRecord writes a record as the server sent it, or a plain-text line +// as {"line": ...}. +func writeLogRecord(w io.Writer, record api.LogRecord) error { + if record.Raw == nil { + return writeJSONLine(w, logLine{Line: record.Line}) } - line := string(lw.buf) - lw.buf = nil - return writeJSONLine(lw.w, logLine{Content: line}) + _, err := w.Write(append(record.Raw, '\n')) + return err } // logOutput returns where raw log output goes, and a flush to call once it @@ -244,6 +222,6 @@ func logOutput() (io.Writer, func() error) { if !outputJSON { return stdout, func() error { return nil } } - lw := &jsonLineWriter{w: stdout} + lw := &api.TextRecords{Emit: func(record api.LogRecord) error { return writeLogRecord(stdout, record) }} return lw, lw.Flush } diff --git a/cmd/output_test.go b/cmd/output_test.go index a53f4f4..cb6363a 100644 --- a/cmd/output_test.go +++ b/cmd/output_test.go @@ -123,18 +123,18 @@ func TestJSONRequested(t *testing.T) { } } -func TestJSONLineWriter(t *testing.T) { - var out bytes.Buffer - lw := &jsonLineWriter{w: &out} +func TestLogOutput_JSON(t *testing.T) { + out := setJSON(t, true) + lw, flush := logOutput() lw.Write([]byte("first\nsec")) lw.Write([]byte("ond\r\n\"quoted\" \nlast")) - if err := lw.Flush(); err != nil { + if err := flush(); err != nil { t.Fatal(err) } - want := `{"content":"first"} -{"content":"second"} -{"content":"\"quoted\" "} -{"content":"last"} + want := `{"line":"first"} +{"line":"second"} +{"line":"\"quoted\" "} +{"line":"last"} ` if out.String() != want { t.Errorf("got\n%s\nwant\n%s", out.String(), want) diff --git a/cmd/services.go b/cmd/services.go index 041fffa..a5a6e34 100644 --- a/cmd/services.go +++ b/cmd/services.go @@ -149,15 +149,14 @@ func lastDeployed(svc api.Service) string { } var ( - serviceLogsFollow bool - serviceLogsTail bool - serviceLogsLines int - serviceLogsService string + serviceLogsOptions api.LogOptions + serviceLogsTimestamps bool + serviceLogsService string ) var serviceLogsCmd = &cobra.Command{ Use: "logs [--service service]", - Short: "Show the logs of the latest deployment.", + Short: "Show the logs of the latest deployment, one deployment or all of them.", Args: cobra.NoArgs, Run: runAndHandle(func(cmd *cobra.Command, args []string) error { client, err := globalConfiguration.APIClient() @@ -168,14 +167,38 @@ var serviceLogsCmd = &cobra.Command{ if err != nil { return err } - w, flush := logOutput() - if err := client.StreamServiceLogs(cfg.Project(), cfg.Service(), w, serviceLogsFollow, serviceLogsTail, serviceLogsLines); err != nil { - return err - } - return flush() + return showServiceLogs(client, cfg, serviceLogsOptions, serviceLogsTimestamps) }), } +// showServiceLogs prints a service log: as plain text by default, as records +// with --json, or as lines prefixed with their time with timestamps. +func showServiceLogs(client *api.Client, cfg *config.ValidatedServiceConfig, opts api.LogOptions, timestamps bool) error { + switch { + case opts.Deployment < 0: + return newError(kindInvalid, "--deployment must be a deployment version") + case opts.All && (opts.Deployment > 0 || opts.Tail || opts.Skip > 0): + return newError(kindInvalid, "--all cannot be combined with --deployment, --tail or --skip") + } + if !outputJSON && !timestamps { + return client.StreamServiceLogs(cfg.Project(), cfg.Service(), stdout, opts) + } + return client.StreamServiceLogRecords(cfg.Project(), cfg.Service(), opts, func(record api.LogRecord) error { + if outputJSON { + return writeLogRecord(stdout, record) + } + line := record.Line + if record.Stream == "platform" { + line = "[platform] " + line + } + if record.TS != "" { + line = record.TS + " " + line + } + _, err := fmt.Fprintln(stdout, line) + return err + }) +} + var serviceDisableService string var serviceDisableCmd = &cobra.Command{ @@ -355,9 +378,12 @@ func initServicesCmd() { initPf.StringVarP(&initConstructor, "type", "t", "", "Build constructor type, detected from the project files when omitted") initPf.StringVarP(&initProject, "project", "p", "", "Project to deploy service to, defaults to project set in global config") initPf.BoolVarP(&initForce, "force", "f", false, "Allow configuration override") - serviceLogsCmd.Flags().BoolVarP(&serviceLogsFollow, "follow", "f", false, "Follow logs") - serviceLogsCmd.Flags().BoolVarP(&serviceLogsTail, "tail", "t", false, "Jump to end of logs") - serviceLogsCmd.Flags().IntVarP(&serviceLogsLines, "skip", "n", 0, "Lines to skip/rewind when reading logs") + serviceLogsCmd.Flags().BoolVarP(&serviceLogsOptions.Follow, "follow", "f", false, "Follow logs") + serviceLogsCmd.Flags().BoolVarP(&serviceLogsOptions.Tail, "tail", "t", false, "Jump to end of logs") + serviceLogsCmd.Flags().IntVarP(&serviceLogsOptions.Skip, "skip", "n", 0, "Lines to skip/rewind when reading logs") + serviceLogsCmd.Flags().BoolVar(&serviceLogsOptions.All, "all", false, "Show the logs of every deployment, oldest first") + serviceLogsCmd.Flags().IntVar(&serviceLogsOptions.Deployment, "deployment", 0, "Show the log of this deployment version") + serviceLogsCmd.Flags().BoolVar(&serviceLogsTimestamps, "timestamps", false, "Prefix each line with the time it was written") serviceLogsCmd.Flags().StringVarP(&serviceLogsService, "service", "s", "", "The service to target") serviceURLCmd.Flags().StringVarP(&serviceURLService, "service", "s", "", "The service to target") serviceDisableCmd.Flags().StringVarP(&serviceDisableService, "service", "s", "", "The service to target") diff --git a/cmd/services_test.go b/cmd/services_test.go index 2743a49..9f3a40a 100644 --- a/cmd/services_test.go +++ b/cmd/services_test.go @@ -1,6 +1,10 @@ package cmd import ( + "net/http" + "net/http/httptest" + "net/url" + "reflect" "testing" "time" @@ -54,3 +58,142 @@ func TestServiceIsBatch(t *testing.T) { } } } + +const logsPath = "/projects/p/services/s/logs" + +func TestShowServiceLogs(t *testing.T) { + const ( + record = `{"ts":"2026-11-21T10:00:00.000000001Z","deployment":"3","stream":"output","line":"hello","instance":"ab12","future":1}` + platform = `{"ts":"2026-11-21T10:00:01Z","deployment":"3","stream":"platform","line":"instance started","event":"instance.start","attrs":{"cpu":"shared"}}` + ) + for _, tc := range []struct { + Name string + Options api.LogOptions + JSON bool + Timestamps bool + ContentType string + Body string + WantQuery url.Values + WantOutput string + WantErr bool + }{ + { + Name: "RecordsPassedThrough", + JSON: true, + ContentType: "application/x-ndjson", + Body: record + "\n" + platform + "\n", + WantQuery: url.Values{"format": {"json"}, "seek": {"start"}, "skip": {"0"}}, + WantOutput: record + "\n" + platform + "\n", + }, + { + Name: "KeepaliveSkipped", + JSON: true, + ContentType: "application/x-ndjson", + Body: `{"keepalive":true}` + "\n" + record + "\n" + `{"keepalive":true}` + "\n", + WantQuery: url.Values{"format": {"json"}, "seek": {"start"}, "skip": {"0"}}, + WantOutput: record + "\n", + }, + { + Name: "PlainTextFallback", + JSON: true, + ContentType: "text/plain; charset=utf-8", + Body: "\n{\"msg\":\"json, but no line\"}\n[platform] instance started\nlast", + WantQuery: url.Values{"format": {"json"}, "seek": {"start"}, "skip": {"0"}}, + WantOutput: `{"line":""}` + "\n" + `{"line":"{\"msg\":\"json, but no line\"}"}` + "\n" + `{"line":"[platform] instance started"}` + "\n" + `{"line":"last"}` + "\n", + }, + { + Name: "FramedTextFallback", + JSON: true, + ContentType: "application/x-ndjson", + Body: `{"keepalive":true}` + "\n" + `{"data":"aGVsbG8Kd29y"}` + "\n" + `{"data":"bGQK"}` + "\n", + WantQuery: url.Values{"format": {"json"}, "seek": {"start"}, "skip": {"0"}}, + WantOutput: `{"line":"hello"}` + "\n" + `{"line":"world"}` + "\n", + }, + { + Name: "All", + Options: api.LogOptions{All: true}, + JSON: true, + ContentType: "application/x-ndjson", + Body: record + "\n", + WantQuery: url.Values{"format": {"json"}, "all": {"true"}}, + WantOutput: record + "\n", + }, + { + Name: "Deployment", + Options: api.LogOptions{Deployment: 3}, + JSON: true, + ContentType: "application/x-ndjson", + Body: record + "\n", + WantQuery: url.Values{"format": {"json"}, "deployment": {"3"}, "seek": {"start"}, "skip": {"0"}}, + WantOutput: record + "\n", + }, + { + Name: "HumanUnchanged", + Options: api.LogOptions{All: true}, + ContentType: "text/plain; charset=utf-8", + Body: "hello\n[platform] instance started\n", + WantQuery: url.Values{"all": {"true"}}, + WantOutput: "hello\n[platform] instance started\n", + }, + { + Name: "Timestamps", + Options: api.LogOptions{Tail: true}, + Timestamps: true, + ContentType: "application/x-ndjson", + Body: record + "\n" + platform + "\n", + WantQuery: url.Values{"format": {"json"}, "seek": {"end"}, "skip": {"0"}}, + WantOutput: "2026-11-21T10:00:00.000000001Z hello\n2026-11-21T10:00:01Z [platform] instance started\n", + }, + { + Name: "AllWithDeployment", + Options: api.LogOptions{All: true, Deployment: 3}, + WantErr: true, + }, + { + Name: "AllWithSkip", + Options: api.LogOptions{All: true, Skip: 5}, + WantErr: true, + }, + } { + t.Run(tc.Name, func(t *testing.T) { + cfg, _ := writeServiceConfig(t, deployConfig) + var queries []url.Values + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/" { + w.Write([]byte(`{"version":"v2"}`)) + return + } + if r.URL.Path != logsPath { + http.NotFound(w, r) + return + } + queries = append(queries, r.URL.Query()) + w.Header().Set("Content-Type", tc.ContentType) + w.Write([]byte(tc.Body)) + })) + t.Cleanup(srv.Close) + client, err := api.NewClient(srv.URL, "token") + if err != nil { + t.Fatalf("new client: %v", err) + } + out := setJSON(t, tc.JSON) + + err = showServiceLogs(client, cfg, tc.Options, tc.Timestamps) + if tc.WantErr { + if classify(err, kindFailed) != kindInvalid || len(queries) != 0 { + t.Errorf("got %v after %d requests, want an invalid error before any", err, len(queries)) + } + return + } + if err != nil { + t.Fatalf("showServiceLogs: %v", err) + } + if len(queries) != 1 || !reflect.DeepEqual(queries[0], tc.WantQuery) { + t.Errorf("got queries %v, want %v", queries, tc.WantQuery) + } + if out.String() != tc.WantOutput { + t.Errorf("got\n%s\nwant\n%s", out.String(), tc.WantOutput) + } + }) + } +}