π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: surface what a hung publishing activity was waiting on
Gilad Resisi1b71e75e47a6
diff --git a/apps/orchestrator/src/activities/post.activity.ts b/apps/orchestrator/src/activities/post.activity.tsindex cd05c667c..366da7a48 100644--- a/apps/orchestrator/src/activities/post.activity.ts+++ b/apps/orchestrator/src/activities/post.activity.ts@@ -24,7 +24,10 @@ import {postId as postIdSearchParam,} from '@gitroom/nestjs-libraries/temporal/temporal.search.attribute';import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';-import { withHeartbeat } from '@gitroom/nestjs-libraries/temporal/temporal.heartbeat';+import {+ setHeartbeatDetails,+ withHeartbeat,+} from '@gitroom/nestjs-libraries/temporal/temporal.heartbeat';import {BadBody,Disconnect,@@ -323,6 +326,11 @@ export class PostActivity {posts: Post[],allowPending: boolean) {+ // Stage markers: whatever ran last is what a timed-out activity reports.+ // Providers that go through this.fetch overwrite these with the exact URL;+ // the ones on their own HTTP client (x, youtube, bluesky) are still+ // narrowed down to the step they hung on.+ setHeartbeatDetails('subscription lookup');if (process.env.STRIPE_SECRET_KEY) {const subscription = await this._subscriptionService.getSubscription(integration.organizationId@@ -337,11 +345,13 @@ export class PostActivity {integration.providerIdentifier);+ setHeartbeatDetails('update tags');const newPosts = await this._postService.updateTags(integration.organizationId,posts);+ setHeartbeatDetails('resolve media');const mappedPosts = await Promise.all((newPosts || []).map(async (p) => ({id: p.id,@@ -362,6 +372,7 @@ export class PostActivity {})));+ setHeartbeatDetails(`${integration.providerIdentifier}: publish`);const postNow =allowPending && getIntegration.postPending? await getIntegration.postPending(@@ -379,6 +390,7 @@ export class PostActivity {// The post is already published at this point: the streak is best-effort,// failing the activity here would retry it and publish again.+ setHeartbeatDetails(`${integration.providerIdentifier}: published, streak`);try {await this._temporalService.client.getRawClient()diff --git a/libraries/nestjs-libraries/src/integrations/social.abstract.ts b/libraries/nestjs-libraries/src/integrations/social.abstract.tsindex 451e5015f..93c1ec2ce 100644--- a/libraries/nestjs-libraries/src/integrations/social.abstract.ts+++ b/libraries/nestjs-libraries/src/integrations/social.abstract.ts@@ -6,6 +6,7 @@ import {} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';import { ApplicationFailure } from '@temporalio/activity';import { readOrFetch } from '@gitroom/helpers/utils/read.or.fetch';+import { setHeartbeatDetails } from '@gitroom/nestjs-libraries/temporal/temporal.heartbeat';import {getSsrfSafeAxios,getSsrfSafeDispatcher,@@ -14,6 +15,15 @@ import sharp from 'sharp';import { createReadStream, statSync } from 'fs';import { Readable } from 'stream';+export const stripQuery = (url: string) => {+ try {+ const parsed = new URL(url);+ return `${parsed.origin}${parsed.pathname}`;+ } catch (err) {+ return url.split('?')[0];+ }+};+export type ValidityMedia = {path: string;thumbnail?: string;@@ -219,6 +229,7 @@ export abstract class SocialAbstract {path?.indexOf('http') === -1? `${process.env.FRONTEND_URL}/${path}`: path;+ setHeartbeatDetails(`read media ${stripQuery(url)}`);const { width = 0, height = 0 } = await sharp(await readOrFetch(url)).metadata();@@ -233,6 +244,7 @@ export abstract class SocialAbstract {// this.fetch applies to every other outbound request. identity encoding// so content-length matches the bytes a later GET actually streams// (fetch transparently decompresses encoded bodies).+ setHeartbeatDetails(`media size ${stripQuery(path)}`);const head = await fetch(path, {method: 'HEAD',headers: { 'accept-encoding': 'identity' },@@ -265,6 +277,9 @@ export abstract class SocialAbstract {identifier = ''): Promise<Buffer> {if (path.indexOf('http') === 0) {+ setHeartbeatDetails(+ `media chunk ${start}-${end} ${stripQuery(path)}`+ );const response = await fetch(path, {headers: {Range: `bytes=${start}-${end}`,@@ -447,6 +462,12 @@ export abstract class SocialAbstract {ignoreConcurrency = false,message = ''): Promise<Response> {+ // A platform that accepts the connection and then goes silent leaves the+ // activity with nothing logged until startToCloseTimeout. Record the call+ // first so the timeout failure names it. Query string is dropped - some+ // providers carry access_token there and details are stored by Temporal.+ setHeartbeatDetails(`fetch ${stripQuery(url)}`);+const request = await fetch(url, {...options,// @ts-ignore - undici-only option, not in the lib.dom RequestInit typediff --git a/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts b/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.tsindex 2ec32a86c..cb7ff2c3a 100644--- a/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts@@ -6,6 +6,7 @@ import {SocialProvider,} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';+import { setHeartbeatDetails } from '@gitroom/nestjs-libraries/temporal/temporal.heartbeat';import {BadBody,RefreshToken,@@ -86,6 +87,7 @@ async function startVideoUpload(// 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.+ setHeartbeatDetails('bluesky: video size');const headResponse = await fetch(videoPath, {method: 'HEAD',// identity encoding so content-length matches the bytes the GET streams@@ -103,6 +105,7 @@ async function startVideoUpload();}+ setHeartbeatDetails('bluesky: read video');const videoResponse = await fetch(videoPath, {headers: { 'accept-encoding': 'identity' },// @ts-ignore - undici-only option; blocks SSRF to internal IPs@@ -120,6 +123,7 @@ async function startVideoUpload(uploadUrl.searchParams.append('did', agent.session!.did);uploadUrl.searchParams.append('name', videoPath.split('/').pop()!);+ setHeartbeatDetails('bluesky: upload video');const uploadResponse = await fetch(uploadUrl, {method: 'POST',headers: {@@ -391,7 +395,10 @@ export class BlueskyProvider extends SocialAbstract implements SocialProvider {return {width,height,- buffer: await agent.uploadBlob(new Blob([buffer])),+ buffer: await (async () => {+ setHeartbeatDetails('bluesky: upload blob');+ return agent.uploadBlob(new Blob([buffer]));+ })(),};}));@@ -628,6 +635,7 @@ export class BlueskyProvider extends SocialAbstract implements SocialProvider {let uri: string;try {+ setHeartbeatDetails('bluesky: create post');// @ts-ignoreconst created = await agent.post({text: rt.text,@@ -778,6 +786,7 @@ export class BlueskyProvider extends SocialAbstract implements SocialProvider {// @ts-ignoreconst rootCid = parentThread.data.thread.post?.record?.reply?.root?.cid || parentCid;+ setHeartbeatDetails('bluesky: create post');// @ts-ignoreconst { cid, uri, commit } = await agent.post({text: rt.text,diff --git a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts b/libraries/nestjs-libraries/src/integrations/social/x.provider.tsindex b6778b0c8..080262d86 100644--- a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/x.provider.ts@@ -12,10 +12,12 @@ import {import { lookup } from 'mime-types';import sharp from 'sharp';import { readOrFetch } from '@gitroom/helpers/utils/read.or.fetch';+import { setHeartbeatDetails } from '@gitroom/nestjs-libraries/temporal/temporal.heartbeat';import {BadBody,RefreshToken,SocialAbstract,+ stripQuery,} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { Plug } from '@gitroom/helpers/decorators/plug.decorator';import { Integration } from '@prisma/client';@@ -516,6 +518,10 @@ export class XProvider extends SocialAbstract implements SocialProvider {const totalBytes = await this.mediaSize(path, this.identifier);const mediaType = String(lookup(path) || 'video/mp4');+ // twitter-api-v2 is not this.fetch, so these legs record their own+ // heartbeat details - otherwise a stall here reports only the generic+ // "x: publish" stage marker set by the activity.+ setHeartbeatDetails(`x: upload initialize (${totalBytes} bytes)`);const init = await client.v2.post<{ data: { id: string } }>('media/upload/initialize',{@@ -531,6 +537,9 @@ export class XProvider extends SocialAbstract implements SocialProvider {for (let i = 0; i < totalChunkCount; i++) {const start = i * chunkSize;const end = Math.min(start + chunkSize, totalBytes) - 1;+ setHeartbeatDetails(+ `x: upload append ${i + 1}/${totalChunkCount} media=${mediaId}`+ );await client.v2.post(`media/upload/${mediaId}/append`,{@@ -541,6 +550,7 @@ export class XProvider extends SocialAbstract implements SocialProvider {);}+ setHeartbeatDetails(`x: upload finalize media=${mediaId}`);const finalize = await client.v2.post<{data: {id: string;@@ -577,6 +587,7 @@ export class XProvider extends SocialAbstract implements SocialProvider {// loop lives in the post workflow (checkPostStatus) or, for the legacy// paths, in waitForMediaProcessing.private async mediaProcessingStatus(client: TwitterApi, mediaId: string) {+ setHeartbeatDetails(`x: media status media=${mediaId}`);const status = await client.v2.get<{data: {processing_info?: {@@ -651,6 +662,7 @@ export class XProvider extends SocialAbstract implements SocialProvider {const processingIds: string[] = [];for (const p of postDetails) {for (const m of p?.media || []) {+ setHeartbeatDetails(`x: upload media ${stripQuery(m.path)}`);const uploaded = await this.runInConcurrent(async () =>hasExtension(m.path, 'mp4')diff --git a/libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts b/libraries/nestjs-libraries/src/integrations/social/youtube.provider.tsindex d112c2c7d..2e9263bca 100644--- a/libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts@@ -16,11 +16,13 @@ import {RefreshToken,SocialAbstract,ValidityMedia,+ stripQuery,} from '@gitroom/nestjs-libraries/integrations/social.abstract';import * as process from 'node:process';import dayjs from 'dayjs';import { createReadStream, statSync } from 'fs';import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';+import { setHeartbeatDetails } from '@gitroom/nestjs-libraries/temporal/temporal.heartbeat';import { Rules } from '@gitroom/nestjs-libraries/chat/rules.description.decorator';const clientAndYoutube = () => {@@ -432,6 +434,7 @@ export class YoutubeProvider extends SocialAbstract implements SocialProvider {// this.fetch applies to every other outbound request. identity encoding// so content-length matches the bytes a later GET actually streams// (fetch transparently decompresses encoded bodies).+ setHeartbeatDetails(`youtube: media size ${stripQuery(path)}`);const head = await fetch(path, {method: 'HEAD',headers: { 'accept-encoding': 'identity' },@@ -460,6 +463,9 @@ export class YoutubeProvider extends SocialAbstract implements SocialProvider {// identity encoding so the store keeps content-length and can answer// with the requested range: a transformed (compressed) response loses// its length, and a length-less object is answered with the full body.+ setHeartbeatDetails(+ `youtube: read media ${start}-${end} ${stripQuery(path)}`+ );const response = await fetch(path, {headers: {Range: `bytes=${start}-${end}`,@@ -494,6 +500,7 @@ export class YoutubeProvider extends SocialAbstract implements SocialProvider {uploadUri: string,videoSize: number): Promise<{ videoId: string } | { uploadedBytes: number }> {+ setHeartbeatDetails('youtube: probe resumable session');const probe = await fetch(uploadUri, {method: 'PUT',headers: {@@ -710,6 +717,7 @@ export class YoutubeProvider extends SocialAbstract implements SocialProvider {end);+ setHeartbeatDetails('youtube: upload chunk to google');const upload = await fetch(pendingData.uploadUri, {method: 'PUT',headers: {diff --git a/libraries/nestjs-libraries/src/temporal/temporal.heartbeat.ts b/libraries/nestjs-libraries/src/temporal/temporal.heartbeat.tsindex 04cfebaf8..99a67f0d0 100644--- a/libraries/nestjs-libraries/src/temporal/temporal.heartbeat.ts+++ b/libraries/nestjs-libraries/src/temporal/temporal.heartbeat.ts@@ -7,14 +7,63 @@ import { Context } from '@temporalio/activity';// workflow versions that set no heartbeatTimeout) heartbeating is a no-op.const HEARTBEAT_INTERVAL = 15_000;+// Heartbeat *details* are the only channel that survives a StartToClose+// timeout: the server keeps the last details in the activity's mutable state,+// shows them under Pending Activities while it is still running, and copies+// them into the timeout failure - which we already persist into Errors. An+// activity that dies at startToCloseTimeout logs nothing at all today, so this+// is what tells us afterwards which call it was waiting on. Recording details+// needs no heartbeatTimeout, so nothing here can time an activity out.+//+// The value hangs off the per-activity Context instance rather than a module+// or provider field: providers are singletons shared by every activity running+// on the worker, so anything instance-scoped would report another post's URL.+const DETAILS = Symbol.for('postiz.heartbeatDetails');++const readDetails = (ctx: any) => ctx[DETAILS];++// Records what this activity is about to wait on. Deliberately does NOT+// heartbeat: the sending is left to the interval below, which already runs.+// Most publishes finish well inside HEARTBEAT_INTERVAL and send no heartbeat+// at all today, so heartbeating here would add an RPC per activity - a burst+// of them at the publish spike, against a server that is already slow there.+// Nothing is lost: the details only have to reach the server before a+// startToCloseTimeout 30 minutes away, and an activity that finishes before+// the first tick is by definition not the one that hung.+//+// Safe to call from code that also runs outside an activity (API requests,+// analytics), where there is no context and this does nothing.+export const setHeartbeatDetails = (details: string) => {+ try {+ const ctx = Context.current() as any;+ ctx[DETAILS] = details;+ } catch (err) {+ /**empty - not inside an activity**/+ }+};+export const withHeartbeat = async <T>(fn: () => Promise<T>): Promise<T> => {+ // Mark the activity as entered before anything can block. If a timed-out+ // activity carries no details at all, it never got this far - meaning the+ // task was dispatched to the worker and the function was never invoked,+ // which is a different failure from stalling on an outbound call.+ try {+ const ctx = Context.current() as any;+ setHeartbeatDetails(`${ctx.info?.activityType || 'activity'}: entered`);+ } catch (err) {+ /**empty**/+ }+// Heartbeating must never fail the activity, but a heartbeat that silently// never fires would surface only as an unexplained heartbeat timeout - log// the first failure (once, not every 15s) so a broken context is visible.let logged = false;const interval = setInterval(() => {try {- Context.current().heartbeat();+ const ctx = Context.current() as any;+ // resend the last details, otherwise this keepalive would blank out the+ // URL that setHeartbeatDetails recorded+ ctx.heartbeat(readDetails(ctx));} catch (err) {if (!logged) {logged = true;