jskelet 0.3.0 → 0.3.2

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.
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Minimal S3 PutObject — yalnızca SigV4 + `fetch`.
3
+ *
4
+ * `@aws-sdk/client-s3` taşınmıyor: tek operasyon için SDK'nın maliyeti ve
5
+ * peer yüzeyi gereksiz. Credential zinciri env'den okunur
6
+ * (`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `AWS_SESSION_TOKEN`);
7
+ * IAM role / instance metadata yok — container'a key vermeyen kurulumlar
8
+ * için sink zaten açılışta no-op'a düşer.
9
+ */
10
+ import crypto from "node:crypto";
11
+
12
+ /**
13
+ * @typedef {{ accessKeyId: string, secretAccessKey: string,
14
+ * sessionToken?: string | null }} AwsCredentials
15
+ *
16
+ * @typedef {{ bucket: string, key: string, body: string | Buffer,
17
+ * region: string, endpoint?: string | null, credentials: AwsCredentials,
18
+ * now?: Date }} PutObjectInput
19
+ */
20
+
21
+ /**
22
+ * @param {string} algorithm
23
+ * @param {string | Buffer} key
24
+ * @param {string | Buffer} data
25
+ * @returns {Buffer}
26
+ */
27
+ function hmac(algorithm, key, data) {
28
+ return crypto.createHmac(algorithm, key).update(data).digest();
29
+ }
30
+
31
+ /**
32
+ * @param {string | Buffer} data
33
+ * @returns {string}
34
+ */
35
+ export function sha256Hex(data) {
36
+ return crypto.createHash("sha256").update(data).digest("hex");
37
+ }
38
+
39
+ /**
40
+ * @param {Date} date
41
+ * @returns {{ amzDate: string, dateStamp: string }}
42
+ */
43
+ export function formatAmzDates(date) {
44
+ const iso = date.toISOString().replace(/[:-]|\.\d{3}/g, "");
45
+ return {
46
+ amzDate: iso,
47
+ dateStamp: iso.slice(0, 8),
48
+ };
49
+ }
50
+
51
+ /**
52
+ * @param {string} secretAccessKey
53
+ * @param {string} dateStamp
54
+ * @param {string} region
55
+ * @param {string} service
56
+ * @returns {Buffer}
57
+ */
58
+ export function deriveSigningKey(secretAccessKey, dateStamp, region, service) {
59
+ const kDate = hmac("sha256", `AWS4${secretAccessKey}`, dateStamp);
60
+ const kRegion = hmac("sha256", kDate, region);
61
+ const kService = hmac("sha256", kRegion, service);
62
+ return hmac("sha256", kService, "aws4_request");
63
+ }
64
+
65
+ /**
66
+ * @param {{ method: string, canonicalUri: string, canonicalQuerystring?: string,
67
+ * headers: Record<string, string>, payloadHash: string }} parts
68
+ * @returns {{ canonicalRequest: string, signedHeaders: string }}
69
+ */
70
+ export function buildCanonicalRequest(parts) {
71
+ const names = Object.keys(parts.headers)
72
+ .map((name) => name.toLowerCase())
73
+ .sort();
74
+ const canonicalHeaders = names
75
+ .map((name) => `${name}:${parts.headers[name].trim().replace(/\s+/g, " ")}\n`)
76
+ .join("");
77
+ const signedHeaders = names.join(";");
78
+
79
+ const canonicalRequest = [
80
+ parts.method,
81
+ parts.canonicalUri,
82
+ parts.canonicalQuerystring ?? "",
83
+ canonicalHeaders,
84
+ signedHeaders,
85
+ parts.payloadHash,
86
+ ].join("\n");
87
+
88
+ return { canonicalRequest, signedHeaders };
89
+ }
90
+
91
+ /**
92
+ * @param {{ amzDate: string, dateStamp: string, region: string, service: string,
93
+ * canonicalRequest: string }} parts
94
+ * @returns {string}
95
+ */
96
+ export function buildStringToSign(parts) {
97
+ const scope = `${parts.dateStamp}/${parts.region}/${parts.service}/aws4_request`;
98
+ return [
99
+ "AWS4-HMAC-SHA256",
100
+ parts.amzDate,
101
+ scope,
102
+ sha256Hex(parts.canonicalRequest),
103
+ ].join("\n");
104
+ }
105
+
106
+ /**
107
+ * URI path encode (S3 key segment'leri). `/` korunur.
108
+ *
109
+ * @param {string} value
110
+ * @returns {string}
111
+ */
112
+ export function encodeS3Path(value) {
113
+ return value
114
+ .split("/")
115
+ .map((segment) => encodeURIComponent(segment).replace(/[!'()*]/g, (char) =>
116
+ `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
117
+ ))
118
+ .join("/");
119
+ }
120
+
121
+ /**
122
+ * PutObject isteğini imzalar; ağ çağrısı yapmaz — test edilebilir olsun diye.
123
+ *
124
+ * @param {PutObjectInput} input
125
+ * @returns {{ url: string, headers: Record<string, string>, body: Buffer }}
126
+ */
127
+ export function buildSignedPutObject(input) {
128
+ const body = Buffer.isBuffer(input.body) ? input.body : Buffer.from(input.body);
129
+ const now = input.now ?? new Date();
130
+ const { amzDate, dateStamp } = formatAmzDates(now);
131
+ const service = "s3";
132
+ const payloadHash = sha256Hex(body);
133
+
134
+ const keyPath = encodeS3Path(input.key.replace(/^\/+/, ""));
135
+ const usePathStyle = Boolean(input.endpoint);
136
+ const endpointHost = input.endpoint
137
+ ? new URL(input.endpoint).host
138
+ : `${input.bucket}.s3.${input.region}.amazonaws.com`;
139
+ const host = usePathStyle ? new URL(input.endpoint ?? "").host : endpointHost;
140
+
141
+ const canonicalUri = usePathStyle
142
+ ? `/${encodeS3Path(input.bucket)}/${keyPath}`
143
+ : `/${keyPath}`;
144
+
145
+ /** @type {Record<string, string>} */
146
+ const headers = {
147
+ host,
148
+ "content-type": "application/x-ndjson",
149
+ "content-length": String(body.length),
150
+ "x-amz-content-sha256": payloadHash,
151
+ "x-amz-date": amzDate,
152
+ };
153
+
154
+ if (input.credentials.sessionToken) {
155
+ headers["x-amz-security-token"] = input.credentials.sessionToken;
156
+ }
157
+
158
+ const { canonicalRequest, signedHeaders } = buildCanonicalRequest({
159
+ method: "PUT",
160
+ canonicalUri,
161
+ headers,
162
+ payloadHash,
163
+ });
164
+
165
+ const stringToSign = buildStringToSign({
166
+ amzDate,
167
+ dateStamp,
168
+ region: input.region,
169
+ service,
170
+ canonicalRequest,
171
+ });
172
+
173
+ const signingKey = deriveSigningKey(
174
+ input.credentials.secretAccessKey,
175
+ dateStamp,
176
+ input.region,
177
+ service,
178
+ );
179
+ const signature = hmac("sha256", signingKey, stringToSign).toString("hex");
180
+ const credentialScope = `${dateStamp}/${input.region}/${service}/aws4_request`;
181
+
182
+ headers.authorization =
183
+ `AWS4-HMAC-SHA256 Credential=${input.credentials.accessKeyId}/${credentialScope}, ` +
184
+ `SignedHeaders=${signedHeaders}, Signature=${signature}`;
185
+
186
+ const base = usePathStyle
187
+ ? String(input.endpoint).replace(/\/+$/, "")
188
+ : `https://${host}`;
189
+ const url = usePathStyle
190
+ ? `${base}/${encodeS3Path(input.bucket)}/${keyPath}`
191
+ : `${base}/${keyPath}`;
192
+
193
+ return { url, headers, body };
194
+ }
195
+
196
+ /**
197
+ * @param {PutObjectInput} input
198
+ * @returns {Promise<void>}
199
+ */
200
+ export async function putObject(input) {
201
+ const signed = buildSignedPutObject(input);
202
+ const response = await fetch(signed.url, {
203
+ method: "PUT",
204
+ headers: signed.headers,
205
+ body: signed.body,
206
+ });
207
+
208
+ if (!response.ok) {
209
+ const text = await response.text().catch(() => "");
210
+ throw new Error(
211
+ `S3 PutObject ${response.status}: ${text.slice(0, 200) || response.statusText}`,
212
+ );
213
+ }
214
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * S3 batch sink — satırları biriktirir, aralık / maxBatch ile PutObject atar.
3
+ *
4
+ * Başarısız bir yükleme süreci düşürmez: bir kez uyarır, batch'i bırakır.
5
+ * Backpressure için yeniden kuyruk yok — log kaybı, belleğin şişmesinden
6
+ * tercih edilir.
7
+ */
8
+ import os from "node:os";
9
+ import process from "node:process";
10
+ import { putObject } from "./s3-put.js";
11
+
12
+ /**
13
+ * @typedef {import('./file-sink.js').LogSink} LogSink
14
+ * @typedef {import('./s3-put.js').AwsCredentials} AwsCredentials
15
+ */
16
+
17
+ /**
18
+ * @param {{ bucket: string, prefix: string, region: string,
19
+ * endpoint?: string | null, credentials: AwsCredentials,
20
+ * flushIntervalMs: number, maxBatch: number,
21
+ * put?: typeof putObject }} options
22
+ * @returns {LogSink & { pendingCount: () => number }}
23
+ */
24
+ export function createS3Sink(options) {
25
+ /** @type {string[]} */
26
+ let buffer = [];
27
+ let seq = 0;
28
+ let warned = false;
29
+ /** @type {Promise<void>} */
30
+ let chain = Promise.resolve();
31
+ /** @type {ReturnType<typeof setInterval> | null} */
32
+ let timer = null;
33
+
34
+ const put = options.put ?? putObject;
35
+ const host = os.hostname().replace(/[^a-zA-Z0-9._-]/g, "-") || "host";
36
+ const prefix = options.prefix.endsWith("/")
37
+ ? options.prefix
38
+ : `${options.prefix}/`;
39
+
40
+ /**
41
+ * @param {Date} [date]
42
+ * @returns {string}
43
+ */
44
+ function objectKey(date = new Date()) {
45
+ const y = date.getUTCFullYear();
46
+ const m = String(date.getUTCMonth() + 1).padStart(2, "0");
47
+ const d = String(date.getUTCDate()).padStart(2, "0");
48
+ const iso = date.toISOString().replace(/[:.]/g, "-");
49
+ seq += 1;
50
+ return `${prefix}${y}/${m}/${d}/${host}-${process.pid}-${iso}-${seq}.ndjson`;
51
+ }
52
+
53
+ /**
54
+ * @param {string} message
55
+ * @param {unknown} [error]
56
+ */
57
+ function warnOnce(message, error) {
58
+ if (warned) return;
59
+ warned = true;
60
+ console.warn(`[logs] ${message}`, error ?? "");
61
+ }
62
+
63
+ async function flushNow() {
64
+ if (!buffer.length) return;
65
+ const lines = buffer;
66
+ buffer = [];
67
+ const body = `${lines.join("\n")}\n`;
68
+ try {
69
+ await put({
70
+ bucket: options.bucket,
71
+ key: objectKey(),
72
+ body,
73
+ region: options.region,
74
+ endpoint: options.endpoint ?? null,
75
+ credentials: options.credentials,
76
+ });
77
+ } catch (error) {
78
+ warnOnce("S3 PutObject failed; dropping batch", error);
79
+ }
80
+ }
81
+
82
+ /** Flush'ları sıraya dizer — iki timer çakışmasın. */
83
+ function enqueueFlush() {
84
+ chain = chain.then(flushNow).catch(() => {});
85
+ return chain;
86
+ }
87
+
88
+ timer = setInterval(() => {
89
+ void enqueueFlush();
90
+ }, options.flushIntervalMs);
91
+ timer.unref?.();
92
+
93
+ return {
94
+ pendingCount() {
95
+ return buffer.length;
96
+ },
97
+ async write(entry) {
98
+ buffer.push(JSON.stringify(entry));
99
+ if (buffer.length >= options.maxBatch) await enqueueFlush();
100
+ },
101
+ async flush() {
102
+ await enqueueFlush();
103
+ },
104
+ async close() {
105
+ if (timer) {
106
+ clearInterval(timer);
107
+ timer = null;
108
+ }
109
+ await enqueueFlush();
110
+ },
111
+ };
112
+ }