Files
larksuite__cli/internal/event/consume/sink.go
evandance 2b4c6349a1 feat(event): emit typed error envelopes across the event domain (#1289)
Replace every command-facing error path in the event domain — the
consume/schema command layer, the +subscribe shortcut, EventKey
definitions, and the consume orchestration — with typed errs.*
envelopes, so consumers get stable type, subtype, param, hint, and
missing_scopes metadata for classification and recovery instead of
free-form message text.

- Input validation (--jq, --param, --output-dir, --filter, --route,
  unknown EventKey, EventKey params) reports validation /
  invalid_argument with the offending flag in param and an actionable
  hint.
- Scope preflight reports authorization / missing_scope with the
  machine-readable missing_scopes list; console-subscription and
  single-bus preconditions report failed_precondition with recovery
  hints.
- The consume API boundary passes already-typed errors through and
  classifies transport, non-JSON HTTP, and unparsable responses; the
  vc note-detail retry now matches the not-found code on typed errors
  (it silently never fired against the legacy envelope shape).
- Previously-bare failures exited 1 with a plain-text "Error:" line
  and now exit with their category code (validation 2, auth 3,
  network 4, internal 5) alongside the typed stderr envelope.
- forbidigo and errscontract guards now cover the event paths so
  regressions fail lint; AGENTS.md and the lark-event skill document
  the typed contract for agent consumers.

Validation: make unit-test (race) green; event unit and e2e suites
assert category/subtype/param/hint and cause preservation against the
real binary; errscontract and golangci lint clean.
2026-06-09 17:12:55 +08:00

79 lines
2.1 KiB
Go

// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package consume
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/vfs"
)
type Sink interface {
Write(data json.RawMessage) error
}
func newSink(opts Options) (Sink, error) {
if opts.OutputDir != "" {
if err := vfs.MkdirAll(opts.OutputDir, 0755); err != nil {
return nil, errs.NewInternalError(errs.SubtypeFileIO,
"create output dir: %s", err).WithCause(err)
}
// PID disambiguates filenames across processes sharing a Dir.
return &DirSink{Dir: opts.OutputDir, pid: os.Getpid()}, nil
}
out := opts.Out
if out == nil {
out = os.Stdout //nolint:forbidigo // library-caller fallback; cmd path always sets Options.Out
}
return &WriterSink{W: out, ErrOut: opts.ErrOut}, nil
}
// WriterSink writes one JSON event per line; mu serialises concurrent worker writes.
type WriterSink struct {
W io.Writer
Pretty bool
ErrOut io.Writer
prettyWarned atomic.Bool
mu sync.Mutex
}
func (s *WriterSink) Write(data json.RawMessage) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.Pretty {
var v interface{}
if err := json.Unmarshal(data, &v); err == nil {
pretty, _ := json.MarshalIndent(v, "", " ")
_, err := fmt.Fprintln(s.W, string(pretty))
return err
}
// non-JSON payload (e.g. --jq output): fall through to raw, log once
if s.ErrOut != nil && s.prettyWarned.CompareAndSwap(false, true) {
fmt.Fprintln(s.ErrOut, "WARN: --pretty: payload is not valid JSON; falling back to raw output (this and future malformed events)")
}
}
_, err := fmt.Fprintln(s.W, string(data))
return err
}
// DirSink writes one JSON file per event; nanos+pid+seq filename avoids cross-process collisions.
type DirSink struct {
Dir string
pid int
seq atomic.Int64
}
func (s *DirSink) Write(data json.RawMessage) error {
name := fmt.Sprintf("%d_%d_%d.json", time.Now().UnixNano(), s.pid, s.seq.Add(1))
return vfs.WriteFile(filepath.Join(s.Dir, name), data, 0600) // 0600: payloads may carry PII
}