|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + b64 "encoding/base64" |
| 7 | + "encoding/json" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "io/ioutil" |
| 11 | + "log" |
| 12 | + "net/http" |
| 13 | + "os" |
| 14 | + "runtime" |
| 15 | + "time" |
| 16 | + |
| 17 | + "github.com/pkg/errors" |
| 18 | + |
| 19 | + "github.com/cdnjs/tools/audit" |
| 20 | + "github.com/cdnjs/tools/gcp" |
| 21 | + "github.com/cdnjs/tools/metrics" |
| 22 | + "github.com/cdnjs/tools/packages" |
| 23 | + "github.com/cdnjs/tools/sentry" |
| 24 | + |
| 25 | + "github.com/aws/aws-sdk-go-v2/aws" |
| 26 | + "github.com/aws/aws-sdk-go-v2/config" |
| 27 | + "github.com/aws/aws-sdk-go-v2/credentials" |
| 28 | + "github.com/aws/aws-sdk-go-v2/service/s3" |
| 29 | + |
| 30 | + "cloud.google.com/go/pubsub" |
| 31 | +) |
| 32 | + |
| 33 | +var ( |
| 34 | + PROJECT = os.Getenv("PROJECT") |
| 35 | + SUBSCRIPTION = os.Getenv("SUBSCRIPTION") |
| 36 | + |
| 37 | + R2_BUCKET = os.Getenv("R2_BUCKET") |
| 38 | + R2_KEY_ID = os.Getenv("R2_KEY_ID") |
| 39 | + R2_KEY_SECRET = os.Getenv("R2_KEY_SECRET") |
| 40 | + R2_ENDPOINT = os.Getenv("R2_ENDPOINT") |
| 41 | +) |
| 42 | + |
| 43 | +func init() { |
| 44 | + sentry.Init() |
| 45 | +} |
| 46 | + |
| 47 | +func main() { |
| 48 | + ctx := context.Background() |
| 49 | + client, err := pubsub.NewClient(ctx, PROJECT) |
| 50 | + if err != nil { |
| 51 | + log.Fatalf("could not create pubsub Client: %v", err) |
| 52 | + } |
| 53 | + sub := client.Subscription(SUBSCRIPTION) |
| 54 | + sub.ReceiveSettings.Synchronous = true |
| 55 | + sub.ReceiveSettings.MaxOutstandingMessages = 5 |
| 56 | + sub.ReceiveSettings.NumGoroutines = runtime.NumCPU() |
| 57 | + |
| 58 | + for { |
| 59 | + log.Printf("started consuming messages\n") |
| 60 | + if err := consume(ctx, client, sub); err != nil { |
| 61 | + log.Fatalf("could not pull messages: %s", err) |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +type Message struct { |
| 67 | + GCSEvent gcp.GCSEvent `json:"gcsEvent"` |
| 68 | +} |
| 69 | + |
| 70 | +func consume(ctx context.Context, client *pubsub.Client, sub *pubsub.Subscription) error { |
| 71 | + err := sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) { |
| 72 | + log.Printf("received message: %s\n", msg.Data) |
| 73 | + |
| 74 | + msg.Ack() |
| 75 | + if err := processMessage(ctx, msg.Data); err != nil { |
| 76 | + log.Printf("failed to process message: %s\n", err) |
| 77 | + } |
| 78 | + }) |
| 79 | + if err != nil { |
| 80 | + return errors.Wrap(err, "could not receive from subscription") |
| 81 | + } |
| 82 | + return nil |
| 83 | +} |
| 84 | + |
| 85 | +func processMessage(ctx context.Context, data []byte) error { |
| 86 | + var message Message |
| 87 | + if err := json.Unmarshal(data, &message); err != nil { |
| 88 | + return errors.Wrap(err, "failed to parse") |
| 89 | + } |
| 90 | + |
| 91 | + return invoke(ctx, message.GCSEvent) |
| 92 | +} |
| 93 | + |
| 94 | +func invoke(ctx context.Context, e gcp.GCSEvent) error { |
| 95 | + sentry.Init() |
| 96 | + defer sentry.PanicHandler() |
| 97 | + |
| 98 | + pkgName := e.Metadata["package"].(string) |
| 99 | + version := e.Metadata["version"].(string) |
| 100 | + log.Printf("Invoke %s %s\n", pkgName, version) |
| 101 | + |
| 102 | + configStr, err := b64.StdEncoding.DecodeString(e.Metadata["config"].(string)) |
| 103 | + if err != nil { |
| 104 | + return fmt.Errorf("could not decode config: %v", err) |
| 105 | + } |
| 106 | + |
| 107 | + archive, err := gcp.ReadObject(ctx, e.Bucket, e.Name) |
| 108 | + if err != nil { |
| 109 | + return fmt.Errorf("could not read object: %v", err) |
| 110 | + } |
| 111 | + |
| 112 | + bucket := aws.String(R2_BUCKET) |
| 113 | + |
| 114 | + r2Resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) { |
| 115 | + return aws.Endpoint{ |
| 116 | + URL: R2_ENDPOINT, |
| 117 | + }, nil |
| 118 | + }) |
| 119 | + |
| 120 | + cfg, err := config.LoadDefaultConfig(ctx, |
| 121 | + config.WithEndpointResolverWithOptions(r2Resolver), |
| 122 | + config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(R2_KEY_ID, R2_KEY_SECRET, "")), |
| 123 | + ) |
| 124 | + if err != nil { |
| 125 | + return fmt.Errorf("could not load config: %s", err) |
| 126 | + } |
| 127 | + |
| 128 | + s3Client := s3.NewFromConfig(cfg) |
| 129 | + |
| 130 | + keys := make([]string, 0) |
| 131 | + |
| 132 | + onFile := func(name string, r io.Reader) error { |
| 133 | + // remove leading slash |
| 134 | + name = name[1:] |
| 135 | + key := fmt.Sprintf("%s/%s/%s", pkgName, version, name) |
| 136 | + |
| 137 | + content, err := ioutil.ReadAll(r) |
| 138 | + if err != nil { |
| 139 | + return errors.Wrap(err, "could not read file") |
| 140 | + } |
| 141 | + |
| 142 | + keys = append(keys, key) |
| 143 | + |
| 144 | + meta := newMetadata(len(content)) |
| 145 | + |
| 146 | + s3Object := s3.PutObjectInput{ |
| 147 | + Body: bytes.NewReader(content), |
| 148 | + Bucket: bucket, |
| 149 | + Key: aws.String(key), |
| 150 | + Metadata: meta, |
| 151 | + } |
| 152 | + if err := uploadFile(ctx, s3Client, &s3Object); err != nil { |
| 153 | + return errors.Wrap(err, "failed to upload file") |
| 154 | + } |
| 155 | + return nil |
| 156 | + } |
| 157 | + if err := gcp.Inflate(bytes.NewReader(archive), onFile); err != nil { |
| 158 | + return fmt.Errorf("could not inflate archive: %s", err) |
| 159 | + } |
| 160 | + |
| 161 | + if len(keys) == 0 { |
| 162 | + log.Printf("%s: no files to publish\n", pkgName) |
| 163 | + } |
| 164 | + |
| 165 | + pkg := new(packages.Package) |
| 166 | + if err := json.Unmarshal([]byte(configStr), &pkg); err != nil { |
| 167 | + return fmt.Errorf("failed to parse config: %s", err) |
| 168 | + } |
| 169 | + |
| 170 | + if err := audit.WroteR2(ctx, pkgName, version, keys); err != nil { |
| 171 | + log.Printf("failed to audit: %s\n", err) |
| 172 | + } |
| 173 | + if err := metrics.NewUpdatePublishedR2(); err != nil { |
| 174 | + return errors.Wrap(err, "could not report metrics") |
| 175 | + } |
| 176 | + |
| 177 | + return nil |
| 178 | +} |
| 179 | + |
| 180 | +func newMetadata(size int) map[string]string { |
| 181 | + lastModifiedTime := time.Now() |
| 182 | + lastModifiedSeconds := lastModifiedTime.UnixNano() / int64(time.Second) |
| 183 | + lastModifiedStr := lastModifiedTime.Format(http.TimeFormat) |
| 184 | + etag := fmt.Sprintf("%x-%x", lastModifiedSeconds, size) |
| 185 | + |
| 186 | + meta := make(map[string]string) |
| 187 | + |
| 188 | + // https://github.com/cdnjs/origin-worker/blob/ff91d30586c9e924ff919407401dff6f52826b4d/src/index.js#L212-L213 |
| 189 | + meta["etag"] = etag |
| 190 | + meta["last_modified"] = lastModifiedStr |
| 191 | + |
| 192 | + return meta |
| 193 | +} |
| 194 | + |
| 195 | +func uploadFile(ctx context.Context, s3Client *s3.Client, obj *s3.PutObjectInput) error { |
| 196 | + if _, err := s3Client.PutObject(ctx, obj); err != nil { |
| 197 | + return errors.Wrapf(err, "failed to put Object %s", *obj.Key) |
| 198 | + } |
| 199 | + |
| 200 | + return nil |
| 201 | +} |
0 commit comments