File size: 7,424 Bytes
95b671e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import { createHash } from "node:crypto";
import { gzipSync } from "node:zlib";
import { GetObjectCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import type { DB } from "@superlog/db";
import * as schema from "@superlog/db/schema";
import { and, eq } from "drizzle-orm";
import { z } from "zod";

const MAX_SOURCE_MAP_BYTES = 25 * 1024 * 1024;

export const sourceMapUploadSchema = z.object({
  platform: z.string().min(1).max(32),
  release: z.string().min(1).max(200),
  dist: z.string().min(1).max(200).optional(),
  debugId: z.string().min(1).max(200).optional(),
  bundleFile: z.string().min(1).max(500).optional(),
  mapFile: z.string().min(1).max(500),
  sourceMap: z.string().min(2),
  sourceMapHash: z.string().regex(/^[a-f0-9]{64}$/),
  sourceMapBytes: z.number().int().positive().max(MAX_SOURCE_MAP_BYTES),
});

export type SourceMapUploadInput = z.infer<typeof sourceMapUploadSchema>;

export type StoredSourceMapObject = {
  bucket: string;
  key: string;
};

export type SourceMapObjectStore = {
  putSourceMapObject(input: {
    projectId: string;
    artifact: PreparedSourceMapUpload;
  }): Promise<StoredSourceMapObject>;
};

export type SourceMapObjectReader = {
  getSourceMapObject(input: StoredSourceMapObject): Promise<Buffer>;
};

export class S3SourceMapObjectStore implements SourceMapObjectStore, SourceMapObjectReader {
  private readonly s3: S3Client;

  constructor(
    private readonly config: {
      bucket: string;
      prefix?: string;
      region?: string;
      endpoint?: string;
    },
  ) {
    if (!config.bucket) throw new Error("source map bucket is required");
    this.s3 = new S3Client({
      region: config.region,
      endpoint: config.endpoint,
      forcePathStyle: Boolean(config.endpoint),
    });
  }

  async putSourceMapObject(input: {
    projectId: string;
    artifact: PreparedSourceMapUpload;
  }): Promise<StoredSourceMapObject> {
    const key = sourceMapObjectKey({
      prefix: this.config.prefix ?? "source-maps",
      projectId: input.projectId,
      platform: input.artifact.input.platform,
      sourceMapHash: input.artifact.sourceMapHash,
    });
    await this.s3.send(
      new PutObjectCommand({
        Bucket: this.config.bucket,
        Key: key,
        Body: input.artifact.content,
        ContentType: "application/json",
        ContentEncoding: "gzip",
        Metadata: {
          project_id: input.projectId,
          platform: input.artifact.input.platform,
          release: input.artifact.input.release,
          source_map_hash: input.artifact.sourceMapHash,
        },
      }),
    );
    return { bucket: this.config.bucket, key };
  }

  async getSourceMapObject(input: StoredSourceMapObject): Promise<Buffer> {
    const output = await this.s3.send(
      new GetObjectCommand({
        Bucket: input.bucket,
        Key: input.key,
      }),
    );
    if (!output.Body) throw new Error("source map object response is missing body");
    return Buffer.from(await output.Body.transformToByteArray());
  }
}

export function sourceMapObjectStoreFromEnv(
  env: NodeJS.ProcessEnv,
): (SourceMapObjectStore & SourceMapObjectReader) | null {
  const bucket = env.SOURCE_MAP_BUCKET;
  if (!bucket) return null;
  return new S3SourceMapObjectStore({
    bucket,
    prefix: env.SOURCE_MAP_PREFIX || "source-maps",
    region: env.AWS_REGION || env.AWS_DEFAULT_REGION || undefined,
    endpoint: env.AWS_ENDPOINT_URL_S3 || env.S3_ENDPOINT_URL || undefined,
  });
}

export type PreparedSourceMapUpload = {
  input: SourceMapUploadInput;
  content: Buffer;
  sourceMapHash: string;
  sourceMapBytes: number;
};

export function prepareSourceMapUpload(input: SourceMapUploadInput): {
  input: SourceMapUploadInput;
  content: Buffer;
  sourceMapHash: string;
  sourceMapBytes: number;
} {
  const sourceMapBytes = Buffer.byteLength(input.sourceMap);
  if (sourceMapBytes !== input.sourceMapBytes) {
    throw new Error("sourceMapBytes does not match sourceMap byte length");
  }
  const sourceMapHash = createHash("sha256").update(input.sourceMap).digest("hex");
  if (sourceMapHash !== input.sourceMapHash) {
    throw new Error("sourceMapHash does not match sourceMap content");
  }
  const parsed = JSON.parse(input.sourceMap) as { sources?: unknown };
  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.sources)) {
    throw new Error("sourceMap must be a JSON source map with a sources array");
  }
  return {
    input,
    content: gzipSync(input.sourceMap),
    sourceMapHash,
    sourceMapBytes,
  };
}

