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(scheduling): limit the manual publish trigger to the caller's posts

spacesdrive2abc2da8a336
diff --git a/backend/controllers/scheduledPostController.ts b/backend/controllers/scheduledPostController.ts
index 514fe56..1f3960d 100644
--- a/backend/controllers/scheduledPostController.ts
+++ b/backend/controllers/scheduledPostController.ts
@@ -32,6 +32,6 @@ export const deleteScheduledPost = controller.createHandlers(async c => {
});
export const publishDuePosts = controller.createHandlers(async c => {
- const result = await servicesFor(c).scheduledPosts.publishDueNow();
+ const result = await servicesFor(c).scheduledPosts.publishDueNow(c.get('userId'));
return c.json({ success: true, ...result, timestamp: new Date().toISOString() } satisfies ScheduledPublishRunResponse);
});
diff --git a/backend/repositories/scheduledPostRepository.ts b/backend/repositories/scheduledPostRepository.ts
index e128069..895ef57 100644
--- a/backend/repositories/scheduledPostRepository.ts
+++ b/backend/repositories/scheduledPostRepository.ts
@@ -31,12 +31,15 @@ function toPost(row: ScheduledPostRow): ScheduledPost {
};
}
-// methods named ...ForUser filter by the verified user id; listDue, listStale, 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,
+// and the manual trigger lists only its caller's posts through listDueForUser and listStaleForUser
export interface ScheduledPostRepository {
listForUser(userId: string): Promise<ScheduledPost[]>;
findForUser(id: string, userId: string): Promise<ScheduledPost | null>;
listDue(): Promise<ScheduledPost[]>;
listStale(claimedBefore: string): Promise<ScheduledPost[]>;
+ listDueForUser(userId: string): Promise<ScheduledPost[]>;
+ listStaleForUser(claimedBefore: string, userId: string): Promise<ScheduledPost[]>;
claim(post: ScheduledPost): Promise<ScheduledPost | null>;
create(post: ScheduledPost, userId: string): Promise<void>;
updatePendingForUser(id: string, updates: Partial<ScheduledPost>, userId: string): Promise<boolean>;
@@ -98,6 +101,26 @@ export function createScheduledPostRepository(db: SupabaseClient): ScheduledPost
return found.map(toPost);
},
+ async listDueForUser(userId) {
+ const found = await rows<ScheduledPostRow>('scheduledPosts.listDueForUser', () => db
+ .from('scheduled_posts')
+ .select(COLUMNS)
+ .eq('status', 'pending')
+ .lte('scheduled_at', new Date().toISOString())
+ .eq('user_id', userId));
+ return found.map(toPost);
+ },
+
+ async listStaleForUser(claimedBefore, userId) {
+ const found = await rows<ScheduledPostRow>('scheduledPosts.listStaleForUser', () => db
+ .from('scheduled_posts')
+ .select(COLUMNS)
+ .eq('status', 'publishing')
+ .lt('claimed_at', claimedBefore)
+ .eq('user_id', userId));
+ 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', () => {
diff --git a/backend/services/scheduledPostService.ts b/backend/services/scheduledPostService.ts
index 2d632f5..2f7d668 100644
--- a/backend/services/scheduledPostService.ts
+++ b/backend/services/scheduledPostService.ts
@@ -20,7 +20,7 @@ export interface ScheduledPostService {
update(userId: string, postId: string, changes: ScheduledPostUpdateRequest): Promise<ScheduledPost | null>;
remove(userId: string, postId: string): Promise<void>;
removeAll(userId: string): Promise<DeleteAllResult>;
- publishDueNow(): Promise<ScheduledPublishRun>;
+ publishDueNow(userId: string): Promise<ScheduledPublishRun>;
}
function futureDate(value: string): string {
@@ -91,6 +91,6 @@ export function createScheduledPostService({ accounts, posts, publisher }: Sched
removeAll: userId => posts.deleteAllForUser(userId),
// the manual trigger runs the same publisher the cron uses, for every user's due posts
- publishDueNow: () => publisher.publishDue(),
+ publishDueNow: userId => publisher.publishDueForUser(userId),
};
}
diff --git a/backend/services/scheduledPublisher.ts b/backend/services/scheduledPublisher.ts
index 6d9897a..6196e37 100644
--- a/backend/services/scheduledPublisher.ts
+++ b/backend/services/scheduledPublisher.ts
@@ -20,6 +20,8 @@ export interface ScheduledPublisherDeps {
export interface ScheduledPublisher {
publishDue(): Promise<ScheduledPublishRun>;
+ // the manual trigger: only the caller's own due posts, so one person never runs, settles or reads another's
+ publishDueForUser(userId: string): Promise<ScheduledPublishRun>;
}
// what one claimed post ended as; 'left' means the outcome on Instagram is unknown and the lease decides later
@@ -153,35 +155,41 @@ export function createScheduledPublisher({ accounts, posts, context }: Scheduled
}
}
- return {
- async publishDue() {
- let processed = 0;
- const errors: ScheduledPublishFailure[] = [];
- let candidates: ScheduledPost[];
+ // claims and publishes the listed posts one at a time; the cron run lists everyone's, the manual trigger only its caller's
+ async function publishCandidates(load: () => Promise<[ScheduledPost[], ScheduledPost[]]>): Promise<ScheduledPublishRun> {
+ let processed = 0;
+ const errors: ScheduledPublishFailure[] = [];
+ let candidates: ScheduledPost[];
+ try {
+ const [due, stale] = await load();
+ candidates = [...stale, ...due];
+ } catch (err) {
+ log.error('scheduler could not load due posts', errorFields(err));
+ return { processed, errors };
+ }
+
+ 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 [due, stale] = await Promise.all([posts.listDue(), posts.listStale(staleClaimCutoff(Date.now()))]);
- candidates = [...stale, ...due];
+ // null when the other scheduler claimed it first
+ post = await posts.claim(candidate);
} catch (err) {
- log.error('scheduler could not load due posts', errorFields(err));
- return { processed, errors };
+ 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 };
+ }
- 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 {
- // null when the other scheduler claimed it first
- post = await posts.claim(candidate);
- } catch (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 };
- },
+ return {
+ publishDue: () => publishCandidates(() => Promise.all([posts.listDue(), posts.listStale(staleClaimCutoff(Date.now()))])),
+ publishDueForUser: userId => publishCandidates(() => Promise.all([
+ posts.listDueForUser(userId), posts.listStaleForUser(staleClaimCutoff(Date.now()), userId),
+ ])),
};
}
diff --git a/backend/tests/routes/scheduledPostRoutes.test.ts b/backend/tests/routes/scheduledPostRoutes.test.ts
index a3c53cf..88099aa 100644
--- a/backend/tests/routes/scheduledPostRoutes.test.ts
+++ b/backend/tests/routes/scheduledPostRoutes.test.ts
@@ -100,3 +100,20 @@ describe('scheduled post routes', () => {
assert.deepEqual(supabase.table.filter(row => row._table === 'scheduled_posts').map(row => row.id).sort(), ['busy', 'theirs']);
});
});
+
+describe('the manual publishing trigger', () => {
+ test('runs only the caller\'s own due posts, so another person\'s posts are never claimed or reported', async () => {
+ const due = (id: string, userId: string, accountId: string) => tableRow('scheduled_posts', {
+ id, user_id: userId, account_id: accountId, status: 'pending', scheduled_at: '2026-09-01T11:00:00.000Z', attempts: 0, claimed_at: null, data: { mediaUrl: 'https://cdn/a.jpg' },
+ });
+ mock.method(console, 'error', () => undefined);
+ const { supabase, call } = setup([due('mine', 'user-1', 'missing-1'), due('theirs', 'user-2', 'missing-2')]);
+ const { status, body } = await call('POST', '/process-scheduled');
+ assert.equal(status, 200);
+ assert.deepEqual((body.errors as { id: string }[]).map(failure => failure.id), ['mine']);
+ const theirs = supabase.table.find(row => row.id === 'theirs');
+ assert.equal(theirs?.status, 'pending');
+ assert.equal(theirs?.attempts, 0);
+ assert.ok(supabase.calls.filter(call => call.table === 'scheduled_posts' && call.type === 'select').every(call => call.filters.some(([column, value]) => column === 'user_id' && value === 'user-1') || call.filters.some(([column]) => column === 'id')));
+ });
+});