@atproto/aws 0.3.18 → 0.3.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/s3.d.ts +29 -7
- package/dist/s3.d.ts.map +1 -1
- package/dist/s3.js +61 -27
- package/dist/s3.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @atproto/aws
|
|
2
2
|
|
|
3
|
+
## 0.3.19
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#5576](https://github.com/bluesky-social/atproto/pull/5576) [`13b7cb0`](https://github.com/bluesky-social/atproto/commit/13b7cb000d7358a570be46854a93e441c8fa791e) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Add explicit resource management to `BlobStore` and `BlobStoreCreator` interfaces
|
|
8
|
+
|
|
9
|
+
- [#5575](https://github.com/bluesky-social/atproto/pull/5575) [`52e51de`](https://github.com/bluesky-social/atproto/commit/52e51de0fc7b27173fe7ecc2c7b47ec476a8c1bf) Thanks [@jcalabro](https://github.com/jcalabro)! - Share one S3 client across the blob stores returned by `S3BlobStore.creator()` so that connections to S3 are reused instead of opening a new one for every blob request, and add a `maxSockets` option (uncapped by default).
|
|
10
|
+
- Updated dependencies [[`13b7cb0`](https://github.com/bluesky-social/atproto/commit/13b7cb000d7358a570be46854a93e441c8fa791e), [`f8ed258`](https://github.com/bluesky-social/atproto/commit/f8ed25853dc91a16639decfaee2e0dcbb60808cd), [`a6561d5`](https://github.com/bluesky-social/atproto/commit/a6561d54227756876a0901e4a87675df17972d32)]:
|
|
11
|
+
- @atproto/repo@0.11.0
|
|
12
|
+
- @atproto/crypto@0.5.7
|
|
13
|
+
- @atproto/common@0.8.5
|
|
14
|
+
- @atproto/common-web@0.5.14
|
|
15
|
+
|
|
3
16
|
## 0.3.18
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
package/dist/s3.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type stream from 'node:stream';
|
|
2
|
-
import { type S3ClientConfig } from '@aws-sdk/client-s3';
|
|
2
|
+
import { S3, type S3ClientConfig } from '@aws-sdk/client-s3';
|
|
3
3
|
import type { CID } from 'multiformats/cid';
|
|
4
|
-
import { type BlobStore } from '@atproto/repo';
|
|
4
|
+
import { type BlobStore, type BlobStoreCreator } from '@atproto/repo';
|
|
5
5
|
export type S3Config = {
|
|
6
6
|
bucket: string;
|
|
7
7
|
/**
|
|
@@ -47,14 +47,29 @@ export type S3Config = {
|
|
|
47
47
|
* enough to accommodate slow clients uploading large blobs.
|
|
48
48
|
*/
|
|
49
49
|
uploadTimeoutMs?: number;
|
|
50
|
+
/**
|
|
51
|
+
* The maximum number of concurrent connections to S3 per client. Blob
|
|
52
|
+
* downloads are streamed at the pace of the downstream consumer, so a finite
|
|
53
|
+
* cap lets slow consumers hold every connection and queue all other blob
|
|
54
|
+
* reads and writes behind them.
|
|
55
|
+
*
|
|
56
|
+
* Defaults to `Infinity`.
|
|
57
|
+
*/
|
|
58
|
+
maxSockets?: number;
|
|
50
59
|
} & Omit<S3ClientConfig, 'apiVersion' | 'requestHandler'>;
|
|
51
60
|
export declare class S3BlobStore implements BlobStore {
|
|
52
61
|
did: string;
|
|
53
|
-
private
|
|
54
|
-
private
|
|
55
|
-
private
|
|
56
|
-
|
|
57
|
-
|
|
62
|
+
private readonly clientOwned;
|
|
63
|
+
private readonly client;
|
|
64
|
+
private readonly bucket;
|
|
65
|
+
private readonly uploadTimeoutMs;
|
|
66
|
+
/**
|
|
67
|
+
* @param client Shared by every store returned from
|
|
68
|
+
* {@link S3BlobStore.creator}, so that they reuse one connection pool.
|
|
69
|
+
* Defaults to a new client built from `cfg`.
|
|
70
|
+
*/
|
|
71
|
+
constructor(did: string, cfg: S3Config, client?: S3);
|
|
72
|
+
static creator(cfg: S3Config): BlobStoreCreator;
|
|
58
73
|
private genKey;
|
|
59
74
|
private getTmpPath;
|
|
60
75
|
private getStoredPath;
|
|
@@ -76,6 +91,13 @@ export declare class S3BlobStore implements BlobStore {
|
|
|
76
91
|
private deleteKey;
|
|
77
92
|
private deleteManyKeys;
|
|
78
93
|
private move;
|
|
94
|
+
/**
|
|
95
|
+
* Destroy underlying resources, like sockets. It's usually not necessary to
|
|
96
|
+
* do this. However in Node.js, it's best to explicitly shut down the client's
|
|
97
|
+
* agent when it is no longer needed. Otherwise, sockets might stay open for
|
|
98
|
+
* quite a long time before the server terminates them.
|
|
99
|
+
*/
|
|
100
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
79
101
|
}
|
|
80
102
|
export default S3BlobStore;
|
|
81
103
|
//# sourceMappingURL=s3.d.ts.map
|
package/dist/s3.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"s3.d.ts","sourceRoot":"","sources":["../src/s3.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,
|
|
1
|
+
{"version":3,"file":"s3.d.ts","sourceRoot":"","sources":["../src/s3.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,EAAa,EAAE,EAAE,KAAK,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAEvE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAG3C,OAAO,EAEL,KAAK,SAAS,EACd,KAAK,gBAAgB,EACtB,MAAM,eAAe,CAAA;AAEtB,MAAM,MAAM,QAAQ,GAAG;IACrB,MAAM,EAAE,MAAM,CAAA;IACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB;;;;;;;OA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AO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAGlD;IAEK,MAAM,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAEpC;IAEK,UAAU,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAW3C;IAEK,SAAS,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,CAE1C;IAEK,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAE3C;YAEa,MAAM;YAYN,SAAS;YAOT,cAAc;YASd,IAAI;IA+BlB;;;;;OAKG;IACG,CAAC,MAAM,CAAC,YAAY,CAAC,kBAE1B;CACF;eAEc,WAAW"}
|
package/dist/s3.js
CHANGED
|
@@ -2,38 +2,62 @@ import { NoSuchKey, S3 } from '@aws-sdk/client-s3';
|
|
|
2
2
|
import { Upload } from '@aws-sdk/lib-storage';
|
|
3
3
|
import { SECOND, aggregateErrors, chunkArray } from '@atproto/common-web';
|
|
4
4
|
import { randomStr } from '@atproto/crypto';
|
|
5
|
-
import { BlobNotFoundError } from '@atproto/repo';
|
|
5
|
+
import { BlobNotFoundError, } from '@atproto/repo';
|
|
6
|
+
const DEFAULT_UPLOAD_TIMEOUT_MS = 10 * SECOND;
|
|
7
|
+
function createS3Client(cfg) {
|
|
8
|
+
const { bucket, uploadTimeoutMs = DEFAULT_UPLOAD_TIMEOUT_MS,
|
|
9
|
+
// @NOTE The request timeout acts as a stall detector (socket idle
|
|
10
|
+
// timeout) and should stay short even when uploadTimeoutMs is large,
|
|
11
|
+
// so that stalled S3 connections are reaped and retried quickly. The 6s
|
|
12
|
+
// floor keeps the idle timeout from applying to streamed (client-paced)
|
|
13
|
+
// blob downloads (see S3Config.requestTimeoutMs).
|
|
14
|
+
requestTimeoutMs = Math.max(Math.min(uploadTimeoutMs, 15 * SECOND), 6 * SECOND), connectionTimeoutMs = 5 * SECOND, maxSockets = Infinity, ...rest } = cfg;
|
|
15
|
+
return new S3({
|
|
16
|
+
...rest,
|
|
17
|
+
apiVersion: '2006-03-01',
|
|
18
|
+
// Ensures that all requests timeout under "requestTimeoutMs".
|
|
19
|
+
//
|
|
20
|
+
// @NOTE This will also apply to the upload of each individual blob
|
|
21
|
+
// chunk when using Upload from @aws-sdk/lib-storage. This is fine
|
|
22
|
+
// because chunks are buffered in memory before being sent, meaning that
|
|
23
|
+
// requests to S3 are not client-paced.
|
|
24
|
+
requestHandler: {
|
|
25
|
+
requestTimeout: requestTimeoutMs,
|
|
26
|
+
connectionTimeout: connectionTimeoutMs,
|
|
27
|
+
httpAgent: { maxSockets },
|
|
28
|
+
httpsAgent: { maxSockets },
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
}
|
|
6
32
|
export class S3BlobStore {
|
|
7
|
-
|
|
33
|
+
/**
|
|
34
|
+
* @param client Shared by every store returned from
|
|
35
|
+
* {@link S3BlobStore.creator}, so that they reuse one connection pool.
|
|
36
|
+
* Defaults to a new client built from `cfg`.
|
|
37
|
+
*/
|
|
38
|
+
constructor(did, cfg, client) {
|
|
8
39
|
this.did = did;
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
// floor keeps the idle timeout from applying to streamed (client-paced)
|
|
14
|
-
// blob downloads (see S3Config.requestTimeoutMs).
|
|
15
|
-
requestTimeoutMs = Math.max(Math.min(uploadTimeoutMs, 15 * SECOND), 6 * SECOND), connectionTimeoutMs = 5 * SECOND, ...rest } = cfg;
|
|
16
|
-
this.bucket = bucket;
|
|
17
|
-
this.uploadTimeoutMs = uploadTimeoutMs;
|
|
18
|
-
this.client = new S3({
|
|
19
|
-
...rest,
|
|
20
|
-
apiVersion: '2006-03-01',
|
|
21
|
-
// Ensures that all requests timeout under "requestTimeoutMs".
|
|
22
|
-
//
|
|
23
|
-
// @NOTE This will also apply to the upload of each individual blob
|
|
24
|
-
// chunk when using Upload from @aws-sdk/lib-storage. This is fine
|
|
25
|
-
// because chunks are buffered in memory before being sent, meaning that
|
|
26
|
-
// requests to S3 are not client-paced.
|
|
27
|
-
requestHandler: {
|
|
28
|
-
requestTimeout: requestTimeoutMs,
|
|
29
|
-
connectionTimeout: connectionTimeoutMs,
|
|
30
|
-
},
|
|
31
|
-
});
|
|
40
|
+
this.bucket = cfg.bucket;
|
|
41
|
+
this.uploadTimeoutMs = cfg.uploadTimeoutMs ?? DEFAULT_UPLOAD_TIMEOUT_MS;
|
|
42
|
+
this.client = client ?? createS3Client(cfg);
|
|
43
|
+
this.clientOwned = client === undefined;
|
|
32
44
|
}
|
|
33
45
|
static creator(cfg) {
|
|
34
|
-
|
|
35
|
-
|
|
46
|
+
// @NOTE A store is created for every actor store access. A client per
|
|
47
|
+
// store would open a fresh TLS connection to S3 for every blob request and
|
|
48
|
+
// leave it idle in an unreachable pool, exhausting ephemeral ports under
|
|
49
|
+
// load.
|
|
50
|
+
const client = createS3Client(cfg);
|
|
51
|
+
const creator = (did) => {
|
|
52
|
+
return new S3BlobStore(did, cfg, client);
|
|
36
53
|
};
|
|
54
|
+
// The S3BlobStore instances won't own the client, the BlobStoreCreator
|
|
55
|
+
// does. In order to properly clean up the client, we attach an async
|
|
56
|
+
// dispose method to the creator itself.
|
|
57
|
+
Object.defineProperty(creator, Symbol.asyncDispose, {
|
|
58
|
+
value: async () => client.destroy(),
|
|
59
|
+
});
|
|
60
|
+
return creator;
|
|
37
61
|
}
|
|
38
62
|
genKey() {
|
|
39
63
|
return randomStr(32, 'base32');
|
|
@@ -224,6 +248,16 @@ export class S3BlobStore {
|
|
|
224
248
|
throw err;
|
|
225
249
|
}
|
|
226
250
|
}
|
|
251
|
+
/**
|
|
252
|
+
* Destroy underlying resources, like sockets. It's usually not necessary to
|
|
253
|
+
* do this. However in Node.js, it's best to explicitly shut down the client's
|
|
254
|
+
* agent when it is no longer needed. Otherwise, sockets might stay open for
|
|
255
|
+
* quite a long time before the server terminates them.
|
|
256
|
+
*/
|
|
257
|
+
async [Symbol.asyncDispose]() {
|
|
258
|
+
if (this.clientOwned)
|
|
259
|
+
this.client.destroy();
|
|
260
|
+
}
|
|
227
261
|
}
|
|
228
262
|
export default S3BlobStore;
|
|
229
263
|
//# sourceMappingURL=s3.js.map
|
package/dist/s3.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"s3.js","sourceRoot":"","sources":["../src/s3.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,EAAE,EAAuB,MAAM,oBAAoB,CAAA;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAE7C,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AACzE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAE,iBAAiB,EAAkB,MAAM,eAAe,CAAA;AAiDjE,MAAM,OAAO,WAAW;IAKtB,YACS,GAAW,EAClB,GAAa;mBADN,GAAG;QAGV,MAAM,EACJ,MAAM,EACN,eAAe,GAAG,EAAE,GAAG,MAAM;QAC7B,kEAAkE;QAClE,qEAAqE;QACrE,wEAAwE;QACxE,wEAAwE;QACxE,kDAAkD;QAClD,gBAAgB,GAAG,IAAI,CAAC,GAAG,CACzB,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,EAAE,GAAG,MAAM,CAAC,EACtC,CAAC,GAAG,MAAM,CACX,EACD,mBAAmB,GAAG,CAAC,GAAG,MAAM,EAChC,GAAG,IAAI,EACR,GAAG,GAAG,CAAA;QACP,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAA;QACtC,IAAI,CAAC,MAAM,GAAG,IAAI,EAAE,CAAC;YACnB,GAAG,IAAI;YACP,UAAU,EAAE,YAAY;YACxB,8DAA8D;YAC9D,EAAE;YACF,mEAAmE;YACnE,kEAAkE;YAClE,wEAAwE;YACxE,uCAAuC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;gBACnB,GAAG,EAAE,IAAI,CAAC,IAAI;aACf,CAAC,CAAA;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,SAAS,EAAE,CAAC;gBAC7B,8DAA8D;gBAC9D,OAAM;YACR,CAAC;YAED,MAAM,GAAG,CAAA;QACX,CAAC;IACH,CAAC;CACF;AAED,eAAe,WAAW,CAAA","sourcesContent":["import type stream from 'node:stream'\nimport { NoSuchKey, S3, type S3ClientConfig } from '@aws-sdk/client-s3'\nimport { Upload } from '@aws-sdk/lib-storage'\nimport type { CID } from 'multiformats/cid'\nimport { SECOND, aggregateErrors, chunkArray } from '@atproto/common-web'\nimport { randomStr } from '@atproto/crypto'\nimport { BlobNotFoundError, type BlobStore } from '@atproto/repo'\n\nexport type S3Config = {\n bucket: string\n /**\n * The maximum time any single HTTP request to S3 can remain idle (socket\n * idle timeout), in milliseconds. This acts as a stall detector: a stalled\n * or dead connection is reaped after this delay and the request is retried\n * by the SDK. It should be kept short, independently of\n * {@link S3Config.uploadTimeoutMs}, because blob bytes are buffered in\n * memory before each S3 request is dispatched (uploads to S3 are never\n * client-paced).\n *\n * @note Do not set this below 6 seconds. For values >= 6s, the SDK's socket\n * idle timeout is only armed if the response headers take more than 3s to\n * arrive, so blob *downloads* streamed to slow (client-paced) consumers are\n * unaffected. Below 6s, the timeout is armed immediately and stays armed\n * while the response body is streamed, causing slow-but-legitimate\n * downloads to be reaped mid-transfer (see \"downloads\" tests in\n * s3.test.ts).\n *\n * @note Maintenance context: the 6s threshold and 3s deferral are\n * *undocumented internals* of `@smithy/node-http-handler` (the AWS SDK's\n * node request handler; see `setSocketTimeout` in its `set-socket-timeout`\n * module, `DEFER_EVENT_LISTENER_TIME`). They are not part of any public API\n * contract and could change in a future SDK release. The \"downloads\" tests\n * in s3.test.ts characterize this behavior and will fail if it drifts — if\n * they break after a dependency bump, re-read the handler source and\n * re-evaluate the 6s floor below.\n *\n * Defaults to `min(uploadTimeoutMs, 15_000)`, clamped to a minimum of\n * `6_000`.\n */\n requestTimeoutMs?: number\n /**\n * The maximum time establishing a connection to S3 can take, in\n * milliseconds.\n *\n * Defaults to 5_000.\n */\n connectionTimeoutMs?: number\n /**\n * The maximum total time a blob upload can take, in milliseconds. Since\n * uploaded bytes are streamed from the client, this timeout should be large\n * enough to accommodate slow clients uploading large blobs.\n */\n uploadTimeoutMs?: number\n} & Omit<S3ClientConfig, 'apiVersion' | 'requestHandler'>\n\nexport class S3BlobStore implements BlobStore {\n private client: S3\n private bucket: string\n private uploadTimeoutMs: number\n\n constructor(\n public did: string,\n cfg: S3Config,\n ) {\n const {\n bucket,\n uploadTimeoutMs = 10 * SECOND,\n // @NOTE The request timeout acts as a stall detector (socket idle\n // timeout) and should stay short even when uploadTimeoutMs is large,\n // so that stalled S3 connections are reaped and retried quickly. The 6s\n // floor keeps the idle timeout from applying to streamed (client-paced)\n // blob downloads (see S3Config.requestTimeoutMs).\n requestTimeoutMs = Math.max(\n Math.min(uploadTimeoutMs, 15 * SECOND),\n 6 * SECOND,\n ),\n connectionTimeoutMs = 5 * SECOND,\n ...rest\n } = cfg\n this.bucket = bucket\n this.uploadTimeoutMs = uploadTimeoutMs\n this.client = new S3({\n ...rest,\n apiVersion: '2006-03-01',\n // Ensures that all requests timeout under \"requestTimeoutMs\".\n //\n // @NOTE This will also apply to the upload of each individual blob\n // chunk when using Upload from @aws-sdk/lib-storage. This is fine\n // because chunks are buffered in memory before being sent, meaning that\n // requests to S3 are not client-paced.\n requestHandler: {\n requestTimeout: requestTimeoutMs,\n connectionTimeout: connectionTimeoutMs,\n },\n })\n }\n\n static creator(cfg: S3Config) {\n return (did: string) => {\n return new S3BlobStore(did, cfg)\n }\n }\n\n private genKey() {\n return randomStr(32, 'base32')\n }\n\n private getTmpPath(key: string): string {\n return `tmp/${this.did}/${key}`\n }\n\n private getStoredPath(cid: CID): string {\n return `blocks/${this.did}/${cid.toString()}`\n }\n\n private getQuarantinedPath(cid: CID): string {\n return `quarantine/${this.did}/${cid.toString()}`\n }\n\n private async uploadBytes(path: string, bytes: Uint8Array | stream.Readable) {\n // @NOTE we use Upload rather than client.putObject because stream length is\n // not known in advance. See also aws/aws-sdk-js-v3#2348.\n //\n // See also https://github.com/aws/aws-sdk-js-v3/issues/6426, wherein Upload\n // may hang the s3 connection under certain circumstances. We don't have a\n // good way to avoid this, so we use timeouts defensively on all s3\n // requests.\n\n const abortSignal = AbortSignal.timeout(this.uploadTimeoutMs)\n const abortController = new AbortController()\n abortSignal.addEventListener('abort', () => abortController.abort())\n\n const upload = new Upload({\n client: this.client,\n params: {\n Bucket: this.bucket,\n Body: bytes,\n Key: path,\n },\n abortController,\n })\n\n try {\n await upload.done()\n } catch (err) {\n // Translate aws-sdk's abort error (total upload timeout) and timeout\n // errors (stalled connections, after the SDK exhausted its retries) to\n // something more specific\n if (\n err instanceof Error &&\n (err.name === 'AbortError' || err.name === 'TimeoutError')\n ) {\n throw new Error('Blob upload timed out', { cause: err })\n }\n\n throw err\n }\n }\n\n async putTemp(bytes: Uint8Array | stream.Readable): Promise<string> {\n const key = this.genKey()\n await this.uploadBytes(this.getTmpPath(key), bytes)\n return key\n }\n\n async makePermanent(key: string, cid: CID): Promise<void> {\n try {\n // @NOTE we normally call this method when we know the file is temporary.\n // Because of this, we optimistically move the file, allowing to make\n // fewer network requests in the happy path.\n await this.move({\n from: this.getTmpPath(key),\n to: this.getStoredPath(cid),\n })\n } catch (err) {\n // If the optimistic move failed because the temp file was not found,\n // check if the permanent file already exists. If it does, we can assume\n // that another process made the file permanent concurrently, and we can\n // no-op.\n if (err instanceof BlobNotFoundError) {\n // Blob was not found from temp storage...\n const alreadyHas = await this.hasStored(cid)\n // already saved, so we no-op\n if (alreadyHas) return\n }\n\n throw err\n }\n }\n\n async putPermanent(\n cid: CID,\n bytes: Uint8Array | stream.Readable,\n ): Promise<void> {\n await this.uploadBytes(this.getStoredPath(cid), bytes)\n }\n\n async quarantine(cid: CID): Promise<void> {\n await this.move({\n from: this.getStoredPath(cid),\n to: this.getQuarantinedPath(cid),\n })\n }\n\n async unquarantine(cid: CID): Promise<void> {\n await this.move({\n from: this.getQuarantinedPath(cid),\n to: this.getStoredPath(cid),\n })\n }\n\n private async getObject(cid: CID) {\n const res = await this.client.getObject({\n Bucket: this.bucket,\n Key: this.getStoredPath(cid),\n })\n if (res.Body) {\n return res.Body\n } else {\n throw new BlobNotFoundError()\n }\n }\n\n async getBytes(cid: CID): Promise<Uint8Array> {\n const res = await this.getObject(cid)\n return res.transformToByteArray()\n }\n\n async getStream(cid: CID): Promise<stream.Readable> {\n const res = await this.getObject(cid)\n return res as stream.Readable\n }\n\n async delete(cid: CID): Promise<void> {\n await this.deleteKey(this.getStoredPath(cid))\n }\n\n async deleteMany(cids: CID[]): Promise<void> {\n const errors: unknown[] = []\n for (const chunk of chunkArray(cids, 500)) {\n try {\n const keys = chunk.map((cid) => this.getStoredPath(cid))\n await this.deleteManyKeys(keys)\n } catch (err) {\n errors.push(err)\n }\n }\n if (errors.length) throw aggregateErrors(errors)\n }\n\n async hasStored(cid: CID): Promise<boolean> {\n return this.hasKey(this.getStoredPath(cid))\n }\n\n async hasTemp(key: string): Promise<boolean> {\n return this.hasKey(this.getTmpPath(key))\n }\n\n private async hasKey(key: string) {\n try {\n const res = await this.client.headObject({\n Bucket: this.bucket,\n Key: key,\n })\n return res.$metadata.httpStatusCode === 200\n } catch (err) {\n return false\n }\n }\n\n private async deleteKey(key: string) {\n await this.client.deleteObject({\n Bucket: this.bucket,\n Key: key,\n })\n }\n\n private async deleteManyKeys(keys: string[]) {\n await this.client.deleteObjects({\n Bucket: this.bucket,\n Delete: {\n Objects: keys.map((k) => ({ Key: k })),\n },\n })\n }\n\n private async move(keys: { from: string; to: string }) {\n try {\n await this.client.copyObject({\n Bucket: this.bucket,\n CopySource: `${this.bucket}/${keys.from}`,\n Key: keys.to,\n })\n } catch (cause) {\n if (cause instanceof NoSuchKey) {\n // Already deleted, possibly by a concurrently running process\n throw new BlobNotFoundError(undefined, { cause })\n }\n\n throw cause\n }\n\n try {\n await this.client.deleteObject({\n Bucket: this.bucket,\n Key: keys.from,\n })\n } catch (err) {\n if (err instanceof NoSuchKey) {\n // Already deleted, possibly by a concurrently running process\n return\n }\n\n throw err\n }\n }\n}\n\nexport default S3BlobStore\n"]}
|
|
1
|
+
{"version":3,"file":"s3.js","sourceRoot":"","sources":["../src/s3.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,EAAE,EAAuB,MAAM,oBAAoB,CAAA;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAE7C,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AACzE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EACL,iBAAiB,GAGlB,MAAM,eAAe,CAAA;AA0DtB,MAAM,yBAAyB,GAAG,EAAE,GAAG,MAAM,CAAA;AAE7C,SAAS,cAAc,CAAC,GAAa;IACnC,MAAM,EACJ,MAAM,EACN,eAAe,GAAG,yBAAyB;IAC3C,kEAAkE;IAClE,qEAAqE;IACrE,wEAAwE;IACxE,wEAAwE;IACxE,kDAAkD;IAClD,gBAAgB,GAAG,IAAI,CAAC,GAAG,CACzB,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,EAAE,GAAG,MAAM,CAAC,EACtC,CAAC,GAAG,MAAM,CACX,EACD,mBAAmB,GAAG,CAAC,GAAG,MAAM,EAChC,UAAU,GAAG,QAAQ,EACrB,GAAG,IAAI,EACR,GAAG,GAAG,CAAA;IACP,OAAO,IAAI,EAAE,CAAC;QACZ,GAAG,IAAI;QACP,UAAU,EAAE,YAAY;QACxB,8DAA8D;QAC9D,EAAE;QACF,mEAAmE;QACnE,kEAAkE;QAClE,wEAAwE;QACxE,uCAAuC;QACvC,cAAc,EAAE;YACd,cAAc,EAAE,gBAAgB;YAChC,iBAAiB,EAAE,mBAAmB;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,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;aACvC;SACF,CAAC,CAAA;IACJ,CAAC;IAEO,KAAK,CAAC,IAAI,CAAC,IAAkC;QACnD,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC;gBAC3B,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,UAAU,EAAE,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE;gBACzC,GAAG,EAAE,IAAI,CAAC,EAAE;aACb,CAAC,CAAA;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,SAAS,EAAE,CAAC;gBAC/B,8DAA8D;gBAC9D,MAAM,IAAI,iBAAiB,CAAC,SAAS,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;YACnD,CAAC;YAED,MAAM,KAAK,CAAA;QACb,CAAC;QAED,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC;gBAC7B,MAAM,EAAE,IAAI,CAAC,MAAM;gBACnB,GAAG,EAAE,IAAI,CAAC,IAAI;aACf,CAAC,CAAA;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,SAAS,EAAE,CAAC;gBAC7B,8DAA8D;gBAC9D,OAAM;YACR,CAAC;YAED,MAAM,GAAG,CAAA;QACX,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC;QACzB,IAAI,IAAI,CAAC,WAAW;YAAE,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;IAC7C,CAAC;CACF;AAED,eAAe,WAAW,CAAA","sourcesContent":["import type stream from 'node:stream'\nimport { NoSuchKey, S3, type S3ClientConfig } from '@aws-sdk/client-s3'\nimport { Upload } from '@aws-sdk/lib-storage'\nimport type { CID } from 'multiformats/cid'\nimport { SECOND, aggregateErrors, chunkArray } from '@atproto/common-web'\nimport { randomStr } from '@atproto/crypto'\nimport {\n BlobNotFoundError,\n type BlobStore,\n type BlobStoreCreator,\n} from '@atproto/repo'\n\nexport type S3Config = {\n bucket: string\n /**\n * The maximum time any single HTTP request to S3 can remain idle (socket\n * idle timeout), in milliseconds. This acts as a stall detector: a stalled\n * or dead connection is reaped after this delay and the request is retried\n * by the SDK. It should be kept short, independently of\n * {@link S3Config.uploadTimeoutMs}, because blob bytes are buffered in\n * memory before each S3 request is dispatched (uploads to S3 are never\n * client-paced).\n *\n * @note Do not set this below 6 seconds. For values >= 6s, the SDK's socket\n * idle timeout is only armed if the response headers take more than 3s to\n * arrive, so blob *downloads* streamed to slow (client-paced) consumers are\n * unaffected. Below 6s, the timeout is armed immediately and stays armed\n * while the response body is streamed, causing slow-but-legitimate\n * downloads to be reaped mid-transfer (see \"downloads\" tests in\n * s3.test.ts).\n *\n * @note Maintenance context: the 6s threshold and 3s deferral are\n * *undocumented internals* of `@smithy/node-http-handler` (the AWS SDK's\n * node request handler; see `setSocketTimeout` in its `set-socket-timeout`\n * module, `DEFER_EVENT_LISTENER_TIME`). They are not part of any public API\n * contract and could change in a future SDK release. The \"downloads\" tests\n * in s3.test.ts characterize this behavior and will fail if it drifts — if\n * they break after a dependency bump, re-read the handler source and\n * re-evaluate the 6s floor below.\n *\n * Defaults to `min(uploadTimeoutMs, 15_000)`, clamped to a minimum of\n * `6_000`.\n */\n requestTimeoutMs?: number\n /**\n * The maximum time establishing a connection to S3 can take, in\n * milliseconds.\n *\n * Defaults to 5_000.\n */\n connectionTimeoutMs?: number\n /**\n * The maximum total time a blob upload can take, in milliseconds. Since\n * uploaded bytes are streamed from the client, this timeout should be large\n * enough to accommodate slow clients uploading large blobs.\n */\n uploadTimeoutMs?: number\n /**\n * The maximum number of concurrent connections to S3 per client. Blob\n * downloads are streamed at the pace of the downstream consumer, so a finite\n * cap lets slow consumers hold every connection and queue all other blob\n * reads and writes behind them.\n *\n * Defaults to `Infinity`.\n */\n maxSockets?: number\n} & Omit<S3ClientConfig, 'apiVersion' | 'requestHandler'>\n\nconst DEFAULT_UPLOAD_TIMEOUT_MS = 10 * SECOND\n\nfunction createS3Client(cfg: S3Config): S3 {\n const {\n bucket,\n uploadTimeoutMs = DEFAULT_UPLOAD_TIMEOUT_MS,\n // @NOTE The request timeout acts as a stall detector (socket idle\n // timeout) and should stay short even when uploadTimeoutMs is large,\n // so that stalled S3 connections are reaped and retried quickly. The 6s\n // floor keeps the idle timeout from applying to streamed (client-paced)\n // blob downloads (see S3Config.requestTimeoutMs).\n requestTimeoutMs = Math.max(\n Math.min(uploadTimeoutMs, 15 * SECOND),\n 6 * SECOND,\n ),\n connectionTimeoutMs = 5 * SECOND,\n maxSockets = Infinity,\n ...rest\n } = cfg\n return new S3({\n ...rest,\n apiVersion: '2006-03-01',\n // Ensures that all requests timeout under \"requestTimeoutMs\".\n //\n // @NOTE This will also apply to the upload of each individual blob\n // chunk when using Upload from @aws-sdk/lib-storage. This is fine\n // because chunks are buffered in memory before being sent, meaning that\n // requests to S3 are not client-paced.\n requestHandler: {\n requestTimeout: requestTimeoutMs,\n connectionTimeout: connectionTimeoutMs,\n httpAgent: { maxSockets },\n httpsAgent: { maxSockets },\n },\n })\n}\n\nexport class S3BlobStore implements BlobStore {\n private readonly clientOwned: boolean\n private readonly client: S3\n private readonly bucket: string\n private readonly uploadTimeoutMs: number\n\n /**\n * @param client Shared by every store returned from\n * {@link S3BlobStore.creator}, so that they reuse one connection pool.\n * Defaults to a new client built from `cfg`.\n */\n constructor(\n public did: string,\n cfg: S3Config,\n client?: S3,\n ) {\n this.bucket = cfg.bucket\n this.uploadTimeoutMs = cfg.uploadTimeoutMs ?? DEFAULT_UPLOAD_TIMEOUT_MS\n this.client = client ?? createS3Client(cfg)\n this.clientOwned = client === undefined\n }\n\n static creator(cfg: S3Config): BlobStoreCreator {\n // @NOTE A store is created for every actor store access. A client per\n // store would open a fresh TLS connection to S3 for every blob request and\n // leave it idle in an unreachable pool, exhausting ephemeral ports under\n // load.\n const client = createS3Client(cfg)\n const creator = (did: string): BlobStore => {\n return new S3BlobStore(did, cfg, client)\n }\n // The S3BlobStore instances won't own the client, the BlobStoreCreator\n // does. In order to properly clean up the client, we attach an async\n // dispose method to the creator itself.\n Object.defineProperty(creator, Symbol.asyncDispose, {\n value: async () => client.destroy(),\n })\n return creator as BlobStoreCreator\n }\n\n private genKey() {\n return randomStr(32, 'base32')\n }\n\n private getTmpPath(key: string): string {\n return `tmp/${this.did}/${key}`\n }\n\n private getStoredPath(cid: CID): string {\n return `blocks/${this.did}/${cid.toString()}`\n }\n\n private getQuarantinedPath(cid: CID): string {\n return `quarantine/${this.did}/${cid.toString()}`\n }\n\n private async uploadBytes(path: string, bytes: Uint8Array | stream.Readable) {\n // @NOTE we use Upload rather than client.putObject because stream length is\n // not known in advance. See also aws/aws-sdk-js-v3#2348.\n //\n // See also https://github.com/aws/aws-sdk-js-v3/issues/6426, wherein Upload\n // may hang the s3 connection under certain circumstances. We don't have a\n // good way to avoid this, so we use timeouts defensively on all s3\n // requests.\n\n const abortSignal = AbortSignal.timeout(this.uploadTimeoutMs)\n const abortController = new AbortController()\n abortSignal.addEventListener('abort', () => abortController.abort())\n\n const upload = new Upload({\n client: this.client,\n params: {\n Bucket: this.bucket,\n Body: bytes,\n Key: path,\n },\n abortController,\n })\n\n try {\n await upload.done()\n } catch (err) {\n // Translate aws-sdk's abort error (total upload timeout) and timeout\n // errors (stalled connections, after the SDK exhausted its retries) to\n // something more specific\n if (\n err instanceof Error &&\n (err.name === 'AbortError' || err.name === 'TimeoutError')\n ) {\n throw new Error('Blob upload timed out', { cause: err })\n }\n\n throw err\n }\n }\n\n async putTemp(bytes: Uint8Array | stream.Readable): Promise<string> {\n const key = this.genKey()\n await this.uploadBytes(this.getTmpPath(key), bytes)\n return key\n }\n\n async makePermanent(key: string, cid: CID): Promise<void> {\n try {\n // @NOTE we normally call this method when we know the file is temporary.\n // Because of this, we optimistically move the file, allowing to make\n // fewer network requests in the happy path.\n await this.move({\n from: this.getTmpPath(key),\n to: this.getStoredPath(cid),\n })\n } catch (err) {\n // If the optimistic move failed because the temp file was not found,\n // check if the permanent file already exists. If it does, we can assume\n // that another process made the file permanent concurrently, and we can\n // no-op.\n if (err instanceof BlobNotFoundError) {\n // Blob was not found from temp storage...\n const alreadyHas = await this.hasStored(cid)\n // already saved, so we no-op\n if (alreadyHas) return\n }\n\n throw err\n }\n }\n\n async putPermanent(\n cid: CID,\n bytes: Uint8Array | stream.Readable,\n ): Promise<void> {\n await this.uploadBytes(this.getStoredPath(cid), bytes)\n }\n\n async quarantine(cid: CID): Promise<void> {\n await this.move({\n from: this.getStoredPath(cid),\n to: this.getQuarantinedPath(cid),\n })\n }\n\n async unquarantine(cid: CID): Promise<void> {\n await this.move({\n from: this.getQuarantinedPath(cid),\n to: this.getStoredPath(cid),\n })\n }\n\n private async getObject(cid: CID) {\n const res = await this.client.getObject({\n Bucket: this.bucket,\n Key: this.getStoredPath(cid),\n })\n if (res.Body) {\n return res.Body\n } else {\n throw new BlobNotFoundError()\n }\n }\n\n async getBytes(cid: CID): Promise<Uint8Array> {\n const res = await this.getObject(cid)\n return res.transformToByteArray()\n }\n\n async getStream(cid: CID): Promise<stream.Readable> {\n const res = await this.getObject(cid)\n return res as stream.Readable\n }\n\n async delete(cid: CID): Promise<void> {\n await this.deleteKey(this.getStoredPath(cid))\n }\n\n async deleteMany(cids: CID[]): Promise<void> {\n const errors: unknown[] = []\n for (const chunk of chunkArray(cids, 500)) {\n try {\n const keys = chunk.map((cid) => this.getStoredPath(cid))\n await this.deleteManyKeys(keys)\n } catch (err) {\n errors.push(err)\n }\n }\n if (errors.length) throw aggregateErrors(errors)\n }\n\n async hasStored(cid: CID): Promise<boolean> {\n return this.hasKey(this.getStoredPath(cid))\n }\n\n async hasTemp(key: string): Promise<boolean> {\n return this.hasKey(this.getTmpPath(key))\n }\n\n private async hasKey(key: string) {\n try {\n const res = await this.client.headObject({\n Bucket: this.bucket,\n Key: key,\n })\n return res.$metadata.httpStatusCode === 200\n } catch (err) {\n return false\n }\n }\n\n private async deleteKey(key: string) {\n await this.client.deleteObject({\n Bucket: this.bucket,\n Key: key,\n })\n }\n\n private async deleteManyKeys(keys: string[]) {\n await this.client.deleteObjects({\n Bucket: this.bucket,\n Delete: {\n Objects: keys.map((k) => ({ Key: k })),\n },\n })\n }\n\n private async move(keys: { from: string; to: string }) {\n try {\n await this.client.copyObject({\n Bucket: this.bucket,\n CopySource: `${this.bucket}/${keys.from}`,\n Key: keys.to,\n })\n } catch (cause) {\n if (cause instanceof NoSuchKey) {\n // Already deleted, possibly by a concurrently running process\n throw new BlobNotFoundError(undefined, { cause })\n }\n\n throw cause\n }\n\n try {\n await this.client.deleteObject({\n Bucket: this.bucket,\n Key: keys.from,\n })\n } catch (err) {\n if (err instanceof NoSuchKey) {\n // Already deleted, possibly by a concurrently running process\n return\n }\n\n throw err\n }\n }\n\n /**\n * Destroy underlying resources, like sockets. It's usually not necessary to\n * do this. However in Node.js, it's best to explicitly shut down the client's\n * agent when it is no longer needed. Otherwise, sockets might stay open for\n * quite a long time before the server terminates them.\n */\n async [Symbol.asyncDispose]() {\n if (this.clientOwned) this.client.destroy()\n }\n}\n\nexport default S3BlobStore\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atproto/aws",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.19",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Shared AWS cloud API helpers for atproto services",
|
|
6
6
|
"keywords": [
|
|
@@ -36,10 +36,10 @@
|
|
|
36
36
|
"@noble/curves": "^1.7.0",
|
|
37
37
|
"multiformats": "^13.0.0",
|
|
38
38
|
"uint8arrays": "^5.0.0",
|
|
39
|
-
"@atproto/common
|
|
40
|
-
"@atproto/repo": "^0.
|
|
41
|
-
"@atproto/crypto": "^0.5.
|
|
42
|
-
"@atproto/common": "^0.
|
|
39
|
+
"@atproto/common": "^0.8.5",
|
|
40
|
+
"@atproto/repo": "^0.11.0",
|
|
41
|
+
"@atproto/crypto": "^0.5.7",
|
|
42
|
+
"@atproto/common-web": "^0.5.14"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"vitest": "^4.1.10"
|