export async function storeSourceMapArtifact(opts: {
  database: DB;
  projectId: string;
  uploadedByOrgApiKeyId: string | null;
  objectStore: SourceMapObjectStore;
  input: SourceMapUploadInput;
}): Promise<schema.SourceMapArtifact> {
  const database = opts.database;
  const prepared = prepareSourceMapUpload(opts.input);
  const storedObject = await opts.objectStore.putSourceMapObject({
    projectId: opts.projectId,
    artifact: prepared,
  });
  const now = new Date();

  if (opts.input.debugId) {
    const existing = await database.query.sourceMapArtifacts.findFirst({
      where: and(
        eq(schema.sourceMapArtifacts.projectId, opts.projectId),
        eq(schema.sourceMapArtifacts.debugId, opts.input.debugId),
      ),
    });
    if (existing) {
      const [row] = await database
        .update(schema.sourceMapArtifacts)
        .set({
          platform: opts.input.platform,
          release: opts.input.release,
          dist: opts.input.dist ?? null,
          bundleFile: opts.input.bundleFile ?? null,
          mapFile: opts.input.mapFile,
          sourceMapHash: prepared.sourceMapHash,
          sourceMapBytes: prepared.sourceMapBytes,
          storageBucket: storedObject.bucket,
          storageKey: storedObject.key,
          contentEncoding: "gzip",
          uploadedByOrgApiKeyId: opts.uploadedByOrgApiKeyId,
          updatedAt: now,
        })
        .where(eq(schema.sourceMapArtifacts.id, existing.id))
        .returning();
      if (!row) throw new Error("failed to update source map artifact");
      return row;
    }
  }

  const [row] = await database
    .insert(schema.sourceMapArtifacts)
    .values({
      projectId: opts.projectId,
      platform: opts.input.platform,
      release: opts.input.release,
      dist: opts.input.dist ?? null,
      debugId: opts.input.debugId ?? null,
      bundleFile: opts.input.bundleFile ?? null,
      mapFile: opts.input.mapFile,
      sourceMapHash: prepared.sourceMapHash,
      sourceMapBytes: prepared.sourceMapBytes,
      storageBucket: storedObject.bucket,
      storageKey: storedObject.key,
      contentEncoding: "gzip",
      uploadedByOrgApiKeyId: opts.uploadedByOrgApiKeyId,
    })
    .returning();
  if (!row) throw new Error("failed to insert source map artifact");
  return row;
}

export function sourceMapObjectKey(input: {
  prefix: string;
  projectId: string;
  platform: string;
  sourceMapHash: string;
}): string {
  const prefix = trimSlashes(input.prefix) || "source-maps";
  return [
    prefix,
    input.projectId,
    sanitizePathSegment(input.platform),
    input.sourceMapHash.slice(0, 2),
    `${input.sourceMapHash}.map.gz`,
  ].join("/");
}

function sanitizePathSegment(value: string): string {
  return value.replace(/[^a-zA-Z0-9._-]/g, "_");
}

function trimSlashes(value: string): string {
  return value.replace(/^\/+|\/+$/g, "");
}