Перенеси реализацию мессенджера из ЛР 6
Application / e2e (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
Application / unit (pull_request) Canceled after 0s

Источник — проверенное рабочее дерево ЛР 6 поверх 18878d6, включая изменения после повторного ревью. SHA-256 списка исходных файлов: e45a3d85b41feff1da78dce3f20fd1f4af1c5ee629e6ed703218bc8e21ad58fe.
This commit is contained in:
2026-11-30 10:54:41 +03:00
parent 20afc2c790
commit 8054913ef9
204 changed files with 23709 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
package processing
import (
"context"
"fmt"
"path/filepath"
"messenger/internal/pipeline"
"messenger/internal/platform/faultbarrier"
)
// Only the explicit fault experiment enables these one-shot barriers.
func FileBarrier(dir string) func(context.Context, pipeline.Job, string) error {
return func(ctx context.Context, j pipeline.Job, phase string) error {
base := filepath.Join(dir, fmt.Sprintf("%s-v%d-%s", j.AttachmentID, j.PipelineVersion, phase))
return faultbarrier.Wait(ctx, base, "")
}
}
+103
View File
@@ -0,0 +1,103 @@
package processing
import (
"context"
"encoding/json"
"errors"
"log/slog"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"messenger/internal/broker"
"messenger/internal/pipeline"
"messenger/internal/platform/config"
"messenger/internal/platform/telemetry"
"messenger/internal/platform/tracectx"
)
func retryPolicy(cfg config.Jobs) pipeline.RetryPolicy {
return pipeline.RetryPolicy{MaxAttempts: cfg.MaxAttempts, BaseDelay: time.Second, MaxDelay: time.Minute}
}
func pause(ctx context.Context, d time.Duration) {
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-ctx.Done():
case <-timer.C:
}
}
func logRetry(ctx context.Context, log *slog.Logger, role string, err error) {
reason := "processing_error"
var brokerCode broker.FailureCode
if errors.As(err, &brokerCode) {
reason = string(brokerCode)
}
log.WarnContext(ctx, "attachment session will retry", "role", role, "error_code", reason)
telemetry.Event(ctx, "attachment.retry", attribute.String("outcome", role), attribute.String("error_code", reason))
}
func Dispatch(ctx context.Context, log *slog.Logger, store *pipeline.Store, cfg config.Jobs, barrier func(context.Context, pipeline.Job, string) error) {
for ctx.Err() == nil {
err := dispatchSession(ctx, store, cfg, barrier)
if ctx.Err() == nil {
logRetry(ctx, log, "dispatcher", err)
pause(ctx, time.Second)
}
}
}
func dispatchSession(ctx context.Context, store *pipeline.Store, cfg config.Jobs, barrier func(context.Context, pipeline.Job, string) error) error {
var publisher *broker.Publisher
publish := func(ctx context.Context, j pipeline.Job) (publishErr error) {
ctx = tracectx.Restore(ctx, j.Traceparent, j.Tracestate)
ctx, span := otel.Tracer("messenger/processing").Start(ctx, "attachment.publish", trace.WithSpanKind(trace.SpanKindProducer))
defer func() {
outcome := "published"
if publishErr != nil {
outcome = "error"
span.SetStatus(codes.Error, "publish failed")
}
telemetry.Event(ctx, "attachment.publish", attribute.String("outcome", outcome), attribute.Int("attempt", j.Attempt))
span.End()
}()
j.Traceparent, j.Tracestate = tracectx.Fields(ctx)
body, err := json.Marshal(j)
if err != nil {
return err
}
if err := publisher.Publish(ctx, body); err != nil {
return err
}
if barrier != nil {
return barrier(ctx, j, "published")
}
return nil
}
for ctx.Err() == nil {
if _, err := store.RecoverOne(ctx, retryPolicy(cfg)); err != nil {
return err
}
if publisher == nil {
var err error
publisher, err = broker.NewPublisher(ctx, cfg.URL)
if err != nil {
return err
}
defer publisher.Close()
}
sent, err := store.PublishOne(ctx, publish)
if err != nil {
return err
}
if !sent {
pause(ctx, 250*time.Millisecond)
}
}
return ctx.Err()
}
+262
View File
@@ -0,0 +1,262 @@
package processing
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"os"
"os/exec"
"sync"
"time"
"github.com/minio/minio-go/v7"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"messenger/internal/attachment"
"messenger/internal/broker"
"messenger/internal/imaging"
"messenger/internal/pipeline"
"messenger/internal/platform/config"
"messenger/internal/platform/telemetry"
"messenger/internal/platform/tracectx"
)
var workerMeter = otel.Meter("messenger/processing")
var workerActive, _ = workerMeter.Int64UpDownCounter("messenger.worker.active")
var workerCapacity, _ = workerMeter.Int64UpDownCounter("messenger.worker.capacity")
var jobs, _ = workerMeter.Int64Counter("messenger.jobs")
var jobDuration, _ = workerMeter.Float64Histogram("messenger.job.duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.01, .05, .1, .25, .5, 1, 2, 5, 10, 30, 60))
var errSourceMismatch = errors.New("original differs from accepted metadata")
type Worker struct {
Store *pipeline.Store
Blobs attachment.Blobs
Config config.Jobs
Log *slog.Logger
// An experiment may pause an individual attempt at an exact durability boundary.
Checkpoint func(context.Context, pipeline.Job, string) error
}
func (w *Worker) Run(ctx context.Context) {
workerCapacity.Add(ctx, int64(w.Config.Concurrency))
defer workerCapacity.Add(ctx, -int64(w.Config.Concurrency))
workerActive.Add(ctx, 0)
var wg sync.WaitGroup
for range w.Config.Concurrency {
wg.Go(func() {
for ctx.Err() == nil {
err := w.consume(ctx)
if ctx.Err() == nil {
logRetry(ctx, w.Log, "consumer", err)
pause(ctx, time.Second)
}
}
})
}
wg.Wait()
}
func (w *Worker) consume(ctx context.Context) error {
c, err := broker.NewConsumer(ctx, w.Config.URL)
if err != nil {
return err
}
defer c.Close()
for d := range c.Deliveries {
var j pipeline.Job
dec := json.NewDecoder(bytes.NewReader(d.Body))
dec.DisallowUnknownFields()
decodeErr := dec.Decode(&j)
j.Tracestate = tracectx.BoundState(j.Tracestate)
if decodeErr != nil || !j.Valid() || dec.Decode(new(any)) != io.EOF {
w.Log.Warn("discarding invalid attachment envelope")
if err := d.Reject(false); err != nil {
return broker.ErrAcknowledge
}
continue
}
if err := w.process(ctx, j); err != nil {
return err
}
if err := d.Ack(false); err != nil {
return broker.ErrAcknowledge
}
if err := w.checkpoint(ctx, j, "acked"); err != nil {
return err
}
}
return broker.ErrStreamClosed
}
func (w *Worker) checkpoint(ctx context.Context, j pipeline.Job, phase string) error {
if w.Checkpoint != nil {
return w.Checkpoint(ctx, j, phase)
}
return nil
}
func (w *Worker) process(ctx context.Context, j pipeline.Job) (processErr error) {
ctx = tracectx.Restore(ctx, j.Traceparent, j.Tracestate)
ctx, span := otel.Tracer("messenger/processing").Start(ctx, "attachment.process", trace.WithSpanKind(trace.SpanKindConsumer))
start := time.Now()
outcome := "lost_claim"
var code string
workerActive.Add(ctx, 1)
defer func() {
workerActive.Add(ctx, -1)
if processErr != nil {
outcome = "error"
}
if code != "" || processErr != nil {
span.SetStatus(codes.Error, "attempt failed")
}
label := attribute.String("outcome", outcome)
span.SetAttributes(label, attribute.Int("attempt", j.Attempt))
dimensions := metric.WithAttributes(label, attribute.String("job_type", j.Type))
jobs.Add(ctx, 1, dimensions)
jobDuration.Record(ctx, time.Since(start).Seconds(), dimensions)
telemetry.Event(ctx, "attachment.process", label, attribute.Int("attempt", j.Attempt), attribute.String("error_code", code))
span.End()
}()
c, err := w.Store.Claim(ctx, j, w.Config.Timeout+5*time.Second)
if err != nil {
return err
}
if c == nil {
outcome = "duplicate"
return w.checkpoint(ctx, j, "duplicate")
}
if err := w.checkpoint(ctx, j, "claimed"); err != nil {
return err
}
jobCtx, cancel := context.WithTimeout(ctx, w.Config.Timeout)
defer cancel()
variants, failure := w.writeObjects(jobCtx, c)
if failure != nil {
if ctx.Err() != nil {
return ctx.Err()
}
code = failure.Code
var changed bool
changed, err = w.Store.Fail(ctx, c, *failure, retryPolicy(w.Config))
if changed {
outcome = "failed_attempt"
}
return err
}
if err := w.checkpoint(ctx, j, "objects"); err != nil {
return err
}
saved, err := w.Store.Complete(ctx, c, variants)
if err != nil || !saved {
return err
}
outcome = "ready"
return w.checkpoint(ctx, j, "committed")
}
func readOriginal(ctx context.Context, blobs attachment.Blobs, c *pipeline.Claim) ([]byte, error) {
if c.SizeBytes < 1 || c.SizeBytes > imaging.MaxUploadBytes {
return nil, errSourceMismatch
}
r, err := blobs.Open(ctx, c.SourceKey)
if err != nil {
return nil, err
}
data, err := io.ReadAll(io.LimitReader(r, c.SizeBytes+1))
closeErr := r.Close()
if err != nil {
return nil, err
}
if closeErr != nil {
return nil, closeErr
}
h := sha256.Sum256(data)
if int64(len(data)) != c.SizeBytes || !bytes.Equal(h[:], c.Hash) {
return nil, errSourceMismatch
}
return data, nil
}
// Log only classified reasons. Storage and codec errors may contain URLs,
// object keys, filenames or input-derived diagnostics.
func (w *Worker) attemptFailure(c *pipeline.Claim, stage string, err error) *pipeline.Failure {
failure := &pipeline.Failure{Code: "processing_failed"}
reason := "operation_failed"
var network net.Error
var exit *exec.ExitError
var storage minio.ErrorResponse
switch {
case errors.Is(err, imaging.ErrInvalidImage):
failure.Code, failure.Permanent = "invalid_image", true
reason = failure.Code
case errors.Is(err, errSourceMismatch):
failure.Code, failure.Permanent = "source_mismatch", true
reason = failure.Code
case errors.Is(err, attachment.ErrObjectMissing):
failure.Code = "source_missing"
reason = failure.Code
case errors.Is(err, context.DeadlineExceeded):
reason = "deadline_exceeded"
case errors.Is(err, context.Canceled):
reason = "canceled"
case errors.As(err, &exit):
reason = fmt.Sprintf("codec_exit_%d", exit.ExitCode())
case errors.Is(err, exec.ErrNotFound):
reason = "codec_not_found"
case errors.As(err, &storage):
reason = fmt.Sprintf("s3_http_%d", storage.StatusCode)
case errors.As(err, &network):
reason = "network_error"
if network.Timeout() {
reason = "network_timeout"
}
case errors.Is(err, os.ErrPermission):
reason = "permission_denied"
}
w.Log.Warn("attachment attempt failed", "job_id", c.JobID, "attempt", c.Attempt,
"error_code", failure.Code, "stage", stage, "reason", reason)
return failure
}
func (w *Worker) writeObjects(ctx context.Context, c *pipeline.Claim) ([]pipeline.Variant, *pipeline.Failure) {
data, err := readOriginal(ctx, w.Blobs, c)
if err != nil {
return nil, w.attemptFailure(c, "read_original", err)
}
encoded, err := imaging.Render(ctx, data, c.PipelineVersion)
if err != nil {
return nil, w.attemptFailure(c, "render", err)
}
key := attachment.BlobKey(c.Hash)
if c.SourceKey != key {
if err := w.Blobs.Put(ctx, key, bytes.NewReader(data), c.SizeBytes, c.MIMEType); err != nil {
return nil, w.attemptFailure(c, "write_original", err)
}
}
var variants []pipeline.Variant
for _, v := range encoded {
hash := sha256.Sum256(v.Data)
key := pipeline.VariantKey(c.AttachmentID, c.PipelineVersion, v.Name, hash[:])
n := int64(len(v.Data))
if err := w.Blobs.Put(ctx, key, bytes.NewReader(v.Data), n, v.MIMEType); err != nil {
return nil, w.attemptFailure(c, "write_variant", err)
}
variants = append(variants, pipeline.Variant{
Name: v.Name, Key: key, MIMEType: v.MIMEType,
Width: v.Width, Height: v.Height, SizeBytes: n, SHA256: hash[:],
})
}
return variants, nil
}
+85
View File
@@ -0,0 +1,85 @@
package processing
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"log/slog"
"strings"
"testing"
"messenger/internal/attachment"
"messenger/internal/broker"
"messenger/internal/pipeline"
)
type stagedSource struct {
attachment.Blobs
body string
}
func (s stagedSource) Open(context.Context, string) (io.ReadCloser, error) {
return io.NopCloser(strings.NewReader(s.body)), nil
}
func TestReadOriginalValidatesPersistedSizeAndDigest(t *testing.T) {
h := sha256.Sum256([]byte("accepted"))
c := &pipeline.Claim{SizeBytes: 8, Hash: h[:], SourceKey: "staging/test"}
for _, bad := range []string{"accept", "altered!", "oversized bytes"} {
_, err := readOriginal(t.Context(), stagedSource{body: bad}, c)
if !errors.Is(err, errSourceMismatch) {
t.Fatalf("body %q: %v", bad, err)
}
}
got, err := readOriginal(t.Context(), stagedSource{body: "accepted"}, c)
if err != nil || string(got) != "accepted" {
t.Fatalf("valid original: %v", err)
}
}
type failingSource struct{ attachment.Blobs }
func (failingSource) Open(context.Context, string) (io.ReadCloser, error) {
return nil, fmt.Errorf("credentials=private-source-data: %w", context.DeadlineExceeded)
}
func TestFailureLogReportsStageAndReason(t *testing.T) {
var log strings.Builder
w := Worker{Blobs: failingSource{}, Log: slog.New(slog.NewJSONHandler(&log, nil))}
c := &pipeline.Claim{SizeBytes: 5, SourceKey: "sensitive-source-key"}
_, failure := w.writeObjects(t.Context(), c)
if failure == nil {
t.Fatal("expected failure reading source")
}
got := log.String()
for _, want := range []string{`"stage":"read_original"`, `"reason":"deadline_exceeded"`, `"error_code":"processing_failed"`, `"job_id":`, `"attempt":`} {
if !strings.Contains(got, want) {
t.Errorf("log missing %s: %s", want, got)
}
}
if strings.Contains(got, "private-source-data") || strings.Contains(got, "sensitive-source-key") {
t.Errorf("leaked source details: %s", got)
}
}
func TestConsumerSetupRetryClassifiesFailureWithoutCredentials(t *testing.T) {
var logs strings.Builder
w := Worker{Log: slog.New(slog.NewJSONHandler(&logs, nil))}
w.Config.URL = "amqp://secret-user:secret-password@%invalidhost"
err := w.consume(t.Context())
if err == nil {
t.Fatal("invalid address connected")
}
logRetry(t.Context(), w.Log, "consumer", err)
got := logs.String()
if !strings.Contains(got, "broker_connect") || strings.Contains(got, "secret-") || strings.Contains(got, "invalidhost") {
t.Fatalf("unsafe or unclassified: %s", got)
}
logs.Reset()
logRetry(t.Context(), w.Log, "dispatcher", fmt.Errorf("sensitive URL: %w", broker.ErrPublish))
if got := logs.String(); !strings.Contains(got, "broker_publish") || strings.Contains(got, "sensitive") {
t.Fatalf("unsafe or unclassified: %s", got)
}
}