Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

fix(scheduler): lease each claim and check Instagram before deciding

spacesdrive420de118bd46
diff --git a/backend/lib/scheduledPublishing.ts b/backend/lib/scheduledPublishing.ts
new file mode 100644
index 0000000..904273d
--- /dev/null
+++ b/backend/lib/scheduledPublishing.ts
@@ -0,0 +1,43 @@
+import type { InstagramContainerStatusCode } from '../../shared/types/instagram.ts';
+
+// both schedulers follow these rules; scripts/publish-scheduled.ts imports this file, so it must import nothing at runtime
+
+// the Worker's cron deadline and the GitHub job's time limit are both 14 minutes, so an older claim belongs to a run that died
+export const PUBLISH_LEASE_MS = 20 * 60 * 1000;
+
+// three runs of a 15 minute scheduler give a passing Instagram or network problem about half an hour to clear
+export const MAX_PUBLISH_ATTEMPTS = 3;
+
+// Graph API codes Meta documents as temporary: unknown and service errors, rate limits, and media that is not ready yet
+const TRANSIENT_GRAPH_CODES = new Set([-1, 1, 2, 4, 17, 341, 9007]);
+
+export type ContainerStep = 'published' | 'publish' | 'wait' | 'recreate' | 'fail';
+
+export type FailureOutcome = 'retry' | 'fail';
+
+// what a run does with the container an earlier attempt left, from the container's status on Instagram
+export function containerStep(statusCode: InstagramContainerStatusCode): ContainerStep {
+ if (statusCode === 'PUBLISHED') return 'published';
+ if (statusCode === 'FINISHED') return 'publish';
+ if (statusCode === 'EXPIRED') return 'recreate';
+ if (statusCode === 'ERROR') return 'fail';
+ return 'wait';
+}
+
+export function isTransientGraphCode(code: number | undefined): boolean {
+ return code !== undefined && TRANSIENT_GRAPH_CODES.has(code);
+}
+
+export function staleClaimCutoff(now: number): string {
+ return new Date(now - PUBLISH_LEASE_MS).toISOString();
+}
+
+// attempts counts the claim being settled, so the third failure of a passing problem is final
+export function failureOutcome(transient: boolean, attempts: number): FailureOutcome {
+ return transient && attempts < MAX_PUBLISH_ATTEMPTS ? 'retry' : 'fail';
+}
+
+export function failureMessage(reason: string, transient: boolean, attempts: number): string {
+ if (!transient || attempts < MAX_PUBLISH_ATTEMPTS) return reason;
+ return `${reason.replace(/\.?$/, '.')} Publishing stopped after ${MAX_PUBLISH_ATTEMPTS} attempts; schedule the post again.`;
+}
diff --git a/backend/repositories/scheduledPostRepository.ts b/backend/repositories/scheduledPostRepository.ts
index b6e7d46..91fea50 100644
--- a/backend/repositories/scheduledPostRepository.ts
+++ b/backend/repositories/scheduledPostRepository.ts
@@ -7,6 +7,8 @@ interface ScheduledPostRow {
account_id: string;
status: PostStatus;
scheduled_at: string;
+ claimed_at: string | null;
+ attempts: number | null;
data: Partial<ScheduledPost> | null;
}
@@ -21,7 +23,7 @@ export interface DeleteAllResult {
kept: number;
}
-const COLUMNS = 'id, account_id, status, scheduled_at, data';
+const COLUMNS = 'id, account_id, status, scheduled_at, claimed_at, attempts, data';
function toPost(row: ScheduledPostRow): ScheduledPost {
return {
@@ -30,26 +32,29 @@ function toPost(row: ScheduledPostRow): ScheduledPost {
status: row.status,
scheduledAt: row.scheduled_at,
...(row.data || {}),
+ claimedAt: row.claimed_at,
+ attempts: row.attempts ?? 0,
};
}
-// methods named ...ForUser filter by the verified user id; listDue, claim and updateById serve the schedulers across all users
+// methods named ...ForUser filter by the verified user id; listDue, listStale, claim and updateById serve the schedulers across all users
export interface ScheduledPostRepository {
listForUser(userId: string): Promise<ScheduledPost[]>;
findForUser(id: string, userId: string): Promise<ScheduledPost | null>;
listDue(): Promise<ScheduledPost[]>;
- claim(id: string): Promise<boolean>;
+ listStale(claimedBefore: string): Promise<ScheduledPost[]>;
+ claim(post: ScheduledPost): Promise<ScheduledPost | null>;
create(post: ScheduledPost, userId: string): Promise<void>;
- updateForUser(id: string, updates: Partial<ScheduledPost>, userId: string): Promise<void>;
+ updatePendingForUser(id: string, updates: Partial<ScheduledPost>, userId: string): Promise<boolean>;
updateById(id: string, updates: Partial<ScheduledPost>): Promise<void>;
- deleteForUser(id: string, userId: string): Promise<void>;
+ deleteForUser(id: string, userId: string): Promise<boolean>;
deleteAllForUser(userId: string): Promise<DeleteAllResult>;
}
export function createScheduledPostRepository(db: SupabaseClient): ScheduledPostRepository {
- // status and scheduledAt are columns; every other field is merged into data
- async function update(id: string, updates: Partial<ScheduledPost>, userId: string | null): Promise<void> {
- const { status, scheduledAt, accountId: _accountId, ...dataUpdates } = updates;
+ // status and scheduledAt are columns; every other field is merged into data; claimedAt and attempts change only in claim
+ async function update(id: string, updates: Partial<ScheduledPost>, userId: string | null, onlyStatus?: PostStatus): Promise<boolean> {
+ const { status, scheduledAt, accountId: _accountId, claimedAt: _claimedAt, attempts: _attempts, ...dataUpdates } = updates;
const columns: PostColumnUpdates = {};
if (status !== undefined) columns.status = status;
if (scheduledAt !== undefined) columns.scheduled_at = scheduledAt;
@@ -62,10 +67,20 @@ export function createScheduledPostRepository(db: SupabaseClient): ScheduledPost
columns.data = { ...(current[0]?.data || {}), ...dataUpdates };
}
- await execute('scheduledPosts.update', () => {
- const query = db.from('scheduled_posts').update(columns).eq('id', id);
- return userId ? query.eq('user_id', userId) : query;
+ if (!onlyStatus) {
+ await execute('scheduledPosts.update', () => {
+ const query = db.from('scheduled_posts').update(columns).eq('id', id);
+ return userId ? query.eq('user_id', userId) : query;
+ });
+ return true;
+ }
+
+ // the status check sits in the same statement, so a scheduler claiming the post in between makes this change nothing
+ const changed = await rows<{ id: string }>('scheduledPosts.updateIfStatus', () => {
+ const query = db.from('scheduled_posts').update(columns).eq('id', id).eq('status', onlyStatus);
+ return (userId ? query.eq('user_id', userId) : query).select('id');
});
+ return changed.length > 0;
}
return {
@@ -97,15 +112,29 @@ export function createScheduledPostRepository(db: SupabaseClient): ScheduledPost
return found.map(toPost);
},
- // atomic pending to publishing; false means the other scheduler claimed it first
- async claim(id) {
- const claimed = await rows<{ id: string }>('scheduledPosts.claim', () => db
+ async listStale(claimedBefore) {
+ const found = await rows<ScheduledPostRow>('scheduledPosts.listStale', () => db
.from('scheduled_posts')
- .update({ status: 'publishing' })
- .eq('id', id)
- .eq('status', 'pending')
- .select('id'));
- return claimed.length > 0;
+ .select(COLUMNS)
+ .eq('status', 'publishing')
+ .lt('claimed_at', claimedBefore));
+ return found.map(toPost);
+ },
+
+ // matches only the post as it was listed (pending, or the same expired claim) with the same attempts; null means another run won
+ async claim(post) {
+ const claimed = await rows<ScheduledPostRow>('scheduledPosts.claim', () => {
+ const query = db
+ .from('scheduled_posts')
+ .update({ status: 'publishing', claimed_at: new Date().toISOString(), attempts: (post.attempts ?? 0) + 1 })
+ .eq('id', post.id)
+ .eq('attempts', post.attempts ?? 0);
+ const unchanged = post.status === 'publishing'
+ ? query.eq('status', 'publishing').eq('claimed_at', post.claimedAt)
+ : query.eq('status', 'pending');
+ return unchanged.select(COLUMNS);
+ });
+ return claimed[0] ? toPost(claimed[0]) : null;
},
async create(post, userId) {
@@ -120,12 +149,22 @@ export function createScheduledPostRepository(db: SupabaseClient): ScheduledPost
}));
},
- updateForUser: (id, updates, userId) => update(id, updates, userId),
+ updatePendingForUser: (id, updates, userId) => update(id, updates, userId, 'pending'),
- updateById: (id, updates) => update(id, updates, null),
+ async updateById(id, updates) {
+ await update(id, updates, null);
+ },
+ // a post being published is never deleted, checked in the delete itself so a claim in between cannot slip past
async deleteForUser(id, userId) {
- await execute('scheduledPosts.delete', () => db.from('scheduled_posts').delete().eq('id', id).eq('user_id', userId));
+ const deleted = await rows<{ id: string }>('scheduledPosts.delete', () => db
+ .from('scheduled_posts')
+ .delete()
+ .eq('id', id)
+ .eq('user_id', userId)
+ .neq('status', 'publishing')
+ .select('id'));
+ return deleted.length > 0;
},
// posts being published right now are kept, so a publish never loses its row
diff --git a/backend/services/instagram/instagramApi.ts b/backend/services/instagram/instagramApi.ts
index 44a47de..d838aef 100644
--- a/backend/services/instagram/instagramApi.ts
+++ b/backend/services/instagram/instagramApi.ts
@@ -71,7 +71,7 @@ export function readGraphResponse<T>(data: T & InstagramApiErrorBody): T {
}
function unreachable(err: unknown): Error {
- return new UpstreamError(`Instagram API unreachable (${(err as Error).message})`, { cause: err });
+ return new UpstreamError(`Instagram API unreachable (${(err as Error).message})`, { reason: 'unreachable', cause: err });
}
// GET with a 15 second timeout and one retry on a network blip; a cancelled request is never retried
diff --git a/backend/services/scheduledPostService.ts b/backend/services/scheduledPostService.ts
index 02a4c1f..dd6e12a 100644
--- a/backend/services/scheduledPostService.ts
+++ b/backend/services/scheduledPostService.ts
@@ -67,17 +67,19 @@ export function createScheduledPostService({ posts, publisher }: ScheduledPostDe
return post;
},
- // only a post that has not started publishing can change
+ // only a post that has not started publishing can change; the repository checks again in the same write
async update(userId, postId, changes) {
const post = await findOwned(userId, postId);
if (post.status !== 'pending') throw new ValidationError('Can only edit pending posts');
const updates: Partial<ScheduledPost> = { ...changes };
if (changes.scheduledAt) updates.scheduledAt = new Date(changes.scheduledAt).toISOString();
- await posts.updateForUser(postId, updates, userId);
+ if (!(await posts.updatePendingForUser(postId, updates, userId))) throw new ValidationError('Can only edit pending posts');
return posts.findForUser(postId, userId);
},
async remove(userId, postId) {
+ if (await posts.deleteForUser(postId, userId)) return;
+ // nothing was deleted: the post is gone, or a scheduler is publishing it
const post = await findOwned(userId, postId);
if (post.status === 'publishing') throw new ValidationError('Cannot delete a post that is currently publishing');
await posts.deleteForUser(postId, userId);
diff --git a/backend/services/scheduledPublisher.ts b/backend/services/scheduledPublisher.ts
index 17ca222..6d9897a 100644
--- a/backend/services/scheduledPublisher.ts
+++ b/backend/services/scheduledPublisher.ts
@@ -1,12 +1,16 @@
import { buildMediaParams, createMediaContainer, fetchContainerStatus, publishMediaContainer } from './instagram/instagramPublishing.ts';
import { publishableAccount } from './publishingService.ts';
-import { NotFoundError, UpstreamError } from '../lib/errors.ts';
+import { DatabaseError, NotFoundError, UpstreamError, UpstreamTimeoutError, isAbortError } from '../lib/errors.ts';
import { errorFields } from '../lib/logger.ts';
+import {
+ MAX_PUBLISH_ATTEMPTS, containerStep, failureMessage, failureOutcome, isTransientGraphCode, staleClaimCutoff,
+} from '../lib/scheduledPublishing.ts';
import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { ScheduledPostRepository } from '../repositories/scheduledPostRepository.ts';
+import type { PublishableAccount } from './publishingService.ts';
import type { RequestContext } from '../types/context.ts';
import type { ScheduledPost, ScheduledPublishFailure, ScheduledPublishRun } from '../../shared/types/domain.ts';
-import type { InstagramPublishMediaType } from '../../shared/types/instagram.ts';
+import type { InstagramContainerStatusCode, InstagramPublishMediaType } from '../../shared/types/instagram.ts';
export interface ScheduledPublisherDeps {
accounts: AccountRepository;
@@ -18,6 +22,15 @@ export interface ScheduledPublisher {
publishDue(): Promise<ScheduledPublishRun>;
}
+// what one claimed post ended as; 'left' means the outcome on Instagram is unknown and the lease decides later
+type Settled = 'published' | 'retry' | 'failed' | 'left';
+
+// the parts of an attempt the error path needs to find out what happened on Instagram
+interface Attempt {
+ account: PublishableAccount | null;
+ containerId: string | null;
+}
+
const STATUS_POLLS = 60;
const STATUS_POLL_MS = 3000;
const IMAGE_SETTLE_MS = 2000;
@@ -26,6 +39,13 @@ function wait(ms: number): Promise<void> {
return new Promise<void>(resolve => setTimeout(resolve, ms));
}
+// timeouts, unreachable hosts, database hiccups and Instagram's temporary codes clear on their own; the rest need a person
+function isTransientFailure(err: unknown): boolean {
+ if (err instanceof UpstreamTimeoutError || err instanceof DatabaseError) return true;
+ if (err instanceof UpstreamError) return err.reason === 'unreachable' || isTransientGraphCode(err.upstreamStatus);
+ return isAbortError(err);
+}
+
// publishes every user's due posts, so it runs from the cron job or the manual trigger, never per user
export function createScheduledPublisher({ accounts, posts, context }: ScheduledPublisherDeps): ScheduledPublisher {
const { signal, log } = context;
@@ -46,43 +66,120 @@ export function createScheduledPublisher({ accounts, posts, context }: Scheduled
throw new UpstreamError('Instagram did not finish processing the media within 3 minutes');
}
- async function publishPost(post: ScheduledPost): Promise<string> {
+ // a container from an earlier attempt is checked first, so a post that already went out is never published again
+ async function publishPost(post: ScheduledPost, attempt: Attempt): Promise<string | null> {
const found = await accounts.findById(post.accountId);
if (!found) throw new NotFoundError('Account not found: ' + post.accountId);
if (found.platform !== 'instagram') throw new UpstreamError('Scheduled posts can only publish to Instagram accounts');
const account = publishableAccount(found);
+ attempt.account = account;
+
+ if (attempt.containerId) {
+ const { statusCode, status } = await fetchContainerStatus(attempt.containerId, account.accessToken, signal);
+ const step = containerStep(statusCode);
+ if (step === 'published') return null;
+ if (step === 'fail') throw new UpstreamError('Processing failed: ' + status);
+ if (step === 'recreate') attempt.containerId = null;
+ }
+ if (!attempt.containerId) {
+ const containerId = await createMediaContainer(account.igUserId, buildMediaParams(post, account.accessToken), signal);
+ await posts.updateById(post.id, { containerId });
+ attempt.containerId = containerId;
+ }
+ await waitForContainer(post.mediaType, attempt.containerId, account.accessToken);
+ return publishMediaContainer(account.igUserId, attempt.containerId, account.accessToken, signal);
+ }
+
+ async function containerStatus({ account, containerId }: Attempt): Promise<InstagramContainerStatusCode | null> {
+ if (!account || !containerId) return null;
+ return (await fetchContainerStatus(containerId, account.accessToken, signal)).statusCode;
+ }
+
+ // an error before Instagram could have published needs no check; after that, the container's status decides
+ async function settleFailure(post: ScheduledPost, attempt: Attempt, err: unknown, transientError = isTransientFailure(err)): Promise<Settled> {
+ let statusCode: InstagramContainerStatusCode | null;
+ try {
+ statusCode = await containerStatus(attempt);
+ } catch (checkErr) {
+ log.warn('scheduled post left for the next run', { postId: post.id, reason: 'container status unknown', ...errorFields(checkErr) });
+ return 'left';
+ }
+ if (statusCode === 'PUBLISHED') {
+ await posts.updateById(post.id, { status: 'published', publishedAt: new Date().toISOString(), error: null });
+ return 'published';
+ }
+
+ const attempts = post.attempts ?? 1;
+ const transient = transientError || statusCode === 'IN_PROGRESS' || statusCode === 'EXPIRED';
+ const reason = (err as Error).message;
+ if (failureOutcome(transient, attempts) === 'retry') {
+ await posts.updateById(post.id, { status: 'pending', error: reason, ...(statusCode === 'EXPIRED' && { containerId: null }) });
+ log.warn('scheduled post will be retried', { postId: post.id, attempts, ...errorFields(err) });
+ return 'retry';
+ }
+ await posts.updateById(post.id, { status: 'failed', error: failureMessage(reason, transient, attempts) });
+ log.error('scheduled post failed', { postId: post.id, attempts, ...errorFields(err) });
+ return 'failed';
+ }
+
+ async function settle(post: ScheduledPost, attempt: Attempt, err: unknown, errors: ScheduledPublishFailure[], transient?: boolean): Promise<Settled> {
+ try {
+ const settled = await settleFailure(post, attempt, err, transient);
+ if (settled === 'failed') errors.push({ id: post.id, error: (err as Error).message });
+ return settled;
+ } catch (writeErr) {
+ // the claim stays, so the next run after the lease finds out what happened from the saved container
+ log.error('scheduled post left for the next run', { postId: post.id, reason: 'could not save the outcome', ...errorFields(writeErr) });
+ return 'left';
+ }
+ }
+
+ async function publishClaimed(post: ScheduledPost, errors: ScheduledPublishFailure[]): Promise<Settled> {
+ const attempt: Attempt = { account: null, containerId: post.containerId ?? null };
- const containerId = await createMediaContainer(account.igUserId, buildMediaParams(post, account.accessToken), signal);
- await waitForContainer(post.mediaType, containerId, account.accessToken);
- return publishMediaContainer(account.igUserId, containerId, account.accessToken, signal);
+ // a post taken over after its last attempt is only checked on Instagram, never started again
+ if ((post.attempts ?? 1) > MAX_PUBLISH_ATTEMPTS) {
+ attempt.account = await accounts.findById(post.accountId).then(publishableAccount).catch(() => null);
+ return settle(post, attempt, new Error('The publishing run stopped before it finished.'), errors, true);
+ }
+
+ try {
+ const mediaId = await publishPost(post, attempt);
+ await posts.updateById(post.id, { status: 'published', publishedMediaId: mediaId, publishedAt: new Date().toISOString(), error: null });
+ log.info('scheduled post published', { postId: post.id, mediaId });
+ return 'published';
+ } catch (err) {
+ return settle(post, attempt, err, errors);
+ }
}
return {
async publishDue() {
let processed = 0;
const errors: ScheduledPublishFailure[] = [];
- let due: ScheduledPost[];
+ let candidates: ScheduledPost[];
try {
- due = await posts.listDue();
+ const [due, stale] = await Promise.all([posts.listDue(), posts.listStale(staleClaimCutoff(Date.now()))]);
+ candidates = [...stale, ...due];
} catch (err) {
log.error('scheduler could not load due posts', errorFields(err));
return { processed, errors };
}
- for (const post of due) {
- // false when the other scheduler claimed it first
- if (!(await posts.claim(post.id))) continue;
+ for (const candidate of candidates) {
+ // past the run's deadline every Instagram call fails, so a new claim would only sit out the lease
+ if (signal.aborted) break;
+ let post: ScheduledPost | null;
try {
- const mediaId = await publishPost(post);
- await posts.updateById(post.id, { status: 'published', publishedMediaId: mediaId, publishedAt: new Date().toISOString() });
- processed++;
- log.info('scheduled post published', { postId: post.id, mediaId });
+ // null when the other scheduler claimed it first
+ post = await posts.claim(candidate);
} catch (err) {
- const message = (err as Error).message;
- await posts.updateById(post.id, { status: 'failed', error: message });
- errors.push({ id: post.id, error: message });
- log.error('scheduled post failed', { postId: post.id, ...errorFields(err) });
+ log.error('scheduler could not claim a post', { postId: candidate.id, ...errorFields(err) });
+ continue;
}
+ if (!post) continue;
+ if (candidate.status === 'publishing') log.warn('scheduled post taken over after its claim expired', { postId: post.id, attempts: post.attempts });
+ if (await publishClaimed(post, errors) === 'published') processed++;
}
return { processed, errors };
},
diff --git a/backend/tests/fixtures/fakeSupabase.ts b/backend/tests/fixtures/fakeSupabase.ts
index e0fd7b6..f5222a7 100644
--- a/backend/tests/fixtures/fakeSupabase.ts
+++ b/backend/tests/fixtures/fakeSupabase.ts
@@ -3,7 +3,7 @@ import type { SupabaseClient } from '../../types/app.ts';
export type Row = Record<string, unknown>;
-type Filter = [column: string, value: unknown, operator?: 'lte' | 'neq'];
+type Filter = [column: string, value: unknown, operator?: 'lte' | 'lt' | 'neq'];
interface Action {
type: 'select' | 'update' | 'insert' | 'upsert' | 'delete';
@@ -24,6 +24,7 @@ interface FakeQuery {
select(): FakeQuery;
eq(column: string, value: unknown): FakeQuery;
lte(column: string, value: unknown): FakeQuery;
+ lt(column: string, value: unknown): FakeQuery;
neq(column: string, value: unknown): FakeQuery;
order(): FakeQuery;
single(): Promise<QueryResult>;
@@ -42,6 +43,7 @@ function copy<T>(value: T): T {
function matchesFilter(row: Row, [column, value, operator]: Filter) {
if (operator === 'lte') return (row[column] as string) <= (value as string);
+ if (operator === 'lt') return row[column] != null && (row[column] as string) < (value as string);
if (operator === 'neq') return row[column] !== value;
return row[column] === value;
}
@@ -67,6 +69,10 @@ function queryBuilder(action: Action, run: Run): FakeQuery {
filters.push([column, value, 'lte']);
return query;
},
+ lt(column: string, value: unknown) {
+ filters.push([column, value, 'lt']);
+ return query;
+ },
neq(column: string, value: unknown) {
filters.push([column, value, 'neq']);
return query;
diff --git a/backend/tests/fixtures/scheduledPublisher.process.golden.json b/backend/tests/fixtures/scheduledPublisher.process.golden.json
index ee1dfb3..6559f11 100644
--- a/backend/tests/fixtures/scheduledPublisher.process.golden.json
+++ b/backend/tests/fixtures/scheduledPublisher.process.golden.json
@@ -6,10 +6,6 @@
"id": "p-story",
"error": "Processing failed: Bad video"
},
- {
- "id": "p-expired",
- "error": "Container expired"
- },
{
"id": "p-missing",
"error": "Account not found: gone"
@@ -21,10 +17,6 @@
{
"id": "p-publish",
"error": "Publish refused"
- },
- {
- "id": "p-slow",
- "error": "Instagram did not finish processing the media within 3 minutes"
}
]
},
@@ -109,27 +101,19 @@
],
[
"error",
- "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-story\",\"error\":\"Processing failed: Bad video\",\"errorName\":\"UpstreamError\"}"
- ],
- [
- "error",
- "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-expired\",\"error\":\"Container expired\",\"errorName\":\"UpstreamError\"}"
- ],
- [
- "error",
- "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-missing\",\"error\":\"Account not found: gone\",\"errorName\":\"NotFoundError\"}"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-story\",\"attempts\":1,\"error\":\"Processing failed: Bad video\",\"errorName\":\"UpstreamError\"}"
],
[
"error",
- "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-create\",\"error\":\"Invalid image\",\"errorName\":\"UpstreamError\"}"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-missing\",\"attempts\":1,\"error\":\"Account not found: gone\",\"errorName\":\"NotFoundError\"}"
],
[
"error",
- "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-publish\",\"error\":\"Publish refused\",\"errorName\":\"UpstreamError\"}"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-create\",\"attempts\":1,\"error\":\"Invalid image\",\"errorName\":\"UpstreamError\"}"
],
[
"error",
- "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-slow\",\"error\":\"Instagram did not finish processing the media within 3 minutes\",\"errorName\":\"UpstreamError\"}"
+ "{\"level\":\"error\",\"message\":\"scheduled post failed\",\"requestId\":\"cron-test\",\"postId\":\"p-publish\",\"attempts\":1,\"error\":\"Publish refused\",\"errorName\":\"UpstreamError\"}"
],
[
"log",
@@ -169,6 +153,10 @@
"url": "https://graph.instagram.com/v25.0/c-ERR?fields=status_code%2Cstatus&access_token=T2",
"method": "GET"
},
+ {
+ "url": "https://graph.instagram.com/v25.0/c-ERR?fields=status_code%2Cstatus&access_token=T2",
+ "method": "GET"
+ },
{
"url": "https://graph.instagram.com/v25.0/EXP/media?access_token=T3&media_type=REELS&video_url=https%3A%2F%2Fcdn%2Fe.mp4",
"method": "POST"
@@ -181,6 +169,10 @@
"url": "https://graph.instagram.com/v25.0/c-EXP?fields=status_code%2Cstatus&access_token=T3",
"method": "GET"
},
+ {
+ "url": "https://graph.instagram.com/v25.0/c-EXP?fields=status_code%2Cstatus&access_token=T3",
+ "method": "GET"
+ },
{
"url": "https://graph.instagram.com/v25.0/BAD/media?access_token=T4&image_url=https%3A%2F%2Fcdn%2Fb.jpg",
"method": "POST"
@@ -193,6 +185,10 @@
"url": "https://graph.instagram.com/v25.0/PUB/media_publish?creation_id=c-PUB&access_token=T5",
"method": "POST"
},
+ {
+ "url": "https://graph.instagram.com/v25.0/c-PUB?fields=status_code%2Cstatus&access_token=T5",
+ "method": "GET"
+ },
{
"url": "https://graph.instagram.com/v25.0/SLOW/media?access_token=T6&media_type=REELS&video_url=https%3A%2F%2Fcdn%2Fslow.mp4",
"method": "POST"
@@ -437,6 +433,10 @@
"url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
"method": "GET"
},
+ {
+ "url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code%2Cstatus&access_token=T6",
+ "method": "GET"
+ },
{
"url": "https://graph.instagram.com/v25.0/IG1/media?access_token=T1&image_url=https%3A%2F%2Fcdn%2Fd.jpg",
"method": "POST"
@@ -450,7 +450,7 @@
{
"type": "select",
"table": "scheduled_posts",
- "columns": "id, account_id, status, scheduled_at, data",
+ "columns": "id, account_id, status, scheduled_at, claimed_at, attempts, data",
"filters": [
[
"status",
@@ -463,17 +463,39 @@
]
]
},
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "id, account_id, status, scheduled_at, claimed_at, attempts, data",
+ "filters": [
+ [
+ "status",
+ "publishing"
+ ],
+ [
+ "claimed_at",
+ "2026-09-01T11:40:00.000Z",
+ "lt"
+ ]
+ ]
+ },
{
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-image"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -502,6 +524,35 @@
]
]
},
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/a.jpg",
+ "caption": "Hello",
+ "containerId": "c-IG1"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-image"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-image"
+ ]
+ ]
+ },
{
"type": "update",
"table": "scheduled_posts",
@@ -511,8 +562,10 @@
"mediaType": "IMAGE",
"mediaUrl": "https://cdn/a.jpg",
"caption": "Hello",
+ "containerId": "c-IG1",
"publishedMediaId": "m-c-IG1",
- "publishedAt": "2026-09-01T12:00:00.000Z"
+ "publishedAt": "2026-09-01T12:00:00.000Z",
+ "error": null
}
},
"filters": [
@@ -526,13 +579,19 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-reel"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -561,6 +620,35 @@
]
]
},
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "data": {
+ "mediaType": "REELS",
+ "mediaUrl": "https://cdn/r.mp4",
+ "shareToFeed": true,
+ "containerId": "c-IG1"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-reel"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-reel"
+ ]
+ ]
+ },
{
"type": "update",
"table": "scheduled_posts",
@@ -570,8 +658,10 @@
"mediaType": "REELS",
"mediaUrl": "https://cdn/r.mp4",
"shareToFeed": true,
+ "containerId": "c-IG1",
"publishedMediaId": "m-c-IG1",
- "publishedAt": "2026-09-01T12:00:00.000Z"
+ "publishedAt": "2026-09-01T12:00:00.000Z",
+ "error": null
}
},
"filters": [
@@ -585,13 +675,19 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-story"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -620,6 +716,34 @@
]
]
},
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "data": {
+ "mediaType": "STORIES",
+ "mediaUrl": "https://cdn/s.mp4",
+ "containerId": "c-ERR"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-story"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-story"
+ ]
+ ]
+ },
{
"type": "update",
"table": "scheduled_posts",
@@ -628,6 +752,7 @@
"data": {
"mediaType": "STORIES",
"mediaUrl": "https://cdn/s.mp4",
+ "containerId": "c-ERR",
"error": "Processing failed: Bad video"
}
},
@@ -642,13 +767,19 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-expired"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -681,10 +812,39 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "failed",
"data": {
"mediaType": "REELS",
"mediaUrl": "https://cdn/e.mp4",
+ "containerId": "c-EXP"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-expired"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-expired"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "pending",
+ "data": {
+ "mediaType": "REELS",
+ "mediaUrl": "https://cdn/e.mp4",
+ "containerId": null,
"error": "Container expired"
}
},
@@ -699,13 +859,19 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-missing"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -756,13 +922,19 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-create"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -813,13 +985,19 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-publish"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -848,6 +1026,34 @@
]
]
},
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/p.jpg",
+ "containerId": "c-PUB"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-publish"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-publish"
+ ]
+ ]
+ },
{
"type": "update",
"table": "scheduled_posts",
@@ -856,6 +1062,7 @@
"data": {
"mediaType": "IMAGE",
"mediaUrl": "https://cdn/p.jpg",
+ "containerId": "c-PUB",
"error": "Publish refused"
}
},
@@ -870,13 +1077,19 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-slow"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -909,10 +1122,39 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "failed",
"data": {
"mediaType": "REELS",
"mediaUrl": "https://cdn/slow.mp4",
+ "containerId": "c-SLOW"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-slow"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-slow"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "status": "pending",
+ "data": {
+ "mediaType": "REELS",
+ "mediaUrl": "https://cdn/slow.mp4",
+ "containerId": "c-SLOW",
"error": "Instagram did not finish processing the media within 3 minutes"
}
},
@@ -927,13 +1169,19 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-dup"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -962,6 +1210,34 @@
]
]
},
+ {
+ "type": "update",
+ "table": "scheduled_posts",
+ "values": {
+ "data": {
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/d.jpg",
+ "containerId": "c-IG1"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "p-dup"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "scheduled_posts",
+ "columns": "data",
+ "filters": [
+ [
+ "id",
+ "p-dup"
+ ]
+ ]
+ },
{
"type": "update",
"table": "scheduled_posts",
@@ -970,8 +1246,10 @@
"data": {
"mediaType": "IMAGE",
"mediaUrl": "https://cdn/d.jpg",
+ "containerId": "c-IG1",
"publishedMediaId": "m-c-IG1",
- "publishedAt": "2026-09-01T12:00:00.000Z"
+ "publishedAt": "2026-09-01T12:00:00.000Z",
+ "error": null
}
},
"filters": [
@@ -985,13 +1263,19 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "publishing"
+ "status": "publishing",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1
},
"filters": [
[
"id",
"p-dup"
],
+ [
+ "attempts",
+ 0
+ ],
[
"status",
"pending"
@@ -1067,12 +1351,16 @@
"account_id": "ig1",
"status": "published",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "IMAGE",
"mediaUrl": "https://cdn/a.jpg",
"caption": "Hello",
+ "containerId": "c-IG1",
"publishedMediaId": "m-c-IG1",
- "publishedAt": "2026-09-01T12:00:00.000Z"
+ "publishedAt": "2026-09-01T12:00:00.000Z",
+ "error": null
}
},
{
@@ -1082,12 +1370,16 @@
"account_id": "ig1",
"status": "published",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "REELS",
"mediaUrl": "https://cdn/r.mp4",
"shareToFeed": true,
+ "containerId": "c-IG1",
"publishedMediaId": "m-c-IG1",
- "publishedAt": "2026-09-01T12:00:00.000Z"
+ "publishedAt": "2026-09-01T12:00:00.000Z",
+ "error": null
}
},
{
@@ -1097,9 +1389,12 @@
"account_id": "igErr",
"status": "failed",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "STORIES",
"mediaUrl": "https://cdn/s.mp4",
+ "containerId": "c-ERR",
"error": "Processing failed: Bad video"
}
},
@@ -1108,11 +1403,14 @@
"id": "p-expired",
"user_id": "user-1",
"account_id": "igExp",
- "status": "failed",
+ "status": "pending",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "REELS",
"mediaUrl": "https://cdn/e.mp4",
+ "containerId": null,
"error": "Container expired"
}
},
@@ -1123,6 +1421,8 @@
"account_id": "gone",
"status": "failed",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "IMAGE",
"mediaUrl": "https://cdn/m.jpg",
@@ -1136,6 +1436,8 @@
"account_id": "igBad",
"status": "failed",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "IMAGE",
"mediaUrl": "https://cdn/b.jpg",
@@ -1149,9 +1451,12 @@
"account_id": "igPub",
"status": "failed",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "IMAGE",
"mediaUrl": "https://cdn/p.jpg",
+ "containerId": "c-PUB",
"error": "Publish refused"
}
},
@@ -1160,11 +1465,14 @@
"id": "p-slow",
"user_id": "user-1",
"account_id": "igSlow",
- "status": "failed",
+ "status": "pending",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "REELS",
"mediaUrl": "https://cdn/slow.mp4",
+ "containerId": "c-SLOW",
"error": "Instagram did not finish processing the media within 3 minutes"
}
},
@@ -1175,11 +1483,15 @@
"account_id": "ig1",
"status": "published",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "IMAGE",
"mediaUrl": "https://cdn/d.jpg",
+ "containerId": "c-IG1",
"publishedMediaId": "m-c-IG1",
- "publishedAt": "2026-09-01T12:00:00.000Z"
+ "publishedAt": "2026-09-01T12:00:00.000Z",
+ "error": null
}
},
{
@@ -1189,11 +1501,15 @@
"account_id": "ig1",
"status": "published",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": "2026-09-01T12:00:00.000Z",
+ "attempts": 1,
"data": {
"mediaType": "IMAGE",
"mediaUrl": "https://cdn/d.jpg",
+ "containerId": "c-IG1",
"publishedMediaId": "m-c-IG1",
- "publishedAt": "2026-09-01T12:00:00.000Z"
+ "publishedAt": "2026-09-01T12:00:00.000Z",
+ "error": null
}
},
{
@@ -1203,6 +1519,8 @@
"account_id": "ig1",
"status": "publishing",
"scheduled_at": "2026-09-01T11:00:00.000Z",
+ "claimed_at": null,
+ "attempts": 0,
"data": {
"mediaType": "IMAGE"
}
@@ -1214,6 +1532,8 @@
"account_id": "ig1",
"status": "pending",
"scheduled_at": "2026-09-02T00:00:00.000Z",
+ "claimed_at": null,
+ "attempts": 0,
"data": {
"mediaType": "IMAGE"
}
diff --git a/backend/tests/lib/scheduledPublishing.test.ts b/backend/tests/lib/scheduledPublishing.test.ts
new file mode 100644
index 0000000..4c9ca4c
--- /dev/null
+++ b/backend/tests/lib/scheduledPublishing.test.ts
@@ -0,0 +1,39 @@
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ MAX_PUBLISH_ATTEMPTS, PUBLISH_LEASE_MS, containerStep, failureMessage, failureOutcome, isTransientGraphCode, staleClaimCutoff,
+} from '../../lib/scheduledPublishing.ts';
+
+describe('scheduled publishing rules', () => {
+ test('the lease outlasts the 14 minute limit both schedulers run under', () => {
+ assert.ok(PUBLISH_LEASE_MS > 14 * 60 * 1000);
+ assert.equal(staleClaimCutoff(Date.parse('2026-09-01T12:00:00Z')), '2026-09-01T11:40:00.000Z');
+ });
+
+ test('a container that already went out is never published again, and a ready one is published as it is', () => {
+ assert.equal(containerStep('PUBLISHED'), 'published');
+ assert.equal(containerStep('FINISHED'), 'publish');
+ assert.equal(containerStep('IN_PROGRESS'), 'wait');
+ assert.equal(containerStep('EXPIRED'), 'recreate');
+ assert.equal(containerStep('ERROR'), 'fail');
+ });
+
+ test('only the Graph API codes Meta calls temporary are retried', () => {
+ assert.equal(isTransientGraphCode(2), true);
+ assert.equal(isTransientGraphCode(9007), true);
+ assert.equal(isTransientGraphCode(190), false);
+ assert.equal(isTransientGraphCode(undefined), false);
+ });
+
+ test('a passing failure retries until the last attempt, and a definite one fails at once', () => {
+ assert.equal(failureOutcome(true, 1), 'retry');
+ assert.equal(failureOutcome(true, MAX_PUBLISH_ATTEMPTS), 'fail');
+ assert.equal(failureOutcome(false, 1), 'fail');
+ });
+
+ test('the final message says publishing stopped only when retries ran out', () => {
+ assert.equal(failureMessage('Invalid image', false, 1), 'Invalid image');
+ assert.equal(failureMessage('Instagram API unreachable (reset)', true, MAX_PUBLISH_ATTEMPTS),
+ 'Instagram API unreachable (reset). Publishing stopped after 3 attempts; schedule the post again.');
+ });
+});
diff --git a/backend/tests/repositories/scheduledPostRepository.test.ts b/backend/tests/repositories/scheduledPostRepository.test.ts
new file mode 100644
index 0000000..04cec7c
--- /dev/null
+++ b/backend/tests/repositories/scheduledPostRepository.test.ts
@@ -0,0 +1,57 @@
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import { createScheduledPostRepository } from '../../repositories/scheduledPostRepository.ts';
+import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
+import type { Row } from '../fixtures/fakeSupabase.ts';
+
+function postRow(id: string, overrides: Row = {}): Row {
+ return tableRow('scheduled_posts', {
+ id, user_id: 'user-1', account_id: 'ig1', status: 'pending', scheduled_at: '2026-09-01T11:00:00.000Z',
+ claimed_at: null, attempts: 0, data: { caption: 'Hi' }, ...overrides,
+ });
+}
+
+const EXPIRED_CLAIM = '2026-09-01T11:30:00.000Z';
+
+describe('scheduled post repository', () => {
+ test('two schedulers claiming the same listed post: only the first gets it, and the claim counts an attempt', async () => {
+ const posts = createScheduledPostRepository(fakeSupabase([postRow('p1')]));
+ const [listed] = await posts.listDue();
+
+ const first = await posts.claim(listed);
+ assert.equal(first?.status, 'publishing');
+ assert.equal(first?.attempts, 1);
+ assert.ok(first?.claimedAt);
+ assert.equal(await posts.claim(listed), null);
+ });
+
+ test('only claims older than the cutoff are stale, and a takeover must match the expired claim it saw', async () => {
+ const posts = createScheduledPostRepository(fakeSupabase([
+ postRow('old', { status: 'publishing', claimed_at: EXPIRED_CLAIM, attempts: 1 }),
+ postRow('live', { status: 'publishing', claimed_at: '2026-09-01T11:55:00.000Z', attempts: 1 }),
+ ]));
+ const stale = await posts.listStale('2026-09-01T11:40:00.000Z');
+ assert.deepEqual(stale.map(post => post.id), ['old']);
+
+ assert.equal((await posts.claim(stale[0]))?.attempts, 2);
+ assert.equal(await posts.claim(stale[0]), null);
+ });
+
+ test('a post being published is not deleted, while a pending one is', async () => {
+ const db = fakeSupabase([postRow('busy', { status: 'publishing', claimed_at: EXPIRED_CLAIM }), postRow('free')]);
+ const posts = createScheduledPostRepository(db);
+
+ assert.equal(await posts.deleteForUser('busy', 'user-1'), false);
+ assert.equal(await posts.deleteForUser('free', 'user-1'), true);
+ assert.deepEqual(db.table.map(row => row.id), ['busy']);
+ });
+
+ test('an edit only lands while the post is still pending', async () => {
+ const db = fakeSupabase([postRow('claimed', { status: 'publishing', claimed_at: EXPIRED_CLAIM }), postRow('free')]);
+ const posts = createScheduledPostRepository(db);
+
+ assert.equal(await posts.updatePendingForUser('claimed', { caption: 'Changed' }, 'user-1'), false);
+ assert.equal(await posts.updatePendingForUser('free', { caption: 'Changed' }, 'user-1'), true);
+ assert.deepEqual(db.table.map(row => (row.data as Row).caption), ['Hi', 'Changed']);
+ });
+});
diff --git a/backend/tests/services/scheduledPublisher.test.ts b/backend/tests/services/scheduledPublisher.test.ts
index abc484d..5a84903 100644
--- a/backend/tests/services/scheduledPublisher.test.ts
+++ b/backend/tests/services/scheduledPublisher.test.ts
@@ -8,13 +8,13 @@ import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow, tableRow } from '../fixtures/fakeSupabase.ts';
-import type { Row } from '../fixtures/fakeSupabase.ts';
+import type { FakeSupabase, Row } from '../fixtures/fakeSupabase.ts';
import type { SupabaseClient } from '../../types/app.ts';
const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
function postRow(id: string, accountId: string, data: Row, overrides: Row = {}) {
- return tableRow('scheduled_posts', { id, user_id: 'user-1', account_id: accountId, status: 'pending', scheduled_at: '2026-09-01T11:00:00.000Z', data, ...overrides });
+ return tableRow('scheduled_posts', { id, user_id: 'user-1', account_id: accountId, status: 'pending', scheduled_at: '2026-09-01T11:00:00.000Z', claimed_at: null, attempts: 0, data, ...overrides });
}
const ACCOUNTS = [
@@ -47,6 +47,7 @@ const STATUS_SEQUENCES: Record<string, string[]> = {
'c-ERR': ['ERROR'],
'c-EXP': ['IN_PROGRESS', 'EXPIRED'],
'c-SLOW': [],
+ 'c-PUB': ['FINISHED'],
};
function graphReply(request: RecordedRequest) {
@@ -61,7 +62,8 @@ function graphReply(request: RecordedRequest) {
return reply({ id: `m-${url.searchParams.get('creation_id')}` });
}
const sequence = STATUS_SEQUENCES[parts[2]] ?? [];
- const statusCode = sequence.shift() ?? 'IN_PROGRESS';
+ // the last status in a sequence holds, as a container's final status does on Instagram
+ const statusCode = (sequence.length > 1 ? sequence.shift() : sequence[0]) ?? 'IN_PROGRESS';
return reply({ status_code: statusCode, status: statusCode === 'ERROR' ? 'Bad video' : undefined });
}
@@ -71,8 +73,8 @@ function describeArg(arg: unknown) {
let fetchMock: FetchMock | null = null;
-function processScheduledPosts(supabase: SupabaseClient) {
- const context = { requestId: 'cron-test', signal: new AbortController().signal, log: createLogger({ requestId: 'cron-test' }) };
+function processScheduledPosts(supabase: SupabaseClient, signal = new AbortController().signal) {
+ const context = { requestId: 'cron-test', signal, log: createLogger({ requestId: 'cron-test' }) };
return createScheduledPublisher({
accounts: createAccountRepository(supabase),
posts: createScheduledPostRepository(supabase),
@@ -134,3 +136,120 @@ describe('scheduled publisher account checks', () => {
assert.deepEqual(fetchMock.requests, []);
});
});
+
+describe('scheduled publisher recovery', () => {
+ before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
+ after(() => mock.timers.reset());
+
+ const INSTAGRAM = [tableRow('accounts', accountRow({ id: 'ig1', platform: 'instagram', igUserId: 'IG1', accessToken: 'T1' }))];
+ const TIMED_OUT = Object.assign(new Error('The operation timed out'), { name: 'TimeoutError' });
+ // 30 minutes before FIXED_NOW, past the 20 minute lease
+ const EXPIRED_CLAIM = '2026-09-01T11:30:00.000Z';
+
+ function instagram(statusCode: string, publish: () => ReturnType<typeof reply> | Error = () => reply({ id: 'media-1' })) {
+ return installFetch(request => {
+ const parts = new URL(request.url).pathname.split('/');
+ if (parts[3] === 'media') return reply({ id: 'c-new' });
+ if (parts[3] === 'media_publish') return publish();
+ return reply({ status_code: statusCode });
+ });
+ }
+
+ function paths(fetched: FetchMock) {
+ return fetched.requests.map(request => `${request.method} ${new URL(request.url).pathname.split('/').slice(2).join('/')}`);
+ }
+
+ function post(supabase: FakeSupabase, id: string) {
+ return supabase.table.find(row => row.id === id && row._table === 'scheduled_posts')!;
+ }
+
+ async function run(rows: Row[]) {
+ const supabase = fakeSupabase([...INSTAGRAM, ...rows]);
+ mock.method(globalThis, 'setTimeout', (callback: () => void) => { callback(); return 0; });
+ mock.method(console, 'log', () => undefined);
+ mock.method(console, 'error', () => undefined);
+ const result = await processScheduledPosts(supabase);
+ mock.restoreAll();
+ return { supabase, result };
+ }
+
+ test('a publish reply lost on the way back is checked on Instagram and the post is marked published', async () => {
+ fetchMock = instagram('PUBLISHED', () => TIMED_OUT);
+ const { supabase, result } = await run([postRow('p1', 'ig1', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/a.jpg' })]);
+
+ assert.deepEqual(result, { processed: 1, errors: [] });
+ assert.equal(post(supabase, 'p1').status, 'published');
+ assert.deepEqual(paths(fetchMock), ['POST IG1/media', 'POST IG1/media_publish', 'GET c-new']);
+ });
+
+ test('when the container status cannot be read either, the post stays claimed for a later run to check', async () => {
+ fetchMock = installFetch(request => {
+ const parts = new URL(request.url).pathname.split('/');
+ if (parts[3] === 'media') return reply({ id: 'c-new' });
+ return TIMED_OUT;
+ });
+ const { supabase } = await run([postRow('p1', 'ig1', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/a.jpg' })]);
+
+ const row = post(supabase, 'p1');
+ assert.equal(row.status, 'publishing');
+ assert.equal(row.claimed_at, '2026-09-01T12:00:00.000Z');
+ assert.equal((row.data as Row).containerId, 'c-new');
+ });
+
+ test('a post whose claim expired is taken over and found already published, without publishing it again', async () => {
+ fetchMock = instagram('PUBLISHED');
+ const { supabase } = await run([postRow('p1', 'ig1', { mediaType: 'IMAGE', containerId: 'c-old' }, { status: 'publishing', claimed_at: EXPIRED_CLAIM, attempts: 1 })]);
+
+ const row = post(supabase, 'p1');
+ assert.equal(row.status, 'published');
+ assert.equal(row.attempts, 2);
+ assert.deepEqual(paths(fetchMock), ['GET c-old']);
+ });
+
+ test('a taken over post whose container is ready publishes that same container', async () => {
+ fetchMock = instagram('FINISHED');
+ const { supabase } = await run([postRow('p1', 'ig1', { mediaType: 'IMAGE', containerId: 'c-old' }, { status: 'publishing', claimed_at: EXPIRED_CLAIM, attempts: 1 })]);
+
+ assert.equal(post(supabase, 'p1').status, 'published');
+ assert.deepEqual(paths(fetchMock), ['GET c-old', 'POST IG1/media_publish']);
+ });
+
+ test('a claim inside its lease is left alone', async () => {
+ fetchMock = instagram('FINISHED');
+ const { supabase } = await run([postRow('p1', 'ig1', { mediaType: 'IMAGE' }, { status: 'publishing', claimed_at: '2026-09-01T11:50:00.000Z', attempts: 1 })]);
+
+ assert.equal(post(supabase, 'p1').attempts, 1);
+ assert.deepEqual(fetchMock.requests, []);
+ });
+
+ test('a passing failure goes back to pending, and the third one fails the post for good', async () => {
+ fetchMock = installFetch(() => TIMED_OUT);
+ const first = await run([postRow('p1', 'ig1', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/a.jpg' })]);
+ assert.equal(post(first.supabase, 'p1').status, 'pending');
+ assert.equal(post(first.supabase, 'p1').attempts, 1);
+
+ const last = await run([postRow('p1', 'ig1', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/a.jpg' }, { attempts: 2, claimed_at: EXPIRED_CLAIM })]);
+ const row = post(last.supabase, 'p1');
+ assert.equal(row.status, 'failed');
+ assert.match((row.data as Row).error as string, /Publishing stopped after 3 attempts; schedule the post again\.$/);
+ });
+
+ test('a run past its deadline claims nothing more, so no post waits out a lease for nothing', async () => {
+ const supabase = fakeSupabase([...INSTAGRAM, postRow('p1', 'ig1', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/a.jpg' })]);
+ fetchMock = instagram('FINISHED');
+ const result = await processScheduledPosts(supabase, AbortSignal.abort());
+
+ assert.deepEqual(result, { processed: 0, errors: [] });
+ assert.equal(post(supabase, 'p1').status, 'pending');
+ assert.deepEqual(fetchMock.requests, []);
+ });
+
+ test('a post taken over after its last attempt is only checked, never started again', async () => {
+ fetchMock = instagram('FINISHED');
+ const { supabase, result } = await run([postRow('p1', 'ig1', { mediaType: 'IMAGE', containerId: 'c-old' }, { status: 'publishing', claimed_at: EXPIRED_CLAIM, attempts: 3 })]);
+
+ assert.equal(post(supabase, 'p1').status, 'failed');
+ assert.deepEqual(result.errors, [{ id: 'p1', error: 'The publishing run stopped before it finished.' }]);
+ assert.deepEqual(paths(fetchMock), ['GET c-old']);
+ });
+});
diff --git a/scripts/publish-scheduled.ts b/scripts/publish-scheduled.ts
index d8f04e2..5adb711 100644
--- a/scripts/publish-scheduled.ts
+++ b/scripts/publish-scheduled.ts
@@ -3,7 +3,11 @@
// Node 22.18+ runs this file directly by stripping its types; it needs SUPABASE_URL and
// SUPABASE_SERVICE_KEY (a sb_secret_ key or the legacy service_role key) as GitHub secrets.
+import {
+ MAX_PUBLISH_ATTEMPTS, containerStep, failureMessage, failureOutcome, isTransientGraphCode, staleClaimCutoff,
+} from '../backend/lib/scheduledPublishing.ts';
import type { Account, Platform, PostStatus, ScheduledPost } from '../shared/types/domain.ts';
+import type { InstagramContainerStatusCode } from '../shared/types/instagram.ts';
interface AccountRow {
id: string;
@@ -16,16 +20,37 @@ interface ScheduledPostRow {
account_id: string;
status: PostStatus;
scheduled_at: string;
+ claimed_at: string | null;
+ attempts: number | null;
data: Partial<ScheduledPost> | null;
}
interface GraphResponse {
id?: string;
- error?: { message: string };
- status_code?: string;
+ error?: { message: string; code?: number };
+ status_code?: InstagramContainerStatusCode;
status?: string;
}
+// the account and container an attempt reached, which the error path needs to ask Instagram what happened
+interface Attempt {
+ account: Account | null;
+ containerId: string | null;
+}
+
+// 'left' means the outcome on Instagram is unknown, so the claim stays and a run after the lease decides
+type Settled = 'published' | 'retry' | 'failed' | 'left';
+
+// transient marks a failure that may pass on its own, such as a timeout or one of Instagram's temporary codes
+class PublishError extends Error {
+ readonly transient: boolean;
+
+ constructor(message: string, transient: boolean) {
+ super(message);
+ this.transient = transient;
+ }
+}
+
const SUPABASE_URL = (process.env.SUPABASE_URL || '').replace(/[^\x20-\x7E]/g, '').trim();
const SUPABASE_SERVICE_KEY = (process.env.SUPABASE_SERVICE_KEY || '').replace(/[^\x20-\x7E]/g, '').trim();
@@ -35,6 +60,12 @@ if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY) {
process.exit(1);
}
+const GRAPH_URL = 'https://graph.instagram.com/v25.0';
+const POST_COLUMNS = 'id,account_id,status,scheduled_at,claimed_at,attempts,data';
+const REQUEST_TIMEOUT_MS = 15000;
+// the workflow stops the job at 14 minutes; Instagram calls stop at 12 so every claimed post still gets its outcome saved
+const RUN_DEADLINE = AbortSignal.timeout(12 * 60 * 1000);
+
// Supabase REST helpers (no SDK, native fetch only)
// Legacy service_role keys are JWTs and go in both headers. New sb_secret_ keys are not JWTs
@@ -46,34 +77,47 @@ const sbHeaders: Record<string, string> = {
};
async function sbGet<T>(path: string): Promise<T> {
- const res = await fetch(`${SUPABASE_URL}/rest/v1${path}`, { headers: sbHeaders });
+ const res = await fetch(`${SUPABASE_URL}/rest/v1${path}`, { headers: sbHeaders, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
if (!res.ok) throw new Error(`Supabase GET ${path}: ${await res.text()}`);
return res.json() as Promise<T>;
}
-async function sbPatch(path: string, body: unknown): Promise<void> {
+async function sbPatch<T>(path: string, body: unknown): Promise<T[]> {
const res = await fetch(`${SUPABASE_URL}/rest/v1${path}`, {
method: 'PATCH',
- headers: { ...sbHeaders, 'Prefer': 'return=minimal' },
+ headers: { ...sbHeaders, 'Prefer': 'return=representation' },
body: JSON.stringify(body),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
if (!res.ok) throw new Error(`Supabase PATCH ${path}: ${await res.text()}`);
+ return res.json() as Promise<T[]>;
}
// Data access
-async function getDuePosts(): Promise<ScheduledPost[]> {
- const now = encodeURIComponent(new Date().toISOString());
- const rows = await sbGet<ScheduledPostRow[]>(
- `/scheduled_posts?status=eq.pending&scheduled_at=lte.${now}&select=id,account_id,status,scheduled_at,data`
- );
- return (rows || []).map(row => ({
+function toPost(row: ScheduledPostRow): ScheduledPost {
+ return {
id: row.id,
accountId: row.account_id,
status: row.status,
scheduledAt: row.scheduled_at,
...(row.data || {}),
- }));
+ claimedAt: row.claimed_at,
+ attempts: row.attempts ?? 0,
+ };
+}
+
+async function getDuePosts(): Promise<ScheduledPost[]> {
+ const now = encodeURIComponent(new Date().toISOString());
+ const rows = await sbGet<ScheduledPostRow[]>(`/scheduled_posts?status=eq.pending&scheduled_at=lte.${now}&select=${POST_COLUMNS}`);
+ return (rows || []).map(toPost);
+}
+
+// posts still publishing under a claim older than the lease belong to a run that died
+async function getStalePosts(): Promise<ScheduledPost[]> {
+ const cutoff = encodeURIComponent(staleClaimCutoff(Date.now()));
+ const rows = await sbGet<ScheduledPostRow[]>(`/scheduled_posts?status=eq.publishing&claimed_at=lt.${cutoff}&select=${POST_COLUMNS}`);
+ return (rows || []).map(toPost);
}
async function getAccount(accountId: string): Promise<Account | null> {
@@ -82,104 +126,189 @@ async function getAccount(accountId: string): Promise<Account | null> {
return { id: rows[0].id, platform: rows[0].platform, ...(rows[0].data || {}) };
}
-async function updatePostStatus(id: string, updates: Partial<ScheduledPost>): Promise<void> {
+async function updatePost(id: string, updates: Partial<ScheduledPost>): Promise<void> {
const { status, ...dataUpdates } = updates;
const patch: { status?: PostStatus; data?: Partial<ScheduledPost> } = {};
if (status) patch.status = status;
if (Object.keys(dataUpdates).length > 0) {
const rows = await sbGet<Pick<ScheduledPostRow, 'data'>[]>(`/scheduled_posts?id=eq.${id}&select=data`);
- const currentData = rows?.[0]?.data || {};
- patch.data = { ...currentData, ...dataUpdates };
+ patch.data = { ...(rows?.[0]?.data || {}), ...dataUpdates };
}
- await sbPatch(`/scheduled_posts?id=eq.${id}`, patch);
+ await sbPatch(`/scheduled_posts?id=eq.${id}&select=id`, patch);
}
-// Moves a post from pending to publishing only if it is still pending, so this workflow and the
-// Worker cron never publish the same post twice. Returns false when the other one claimed it.
-async function claimPost(id: string): Promise<boolean> {
- const res = await fetch(`${SUPABASE_URL}/rest/v1/scheduled_posts?id=eq.${id}&status=eq.pending`, {
- method: 'PATCH',
- headers: { ...sbHeaders, 'Prefer': 'return=representation' },
- body: JSON.stringify({ status: 'publishing' }),
- });
- if (!res.ok) throw new Error(`Supabase PATCH claim ${id}: ${await res.text()}`);
- const rows = await res.json();
- return Array.isArray(rows) && rows.length > 0;
+// matches only the post as it was listed (pending, or the same expired claim) with the same attempts, as the Worker does
+async function claimPost(post: ScheduledPost): Promise<ScheduledPost | null> {
+ const attempts = post.attempts ?? 0;
+ const unchanged = post.status === 'publishing'
+ ? `status=eq.publishing&claimed_at=eq.${encodeURIComponent(post.claimedAt ?? '')}`
+ : 'status=eq.pending';
+ const rows = await sbPatch<ScheduledPostRow>(
+ `/scheduled_posts?id=eq.${post.id}&attempts=eq.${attempts}&${unchanged}&select=${POST_COLUMNS}`,
+ { status: 'publishing', claimed_at: new Date().toISOString(), attempts: attempts + 1 },
+ );
+ return rows[0] ? toPost(rows[0]) : null;
}
// Instagram publishing
function sleep(ms: number): Promise<void> { return new Promise(r => setTimeout(r, ms)); }
-async function publishToInstagram(post: ScheduledPost, account: Account): Promise<string | undefined> {
- if (account.platform !== 'instagram' || !account.igUserId) throw new Error('Scheduled posts can only publish to Instagram accounts');
- if (!account.accessToken) throw new Error('No Instagram access token stored - reconnect this account');
- const igId = account.igUserId;
- const token = account.accessToken;
- // URLSearchParams stringifies the boolean and number values
- const params: Record<string, string | number | boolean | undefined> = { access_token: token };
+async function graph(method: 'GET' | 'POST', path: string, params: Record<string, string>): Promise<GraphResponse> {
+ const url = `${GRAPH_URL}${path}?${new URLSearchParams(params).toString()}`;
+ let res: Response;
+ try {
+ res = await fetch(url, { method, signal: AbortSignal.any([RUN_DEADLINE, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]) });
+ } catch (err) {
+ throw new PublishError(`Instagram API unreachable (${(err as Error).name})`, true);
+ }
+ const data = await res.json().catch(() => ({})) as GraphResponse;
+ if (data.error) throw new PublishError(data.error.message, isTransientGraphCode(data.error.code));
+ if (!res.ok) throw new PublishError(`Instagram answered with status ${res.status}`, res.status >= 500);
+ return data;
+}
+
+function containerParams(post: ScheduledPost, token: string): Record<string, string> {
+ // URLSearchParams needs strings, so the boolean, number and list values are written out here
+ const params: Record<string, string> = { access_token: token };
+ const tags = post.userTags?.length ? JSON.stringify(post.userTags) : '';
if (post.mediaType === 'REELS') {
params.media_type = 'REELS';
- params.video_url = post.mediaUrl;
+ params.video_url = post.mediaUrl ?? '';
if (post.caption) params.caption = post.caption;
- if (post.shareToFeed !== undefined) params.share_to_feed = post.shareToFeed;
+ if (post.shareToFeed !== undefined) params.share_to_feed = String(post.shareToFeed);
if (post.coverUrl) params.cover_url = post.coverUrl;
if (post.collaborators?.length) params.collaborators = JSON.stringify(post.collaborators);
if (post.audioName) params.audio_name = post.audioName;
- if (post.thumbOffset != null) params.thumb_offset = post.thumbOffset;
+ if (post.thumbOffset != null) params.thumb_offset = String(post.thumbOffset);
if (post.locationId) params.location_id = post.locationId;
- if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);
+ if (tags) params.user_tags = tags;
} else if (post.mediaType === 'STORIES') {
params.media_type = 'STORIES';
- if (post.mediaUrl!.match(/\.(mp4|mov|avi|webm)/i)) {
+ if (post.mediaUrl?.match(/\.(mp4|mov|avi|webm)/i)) {
params.video_url = post.mediaUrl;
} else {
- params.image_url = post.mediaUrl;
+ params.image_url = post.mediaUrl ?? '';
}
- if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);
+ if (tags) params.user_tags = tags;
} else {
- params.image_url = post.mediaUrl;
+ params.image_url = post.mediaUrl ?? '';
if (post.caption) params.caption = post.caption;
if (post.locationId) params.location_id = post.locationId;
- if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);
+ if (tags) params.user_tags = tags;
if (post.altText) params.alt_text = post.altText;
}
+ return params;
+}
- const qs = new URLSearchParams(params as Record<string, string>).toString();
- const createRes = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${qs}`, { method: 'POST' });
- const createData = await createRes.json() as GraphResponse;
- if (createData.error) throw new Error(createData.error.message);
-
- const containerId = createData.id;
-
- if (post.mediaType === 'REELS' || post.mediaType === 'STORIES') {
- let finished = false;
- for (let i = 0; i < 60 && !finished; i++) {
- await sleep(3000);
- const statusRes = await fetch(
- `https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${token}`
- );
- const statusData = await statusRes.json() as GraphResponse;
- finished = statusData.status_code === 'FINISHED' || statusData.status_code === 'PUBLISHED';
- if (statusData.status_code === 'ERROR') throw new Error('Processing failed: ' + (statusData.status || ''));
- if (statusData.status_code === 'EXPIRED') throw new Error('Container expired');
- }
- if (!finished) throw new Error('Instagram did not finish processing the media within 3 minutes');
- } else {
+async function containerStatus(containerId: string, token: string): Promise<GraphResponse> {
+ return graph('GET', `/${containerId}`, { fields: 'status_code,status', access_token: token });
+}
+
+async function waitForContainer(post: ScheduledPost, containerId: string, token: string): Promise<void> {
+ if (post.mediaType !== 'REELS' && post.mediaType !== 'STORIES') {
await sleep(2000);
+ return;
+ }
+ for (let i = 0; i < 60; i++) {
+ await sleep(3000);
+ const status = await containerStatus(containerId, token);
+ if (status.status_code === 'FINISHED' || status.status_code === 'PUBLISHED') return;
+ if (status.status_code === 'ERROR') throw new PublishError('Processing failed: ' + (status.status || ''), false);
+ if (status.status_code === 'EXPIRED') throw new PublishError('Container expired', false);
}
+ throw new PublishError('Instagram did not finish processing the media within 3 minutes', false);
+}
- const pubRes = await fetch(
- `https://graph.instagram.com/v25.0/${igId}/media_publish?creation_id=${containerId}&access_token=${token}`,
- { method: 'POST' }
- );
- const pubData = await pubRes.json() as GraphResponse;
- if (pubData.error) throw new Error(pubData.error.message);
+// a container from an earlier attempt is checked first, so a post that already went out is never published again
+async function publishToInstagram(post: ScheduledPost, attempt: Attempt): Promise<string | null> {
+ const account = await getAccount(post.accountId);
+ if (!account) throw new PublishError('Account not found: ' + post.accountId, false);
+ if (account.platform !== 'instagram' || !account.igUserId) throw new PublishError('Scheduled posts can only publish to Instagram accounts', false);
+ if (!account.accessToken) throw new PublishError('No Instagram access token stored - reconnect this account', false);
+ attempt.account = account;
+ const igId = account.igUserId;
+ const token = account.accessToken;
+
+ if (attempt.containerId) {
+ const status = await containerStatus(attempt.containerId, token);
+ const step = containerStep(status.status_code ?? 'IN_PROGRESS');
+ if (step === 'published') return null;
+ if (step === 'fail') throw new PublishError('Processing failed: ' + (status.status || ''), false);
+ if (step === 'recreate') attempt.containerId = null;
+ }
+ if (!attempt.containerId) {
+ const created = await graph('POST', `/${igId}/media`, containerParams(post, token));
+ if (!created.id) throw new PublishError('Instagram did not return a container id', true);
+ await updatePost(post.id, { containerId: created.id });
+ attempt.containerId = created.id;
+ }
+
+ await waitForContainer(post, attempt.containerId, token);
+ const published = await graph('POST', `/${igId}/media_publish`, { creation_id: attempt.containerId, access_token: token });
+ return published.id ?? null;
+}
+
+// an error before Instagram could have published needs no check; after that, the container's status decides
+async function settleFailure(post: ScheduledPost, attempt: Attempt, err: unknown, transientError: boolean): Promise<Settled> {
+ let statusCode: InstagramContainerStatusCode | null = null;
+ if (attempt.account?.accessToken && attempt.containerId) {
+ try {
+ statusCode = (await containerStatus(attempt.containerId, attempt.account.accessToken)).status_code ?? 'IN_PROGRESS';
+ } catch {
+ console.error(' Left for the next run: the container status could not be read');
+ return 'left';
+ }
+ }
+ if (statusCode === 'PUBLISHED') {
+ await updatePost(post.id, { status: 'published', publishedAt: new Date().toISOString(), error: null });
+ return 'published';
+ }
+
+ const attempts = post.attempts ?? 1;
+ const transient = transientError || statusCode === 'IN_PROGRESS' || statusCode === 'EXPIRED';
+ const reason = (err as Error).message;
+ if (failureOutcome(transient, attempts) === 'retry') {
+ await updatePost(post.id, { status: 'pending', error: reason, ...(statusCode === 'EXPIRED' && { containerId: null }) });
+ console.error(` Will retry (attempt ${attempts} of ${MAX_PUBLISH_ATTEMPTS}): ${reason}`);
+ return 'retry';
+ }
+ await updatePost(post.id, { status: 'failed', error: failureMessage(reason, transient, attempts) });
+ console.error(` Failed: ${reason}`);
+ return 'failed';
+}
+
+async function settle(post: ScheduledPost, attempt: Attempt, err: unknown, transient: boolean): Promise<Settled> {
+ try {
+ return await settleFailure(post, attempt, err, transient);
+ } catch (writeErr) {
+ // the claim stays, so the next run after the lease finds out what happened from the saved container
+ console.error(` Left for the next run: the outcome could not be saved (${(writeErr as Error).message})`);
+ return 'left';
+ }
+}
- return pubData.id;
+async function publishClaimed(post: ScheduledPost): Promise<Settled> {
+ const attempt: Attempt = { account: null, containerId: post.containerId ?? null };
+
+ // a post taken over after its last attempt is only checked on Instagram, never started again
+ if ((post.attempts ?? 1) > MAX_PUBLISH_ATTEMPTS) {
+ attempt.account = await getAccount(post.accountId).catch(() => null);
+ return settle(post, attempt, new Error('The publishing run stopped before it finished.'), true);
+ }
+
+ try {
+ const mediaId = await publishToInstagram(post, attempt);
+ await updatePost(post.id, { status: 'published', publishedMediaId: mediaId, publishedAt: new Date().toISOString(), error: null });
+ console.log(` Published: media ${mediaId ?? '(already published by an earlier attempt)'}`);
+ return 'published';
+ } catch (err) {
+ // anything that is not Instagram's answer is the database or the network, which may pass on its own
+ return settle(post, attempt, err, err instanceof PublishError ? err.transient : true);
+ }
}
// Main
@@ -188,42 +317,37 @@ async function main(): Promise<void> {
console.log('Instagram scheduled post publisher');
console.log(` Time: ${new Date().toISOString()}\n`);
- const duePosts = await getDuePosts();
+ const [stalePosts, duePosts] = await Promise.all([getStalePosts(), getDuePosts()]);
+ const candidates = [...stalePosts, ...duePosts];
- if (duePosts.length === 0) {
+ if (candidates.length === 0) {
console.log('No posts due for publishing');
process.exit(0);
}
- console.log(`${duePosts.length} post(s) due for publishing\n`);
+ console.log(`${candidates.length} post(s) due for publishing\n`);
let processed = 0;
- for (const post of duePosts) {
- console.log(` Publishing: ${post.id} (${post.mediaType}) - scheduled ${post.scheduledAt}`);
- if (!(await claimPost(post.id))) {
- console.log(' Skipped: already claimed by the other scheduler');
- continue;
- }
-
+ for (const candidate of candidates) {
+ // past the deadline every Instagram call fails, so a new claim would only sit out the lease
+ if (RUN_DEADLINE.aborted) break;
+ console.log(` Publishing: ${candidate.id} (${candidate.mediaType}) - scheduled ${candidate.scheduledAt}`);
+ let post: ScheduledPost | null;
try {
- const account = await getAccount(post.accountId);
- if (!account) throw new Error('Account not found: ' + post.accountId);
-
- const mediaId = await publishToInstagram(post, account);
- await updatePostStatus(post.id, {
- status: 'published',
- publishedMediaId: mediaId,
- publishedAt: new Date().toISOString(),
- });
- processed++;
- console.log(` Published: media ${mediaId}`);
+ post = await claimPost(candidate);
} catch (err) {
- await updatePostStatus(post.id, { status: 'failed', error: (err as Error).message });
- console.error(` Failed: ${(err as Error).message}`);
+ console.error(` Skipped: the claim could not be saved (${(err as Error).message})`);
+ continue;
+ }
+ if (!post) {
+ console.log(' Skipped: already claimed by the other scheduler');
+ continue;
}
+ if (candidate.status === 'publishing') console.log(` Taken over: the claim from ${candidate.claimedAt} expired`);
+ if (await publishClaimed(post) === 'published') processed++;
}
- console.log(`\nResults: ${processed}/${duePosts.length} published`);
+ console.log(`\nResults: ${processed}/${candidates.length} published`);
process.exit(0);
}
diff --git a/shared/types/domain.ts b/shared/types/domain.ts
index 0300c9c..a804018 100644
--- a/shared/types/domain.ts
+++ b/shared/types/domain.ts
@@ -118,6 +118,11 @@ export interface ScheduledPost {
publishedAt?: string;
publishedMediaId?: string | null;
error?: string | null;
+ // when a scheduler last claimed the post and how many times one has; a claim older than the lease is taken over
+ claimedAt?: string | null;
+ attempts?: number;
+ // saved before the publish call, so a later run can ask Instagram whether the post went out
+ containerId?: string | null;
}
export interface ScheduledPublishFailure {