All files / core/blong-gogo/src/adapter/server s3.ts

81.92% Statements 290/354
36.5% Branches 23/63
100% Functions 5/5
81.92% Lines 290/354

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 3551x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x         45x 45x 45x 45x 45x 45x 45x     45x 45x 45x 14x 14x     14x 14x     14x 14x 14x 14x 14x 14x 12x 12x 45x 1x 1x 1x 1x     1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 45x 12x 12x     12x 12x 12x     12x 12x                                                 12x 12x     12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 12x 12x 45x 45x 9x 9x     9x 9x     9x 9x 9x 9x 9x 9x 9x 45x 45x 5x 5x     5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 5x 5x 5x 5x 5x 5x 45x 45x 3x 3x     3x 3x     3x 3x 3x 3x 3x 3x 3x 45x 1x 1x     1x 1x     1x     1x     1x 1x 1x 1x 1x 1x 1x 1x 45x     45x 45x 45x 45x 3x 3x  
import {
    CopyObjectCommand,
    DeleteObjectCommand,
    GetObjectCommand,
    type GetObjectCommandOutput,
    HeadObjectCommand,
    ListBucketsCommand,
    ListObjectsV2Command,
    PutObjectCommand,
    S3Client,
} from '@aws-sdk/client-s3';
import {Upload} from '@aws-sdk/lib-storage';
import {adapter, type Errors, type IErrorMap, type IMeta} from '@feasibleone/blong/types';
import {createReadStream, statSync} from 'fs';
import {Readable} from 'stream';
 
export interface IConfig {
    s3: {
        region?: string;
        endpoint?: string;
        credentials?: {
            accessKeyId: string;
            secretAccessKey: string;
        };
        forcePathStyle?: boolean;
        requestStreamBufferSize?: number;
    };
    bucket?: {
        Bucket?: string;
    };
    url?: string;
    context: {
        s3?: S3Client;
    };
}
 
const errorMap: IErrorMap = {
    's3.generic': 'S3 Error',
    's3.invalid': 'Invalid S3 Operation',
    's3.notFound': 'S3 Object Not Found',
    's3.exists': 'S3 Object Already Exists',
    's3.accessDenied': 'S3 Access Denied',
    's3.missingKey': 'Missing key value for {key}',
    's3.missingBucket': 'Missing bucket parameter',
};
 
let _errors: Errors<typeof errorMap>;
 
/** The answer a `get` makes: the object buffered whole, for the callers that expect bytes. */
export async function s3BufferAnswer(response: GetObjectCommandOutput) {
    return {
        body: await response.Body?.transformToByteArray(),
        contentType: response.ContentType,
        contentLength: response.ContentLength,
        metadata: response.Metadata,
        lastModified: response.LastModified,
        etag: response.ETag,
    };
}
 
/**
 * The answer a `stream` makes: the object as a stream, with the headers a reader needs to hand it on.
 *
 * Nothing is buffered, so a caller serving a file never holds it — and `range` comes back as
 * `contentRange`, which is what a `206` answer carries (@@D-838).
 */
export function s3StreamAnswer(response: GetObjectCommandOutput) {
    return {
        body: response.Body as unknown as Readable,
        contentType: response.ContentType,
        contentLength: response.ContentLength,
        contentRange: response.ContentRange,
        acceptRanges: response.AcceptRanges,
        metadata: response.Metadata,
        lastModified: response.LastModified,
        etag: response.ETag,
    };
}
 
