|
| 1 | +// Copyright 2024 Factorial GmbH. All rights reserved. |
| 2 | +// |
| 3 | +// Use of this source code is governed by a BSD-style |
| 4 | +// license that can be found in the LICENSE file. |
| 5 | + |
| 6 | +package main |
| 7 | + |
| 8 | +import ( |
| 9 | + "bytes" |
| 10 | + "context" |
| 11 | + "crypto/sha256" |
| 12 | + "encoding/hex" |
| 13 | + "encoding/json" |
| 14 | + "fmt" |
| 15 | + "log/slog" |
| 16 | + "net/url" |
| 17 | + "path/filepath" |
| 18 | + "strings" |
| 19 | + "tobey/internal/collector" |
| 20 | + |
| 21 | + "github.com/aws/aws-sdk-go-v2/aws" |
| 22 | + "github.com/aws/aws-sdk-go-v2/config" |
| 23 | + "github.com/aws/aws-sdk-go-v2/service/s3" |
| 24 | +) |
| 25 | + |
| 26 | +type s3Result struct { |
| 27 | + Run string `json:"run"` |
| 28 | + RunMetadata interface{} `json:"run_metadata,omitempty"` |
| 29 | + RequestURL string `json:"request_url"` |
| 30 | + ResponseBody []byte `json:"response_body"` // Will be base64 encoded when JSON marshalled. |
| 31 | + ResponseStatusCode int `json:"response_status_code"` |
| 32 | +} |
| 33 | + |
| 34 | +type S3ResultReporterConfig struct { |
| 35 | + Bucket string |
| 36 | + Prefix string |
| 37 | +} |
| 38 | + |
| 39 | +func newS3ResultReporterConfigFromDSN(dsn string) (S3ResultReporterConfig, error) { |
| 40 | + s3config := S3ResultReporterConfig{} |
| 41 | + |
| 42 | + u, err := url.Parse(dsn) |
| 43 | + if err != nil { |
| 44 | + return s3config, fmt.Errorf("invalid s3 result reporter DSN: %w", err) |
| 45 | + } |
| 46 | + |
| 47 | + // Extract bucket and optional prefix from the path |
| 48 | + parts := strings.SplitN(strings.TrimPrefix(u.Path, "/"), "/", 2) |
| 49 | + if len(parts) == 0 { |
| 50 | + return s3config, fmt.Errorf("bucket name is required in S3 DSN") |
| 51 | + } |
| 52 | + |
| 53 | + s3config.Bucket = parts[0] |
| 54 | + if len(parts) > 1 { |
| 55 | + s3config.Prefix = parts[1] |
| 56 | + } |
| 57 | + |
| 58 | + return s3config, nil |
| 59 | +} |
| 60 | + |
| 61 | +// ReportResultToS3 stores results in S3 as JSON files. Results are grouped by run |
| 62 | +// in a run specific directory. The directory structure is as follows: |
| 63 | +// |
| 64 | +// <prefix>/<run_uuid>/<url_hash>.json |
| 65 | +// |
| 66 | +// The <url_hash> is the SHA-256 hash of the request URL, encoded as a hex string. |
| 67 | +// The JSON file contains the result as a JSON object. |
| 68 | +func ReportResultToS3(ctx context.Context, s3config S3ResultReporterConfig, run *Run, res *collector.Response) error { |
| 69 | + logger := slog.With("run", run.ID, "url", res.Request.URL) |
| 70 | + logger.Debug("Result reporter: Saving result to S3...") |
| 71 | + |
| 72 | + // Load AWS configuration using aws-sdk-go-v2/config package |
| 73 | + awsCfg, err := config.LoadDefaultConfig(ctx) |
| 74 | + if err != nil { |
| 75 | + return fmt.Errorf("unable to load AWS SDK config: %w", err) |
| 76 | + } |
| 77 | + |
| 78 | + // Create S3 client |
| 79 | + client := s3.NewFromConfig(awsCfg) |
| 80 | + |
| 81 | + result := &s3Result{ |
| 82 | + Run: run.ID, |
| 83 | + RequestURL: res.Request.URL.String(), |
| 84 | + ResponseBody: res.Body[:], |
| 85 | + ResponseStatusCode: res.StatusCode, |
| 86 | + } |
| 87 | + |
| 88 | + // Generate the object key |
| 89 | + hash := sha256.New() |
| 90 | + hash.Write([]byte(res.Request.URL.String())) |
| 91 | + filename := fmt.Sprintf("%s.json", hex.EncodeToString(hash.Sum(nil))) |
| 92 | + |
| 93 | + // Construct the full S3 key |
| 94 | + key := filepath.Join(s3config.Prefix, run.ID, filename) |
| 95 | + key = strings.TrimLeft(key, "/") // Remove leading slash as S3 doesn't need it |
| 96 | + |
| 97 | + // Marshal the result to JSON |
| 98 | + jsonData, err := json.MarshalIndent(result, "", " ") |
| 99 | + if err != nil { |
| 100 | + return err |
| 101 | + } |
| 102 | + |
| 103 | + // Upload to S3 |
| 104 | + _, err = client.PutObject(ctx, &s3.PutObjectInput{ |
| 105 | + Bucket: aws.String(s3config.Bucket), |
| 106 | + Key: aws.String(key), |
| 107 | + Body: bytes.NewReader(jsonData), |
| 108 | + ContentType: aws.String("application/json"), |
| 109 | + }) |
| 110 | + if err != nil { |
| 111 | + return fmt.Errorf("failed to upload to S3: %w", err) |
| 112 | + } |
| 113 | + |
| 114 | + logger.Debug("Result reporter: Successfully saved result to S3", |
| 115 | + "bucket", s3config.Bucket, |
| 116 | + "key", key, |
| 117 | + ) |
| 118 | + return nil |
| 119 | +} |
0 commit comments