@platformatic/sqlite-js-stream-s3 0.2.0 → 0.3.0

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/src/util.ts ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Helpers shared by the S3 replica client and leaser: body reading and the
3
+ * classification of S3 errors (404, 412, 409).
4
+ */
5
+
6
+ /** Reads all bytes from an S3 body (stream or Buffer). */
7
+ export async function readBody(body: any): Promise<Uint8Array> {
8
+ // AWS SDK v3 returns a mix; normalize to a Uint8Array.
9
+ if (body instanceof Uint8Array) return body;
10
+ if (typeof body?.on === 'function') {
11
+ // Node stream.
12
+ const chunks: Uint8Array[] = [];
13
+ for await (const chunk of body as AsyncIterable<Uint8Array | string>) {
14
+ chunks.push(typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk);
15
+ }
16
+ let total = 0;
17
+ for (const c of chunks) total += c.length;
18
+ const out = new Uint8Array(total);
19
+ let o = 0;
20
+ for (const c of chunks) {
21
+ out.set(c, o);
22
+ o += c.length;
23
+ }
24
+ return out;
25
+ }
26
+ // Web ReadableStream or Buffer.
27
+ if (typeof body?.getReader === 'function') {
28
+ const reader = (body as ReadableStream<Uint8Array>).getReader();
29
+ const chunks: Uint8Array[] = [];
30
+ for (;;) {
31
+ const { done, value } = await reader.read();
32
+ if (done) break;
33
+ chunks.push(value);
34
+ }
35
+ let total = 0;
36
+ for (const c of chunks) total += c.length;
37
+ const out = new Uint8Array(total);
38
+ let o = 0;
39
+ for (const c of chunks) {
40
+ out.set(c, o);
41
+ o += c.length;
42
+ }
43
+ return out;
44
+ }
45
+ return new Uint8Array(body as Uint8Array);
46
+ }
47
+
48
+ export function isPreconditionFailed(err: unknown): boolean {
49
+ const code = (err as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode;
50
+ const name = (err as { name?: string })?.name ?? '';
51
+ return code === 412 || name === 'PreconditionFailed';
52
+ }
53
+
54
+ export function isNotFound(err: unknown): boolean {
55
+ const code = (err as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode;
56
+ const name = (err as { name?: string })?.name ?? '';
57
+ return code === 404 || name === 'NoSuchKey' || name === 'NotFound';
58
+ }
59
+
60
+ /**
61
+ * A concurrent conditional write to the same key (`409 ConditionalRequestConflict`).
62
+ * S3 asks the caller to retry the request.
63
+ */
64
+ export function isConditionalConflict(err: unknown): boolean {
65
+ const code = (err as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode;
66
+ const name = (err as { name?: string })?.name ?? '';
67
+ return code === 409 || name === 'ConditionalRequestConflict';
68
+ }