export default adapter<IConfig>(({utError}) => {
    _errors ||= utError.register(errorMap);
 
    return {
        activation: {
            default: {
                type: 's3',
                s3: {
                    requestStreamBufferSize: 64 * 1024,
                },
                bucket: {},
            },
        },
        async start() {
            this.config.context = {s3: new S3Client(this.config.s3)};
            super.connect();
            return super.start();
        },
        async stop(...params: unknown[]) {
            let result;
            try {
                this.config.context.s3!.destroy();
            } finally {
                this.config.context = {};
                result = await super.stop(...params);
            }
            return result;
        },
        async exec(
            params:
                | ({
                      bucket?: string;
                      key?: string;
                      body?: PutObjectCommand['input']['Body'];
                      url?: string;
                      contentType?: string;
                      metadata?: Record<string, string>;
                      prefix?: string;
                      maxKeys?: number;
                      /** An HTTP range (`bytes=0-1023`), honoured by the `stream` operation. */
                      range?: string;
                      sourceBucket?: string;
                      sourceKey?: string;
                  } & Record<string, unknown>)
                | unknown[],
            $meta: IMeta,
        ) {
            const {method} = $meta;
            const [, object, operation] = method!.split('.');
            if (process.env['BLOB_S3_DEBUG'])
                console.log('S3-EXEC', JSON.stringify({method, object, operation}));
            let bucket: string | undefined;
            let actualParams = params;
 
            if (!Array.isArray(params) && params.bucket) {
                bucket = params.bucket;
                const {bucket: _bucketParam, ...rest} = params;
                actualParams = rest;
            }
 
            // Bucket enumeration (`s3.bucket.list`) does not need a target bucket.
            const needsBucket = !(
                object === 'bucket' &&
                (operation === 'list' || operation === 'find')
            );
            if (!bucket && !this.config.bucket?.Bucket && needsBucket) {
                throw this.error(_errors['s3.missingBucket'](), $meta);
            }
 
            switch (operation) {
                case 'get': {
                    // Get object from S3
                    if (Array.isArray(actualParams)) {
                        throw this.error(_errors['s3.invalid'](), $meta);
                    }
                    const {key} = actualParams;
                    if (!key) {
                        throw this.error(_errors['s3.missingKey']({key: 'key'}), $meta);
                    }
 
                    const command = new GetObjectCommand({
                        Bucket: bucket ?? this.config.bucket?.Bucket ?? '',
                        Key: key,
                    });
                    const response = await this.config.context.s3!.send(command);
                    return s3BufferAnswer(response);
                }
                case 'stream': {
                    // The same object as `get`, answered as a stream: a caller that serves a file hands
                    // the bytes on without ever holding them (@@D-838). `range` asks for a slice, which
                    // is what a `Range:` request turns into.
                    if (Array.isArray(actualParams)) {
                        throw this.error(_errors['s3.invalid'](), $meta);
                    }
                    const {key, range} = actualParams as {key?: string; range?: string};
                    if (!key) {
                        throw this.error(_errors['s3.missingKey']({key: 'key'}), $meta);
                    }
 
                    const command = new GetObjectCommand({
                        Bucket: bucket ?? this.config.bucket?.Bucket ?? '',
                        Key: key,
                        ...(range ? {Range: range} : {}),
                    });
                    const response = await this.config.context.s3!.send(command);
                    return s3StreamAnswer(response);
                }
                case 'add': {
                    // Put object to S3
                    if (Array.isArray(actualParams)) {
                        throw this.error(_errors['s3.invalid'](), $meta);
                    }
                    const {url, key, metadata} = actualParams;
                    let {body, contentType} = actualParams;
                    if (!key) {
                        throw this.error(_errors['s3.missingKey']({key: 'key'}), $meta);
                    }
                    let contentLength: number | undefined;
                    if (url && !body) {
                        if (/^https?:\/\//.test(url)) {
                            try {
                                const response = await fetch(url);
                                contentType ||= response.headers.get('content-type') ?? undefined;
                                contentLength = Number(response.headers.get('content-length'));
                                body =
                                    contentLength > 0
                                        ? Readable.fromWeb(
                                              response.body as import('stream/web').ReadableStream,
                                          )
                                        : Buffer.from(await response.arrayBuffer());
                            } catch (error) {
                                this.signal?.frameworkS3ReportFetchFailed?.({
                                    url,
                                    error: (error as Error).message,
                                });
                                throw error;
                            }
                        } else {
                            contentLength = statSync(url).size;
                            body = createReadStream(url);
                            contentType ||= 'text/html';
                        }
                    }
 
                    if (body === undefined) {
                        throw this.error(_errors['s3.missingKey']({key: 'body'}), $meta);
                    }
 
                    // A stream whose length nobody knows — a file being encrypted as it is read, a
                    // response being forwarded — cannot be a `PutObject`: the request signs its length
                    // before the first byte exists, so the SDK refuses it with
                    // `Invalid value "undefined" for header "x-amz-decoded-content-length"`, or the server
                    // answers `MissingContentLength`. The SDK's own uploader splits such a body into parts
                    // and holds one part at a time, which is what serving a large file needs (@@D-838).
                    const streamed =
                        contentLength === undefined &&
                        body != null &&
                        typeof (body as {pipe?: unknown}).pipe === 'function';
                    const putResult = streamed
                        ? await new Upload({
                              client: this.config.context.s3!,
                              params: {
                                  Bucket: bucket ?? this.config.bucket?.Bucket ?? '',
                                  Key: key,
                                  Body: body as import('@aws-sdk/client-s3').PutObjectCommandInput['Body'],
                                  ContentType: contentType ?? undefined,
                                  Metadata: metadata,
                              },
                          }).done()
                        : await this.config.context.s3!.send(
                              new PutObjectCommand({
                                  Bucket: bucket ?? this.config.bucket?.Bucket ?? '',
                                  Key: key,
                                  Body: body as import('@aws-sdk/client-s3').PutObjectCommandInput['Body'],
                                  ContentType: contentType ?? undefined,
                                  ...(contentLength != null &&
                                      contentLength > 0 && {ContentLength: contentLength}),
                                  Metadata: metadata,
                              }),
                          );
                    return this.config.url?.replace?.('{key}', key) ?? {key, etag: putResult.ETag};
                }
                case 'delete':
                case 'remove': {
                    // Delete object from S3
                    if (Array.isArray(actualParams)) {
                        throw this.error(_errors['s3.invalid'](), $meta);
                    }
                    const {key} = actualParams;
                    if (!key) {
                        throw this.error(_errors['s3.missingKey']({key: 'key'}), $meta);
                    }
 
                    const command = new DeleteObjectCommand({
                        Bucket: bucket ?? this.config.bucket?.Bucket ?? '',
                        Key: key,
                    });
                    return this.config.context.s3!.send(command);
                }
                case 'list':
                case 'find': {
                    // List objects in S3 bucket
                    if (Array.isArray(actualParams)) {
                        throw this.error(_errors['s3.invalid'](), $meta);
                    }
                    // `s3.bucket.list` — enumerate buckets on the endpoint
                    if (object === 'bucket') {
                        const command = new ListBucketsCommand({});
                        const response = await this.config.context.s3!.send(command);
                        return {
                            items:
                                response.Buckets?.map(b => ({
                                    bucket: b.Name,
                                    creationDate: b.CreationDate,
                                })) ?? [],
                        };
                    }
                    const {prefix, maxKeys = 1000} = actualParams;
 
                    const command = new ListObjectsV2Command({
                        Bucket: bucket ?? this.config.bucket?.Bucket ?? '',
                        Prefix: prefix,
                        MaxKeys: maxKeys,
                    });
                    return this.config.context.s3!.send(command);
                }
                case 'head':
                case 'metadata': {
                    // Get object metadata
                    if (Array.isArray(actualParams)) {
                        throw this.error(_errors['s3.invalid'](), $meta);
                    }
                    const {key} = actualParams;
                    if (!key) {
                        throw this.error(_errors['s3.missingKey']({key: 'key'}), $meta);
                    }
 
                    const command = new HeadObjectCommand({
                        Bucket: bucket ?? this.config.bucket?.Bucket ?? '',
                        Key: key,
                    });
                    return this.config.context.s3!.send(command);
                }
                case 'copy': {
                    // Copy object within S3
                    if (Array.isArray(actualParams)) {
                        throw this.error(_errors['s3.invalid'](), $meta);
                    }
                    const {key, sourceBucket, sourceKey} = actualParams;
                    if (!key) {
                        throw this.error(_errors['s3.missingKey']({key: 'key'}), $meta);
                    }
                    if (!sourceBucket) {
                        throw this.error(_errors['s3.missingKey']({key: 'sourceBucket'}), $meta);
                    }
                    if (!sourceKey) {
                        throw this.error(_errors['s3.missingKey']({key: 'sourceKey'}), $meta);
                    }
 
                    const command = new CopyObjectCommand({
                        Bucket: bucket ?? this.config.bucket?.Bucket ?? '',
                        Key: key,
                        CopySource: `${sourceBucket}/${sourceKey}`,
                    });
                    return this.config.context.s3!.send(command);
                }
            }
            console.log(
                'S3-FALLTHROUGH',
                JSON.stringify({method: $meta?.method, object, operation}),
            );
            throw this.error(_errors['s3.generic']({}), $meta);
        },
    };
});