@kyyinfinite/zapo-message 0.0.0-stage → 1.0.1
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 +159 -0
- package/LICENSE +20 -0
- package/README.md +1401 -2
- package/build.config.json +28 -0
- package/dist/airich/airich.d.ts +180 -0
- package/dist/airich/airich.js +548 -0
- package/dist/airich/context.d.ts +24 -0
- package/dist/airich/context.js +48 -0
- package/dist/airich/encode.d.ts +3 -0
- package/dist/airich/encode.js +16 -0
- package/dist/airich/index.d.ts +20 -0
- package/dist/airich/index.js +11 -0
- package/dist/airich/inline.d.ts +45 -0
- package/dist/airich/inline.js +152 -0
- package/dist/airich/nodes.d.ts +30 -0
- package/dist/airich/nodes.js +121 -0
- package/dist/airich/primitives.d.ts +144 -0
- package/dist/airich/primitives.js +230 -0
- package/dist/airich/protocol.d.ts +35 -0
- package/dist/airich/protocol.js +65 -0
- package/dist/airich/table.d.ts +22 -0
- package/dist/airich/table.js +35 -0
- package/dist/airich/tokenizer.d.ts +13 -0
- package/dist/airich/tokenizer.js +717 -0
- package/dist/airich/transport.d.ts +15 -0
- package/dist/airich/transport.js +56 -0
- package/dist/branding.d.ts +5 -0
- package/dist/branding.js +9 -0
- package/dist/btn/builders.d.ts +246 -0
- package/dist/btn/builders.js +710 -0
- package/dist/btn/media-slot.d.ts +28 -0
- package/dist/btn/media-slot.js +323 -0
- package/dist/btn/media-source.d.ts +36 -0
- package/dist/btn/media-source.js +116 -0
- package/dist/btn/sharp-loader.d.ts +5 -0
- package/dist/btn/sharp-loader.js +18 -0
- package/dist/btn/thumbnail.d.ts +21 -0
- package/dist/btn/thumbnail.js +124 -0
- package/dist/btn/validators.d.ts +40 -0
- package/dist/btn/validators.js +135 -0
- package/dist/btn.d.ts +1 -0
- package/dist/btn.js +1 -0
- package/dist/core/async-send.d.ts +20 -0
- package/dist/core/async-send.js +1 -0
- package/dist/core/base-builder.d.ts +20 -0
- package/dist/core/base-builder.js +67 -0
- package/dist/core/errors.d.ts +30 -0
- package/dist/core/errors.js +61 -0
- package/dist/download.d.ts +24 -0
- package/dist/download.js +123 -0
- package/dist/index.d.ts +38 -0
- package/dist/index.js +22 -0
- package/dist/integration/augment.d.ts +97 -0
- package/dist/integration/augment.js +1 -0
- package/dist/integration/auto.d.ts +8 -0
- package/dist/integration/auto.js +79 -0
- package/dist/integration/index.d.ts +4 -0
- package/dist/integration/index.js +2 -0
- package/dist/integration/methods.d.ts +25 -0
- package/dist/integration/methods.js +24 -0
- package/dist/interactive.d.ts +24 -0
- package/dist/interactive.js +121 -0
- package/dist/media-gate.d.ts +99 -0
- package/dist/media-gate.js +322 -0
- package/dist/message/album.d.ts +33 -0
- package/dist/message/album.js +107 -0
- package/dist/message/contact.d.ts +29 -0
- package/dist/message/contact.js +123 -0
- package/dist/message/forward.d.ts +23 -0
- package/dist/message/forward.js +77 -0
- package/dist/message/index.d.ts +26 -0
- package/dist/message/index.js +13 -0
- package/dist/message/link-preview.d.ts +28 -0
- package/dist/message/link-preview.js +98 -0
- package/dist/message/location.d.ts +24 -0
- package/dist/message/location.js +94 -0
- package/dist/message/media.d.ts +90 -0
- package/dist/message/media.js +123 -0
- package/dist/message/poll.d.ts +24 -0
- package/dist/message/poll.js +98 -0
- package/dist/message/reaction.d.ts +20 -0
- package/dist/message/reaction.js +71 -0
- package/dist/message/sticker.d.ts +29 -0
- package/dist/message/sticker.js +44 -0
- package/dist/message/target.d.ts +18 -0
- package/dist/message/target.js +24 -0
- package/dist/message/text.d.ts +17 -0
- package/dist/message/text.js +29 -0
- package/dist/message/vcard.d.ts +9 -0
- package/dist/message/vcard.js +23 -0
- package/dist/message/webp.d.ts +6 -0
- package/dist/message/webp.js +57 -0
- package/dist/payloads.d.ts +180 -0
- package/dist/payloads.js +1 -0
- package/dist/serialize.d.ts +41 -0
- package/dist/serialize.js +93 -0
- package/dist/status.d.ts +3 -0
- package/dist/status.js +21 -0
- package/dist/zapo-client.d.ts +44 -0
- package/dist/zapo-client.js +1 -0
- package/examples/airich.ts +59 -0
- package/examples/buttons.ts +48 -0
- package/examples/client-methods.ts +58 -0
- package/examples/hybrid.ts +133 -0
- package/examples/serialize.ts +61 -0
- package/package.json +271 -4
- package/scripts/check-no-comments.mjs +101 -0
- package/scripts/compare-golden.mjs +461 -0
- package/scripts/lib-config.mjs +9 -0
- package/scripts/smoke-auto.mjs +75 -0
- package/scripts/test-external-consumer.mjs +316 -0
- package/scripts/verify-package.mjs +78 -0
- package/src/airich/airich.ts +970 -0
- package/src/airich/context.ts +96 -0
- package/src/airich/encode.ts +25 -0
- package/src/airich/index.ts +98 -0
- package/src/airich/inline.ts +272 -0
- package/src/airich/nodes.ts +174 -0
- package/src/airich/primitives.ts +474 -0
- package/src/airich/protocol.ts +133 -0
- package/src/airich/table.ts +70 -0
- package/src/airich/tokenizer.ts +799 -0
- package/src/airich/transport.ts +106 -0
- package/src/branding.ts +23 -0
- package/src/btn/builders.ts +1073 -0
- package/src/btn/media-slot.ts +486 -0
- package/src/btn/media-source.ts +189 -0
- package/src/btn/sharp-loader.ts +23 -0
- package/src/btn/thumbnail.ts +182 -0
- package/src/btn/validators.ts +237 -0
- package/src/btn.ts +8 -0
- package/src/core/async-send.ts +28 -0
- package/src/core/base-builder.ts +104 -0
- package/src/core/errors.ts +82 -0
- package/src/download.ts +212 -0
- package/src/index.ts +229 -0
- package/src/integration/augment.ts +262 -0
- package/src/integration/auto.ts +103 -0
- package/src/integration/index.ts +8 -0
- package/src/integration/methods.ts +45 -0
- package/src/interactive.ts +188 -0
- package/src/media-gate.ts +499 -0
- package/src/message/album.ts +187 -0
- package/src/message/contact.ts +170 -0
- package/src/message/forward.ts +123 -0
- package/src/message/index.ts +83 -0
- package/src/message/link-preview.ts +148 -0
- package/src/message/location.ts +150 -0
- package/src/message/media.ts +323 -0
- package/src/message/poll.ts +158 -0
- package/src/message/reaction.ts +133 -0
- package/src/message/sticker.ts +100 -0
- package/src/message/target.ts +38 -0
- package/src/message/text.ts +61 -0
- package/src/message/vcard.ts +36 -0
- package/src/message/webp.ts +78 -0
- package/src/payloads.ts +204 -0
- package/src/serialize.ts +180 -0
- package/src/status.ts +29 -0
- package/src/zapo-client.ts +84 -0
- package/test/airich-inline.test.ts +200 -0
- package/test/airich-primitives.test.ts +226 -0
- package/test/airich-tokenizer.test.ts +145 -0
- package/test/airich.golden.test.ts +406 -0
- package/test/airich.test.ts +1006 -0
- package/test/btn-button.test.ts +416 -0
- package/test/btn-header.test.ts +646 -0
- package/test/btn-legacy.test.ts +342 -0
- package/test/btn-lifecycle.test.ts +295 -0
- package/test/btn-list.test.ts +261 -0
- package/test/btn-media-source.test.ts +150 -0
- package/test/btn-thumbnail.test.ts +160 -0
- package/test/builder-compat.test.ts +264 -0
- package/test/helpers.ts +27 -0
- package/test/hybrid-airich.test.ts +345 -0
- package/test/hybrid-client.test.ts +239 -0
- package/test/hybrid-errors.test.ts +557 -0
- package/test/hybrid-interactive.test.ts +455 -0
- package/test/hybrid.golden.test.ts +349 -0
- package/test/hybrid.test.ts +479 -0
- package/test/integration-auto.test.ts +159 -0
- package/test/integration.fakeserver.test.ts +440 -0
- package/test/media-gate.test.ts +215 -0
- package/test/message-album.test.ts +145 -0
- package/test/message-builders.test.ts +401 -0
- package/test/message-media.test.ts +303 -0
- package/test/message.fakeserver.test.ts +284 -0
- package/test/message.golden.test.ts +254 -0
- package/test/serializer.test.ts +448 -0
- package/tsconfig.json +26 -0
- package/tsconfig.test.json +10 -0
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
import { PassThrough, type Readable } from "node:stream";
|
|
2
|
+
|
|
3
|
+
export class QueueOverflowError extends Error {
|
|
4
|
+
code: string;
|
|
5
|
+
detail: Record<string, unknown>;
|
|
6
|
+
|
|
7
|
+
constructor(message: string, detail: Record<string, unknown> = {}) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "QueueOverflowError";
|
|
10
|
+
this.code = "QUEUE_OVERFLOW";
|
|
11
|
+
this.detail = detail;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class QueueClosedError extends Error {
|
|
16
|
+
code: string;
|
|
17
|
+
detail: Record<string, unknown>;
|
|
18
|
+
|
|
19
|
+
constructor(
|
|
20
|
+
message: string = "queue sudah ditutup (shutdown)",
|
|
21
|
+
detail: Record<string, unknown> = {},
|
|
22
|
+
) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "QueueClosedError";
|
|
25
|
+
this.code = "QUEUE_CLOSED";
|
|
26
|
+
this.detail = detail;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class QueueTimeoutError extends Error {
|
|
31
|
+
code: string;
|
|
32
|
+
detail: Record<string, unknown>;
|
|
33
|
+
|
|
34
|
+
constructor(message: string, detail: Record<string, unknown> = {}) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.name = "QueueTimeoutError";
|
|
37
|
+
this.code = "QUEUE_TIMEOUT";
|
|
38
|
+
this.detail = detail;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class MediaAdmissionPausedError extends Error {
|
|
43
|
+
code: string;
|
|
44
|
+
detail: Record<string, unknown>;
|
|
45
|
+
|
|
46
|
+
constructor(
|
|
47
|
+
message: string = "admission media dipause (governor)",
|
|
48
|
+
detail: Record<string, unknown> = {},
|
|
49
|
+
) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = "MediaAdmissionPausedError";
|
|
52
|
+
this.code = "MEDIA_PAUSED";
|
|
53
|
+
this.detail = detail;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ConcurrencyController {
|
|
58
|
+
setFactor(next: number): number;
|
|
59
|
+
getFactor(): number;
|
|
60
|
+
effectiveLimit(baseConcurrency: number): number;
|
|
61
|
+
snapshot(): { factor: number; minConcurrency: number };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const createConcurrencyController = ({
|
|
65
|
+
minConcurrency = 1,
|
|
66
|
+
}: { minConcurrency?: number } = {}): ConcurrencyController => {
|
|
67
|
+
let factor = 1;
|
|
68
|
+
|
|
69
|
+
const setFactor = (next: number): number => {
|
|
70
|
+
const value = Number(next);
|
|
71
|
+
if (!Number.isFinite(value)) return factor;
|
|
72
|
+
factor = Math.max(0, Math.min(1, value));
|
|
73
|
+
return factor;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const getFactor = (): number => factor;
|
|
77
|
+
|
|
78
|
+
const effectiveLimit = (baseConcurrency: number): number => {
|
|
79
|
+
const base = Math.max(1, Number(baseConcurrency) || 1);
|
|
80
|
+
if (factor === 0) return 0;
|
|
81
|
+
return Math.max(minConcurrency, Math.floor(base * factor));
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const snapshot = (): { factor: number; minConcurrency: number } => ({
|
|
85
|
+
factor,
|
|
86
|
+
minConcurrency,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
return { setFactor, getFactor, effectiveLimit, snapshot };
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export interface MediaQueueMetrics {
|
|
93
|
+
inc(name: string): void;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface MediaQueueOptions {
|
|
97
|
+
concurrency?: number | undefined;
|
|
98
|
+
capacity?: number | undefined;
|
|
99
|
+
timeoutMs?: number | undefined;
|
|
100
|
+
maxBytes?: number | undefined;
|
|
101
|
+
controller?: ConcurrencyController | undefined;
|
|
102
|
+
metrics?: MediaQueueMetrics | undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface MediaQueueJobContext {
|
|
106
|
+
signal: AbortSignal;
|
|
107
|
+
maxBytes: number;
|
|
108
|
+
noteBytes: (bytes: number) => void;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface MediaQueueRunOptions {
|
|
112
|
+
label?: string;
|
|
113
|
+
timeoutMs?: number;
|
|
114
|
+
signal?: AbortSignal;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface MediaQueueSnapshot {
|
|
118
|
+
active: number;
|
|
119
|
+
depth: number;
|
|
120
|
+
capacity: number;
|
|
121
|
+
concurrency: number;
|
|
122
|
+
paused: boolean;
|
|
123
|
+
closed: boolean;
|
|
124
|
+
processed: number;
|
|
125
|
+
failed: number;
|
|
126
|
+
timeouts: number;
|
|
127
|
+
oversized: number;
|
|
128
|
+
bytesLastJob: number;
|
|
129
|
+
maxBytes: number;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface MediaQueueStats {
|
|
133
|
+
processed: number;
|
|
134
|
+
failed: number;
|
|
135
|
+
timeouts: number;
|
|
136
|
+
oversized: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface MediaQueue {
|
|
140
|
+
run<T>(
|
|
141
|
+
fn: (context: MediaQueueJobContext) => Promise<T> | T,
|
|
142
|
+
options?: MediaQueueRunOptions,
|
|
143
|
+
): Promise<T>;
|
|
144
|
+
setAdmissionPaused(paused: boolean): boolean;
|
|
145
|
+
shutdown(options?: {
|
|
146
|
+
timeoutMs?: number;
|
|
147
|
+
}): Promise<{ rejectedPending: number; stillRunning: number }>;
|
|
148
|
+
snapshot(): MediaQueueSnapshot;
|
|
149
|
+
isUnderPressure(): boolean;
|
|
150
|
+
readonly pendingCount: number;
|
|
151
|
+
readonly runningCount: number;
|
|
152
|
+
readonly maxBytes: number;
|
|
153
|
+
readonly stats: MediaQueueStats;
|
|
154
|
+
markOversized(): void;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface QueueEntry {
|
|
158
|
+
label: string;
|
|
159
|
+
fn: (context: MediaQueueJobContext) => Promise<unknown> | unknown;
|
|
160
|
+
resolve: (value: unknown) => void;
|
|
161
|
+
reject: (error: unknown) => void;
|
|
162
|
+
controller: AbortController;
|
|
163
|
+
externalSignal: AbortSignal | null;
|
|
164
|
+
timeoutMs: number | undefined;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const MEDIA_QUEUE_DEFAULTS = {
|
|
168
|
+
concurrency: 2,
|
|
169
|
+
capacity: 50,
|
|
170
|
+
timeoutMs: 120_000,
|
|
171
|
+
maxBytes: 50 * 1024 * 1024,
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
export const createMediaQueue = (
|
|
175
|
+
options: MediaQueueOptions = {},
|
|
176
|
+
): MediaQueue => {
|
|
177
|
+
const concurrency = Math.max(
|
|
178
|
+
1,
|
|
179
|
+
Number(options.concurrency) || MEDIA_QUEUE_DEFAULTS.concurrency,
|
|
180
|
+
);
|
|
181
|
+
const capacity = Math.max(
|
|
182
|
+
1,
|
|
183
|
+
Number(options.capacity) || MEDIA_QUEUE_DEFAULTS.capacity,
|
|
184
|
+
);
|
|
185
|
+
const defaultTimeoutMs =
|
|
186
|
+
Number(options.timeoutMs) || MEDIA_QUEUE_DEFAULTS.timeoutMs;
|
|
187
|
+
const maxBytes = Math.max(
|
|
188
|
+
1024,
|
|
189
|
+
Number(options.maxBytes) || MEDIA_QUEUE_DEFAULTS.maxBytes,
|
|
190
|
+
);
|
|
191
|
+
const controller = options.controller ?? null;
|
|
192
|
+
const metrics = options.metrics ?? null;
|
|
193
|
+
|
|
194
|
+
const pending: QueueEntry[] = [];
|
|
195
|
+
const running = new Set<QueueEntry>();
|
|
196
|
+
|
|
197
|
+
let closed = false;
|
|
198
|
+
let admissionPaused = false;
|
|
199
|
+
let processed = 0;
|
|
200
|
+
let failed = 0;
|
|
201
|
+
let timeouts = 0;
|
|
202
|
+
let oversized = 0;
|
|
203
|
+
let bytesLastJob = 0;
|
|
204
|
+
|
|
205
|
+
const effectiveLimit = (): number =>
|
|
206
|
+
controller ? controller.effectiveLimit(concurrency) : concurrency;
|
|
207
|
+
|
|
208
|
+
const pump = (): void => {
|
|
209
|
+
if (closed) return;
|
|
210
|
+
const limit = effectiveLimit();
|
|
211
|
+
while (running.size < limit && pending.length > 0) {
|
|
212
|
+
const entry = pending.shift();
|
|
213
|
+
if (entry === undefined) break;
|
|
214
|
+
startJob(entry);
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
const startJob = (entry: QueueEntry): void => {
|
|
219
|
+
running.add(entry);
|
|
220
|
+
|
|
221
|
+
let settled = false;
|
|
222
|
+
const settleResolve = (value: unknown): void => {
|
|
223
|
+
if (settled) return;
|
|
224
|
+
settled = true;
|
|
225
|
+
processed += 1;
|
|
226
|
+
entry.resolve(value);
|
|
227
|
+
};
|
|
228
|
+
const settleReject = (error: unknown): void => {
|
|
229
|
+
if (settled) return;
|
|
230
|
+
settled = true;
|
|
231
|
+
failed += 1;
|
|
232
|
+
entry.reject(error);
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
const timeoutMs = entry.timeoutMs ?? defaultTimeoutMs;
|
|
236
|
+
let timeout: ReturnType<typeof setTimeout> | null = null;
|
|
237
|
+
let timedOut = false;
|
|
238
|
+
if (timeoutMs > 0) {
|
|
239
|
+
timeout = setTimeout(() => {
|
|
240
|
+
timedOut = true;
|
|
241
|
+
timeouts += 1;
|
|
242
|
+
metrics?.inc("mediaJobTimeouts");
|
|
243
|
+
entry.controller.abort(
|
|
244
|
+
new QueueTimeoutError(
|
|
245
|
+
`media job ${entry.label} melebihi ${timeoutMs}ms`,
|
|
246
|
+
),
|
|
247
|
+
);
|
|
248
|
+
settleReject(
|
|
249
|
+
new QueueTimeoutError(
|
|
250
|
+
`media job ${entry.label} melebihi ${timeoutMs}ms`,
|
|
251
|
+
),
|
|
252
|
+
);
|
|
253
|
+
}, timeoutMs);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const onExternalAbort = (): void => {
|
|
257
|
+
entry.controller.abort(
|
|
258
|
+
entry.externalSignal?.reason ??
|
|
259
|
+
new Error("media job dibatalkan (external)"),
|
|
260
|
+
);
|
|
261
|
+
};
|
|
262
|
+
if (entry.externalSignal) {
|
|
263
|
+
if (entry.externalSignal.aborted) onExternalAbort();
|
|
264
|
+
else
|
|
265
|
+
entry.externalSignal.addEventListener("abort", onExternalAbort, {
|
|
266
|
+
once: true,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
Promise.resolve()
|
|
271
|
+
.then(() =>
|
|
272
|
+
entry.fn({
|
|
273
|
+
signal: entry.controller.signal,
|
|
274
|
+
maxBytes,
|
|
275
|
+
noteBytes: (bytes: number) => {
|
|
276
|
+
bytesLastJob = Math.max(0, Number(bytes) || 0);
|
|
277
|
+
},
|
|
278
|
+
}),
|
|
279
|
+
)
|
|
280
|
+
.then((result: unknown) => {
|
|
281
|
+
if (result instanceof Uint8Array) {
|
|
282
|
+
const bytes = result.byteLength ?? 0;
|
|
283
|
+
bytesLastJob = bytes;
|
|
284
|
+
if (bytes > maxBytes) {
|
|
285
|
+
oversized += 1;
|
|
286
|
+
throw new Error(
|
|
287
|
+
`media melebihi batas ukuran (${bytes} > ${maxBytes} byte)`,
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return result;
|
|
292
|
+
})
|
|
293
|
+
.then(
|
|
294
|
+
(result: unknown) => {
|
|
295
|
+
settleResolve(result);
|
|
296
|
+
},
|
|
297
|
+
(error: unknown) => {
|
|
298
|
+
if (settled) {
|
|
299
|
+
metrics?.inc("mediaOverrunSettled");
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (timedOut) metrics?.inc("mediaJobTimeouts");
|
|
303
|
+
settleReject(error);
|
|
304
|
+
},
|
|
305
|
+
)
|
|
306
|
+
.finally(() => {
|
|
307
|
+
if (timeout) clearTimeout(timeout);
|
|
308
|
+
if (entry.externalSignal)
|
|
309
|
+
entry.externalSignal.removeEventListener("abort", onExternalAbort);
|
|
310
|
+
entry.controller.abort(new Error("media job selesai — cleanup signal"));
|
|
311
|
+
running.delete(entry);
|
|
312
|
+
pump();
|
|
313
|
+
});
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
const run = <T>(
|
|
317
|
+
fn: (context: MediaQueueJobContext) => Promise<T> | T,
|
|
318
|
+
{ label = "", timeoutMs, signal }: MediaQueueRunOptions = {},
|
|
319
|
+
): Promise<T> => {
|
|
320
|
+
if (closed)
|
|
321
|
+
return Promise.reject(new QueueClosedError("media queue ditutup"));
|
|
322
|
+
if (admissionPaused) {
|
|
323
|
+
metrics?.inc("mediaAdmissionPaused");
|
|
324
|
+
return Promise.reject(new MediaAdmissionPausedError());
|
|
325
|
+
}
|
|
326
|
+
if (pending.length >= capacity) {
|
|
327
|
+
metrics?.inc("mediaQueueRejections");
|
|
328
|
+
return Promise.reject(
|
|
329
|
+
new QueueOverflowError(`antrean media penuh (${capacity})`, { label }),
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
return new Promise<T>((resolve, reject) => {
|
|
334
|
+
const entry: QueueEntry = {
|
|
335
|
+
label: String(label || "media"),
|
|
336
|
+
fn: fn as (context: MediaQueueJobContext) => Promise<unknown> | unknown,
|
|
337
|
+
resolve: resolve as (value: unknown) => void,
|
|
338
|
+
reject,
|
|
339
|
+
controller: new AbortController(),
|
|
340
|
+
externalSignal: signal instanceof AbortSignal ? signal : null,
|
|
341
|
+
timeoutMs: Number.isFinite(timeoutMs) ? Number(timeoutMs) : undefined,
|
|
342
|
+
};
|
|
343
|
+
pending.push(entry);
|
|
344
|
+
pump();
|
|
345
|
+
});
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
const setAdmissionPaused = (paused: boolean): boolean => {
|
|
349
|
+
admissionPaused = !!paused;
|
|
350
|
+
return admissionPaused;
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
const shutdown = async ({
|
|
354
|
+
timeoutMs: shutdownTimeoutMs = 10_000,
|
|
355
|
+
}: { timeoutMs?: number } = {}): Promise<{
|
|
356
|
+
rejectedPending: number;
|
|
357
|
+
stillRunning: number;
|
|
358
|
+
}> => {
|
|
359
|
+
closed = true;
|
|
360
|
+
const rejectedCount = pending.length;
|
|
361
|
+
for (const entry of [...pending]) {
|
|
362
|
+
entry.reject(
|
|
363
|
+
new QueueClosedError("shutdown — media job belum dijalankan"),
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
pending.length = 0;
|
|
367
|
+
|
|
368
|
+
const deadline = Date.now() + Math.max(0, Number(shutdownTimeoutMs) || 0);
|
|
369
|
+
while (running.size > 0 && Date.now() < deadline) {
|
|
370
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
371
|
+
}
|
|
372
|
+
return { rejectedPending: rejectedCount, stillRunning: running.size };
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
const snapshot = (): MediaQueueSnapshot => ({
|
|
376
|
+
active: running.size,
|
|
377
|
+
depth: pending.length,
|
|
378
|
+
capacity,
|
|
379
|
+
concurrency: effectiveLimit(),
|
|
380
|
+
paused: admissionPaused,
|
|
381
|
+
closed,
|
|
382
|
+
processed,
|
|
383
|
+
failed,
|
|
384
|
+
timeouts,
|
|
385
|
+
oversized,
|
|
386
|
+
bytesLastJob,
|
|
387
|
+
maxBytes,
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
return {
|
|
391
|
+
run,
|
|
392
|
+
setAdmissionPaused,
|
|
393
|
+
shutdown,
|
|
394
|
+
snapshot,
|
|
395
|
+
isUnderPressure: () => admissionPaused || pending.length >= capacity * 0.6,
|
|
396
|
+
get pendingCount() {
|
|
397
|
+
return pending.length;
|
|
398
|
+
},
|
|
399
|
+
get runningCount() {
|
|
400
|
+
return running.size;
|
|
401
|
+
},
|
|
402
|
+
get maxBytes() {
|
|
403
|
+
return maxBytes;
|
|
404
|
+
},
|
|
405
|
+
get stats() {
|
|
406
|
+
return { processed, failed, timeouts, oversized };
|
|
407
|
+
},
|
|
408
|
+
markOversized: () => {
|
|
409
|
+
oversized += 1;
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
export interface LimitedStream extends Readable {
|
|
415
|
+
bytesRead(): number;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
export const limitStreamBytes = (
|
|
419
|
+
source: Readable,
|
|
420
|
+
maxBytes: number,
|
|
421
|
+
onLimit?: (bytesRead: number) => void,
|
|
422
|
+
): LimitedStream => {
|
|
423
|
+
const limited = new PassThrough() as PassThrough & LimitedStream;
|
|
424
|
+
let total = 0;
|
|
425
|
+
|
|
426
|
+
const onDrain = (): void => {
|
|
427
|
+
source.resume();
|
|
428
|
+
};
|
|
429
|
+
limited.on("drain", onDrain);
|
|
430
|
+
|
|
431
|
+
source.on("data", (chunk: Buffer | string) => {
|
|
432
|
+
total +=
|
|
433
|
+
typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk.length;
|
|
434
|
+
if (total > maxBytes) {
|
|
435
|
+
const error = new Error(
|
|
436
|
+
`media melebihi batas ukuran (${maxBytes} byte)`,
|
|
437
|
+
) as Error & { code: string };
|
|
438
|
+
error.code = "MEDIA_TOO_LARGE";
|
|
439
|
+
onLimit?.(total);
|
|
440
|
+
limited.destroy(error);
|
|
441
|
+
source.destroy(error);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (limited.destroyed) {
|
|
445
|
+
source.destroy();
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
const ready = limited.push(chunk);
|
|
449
|
+
if (!ready) source.pause();
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
source.on("end", () => {
|
|
453
|
+
if (!limited.destroyed) limited.end();
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
source.on("error", (error: Error) => {
|
|
457
|
+
limited.destroy(error);
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
limited.bytesRead = () => total;
|
|
461
|
+
return limited;
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
const envNumber = (name: string, fallback: number): number => {
|
|
465
|
+
const raw = process.env[name];
|
|
466
|
+
if (raw === undefined || raw === "") return fallback;
|
|
467
|
+
const value = Number(raw);
|
|
468
|
+
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
let shared: MediaQueue | null = null;
|
|
472
|
+
|
|
473
|
+
export const configureSharedMediaQueue = (
|
|
474
|
+
options: MediaQueueOptions = {},
|
|
475
|
+
): MediaQueue => {
|
|
476
|
+
shared = createMediaQueue({
|
|
477
|
+
concurrency:
|
|
478
|
+
options.concurrency ??
|
|
479
|
+
envNumber("ARM_MEDIA_CONCURRENCY", MEDIA_QUEUE_DEFAULTS.concurrency),
|
|
480
|
+
capacity: options.capacity ?? 50,
|
|
481
|
+
timeoutMs:
|
|
482
|
+
options.timeoutMs ??
|
|
483
|
+
envNumber("ARM_MEDIA_TIMEOUT_MS", MEDIA_QUEUE_DEFAULTS.timeoutMs),
|
|
484
|
+
maxBytes:
|
|
485
|
+
options.maxBytes ??
|
|
486
|
+
envNumber("ARM_MEDIA_MAX_BYTES", MEDIA_QUEUE_DEFAULTS.maxBytes),
|
|
487
|
+
controller: options.controller,
|
|
488
|
+
});
|
|
489
|
+
return shared;
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
export const getSharedMediaQueue = (): MediaQueue => {
|
|
493
|
+
if (!shared) return configureSharedMediaQueue();
|
|
494
|
+
return shared;
|
|
495
|
+
};
|
|
496
|
+
|
|
497
|
+
export const resetSharedMediaQueue = (): void => {
|
|
498
|
+
shared = null;
|
|
499
|
+
};
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { BaseBuilder, type SendResolutionArg } from "../core/base-builder.js";
|
|
2
|
+
import { MessageError, ProtocolSendError } from "../core/errors.js";
|
|
3
|
+
import { sendConfigured, type MessageSendOptions } from "../core/async-send.js";
|
|
4
|
+
import type { MessageSendResult } from "../zapo-client.js";
|
|
5
|
+
import {
|
|
6
|
+
resolveMediaSlot,
|
|
7
|
+
type MediaSlot,
|
|
8
|
+
type MediaSlotOptions,
|
|
9
|
+
} from "../btn/media-slot.js";
|
|
10
|
+
import type { MediaSource } from "../btn/media-source.js";
|
|
11
|
+
import {
|
|
12
|
+
mediaSlotToMessage,
|
|
13
|
+
type AlbumBuildResult,
|
|
14
|
+
type MediaSlotResolution,
|
|
15
|
+
} from "../payloads.js";
|
|
16
|
+
import type { ZapoClient, ZapoSendOptions } from "../zapo-client.js";
|
|
17
|
+
|
|
18
|
+
export type { MediaSlotOptions } from "../btn/media-slot.js";
|
|
19
|
+
|
|
20
|
+
export interface AlbumMediaItem {
|
|
21
|
+
type: "image" | "video";
|
|
22
|
+
source: MediaSource;
|
|
23
|
+
options?: MediaSlotOptions;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface AlbumConfig {
|
|
27
|
+
media: readonly AlbumMediaItem[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface AlbumChild {
|
|
31
|
+
kind: "image" | "video";
|
|
32
|
+
resolution: MediaSlotResolution;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
type AlbumMediaSlot = MediaSlot & { kind: "image" | "video" };
|
|
36
|
+
|
|
37
|
+
export class AlbumBuilder extends BaseBuilder<AlbumBuildResult> {
|
|
38
|
+
#slots: AlbumMediaSlot[] = [];
|
|
39
|
+
|
|
40
|
+
#addChild(
|
|
41
|
+
kind: "image" | "video",
|
|
42
|
+
source: MediaSource,
|
|
43
|
+
options: MediaSlotOptions | undefined,
|
|
44
|
+
): this {
|
|
45
|
+
this.#slots.push({
|
|
46
|
+
kind,
|
|
47
|
+
source,
|
|
48
|
+
options: options ?? {},
|
|
49
|
+
label: `album:${kind}:${this.#slots.length + 1}`,
|
|
50
|
+
});
|
|
51
|
+
return this;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
image(source: MediaSource, options?: MediaSlotOptions): this {
|
|
55
|
+
return this.#addChild("image", source, options);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
video(source: MediaSource, options?: MediaSlotOptions): this {
|
|
59
|
+
return this.#addChild("video", source, options);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
count(): number {
|
|
63
|
+
return this.#slots.length;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
override build(): AlbumBuildResult {
|
|
67
|
+
if (this.#slots.length === 0) {
|
|
68
|
+
throw new MessageError(
|
|
69
|
+
"album butuh minimal satu media — panggil image()/video() sebelum send()",
|
|
70
|
+
"NO_MEDIA",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
albumMessage: {
|
|
75
|
+
expectedImageCount: this.#slots.filter((s) => s.kind === "image")
|
|
76
|
+
.length,
|
|
77
|
+
expectedVideoCount: this.#slots.filter((s) => s.kind === "video")
|
|
78
|
+
.length,
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async resolveChildren(): Promise<AlbumChild[]> {
|
|
84
|
+
if (this.#slots.length === 0) {
|
|
85
|
+
throw new MessageError(
|
|
86
|
+
"album butuh minimal satu media — panggil image()/video() sebelum send()",
|
|
87
|
+
"NO_MEDIA",
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
const { client } = this._resolve();
|
|
91
|
+
const slots = [...this.#slots];
|
|
92
|
+
const resolutions = await Promise.all(
|
|
93
|
+
slots.map((slot) => resolveMediaSlot(client, slot)),
|
|
94
|
+
);
|
|
95
|
+
return resolutions.map((resolution, index) => ({
|
|
96
|
+
kind: slots[index]!.kind,
|
|
97
|
+
resolution,
|
|
98
|
+
}));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
override async send(jid?: string, arg?: SendResolutionArg): Promise<unknown> {
|
|
102
|
+
const { client, options } = this._resolve(arg);
|
|
103
|
+
const target = typeof jid === "string" && jid ? jid : this._defaultTarget();
|
|
104
|
+
if (!target) {
|
|
105
|
+
throw new MessageError(
|
|
106
|
+
"tujuan album tidak diketahui. panggil send(jid) atau .defaultTo(jid)",
|
|
107
|
+
"NO_TARGET",
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const children = await this.resolveChildren();
|
|
112
|
+
const album = this.build();
|
|
113
|
+
const albumOptions: ZapoSendOptions = { ...options };
|
|
114
|
+
const albumSend = client.message.send.bind(client.message);
|
|
115
|
+
const albumResult = (await (Object.keys(albumOptions).length
|
|
116
|
+
? albumSend(target, album, albumOptions)
|
|
117
|
+
: albumSend(target, album))) as { id?: string } | undefined;
|
|
118
|
+
|
|
119
|
+
const albumId = albumResult?.id;
|
|
120
|
+
if (typeof albumId !== "string" || !albumId) {
|
|
121
|
+
throw new ProtocolSendError("album_id");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const selfJid = resolveSelfJid(client);
|
|
125
|
+
for (const child of children) {
|
|
126
|
+
const childOptions: ZapoSendOptions = {
|
|
127
|
+
...options,
|
|
128
|
+
quote: {
|
|
129
|
+
id: albumId,
|
|
130
|
+
remoteJid: target,
|
|
131
|
+
fromMe: true,
|
|
132
|
+
...(selfJid !== undefined ? { participant: selfJid } : {}),
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
await client.message.send(
|
|
136
|
+
target,
|
|
137
|
+
mediaSlotToMessage(child.resolution),
|
|
138
|
+
childOptions,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
return albumResult;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const resolveSelfJid = (client: ZapoClient): string | undefined => {
|
|
146
|
+
const credentials = client.auth?.getCurrentCredentials?.();
|
|
147
|
+
if (!credentials) return undefined;
|
|
148
|
+
return credentials.meLid ?? credentials.meJid ?? undefined;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
export function album(client?: ZapoClient): AlbumBuilder;
|
|
152
|
+
export function album(
|
|
153
|
+
client: ZapoClient | undefined,
|
|
154
|
+
jid: string,
|
|
155
|
+
config: AlbumConfig,
|
|
156
|
+
options?: MessageSendOptions,
|
|
157
|
+
): Promise<MessageSendResult>;
|
|
158
|
+
export function album(
|
|
159
|
+
client?: ZapoClient,
|
|
160
|
+
jid?: string,
|
|
161
|
+
config?: AlbumConfig,
|
|
162
|
+
options?: MessageSendOptions,
|
|
163
|
+
): AlbumBuilder | Promise<MessageSendResult> {
|
|
164
|
+
if (config === undefined) return new AlbumBuilder(client);
|
|
165
|
+
return sendAlbum(client, jid, config, options);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export const applyAlbumConfig = (
|
|
169
|
+
builder: AlbumBuilder,
|
|
170
|
+
config: AlbumConfig,
|
|
171
|
+
): void => {
|
|
172
|
+
for (const item of config.media) {
|
|
173
|
+
if (item.type === "image") builder.image(item.source, item.options);
|
|
174
|
+
else builder.video(item.source, item.options);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
export const sendAlbum = async (
|
|
179
|
+
client: ZapoClient | undefined,
|
|
180
|
+
jid: string | undefined,
|
|
181
|
+
config: AlbumConfig,
|
|
182
|
+
options?: MessageSendOptions,
|
|
183
|
+
): Promise<MessageSendResult> => {
|
|
184
|
+
const builder = new AlbumBuilder(client);
|
|
185
|
+
applyAlbumConfig(builder, config);
|
|
186
|
+
return sendConfigured(builder, jid, options);
|
|
187
|
+
};
|