Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

fix: stream provider media uploads instead of buffering files in memory

Nevo David9980825aa454
diff --git a/libraries/nestjs-libraries/src/integrations/social.abstract.ts b/libraries/nestjs-libraries/src/integrations/social.abstract.ts
index 42acc7e7e..69d1bb92f 100644
--- a/libraries/nestjs-libraries/src/integrations/social.abstract.ts
+++ b/libraries/nestjs-libraries/src/integrations/social.abstract.ts
@@ -5,6 +5,7 @@ import { ApplicationFailure } from '@temporalio/activity';
import { readOrFetch } from '@gitroom/helpers/utils/read.or.fetch';
import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
import sharp from 'sharp';
+import { createReadStream, statSync } from 'fs';
export type ValidityMedia = {
path: string;
@@ -173,6 +174,122 @@ export abstract class SocialAbstract {
return { width, height };
}
+ // Resolves the total byte size of the media without loading it into memory:
+ // a HEAD request for remote URLs, statSync for local files.
+ protected async mediaSize(path: string, identifier = ''): Promise<number> {
+ if (path.indexOf('http') === 0) {
+ // the media path is user-influenced, keep the SSRF-safe dispatcher that
+ // this.fetch applies to every other outbound request
+ const head = await fetch(path, {
+ method: 'HEAD',
+ dispatcher: getSsrfSafeDispatcher(),
+ } as any);
+ const length = head.headers.get('content-length');
+ // A failed HEAD can still carry a content-length (of the error body),
+ // which would register the media with a garbage size downstream.
+ if (!head.ok || !length) {
+ throw new BadBody(
+ identifier,
+ '{}',
+ Buffer.from('{}'),
+ 'Could not determine the media size for upload'
+ );
+ }
+ return Number(length);
+ }
+
+ return statSync(path).size;
+ }
+
+ // Reads a single [start, end] byte range into memory. Used by providers whose
+ // chunked-upload APIs require a Buffer per segment: only one small chunk is
+ // resident at a time, never the whole file.
+ protected async mediaChunk(
+ path: string,
+ start: number,
+ end: number
+ ): Promise<Buffer> {
+ if (path.indexOf('http') === 0) {
+ const response = await fetch(path, {
+ headers: { Range: `bytes=${start}-${end}` },
+ dispatcher: getSsrfSafeDispatcher(),
+ } as any);
+ // Anything but 206 means the server ignored the Range header: buffering
+ // response.body here would silently load the whole file into memory and
+ // upload corrupted chunks.
+ if (response.status !== 206) {
+ throw new BadBody(
+ '',
+ '{}',
+ Buffer.from('{}'),
+ `Media server did not honor the range request (status ${response.status})`
+ );
+ }
+ return Buffer.from(await response.arrayBuffer());
+ }
+
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ createReadStream(path, { start, end })
+ .on('data', (chunk) => chunks.push(chunk as Buffer))
+ .on('end', () => resolve(Buffer.concat(chunks)))
+ .on('error', reject);
+ });
+ }
+
+ // Streamed request bodies can't be replayed by this.fetch's retry, so
+ // providers wrap streamed uploads in a factory that rebuilds the request
+ // (re-opening its source streams) on every attempt. Errors carrying a
+ // `response` (axios errors, or a thrown { response: { status, data } })
+ // go through the same retry and handleErrors classification rules as
+ // this.fetch; anything else is rethrown untouched so Temporal keeps its
+ // usual retry behavior.
+ protected async runStreamedUpload<T>(
+ func: () => Promise<T>,
+ identifier = '',
+ totalRetries = 0
+ ): Promise<T> {
+ try {
+ return await func();
+ } catch (err: any) {
+ if (!err?.response) {
+ throw err;
+ }
+
+ const status = err.response.status || 500;
+ const data = err.response.data;
+ const json = typeof data === 'string' ? data : safeStringify(data || {});
+ const handleError = this.handleErrors(json, status);
+
+ if (
+ totalRetries <= 2 &&
+ (status === 429 ||
+ (status === 500 && !handleError) ||
+ handleError?.type === 'retry' ||
+ json.includes('rate_limit_exceeded') ||
+ json.includes('Rate limit'))
+ ) {
+ await timer(5000);
+ return this.runStreamedUpload(func, identifier, totalRetries + 1);
+ }
+
+ if (
+ (status === 401 &&
+ (handleError?.type === 'refresh-token' || !handleError)) ||
+ handleError?.type === 'refresh-token'
+ ) {
+ throw new RefreshToken(identifier, json, '{}', handleError?.value);
+ }
+
+ throw new BadBody(
+ identifier,
+ json,
+ '{}',
+ handleError?.value || 'Unknown Error'
+ );
+ }
+ }
+
public async mention(
token: string,
d: { query: string },
diff --git a/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts b/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts
index bdb794c88..bcbbb5a43 100644
--- a/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts
@@ -23,6 +23,7 @@ import dayjs from 'dayjs';
import { Integration } from '@prisma/client';
import { AuthService } from '@gitroom/helpers/auth/auth.service';
import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
+import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
import sharp from 'sharp';
import { Plug } from '@gitroom/helpers/decorators/plug.decorator';
import { timer } from '@gitroom/helpers/utils/timer';
@@ -74,22 +75,32 @@ async function uploadVideo(
exp: Date.now() / 1000 + 60 * 30, // 30 minutes
});
- async function downloadVideo(
- url: string
- ): Promise<{ video: Buffer; size: number }> {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Failed to fetch video: ${response.statusText}`);
- }
- const arrayBuffer = await response.arrayBuffer();
- const video = Buffer.from(arrayBuffer);
- const size = video.length;
- return { video, size };
+ // The video is never buffered in memory: the size comes from a HEAD request
+ // and the bytes are streamed straight from the source into the upload.
+ const headResponse = await fetch(videoPath, {
+ method: 'HEAD',
+ // @ts-ignore - undici-only option; blocks SSRF to internal IPs
+ dispatcher: getSsrfSafeDispatcher(),
+ });
+ const videoSize = Number(headResponse.headers.get('content-length') || 0);
+ if (!headResponse.ok || !videoSize) {
+ throw new BadBody(
+ 'bluesky',
+ '{}',
+ {} as any,
+ 'Could not determine the video size for Bluesky upload'
+ );
}
- const video = await downloadVideo(videoPath);
+ const videoResponse = await fetch(videoPath, {
+ // @ts-ignore - undici-only option; blocks SSRF to internal IPs
+ dispatcher: getSsrfSafeDispatcher(),
+ });
+ if (!videoResponse.ok) {
+ throw new Error(`Failed to fetch video: ${videoResponse.statusText}`);
+ }
- console.log('Downloaded video', videoPath, video.size);
+ console.log('Uploading video', videoPath, videoSize);
const uploadUrl = new URL(
'https://video.bsky.app/xrpc/app.bsky.video.uploadVideo'
@@ -102,10 +113,12 @@ async function uploadVideo(
headers: {
Authorization: `Bearer ${serviceAuth.token}`,
'Content-Type': 'video/mp4',
- 'Content-Length': video.size.toString(),
+ 'Content-Length': videoSize.toString(),
},
- body: video.video,
- });
+ body: videoResponse.body,
+ // Required by undici when streaming a request body.
+ duplex: 'half',
+ } as any);
const jobStatus = (await uploadResponse.json()) as AppBskyVideoDefs.JobStatus;
console.log('JobId:', jobStatus.jobId);
diff --git a/libraries/nestjs-libraries/src/integrations/social/discord.provider.ts b/libraries/nestjs-libraries/src/integrations/social/discord.provider.ts
index a70f36ce1..4781ac69e 100644
--- a/libraries/nestjs-libraries/src/integrations/social/discord.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/discord.provider.ts
@@ -9,6 +9,8 @@ import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.ab
import { Integration } from '@prisma/client';
import { DiscordDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/discord.dto';
import { Tool } from '@gitroom/nestjs-libraries/integrations/tool.decorator';
+import axios from 'axios';
+import FormDataUpload from 'form-data';
export class DiscordProvider extends SocialAbstract implements SocialProvider {
override maxConcurrentJob = 5; // Discord has generous rate limits for webhook posting
@@ -135,6 +137,59 @@ export class DiscordProvider extends SocialAbstract implements SocialProvider {
}));
}
+ // Builds the multipart message and streams each attachment straight from its
+ // source (size from a HEAD request) so files are never buffered in memory.
+ // runStreamedUpload rebuilds the whole form per attempt (a consumed stream
+ // can't be replayed) and keeps handleErrors classification.
+ private async sendMessageWithMedia(
+ channel: string,
+ message: string,
+ media: PostDetails['media']
+ ) {
+ return this.runStreamedUpload(async () => {
+ const form = new FormDataUpload();
+ form.append(
+ 'payload_json',
+ JSON.stringify({
+ content: message.replace(/\[\[\[(@.*?)]]]/g, (match, p1) => {
+ return `<${p1}>`;
+ }),
+ attachments: media?.map((p, index) => ({
+ id: index,
+ description: `Picture ${index}`,
+ filename: p.path.split('/').pop(),
+ })),
+ })
+ );
+
+ let index = 0;
+ for (const item of media || []) {
+ const fileSize = await this.mediaSize(item.path, this.identifier);
+ const { data: stream } = await axios.get(item.path, {
+ responseType: 'stream',
+ });
+ form.append(`files[${index}]`, stream, {
+ filename: item.path.split('/').pop(),
+ knownLength: fileSize,
+ });
+ index++;
+ }
+
+ const { data } = await axios.post(
+ `https://discord.com/api/channels/${channel}/messages`,
+ form,
+ {
+ headers: {
+ ...form.getHeaders(),
+ Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN_ID}`,
+ },
+ }
+ );
+
+ return data;
+ }, this.identifier);
+ }
+
async post(
id: string,
accessToken: string,
@@ -143,43 +198,12 @@ export class DiscordProvider extends SocialAbstract implements SocialProvider {
const [firstPost] = postDetails;
const channel = firstPost.settings.channel;
- const form = new FormData();
- form.append(
- 'payload_json',
- JSON.stringify({
- content: firstPost.message.replace(/\[\[\[(@.*?)]]]/g, (match, p1) => {
- return `<${p1}>`;
- }),
- attachments: firstPost.media?.map((p, index) => ({
- id: index,
- description: `Picture ${index}`,
- filename: p.path.split('/').pop(),
- })),
- })
+ const data = await this.sendMessageWithMedia(
+ channel,
+ firstPost.message,
+ firstPost.media
);
- let index = 0;
- for (const media of firstPost.media || []) {
- const loadMedia = await fetch(media.path);
-
- form.append(
- `files[${index}]`,
- await loadMedia.blob(),
- media.path.split('/').pop()
- );
- index++;
- }
-
- const data = await (
- await this.fetch(`https://discord.com/api/channels/${channel}/messages`, {
- method: 'POST',
- headers: {
- Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN_ID}`,
- },
- body: form,
- })
- ).json();
-
return [
{
id: firstPost.id,
@@ -226,46 +250,12 @@ export class DiscordProvider extends SocialAbstract implements SocialProvider {
threadChannel = threadId;
}
- const form = new FormData();
- form.append(
- 'payload_json',
- JSON.stringify({
- content: commentPost.message.replace(/\[\[\[(@.*?)]]]/g, (match, p1) => {
- return `<${p1}>`;
- }),
- attachments: commentPost.media?.map((p, index) => ({
- id: index,
- description: `Picture ${index}`,
- filename: p.path.split('/').pop(),
- })),
- })
+ const data = await this.sendMessageWithMedia(
+ threadChannel,
+ commentPost.message,
+ commentPost.media
);
- let index = 0;
- for (const media of commentPost.media || []) {
- const loadMedia = await fetch(media.path);
-
- form.append(
- `files[${index}]`,
- await loadMedia.blob(),
- media.path.split('/').pop()
- );
- index++;
- }
-
- const data = await (
- await this.fetch(
- `https://discord.com/api/channels/${threadChannel}/messages`,
- {
- method: 'POST',
- headers: {
- Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN_ID}`,
- },
- body: form,
- }
- )
- ).json();
-
return [
{
id: commentPost.id,
diff --git a/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts b/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts
index 1886096c9..b50bebb48 100644
--- a/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts
@@ -19,7 +19,6 @@ import { Integration } from '@prisma/client';
import { PostPlug } from '@gitroom/helpers/decorators/post.plug';
import { LinkedinDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/linkedin.dto';
import imageToPDF from 'image-to-pdf';
-import { createReadStream, statSync } from 'fs';
import { Readable } from 'stream';
import { Rules } from '@gitroom/nestjs-libraries/chat/rules.description.decorator';
@@ -263,13 +262,20 @@ export class LinkedinProvider extends SocialAbstract implements SocialProvider {
fileName: string,
accessToken: string,
personId: string,
- picture: any,
+ // Either the media bytes (images / converted PDFs) or a `{ path }`
+ // descriptor for videos, which are streamed chunk-by-chunk from the source
+ // instead of being held in memory.
+ picture: Buffer | { path: string },
type = 'personal' as 'company' | 'personal'
) {
// Determine the appropriate endpoint based on file type
const isVideo = hasExtension(fileName, 'mp4');
const isPdf = hasExtension(fileName, 'pdf');
+ const fileSizeBytes = Buffer.isBuffer(picture)
+ ? picture.length
+ : await this.mediaSize(picture.path, this.identifier);
+
let endpoint: string;
if (isVideo) {
endpoint = 'videos';
@@ -279,11 +285,6 @@ export class LinkedinProvider extends SocialAbstract implements SocialProvider {
endpoint = 'images';
}
- // Videos arrive as a path/URL (not a Buffer) so the file is never held in
- // memory whole: the size comes from a HEAD request / stat, and each 2MB
- // part is fetched with a ranged GET right before its PUT.
- const videoSize = isVideo ? await this.videoSize(picture) : 0;
-
const {
value: { uploadUrl, image, video, document, uploadInstructions, ...all },
} = await (
@@ -305,7 +306,7 @@ export class LinkedinProvider extends SocialAbstract implements SocialProvider {
: `urn:li:organization:${personId}`,
...(isVideo
? {
- fileSizeBytes: videoSize,
+ fileSizeBytes,
uploadCaptions: false,
uploadThumbnail: false,
}
@@ -323,8 +324,18 @@ export class LinkedinProvider extends SocialAbstract implements SocialProvider {
if (isVideo) {
// Only the Videos API uses multipart chunked uploads. Each 2MB part is
// PUT separately and the returned etags are passed to finalizeUpload.
- for (let i = 0; i < videoSize; i += 1024 * 1024 * 2) {
- const end = Math.min(i + 1024 * 1024 * 2, videoSize) - 1;
+ // Each part is read on demand (mediaChunk) so only one 2MB chunk is ever
+ // resident in memory instead of the whole video.
+ const chunkSize = 1024 * 1024 * 2;
+ for (let i = 0; i < fileSizeBytes; i += chunkSize) {
+ const body = Buffer.isBuffer(picture)
+ ? picture.slice(i, i + chunkSize)
+ : await this.mediaChunk(
+ picture.path,
+ i,
+ Math.min(i + chunkSize, fileSizeBytes) - 1
+ );
+
const upload = await this.fetch(
sendUrlRequest,
{
@@ -335,7 +346,7 @@ export class LinkedinProvider extends SocialAbstract implements SocialProvider {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/octet-stream',
},
- body: await this.videoChunk(picture, i, end),
+ body,
},
'linkedin',
0,
@@ -359,7 +370,9 @@ export class LinkedinProvider extends SocialAbstract implements SocialProvider {
Authorization: `Bearer ${accessToken}`,
...(isPdf ? { 'Content-Type': 'application/pdf' } : {}),
},
- body: picture,
+ // Only videos arrive as a { path } descriptor; images and documents
+ // are always a Buffer.
+ body: picture as Buffer,
},
'linkedin',
0,
@@ -583,109 +596,56 @@ export class LinkedinProvider extends SocialAbstract implements SocialProvider {
personId: string,
type: 'company' | 'personal'
): Promise<Record<string, string[]>> {
- const mediaUploads = await Promise.all(
- postDetails.flatMap(
- (post) =>
- post.media?.map(async (media) => {
- // Videos are passed through as their path/URL: uploadPicture
- // downloads them in 2MB ranges instead of buffering the whole file.
- let mediaBuffer: Buffer | string;
-
- // Check if media has a buffer (from PDF conversion)
- if (
- media &&
- typeof media === 'object' &&
- 'buffer' in media &&
- Buffer.isBuffer(media.buffer)
- ) {
- mediaBuffer = (media as any).buffer;
- } else if (hasExtension(media.path, 'mp4')) {
- mediaBuffer = media.path;
- } else {
- mediaBuffer = await this.prepareMediaBuffer(media.path);
- }
-
- const uploadedMediaId = await this.uploadPicture(
- media.path,
- accessToken,
- personId,
- mediaBuffer,
- type
- );
-
- return {
- id: uploadedMediaId,
- postId: post.id,
- };
- }) || []
- )
- );
-
- return mediaUploads.reduce((acc, upload) => {
- if (!upload?.id) return acc;
-
- acc[upload.postId] = acc[upload.postId] || [];
- acc[upload.postId].push(upload.id);
- return acc;
- }, {} as Record<string, string[]>);
- }
+ // Media is uploaded sequentially on purpose: uploading everything with
+ // Promise.all holds every file in memory at the same time.
+ const mediaUploads: Record<string, string[]> = {};
+ for (const post of postDetails) {
+ for (const media of post.media || []) {
+ let mediaBuffer: Buffer | { path: string };
+
+ // Check if media has a buffer (from PDF conversion)
+ if (
+ media &&
+ typeof media === 'object' &&
+ 'buffer' in media &&
+ Buffer.isBuffer(media.buffer)
+ ) {
+ mediaBuffer = (media as any).buffer;
+ } else if (hasExtension(media.path, 'mp4')) {
+ // Videos are never buffered: uploadPicture streams them from the
+ // source chunk-by-chunk.
+ mediaBuffer = { path: media.path };
+ } else {
+ mediaBuffer = await this.prepareMediaBuffer(media.path);
+ }
- // Resolves the total byte size of the video without loading it into memory:
- // a HEAD request for remote URLs, statSync for local files.
- private async videoSize(path: string): Promise<number> {
- if (path.indexOf('http') === 0) {
- const head = await fetch(path, { method: 'HEAD' });
- const length = head.headers.get('content-length');
- if (!length) {
- throw new BadBody(
- 'linkedin-error-upload',
- '{}',
- Buffer.from('{}'),
- 'Could not determine the video size for LinkedIn upload'
+ const uploadedMediaId = await this.uploadPicture(
+ media.path,
+ accessToken,
+ personId,
+ mediaBuffer,
+ type
);
- }
- return Number(length);
- }
- return statSync(path).size;
- }
+ if (!uploadedMediaId) {
+ continue;
+ }
- // Returns only the [start, end] byte window of the video as a Buffer (a
- // ranged GET for remote URLs, a ranged read for local files), so memory is
- // bounded by the part size. A Buffer (not a stream) because this.fetch may
- // retry the PUT, which would fail with a consumed one-shot stream body.
- private async videoChunk(
- path: string,
- start: number,
- end: number
- ): Promise<Buffer> {
- if (path.indexOf('http') === 0) {
- const response = await fetch(path, {
- headers: { Range: `bytes=${start}-${end}` },
- });
- // A 200 means the origin ignored the Range header and is sending the
- // whole file: uploading it as this part would silently corrupt the
- // video, so fail loudly instead.
- if (response.status !== 206) {
- throw new BadBody(
- 'linkedin-error-upload',
- '{}',
- Buffer.from('{}'),
- `Media server ignored the ranged request (status ${response.status}); it must support HTTP Range requests for chunked LinkedIn uploads`
- );
+ mediaUploads[post.id] = mediaUploads[post.id] || [];
+ mediaUploads[post.id].push(uploadedMediaId);
}
- return Buffer.from(await response.arrayBuffer());
}
- return this.streamToBuffer(createReadStream(path, { start, end }));
+ return mediaUploads;
}
private async prepareMediaBuffer(mediaUrl: string): Promise<Buffer> {
const isGif = lookup(mediaUrl) === 'image/gif';
- // GIFs pass through untouched (sharp would break animation).
+ // GIFs pass through untouched (sharp would break animation). Videos never
+ // reach this function - they are streamed by uploadPicture instead.
if (isGif) {
- return Buffer.from(await readOrFetch(mediaUrl));
+ return readOrFetch(mediaUrl);
}
const mime = lookup(mediaUrl);
diff --git a/libraries/nestjs-libraries/src/integrations/social/mastodon.provider.ts b/libraries/nestjs-libraries/src/integrations/social/mastodon.provider.ts
index 3e2f17fef..a3c12bff6 100644
--- a/libraries/nestjs-libraries/src/integrations/social/mastodon.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/mastodon.provider.ts
@@ -10,6 +10,8 @@ import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/s
import dayjs from 'dayjs';
import { Integration } from '@prisma/client';
import { number, string } from 'yup';
+import FormDataUpload from 'form-data';
+import { PassThrough, Readable } from 'stream';
export class MastodonProvider extends SocialAbstract implements SocialProvider {
override maxConcurrentJob = 5; // Mastodon instances typically have generous limits
@@ -137,26 +139,68 @@ export class MastodonProvider extends SocialAbstract implements SocialProvider {
accessToken: string,
alt?: string
) {
- const form = new FormData();
- form.append(
- 'file',
- await fetch(fileUrl, {
+ // The file is streamed straight from storage into the Mastodon upload
+ // request instead of being buffered in memory. Both requests keep the
+ // SSRF-safe dispatcher because the URLs are not fully under our control,
+ // and the whole request is rebuilt per attempt by runStreamedUpload since
+ // a consumed stream can't be replayed.
+ const media = await this.runStreamedUpload<{ id: string }>(async () => {
+ const fileResponse = await fetch(fileUrl, {
// @ts-ignore - undici-only option; blocks SSRF to internal IPs
dispatcher: getSsrfSafeDispatcher(),
- }).then((r) => r.blob())
- );
- if (alt) {
- form.append('description', alt);
- }
- const media = await (
- await this.fetch(`${instanceUrl}/api/v1/media`, {
+ });
+ if (!fileResponse.ok || !fileResponse.body) {
+ throw new Error(`Failed to fetch media: ${fileResponse.statusText}`);
+ }
+ const contentLength = Number(
+ fileResponse.headers.get('content-length') || 0
+ );
+
+ const form = new FormDataUpload();
+ form.append('file', Readable.fromWeb(fileResponse.body as any), {
+ filename: fileUrl.split('/').pop()?.split('?')[0] || 'file',
+ ...(contentLength ? { knownLength: contentLength } : {}),
+ });
+ if (alt) {
+ form.append('description', alt);
+ }
+
+ const mediaResponse = await fetch(`${instanceUrl}/api/v1/media`, {
method: 'POST',
headers: {
+ ...form.getHeaders(),
+ // Some Mastodon front-ends reject chunked multipart, so send an
+ // exact Content-Length whenever the source size is known.
+ ...(contentLength
+ ? { 'Content-Length': String(form.getLengthSync()) }
+ : {}),
Authorization: `Bearer ${accessToken}`,
},
- body: form,
- })
- ).json();
+ // form-data is an old-style stream undici can't consume directly;
+ // piping through a PassThrough turns it into a proper Readable.
+ body: form.pipe(new PassThrough()),
+ // Required by undici when streaming a request body.
+ duplex: 'half',
+ // @ts-ignore - undici-only option; blocks SSRF to internal IPs
+ dispatcher: getSsrfSafeDispatcher(),
+ } as any);
+
+ if (
+ mediaResponse.status !== 200 &&
+ mediaResponse.status !== 201 &&
+ mediaResponse.status !== 202
+ ) {
+ throw {
+ response: {
+ status: mediaResponse.status,
+ data: await mediaResponse.text().catch(() => '{}'),
+ },
+ };
+ }
+
+ return (await mediaResponse.json()) as { id: string };
+ }, this.identifier);
+
return media.id;
}
diff --git a/libraries/nestjs-libraries/src/integrations/social/reddit.provider.ts b/libraries/nestjs-libraries/src/integrations/social/reddit.provider.ts
index 8f98245d4..474159833 100644
--- a/libraries/nestjs-libraries/src/integrations/social/reddit.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/reddit.provider.ts
@@ -14,6 +14,7 @@ import {
} from '@gitroom/nestjs-libraries/integrations/social.abstract';
import { lookup } from 'mime-types';
import axios from 'axios';
+import FormDataUpload from 'form-data';
import WebSocket from 'ws';
import { Tool } from '@gitroom/nestjs-libraries/integrations/tool.decorator';
import { Integration } from '@prisma/client';
@@ -177,8 +178,11 @@ export class RedditProvider extends SocialAbstract implements SocialProvider {
)
).json();
+ // Stream the file into Reddit's S3 form instead of buffering it in memory.
+ // S3 requires the exact part length, which comes from a HEAD request.
+ const fileSize = await this.mediaSize(path, this.identifier);
const { data } = await axios.get(path, {
- responseType: 'arraybuffer',
+ responseType: 'stream',
});
const upload = (fields as { name: string; value: string }[]).reduce(
@@ -186,20 +190,22 @@ export class RedditProvider extends SocialAbstract implements SocialProvider {
acc.append(value.name, value.value);
return acc;
},
- new FormData()
+ new FormDataUpload()
);
- upload.append(
- 'file',
- new Blob([Buffer.from(data)], { type: mimeType as string })
- );
+ upload.append('file', data, {
+ filename: path.split('/').pop(),
+ contentType: (mimeType as string) || 'application/octet-stream',
+ knownLength: fileSize,
+ });
- const d = await fetch('https:' + action, {
- method: 'POST',
- body: upload,
+ const d = await axios.post('https:' + action, upload, {
+ headers: upload.getHeaders(),
});
- return [...(await d.text()).matchAll(/<Location>(.*?)<\/Location>/g)][0][1];
+ return [
+ ...(d.data as string).matchAll(/<Location>(.*?)<\/Location>/g),
+ ][0][1];
}
async post(
diff --git a/libraries/nestjs-libraries/src/integrations/social/skool.provider.ts b/libraries/nestjs-libraries/src/integrations/social/skool.provider.ts
index 00e7acad1..7c31bef9d 100644
--- a/libraries/nestjs-libraries/src/integrations/social/skool.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/skool.provider.ts
@@ -1,5 +1,6 @@
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
-import { SocialAbstract } from '../social.abstract';
+import { BadBody, SocialAbstract } from '../social.abstract';
+import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
import {
AuthTokenDetails,
MediaContent,
@@ -206,10 +207,27 @@ export class SkoolProvider extends SocialAbstract implements SocialProvider {
const fileIds: string[] = [];
for (const item of media) {
- const fileResponse = await fetch(item.path);
- const fileBuffer = await fileResponse.arrayBuffer();
+ // Size and type come from a HEAD request; the PUT below streams the
+ // bytes so the file is never buffered in memory.
+ const headResponse = await fetch(item.path, {
+ method: 'HEAD',
+ // @ts-ignore - undici-only option; blocks SSRF to internal IPs
+ dispatcher: getSsrfSafeDispatcher(),
+ });
const contentType =
- fileResponse.headers.get('content-type') || 'application/octet-stream';
+ headResponse.headers.get('content-type') || 'application/octet-stream';
+ const contentLength = Number(
+ headResponse.headers.get('content-length') || 0
+ );
+ if (!headResponse.ok || !contentLength) {
+ // A permanent condition - fail fast instead of letting Temporal retry
+ throw new BadBody(
+ this.identifier,
+ '{}',
+ '{}',
+ 'Could not determine the media size for upload'
+ );
+ }
const fileName = item.path.split('/').pop() || 'file';
const createFileResponse = await (
@@ -222,7 +240,7 @@ export class SkoolProvider extends SocialAbstract implements SocialProvider {
body: JSON.stringify({
file_name: fileName,
content_type: contentType,
- content_length: fileBuffer.byteLength,
+ content_length: contentLength,
content_disposition: '',
ref: '',
owner_id: userId,
@@ -231,14 +249,24 @@ export class SkoolProvider extends SocialAbstract implements SocialProvider {
}, 'create file record')
).json();
+ const fileResponse = await fetch(item.path, {
+ // @ts-ignore - undici-only option; blocks SSRF to internal IPs
+ dispatcher: getSsrfSafeDispatcher(),
+ });
+ if (!fileResponse.ok || !fileResponse.body) {
+ throw new Error(`Failed to fetch media: ${fileResponse.statusText}`);
+ }
await fetch(createFileResponse.write_url, {
method: 'PUT',
headers: {
'Content-Type': createFileResponse.content_type,
+ 'Content-Length': String(contentLength),
'x-amz-acl': createFileResponse.acl,
},
- body: fileBuffer,
- });
+ body: fileResponse.body,
+ // Required by undici when streaming a request body.
+ duplex: 'half',
+ } as any);
fileIds.push(createFileResponse.file.id);
}
diff --git a/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts b/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts
index 31d580c5e..28325f64f 100644
--- a/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts
@@ -16,7 +16,7 @@ import {
import { TikTokDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/tiktok.dto';
import { timer } from '@gitroom/helpers/utils/timer';
import { hasExtension } from '@gitroom/helpers/utils/has.extension';
-import { createReadStream, statSync } from 'fs';
+import { createReadStream } from 'fs';
import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
import { Integration } from '@prisma/client';
import { Rules } from '@gitroom/nestjs-libraries/chat/rules.description.decorator';
@@ -683,31 +683,6 @@ export class TiktokProvider extends SocialAbstract implements SocialProvider {
};
}
- // Resolves the total byte size of the media without loading it into memory:
- // a HEAD request for remote URLs, statSync for local files.
- private async tiktokMediaSize(path: string): Promise<number> {
- if (path.indexOf('http') === 0) {
- // the media path is user-influenced, keep the SSRF-safe dispatcher that
- // this.fetch applies to every other outbound request
- const head = await fetch(path, {
- method: 'HEAD',
- dispatcher: getSsrfSafeDispatcher(),
- } as any);
- const length = head.headers.get('content-length');
- if (!length) {
- throw new BadBody(
- 'tiktok-error-upload',
- '{}',
- Buffer.from('{}'),
- 'Could not determine the video size for TikTok upload'
- );
- }
- return Number(length);
- }
-
- return statSync(path).size;
- }
-
// Returns a streaming body for the [start, end] byte range of the media so we
// never hold the whole file in memory: a ranged GET for remote URLs, a ranged
// read stream for local files.
@@ -833,7 +808,7 @@ export class TiktokProvider extends SocialAbstract implements SocialProvider {
// loaded into memory.
const videoSize = isPhoto
? undefined
- : await this.tiktokMediaSize(videoPath);
+ : await this.mediaSize(videoPath, 'tiktok-error-upload');
const {
data: { publish_id, upload_url },
diff --git a/libraries/nestjs-libraries/src/integrations/social/tumblr.provider.ts b/libraries/nestjs-libraries/src/integrations/social/tumblr.provider.ts
index 0553dc4a5..3fd76e05f 100644
--- a/libraries/nestjs-libraries/src/integrations/social/tumblr.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/tumblr.provider.ts
@@ -12,6 +12,7 @@ import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
import { TumblrDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/tumblr.dto';
import { Integration } from '@prisma/client';
import axios from 'axios';
+import FormDataUpload from 'form-data';
import { lookup } from 'mime-types';
import { hasExtension } from '@gitroom/helpers/utils/has.extension';
@@ -509,37 +510,44 @@ export class TumblrProvider extends SocialAbstract implements SocialProvider {
payload: { content: TumblrContentBlock[]; [key: string]: any },
media: NonNullable<PostDetails['media']>
) {
- const formData = new FormData();
- formData.append(
- 'json',
- new Blob([JSON.stringify(payload)], { type: 'application/json' })
- );
-
- for (const [index, item] of media.entries()) {
- const mimeType = this.getMimeType(item.path);
- const { data } = await axios.get(this.getMediaUrl(item.path), {
- responseType: 'arraybuffer',
+ // Each media part is streamed from its source into the multipart request
+ // (with its size from a HEAD request) so files are never held in memory.
+ // runStreamedUpload rebuilds the whole form per attempt (a consumed
+ // stream can't be replayed) and keeps handleErrors classification.
+ return this.runStreamedUpload<TumblrCreatePostResponse>(async () => {
+ const formData = new FormDataUpload();
+ formData.append('json', JSON.stringify(payload), {
+ contentType: 'application/json',
});
- formData.append(
- `media-${index}`,
- new Blob([Buffer.from(data)], { type: mimeType }),
- item.path.split('/').pop() || `media-${index}`
- );
- }
- return (await (
- await this.fetch(
+ for (const [index, item] of media.entries()) {
+ const mediaUrl = this.getMediaUrl(item.path);
+ const mimeType = this.getMimeType(item.path);
+ const fileSize = await this.mediaSize(mediaUrl, this.identifier);
+ const { data } = await axios.get(mediaUrl, {
+ responseType: 'stream',
+ });
+ formData.append(`media-${index}`, data, {
+ filename: item.path.split('/').pop() || `media-${index}`,
+ contentType: mimeType,
+ knownLength: fileSize,
+ });
+ }
+
+ const { data: response } = await axios.post(
`${TUMBLR_API_URL}/blog/${encodeURIComponent(blogName)}/posts`,
+ formData,
{
- method: 'POST',
headers: {
+ ...formData.getHeaders(),
Authorization: `Bearer ${accessToken}`,
'User-Agent': TUMBLR_USER_AGENT,
},
- body: formData,
}
- )
- ).json()) as TumblrCreatePostResponse;
+ );
+
+ return response as TumblrCreatePostResponse;
+ }, this.identifier);
}
private async createContentBlocks(post: PostDetails<TumblrDto>) {
diff --git a/libraries/nestjs-libraries/src/integrations/social/whop.provider.ts b/libraries/nestjs-libraries/src/integrations/social/whop.provider.ts
index d174b9329..23397c755 100644
--- a/libraries/nestjs-libraries/src/integrations/social/whop.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/whop.provider.ts
@@ -8,7 +8,11 @@ import {
} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
import { timer } from '@gitroom/helpers/utils/timer';
-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';
+import {
+ BadBody,
+ SocialAbstract,
+} from '@gitroom/nestjs-libraries/integrations/social.abstract';
+import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
import { WhopDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/whop.dto';
import { Integration } from '@prisma/client';
import { Tool } from '@gitroom/nestjs-libraries/integrations/tool.decorator';
@@ -225,8 +229,26 @@ export class WhopProvider extends SocialAbstract implements SocialProvider {
const attachments: { id: string }[] = [];
for (const item of media) {
- const fileResponse = await fetch(item.path);
- const fileBuffer = await fileResponse.arrayBuffer();
+ // The size comes from a HEAD request; the PUT below streams the bytes
+ // so the file is never buffered in memory (it used to stay resident
+ // through the whole ~9 minute status poll).
+ const headResponse = await fetch(item.path, {
+ method: 'HEAD',
+ // @ts-ignore - undici-only option; blocks SSRF to internal IPs
+ dispatcher: getSsrfSafeDispatcher(),
+ });
+ const contentLength = Number(
+ headResponse.headers.get('content-length') || 0
+ );
+ if (!headResponse.ok || !contentLength) {
+ // A permanent condition - fail fast instead of letting Temporal retry
+ throw new BadBody(
+ this.identifier,
+ '{}',
+ '{}',
+ 'Could not determine the media size for upload'
+ );
+ }
const fileName = item.path.split('/').pop() || 'file';
const createFileResponse = await (
@@ -247,11 +269,24 @@ export class WhopProvider extends SocialAbstract implements SocialProvider {
).json();
if (createFileResponse.upload_url) {
+ const fileResponse = await fetch(item.path, {
+ // @ts-ignore - undici-only option; blocks SSRF to internal IPs
+ dispatcher: getSsrfSafeDispatcher(),
+ });
+ if (!fileResponse.ok || !fileResponse.body) {
+ throw new Error(`Failed to fetch media: ${fileResponse.statusText}`);
+ }
await fetch(createFileResponse.upload_url, {
method: 'PUT',
- headers: createFileResponse.upload_headers || {},
- body: fileBuffer,
- });
+ headers: {
+ // Whop's own upload_headers win if they ever include a length.
+ 'Content-Length': String(contentLength),
+ ...(createFileResponse.upload_headers || {}),
+ },
+ body: fileResponse.body,
+ // Required by undici when streaming a request body.
+ duplex: 'half',
+ } as any);
let uploadStatus = 'pending';
let attempts = 0;
diff --git a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts b/libraries/nestjs-libraries/src/integrations/social/x.provider.ts
index e3923d86a..5a537ed9b 100644
--- a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/x.provider.ts
@@ -10,7 +10,6 @@ import {
import { lookup } from 'mime-types';
import sharp from 'sharp';
import { readOrFetch } from '@gitroom/helpers/utils/read.or.fetch';
-import { createReadStream, statSync } from 'fs';
import {
BadBody,
SocialAbstract,
@@ -421,173 +420,118 @@ export class XProvider extends SocialAbstract implements SocialProvider {
);
}
- // Same INIT / APPEND / FINALIZE flow as client.v2.uploadMedia, but the
- // video is never held in memory whole: total_bytes comes from a HEAD
- // request (statSync for local files) and each 1MB segment is fetched with
- // a ranged GET right before its APPEND. client.v2.uploadMedia only accepts
- // a Buffer, which is why the loop is replicated here.
- private async uploadVideoChunked(client: TwitterApi, path: string) {
- const size = await this.videoSize(path);
- const chunkSize = 1024 * 1024;
+ // X's v2 chunked upload requires a Buffer per APPEND segment, so we read one
+ // ranged chunk at a time (mediaChunk) instead of buffering the whole video.
+ // 1MB is the exact chunk size client.v2.uploadMedia used in production, so
+ // it is proven against X's APPEND limits; larger chunks are documented but
+ // unproven here.
+ private static readonly X_UPLOAD_CHUNK_SIZE = 1024 * 1024;
- const initResponse = await client.v2.post<{ data: { id: string } }>(
+ private async uploadVideoInChunks(client: TwitterApi, path: string) {
+ const totalBytes = await this.mediaSize(path, this.identifier);
+ const mediaType = String(lookup(path) || 'video/mp4');
+
+ const init = await client.v2.post<{ data: { id: string } }>(
'media/upload/initialize',
{
- media_type: lookup(path) || 'video/mp4',
- total_bytes: size,
+ media_type: mediaType,
+ total_bytes: totalBytes,
media_category: 'tweet_video',
}
);
- const mediaId = initResponse.data.id;
+ const mediaId = init.data.id;
- for (let i = 0; i < size; i += chunkSize) {
- const end = Math.min(i + chunkSize, size) - 1;
+ const chunkSize = XProvider.X_UPLOAD_CHUNK_SIZE;
+ const totalChunkCount = Math.ceil(totalBytes / chunkSize);
+ for (let i = 0; i < totalChunkCount; i++) {
+ const start = i * chunkSize;
+ const end = Math.min(start + chunkSize, totalBytes) - 1;
await client.v2.post(
`media/upload/${mediaId}/append`,
{
- segment_index: i / chunkSize,
- media: await this.videoChunk(path, i, end),
+ segment_index: i,
+ media: await this.mediaChunk(path, start, end),
},
{ forceBodyMode: 'form-data' }
);
}
- const finalizeResponse = await client.v2.post<{
- data: { processing_info?: object };
- }>(`media/upload/${mediaId}/finalize`);
- if (finalizeResponse.data.processing_info) {
- await this.waitForMediaProcessing(client, mediaId);
- }
-
- return mediaId;
- }
-
- // Mirrors the private client.v2.waitForMediaProcessing.
- private async waitForMediaProcessing(client: TwitterApi, mediaId: string) {
- const response = await client.v2.get<{
+ const finalize = await client.v2.post<{
data: {
- processing_info?: {
- state: string;
- check_after_secs?: number;
- error?: { message?: string };
- };
+ id: string;
+ processing_info?: { state: string; check_after_secs?: number };
};
- }>('media/upload', { command: 'STATUS', media_id: mediaId });
-
- const info = response.data.processing_info;
- if (!info || info.state === 'succeeded') {
- return;
- }
- if (info.state === 'failed') {
- throw new BadBody(
- 'x-error-upload',
- JSON.stringify(response.data),
- Buffer.from('{}'),
- `X media processing failed: ${info.error?.message || 'unknown error'}`
- );
- }
- await timer((info.check_after_secs || 1) * 1000);
- await this.waitForMediaProcessing(client, mediaId);
- }
+ }>(`media/upload/${mediaId}/finalize`);
- // Resolves the total byte size of the video without loading it into memory:
- // a HEAD request for remote URLs, statSync for local files.
- private async videoSize(path: string): Promise<number> {
- if (path.indexOf('http') === 0) {
- const head = await fetch(path, { method: 'HEAD' });
- const length = head.headers.get('content-length');
- if (!length) {
+ let processing = finalize.data.processing_info;
+ let attempts = 0;
+ const maxAttempts = 100; // X drives the pace via check_after_secs (~1-5s each)
+ while (processing && processing.state !== 'succeeded') {
+ if (processing.state === 'failed' || attempts >= maxAttempts) {
throw new BadBody(
- 'x-error-upload',
- '{}',
+ this.identifier,
+ JSON.stringify(processing),
Buffer.from('{}'),
- 'Could not determine the video size for X upload'
+ `X failed to process the uploaded video${
+ (processing as any)?.error?.message
+ ? `: ${(processing as any).error.message}`
+ : ''
+ }`
);
}
- return Number(length);
- }
-
- return statSync(path).size;
- }
- // Returns only the [start, end] byte window of the video as a Buffer (a
- // ranged GET for remote URLs, a ranged read for local files), so memory is
- // bounded by the segment size.
- private async videoChunk(
- path: string,
- start: number,
- end: number
- ): Promise<Buffer> {
- if (path.indexOf('http') === 0) {
- const response = await fetch(path, {
- headers: { Range: `bytes=${start}-${end}` },
- });
- // A 200 means the origin ignored the Range header and is sending the
- // whole file: uploading it as this segment would silently corrupt the
- // video, so fail loudly instead.
- if (response.status !== 206) {
- throw new BadBody(
- 'x-error-upload',
- '{}',
- Buffer.from('{}'),
- `Media server ignored the ranged request (status ${response.status}); it must support HTTP Range requests for chunked X uploads`
- );
- }
- return Buffer.from(await response.arrayBuffer());
+ await timer((processing.check_after_secs || 1) * 1000);
+ const status = await client.v2.get<{
+ data: {
+ processing_info?: { state: string; check_after_secs?: number };
+ };
+ }>('media/upload', { command: 'STATUS', media_id: mediaId });
+ processing = status.data.processing_info;
+ attempts++;
}
- return new Promise((resolve, reject) => {
- const chunks: Buffer[] = [];
- createReadStream(path, { start, end })
- .on('data', (chunk) => chunks.push(chunk as Buffer))
- .on('end', () => resolve(Buffer.concat(chunks)))
- .on('error', reject);
- });
+ return mediaId;
}
private async uploadMedia(
client: TwitterApi,
postDetails: PostDetails<any>[]
) {
- return (
- await Promise.all(
- postDetails.flatMap((p) =>
- p?.media?.flatMap(async (m) => {
- return {
- id: await this.runInConcurrent(
- async () =>
- hasExtension(m.path, 'mp4')
- ? this.uploadVideoChunked(client, m.path)
- : client.v2.uploadMedia(
- await sharp(await readOrFetch(m.path), {
- animated: lookup(m.path) === 'image/gif',
- })
- .resize({
- width: 1000,
- })
- .gif()
- .toBuffer(),
- {
- media_type: (lookup(m.path) || '') as any,
- }
- ),
- true
- ),
- postId: p.id,
- };
- })
- )
- )
- ).reduce((acc, val) => {
- if (!val?.id) {
- return acc;
- }
+ // Media is uploaded sequentially on purpose: uploading everything with
+ // Promise.all holds every file in memory at the same time.
+ const media = {} as Record<string, string[]>;
+ for (const p of postDetails) {
+ for (const m of p?.media || []) {
+ const id = await this.runInConcurrent(
+ async () =>
+ hasExtension(m.path, 'mp4')
+ ? this.uploadVideoInChunks(client, m.path)
+ : client.v2.uploadMedia(
+ await sharp(await readOrFetch(m.path), {
+ animated: lookup(m.path) === 'image/gif',
+ })
+ .resize({
+ width: 1000,
+ })
+ .gif()
+ .toBuffer(),
+ {
+ media_type: (lookup(m.path) || '') as any,
+ }
+ ),
+ true
+ );
- acc[val.postId] = acc[val.postId] || [];
- acc[val.postId].push(val.id);
+ if (!id) {
+ continue;
+ }
+
+ media[p.id] = media[p.id] || [];
+ media[p.id].push(id);
+ }
+ }
- return acc;
- }, {} as Record<string, string[]>);
+ return media;
}
async post(