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): claim posts atomically so they publish once
spacesdrive10aaec930deb
diff --git a/backend/lib/db.js b/backend/lib/db.jsindex 84a8289..1a4cd38 100644--- a/backend/lib/db.js+++ b/backend/lib/db.js@@ -117,6 +117,19 @@ export async function getDuePosts(supabase) {return (data || []).map(rowToPost);}+// Atomically moves a due post from pending to publishing. Returns false when another scheduler+// (the Worker cron or the GitHub Actions workflow) already claimed it.+export async function claimPost(supabase, id) {+ const { data, error } = await supabase+ .from('scheduled_posts')+ .update({ status: 'publishing' })+ .eq('id', id)+ .eq('status', 'pending')+ .select('id');+ if (error) throw error;+ return (data || []).length > 0;+}+export async function createPost(supabase, post, userId) {const { id, accountId, status, scheduledAt, ...rest } = post;const { error } = await supabase.from('scheduled_posts').insert({diff --git a/backend/utils/scheduler.js b/backend/utils/scheduler.jsindex c242e37..6095923 100644--- a/backend/utils/scheduler.js+++ b/backend/utils/scheduler.js@@ -1,5 +1,5 @@// fetch is a global in Cloudflare Workers.-import { getDuePosts, updatePost, getAccountById } from '../lib/db.js';+import { getDuePosts, updatePost, getAccountById, claimPost } from '../lib/db.js';import { buildMediaParams } from '../services/instagram.js';export function generateId() {@@ -16,7 +16,7 @@ export async function processScheduledPosts(supabase) {const duePosts = await getDuePosts(supabase);for (const post of duePosts) {- await updatePost(supabase, post.id, { status: 'publishing' });+ if (!(await claimPost(supabase, post.id))) continue;try {const acct = await getAccountById(supabase, post.accountId);diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.mdindex e7b91ba..78f88df 100644--- a/docs/architecture/data-flows/SCHEDULING.md+++ b/docs/architecture/data-flows/SCHEDULING.md@@ -34,7 +34,7 @@ WHERE id = :id AND status = 'pending'The `AND status = 'pending'` condition means only one scheduler can successfully claim a post. The second scheduler to run will find no matching rows for that post ID and skip it.-**Race condition window:** There is a small window between the `SELECT` (fetch due posts) and the `UPDATE` (claim as publishing) where both schedulers could claim the same post. Supabase/PostgreSQL serializes these writes, so one will win and the other will find `status ≠ pending` and skip.+Both schedulers implement this claim: `claimPost()` in `backend/lib/db.js` for the Worker, and `claimPost()` in `scripts/publish-scheduled.js` (a `PATCH` filtered on `status=eq.pending` with `Prefer: return=representation`). A scheduler that gets no row back skips the post. PostgreSQL serializes the two updates, so exactly one scheduler publishes each post even when both run at the same moment.## Post Status Lifecycle@@ -74,5 +74,14 @@ Both schedulers implement the same logic:### For GitHub Actions (System B)- GitHub repo secrets: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`-- The `publish-scheduled.yml` workflow must be enabled+- The `publish-scheduled.yml` workflow must be enabled. Forks start with Actions disabled, and GitHub pauses scheduled workflows in public repositories after 60 days without commits.+- No personal access token is needed. The workflow only reads and updates Supabase.+- Private repositories: a 15-minute schedule exceeds the 2,000 free Actions minutes a month; use `*/30 * * * *`.++The same steps are shown in the app under Settings, Scheduled publishing, with direct links once the repository owner and name are saved.++## What users see++- Publish explains, next to the schedule fields, that the server publishes within 15 minutes after the chosen time.+- Posts still `pending` more than 30 minutes after their time trigger an alert in Publish that names the administrator contact (`VITE_ADMIN_EMAIL`).- Note: These GitHub secrets are only required for System B - the main deploy workflows (`deploy-backend.yml`, `deploy-frontend.yml`) do not need themdiff --git a/scripts/publish-scheduled.js b/scripts/publish-scheduled.jsindex 3cd5b0f..1c2fe4a 100644--- a/scripts/publish-scheduled.js+++ b/scripts/publish-scheduled.js@@ -78,6 +78,19 @@ async function updatePostStatus(id, updates) {await sbPatch(`/scheduled_posts?id=eq.${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) {+ 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;+}+// ─── Instagram publishing ─────────────────────────────────────────────────────function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }@@ -164,7 +177,10 @@ async function main() {for (const post of duePosts) {console.log(` Publishing: ${post.id} (${post.mediaType}) - scheduled ${post.scheduledAt}`);- await updatePostStatus(post.id, { status: 'publishing' });+ if (!(await claimPost(post.id))) {+ console.log(' Skipped: already claimed by the other scheduler');+ continue;+ }try {const account = await getAccount(post.accountId);