package ship import ( "bytes" "compress/gzip" "context" "fmt" "io" "net/http" "os" "path/filepath" "strings" "time" "unicode/utf8" collogspb "go.opentelemetry.io/proto/otlp/collector/logs/v1" commonpb "go.opentelemetry.io/proto/otlp/common/v1" logspb "go.opentelemetry.io/proto/otlp/logs/v1" resourcepb "go.opentelemetry.io/proto/otlp/resource/v1" "google.golang.org/protobuf/proto" ) // sender collects entries into batches, sends each batch, and moves the // place forward only after midden accepts the batch. type sender struct { cfg Config place place batch []entry size int sent int } func (s *sender) file(ctx context.Context, rel string) error { path := filepath.Join(s.cfg.Dir, rel) info, err := os.Stat(path) if err != nil { return err } offset := s.place[rel] if info.Size() < offset { // The file is shorter than the place, so it was replaced. Reading // it again from the start is safe, because midden stores each // entry once. offset = 0 } if info.Size() == offset { return nil } return read(path, rel, offset, func(e entry) error { if s.size > 0 && s.size+len(e.line) > s.cfg.MaxBatch { if err := s.flush(ctx); err != nil { return err } } s.batch = append(s.batch, e) s.size += len(e.line) return nil }) } func (s *sender) flush(ctx context.Context) error { if len(s.batch) == 0 { return nil } if err := s.post(ctx); err != nil { return err } for _, e := range s.batch { s.place[e.file] = e.end } if err := s.place.save(s.cfg.State); err != nil { return err } s.sent += len(s.batch) s.batch, s.size = nil, 0 return nil } func (s *sender) post(ctx context.Context) error { body, err := s.request() if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.cfg.Endpoint, bytes.NewReader(body)) if err != nil { return err } if s.cfg.TokenFile != "" { token, err := os.ReadFile(s.cfg.TokenFile) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(string(token))) } else { req.SetBasicAuth(s.cfg.Username, s.cfg.Password) } req.Header.Set("Content-Type", "application/x-protobuf") req.Header.Set("Content-Encoding", "gzip") resp, err := s.cfg.Client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode/100 != 2 { detail, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) if location := resp.Header.Get("Location"); location != "" { return fmt.Errorf("midden answered %s to %s: check the app password, or the endpoint when sending a pod's token", resp.Status, location) } return fmt.Errorf("midden answered %s: %s", resp.Status, bytes.TrimSpace(detail)) } // Only midden's own answer counts: an OTLP response in protobuf, the // format of the request. Anything else in front of midden that answers // 200 would otherwise move the place past entries midden never stored. if got := resp.Header.Get("Content-Type"); got != "application/x-protobuf" { return fmt.Errorf("the answer is %q, not midden's OTLP response, from %s", got, s.cfg.Endpoint) } return nil } // request encodes the batch as a gzipped OTLP logs request, with one log // record for each entry. func (s *sender) request() ([]byte, error) { now := uint64(time.Now().UnixNano()) records := make([]*logspb.LogRecord, 0, len(s.batch)) for _, e := range s.batch { record := &logspb.LogRecord{ ObservedTimeUnixNano: now, EventName: "transcript.entry", Attributes: []*commonpb.KeyValue{ text("event.name", "transcript.entry"), text("session.id", e.session), text("transcript.entry.key", e.key), text("transcript.path", e.file), }, Body: body(e.line), } if !e.time.IsZero() { record.TimeUnixNano = uint64(e.time.UnixNano()) } records = append(records, record) } data, err := proto.Marshal(&collogspb.ExportLogsServiceRequest{ ResourceLogs: []*logspb.ResourceLogs{{ Resource: &resourcepb.Resource{Attributes: []*commonpb.KeyValue{ text("service.name", "claude-code"), text("host.name", s.cfg.Host), }}, ScopeLogs: []*logspb.ScopeLogs{{ Scope: &commonpb.InstrumentationScope{Name: "midden-ship"}, LogRecords: records, }}, }}, }) if err != nil { return nil, err } var compressed bytes.Buffer gz := gzip.NewWriter(&compressed) if _, err := gz.Write(data); err != nil { return nil, err } if err := gz.Close(); err != nil { return nil, err } return compressed.Bytes(), nil } func text(key, value string) *commonpb.KeyValue { return &commonpb.KeyValue{Key: key, Value: &commonpb.AnyValue{ Value: &commonpb.AnyValue_StringValue{StringValue: value}}} } // body carries the line unchanged. Protobuf strings must be UTF-8, so a // line that is not valid UTF-8 goes as bytes. func body(line []byte) *commonpb.AnyValue { if utf8.Valid(line) { return &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: string(line)}} } return &commonpb.AnyValue{Value: &commonpb.AnyValue_BytesValue{BytesValue: line}} }