DEV Community

Cover image for DotShare 3.8.1: Charging for X posts like a card payment
freerave
freerave

Posted on

DotShare 3.8.1: Charging for X posts like a card payment

DotShare 3.8 started charging for X posts. X bills DotSuite for every post made through DotShare's X app, so each plan got a monthly X budget, and each post was charged the larger of two numbers: X's list price, or what DotSuite's X credit balance actually dropped by.

The first real thread showed that rule was wrong. This post is about what replaced it in DotShare 3.8.1 and dotshare-cli 3.2.1, and the database bug that stopped the thread from posting at all.

The thread that wouldn't post

The first time I posted a real thread to X through the CLI, it failed. The second attempt failed too.

Production logs explained it: X publishing had never been switched on. DotSuite Core applies its database migrations at startup, and three of them, including the one that creates the X billing tables, had failed with permission denied for schema public. Core and the web app share one PostgreSQL database under separate roles, and neither role owns the schema. That's on purpose, since a compromised app can't create or drop tables. But it also means Core can't apply a migration that creates tables.

Core treats a failed migration as "this feature stays off", logs it and carries on. That part worked. The part that didn't was hidden in the pool:

// Before: run on the pool. A failure left that connection mid-transaction.
sqlx::raw_sql(sql).execute(&self.pool).await?;
Enter fullscreen mode Exit fullscreen mode

The migration file runs as one transaction. When it failed halfway, the connection went back to the pool still inside an aborted transaction, and the next query on that connection failed with current transaction is aborted. Now a failed migration runs on its own connection, and that connection is closed instead of returned:

let mut conn = self.pool.acquire().await?;
match sqlx::raw_sql(sql).execute(&mut *conn).await {
    Ok(_) => Ok(()),
    Err(e) => { let _ = conn.detach().close().await; Err(e.into()) }
}
Enter fullscreen mode Exit fullscreen mode

A test proves it with a pool of exactly one connection: run a migration that fails, then check that the next query on the pool still works. The migrations themselves were applied as the database owner, and the role script in the repository now matches production exactly, so the next new table won't surprise me.

Before: a migration run on the pool failed halfway through its transaction, the connection went back to the pool still inside it, and the next query failed with "current transaction is aborted". After: each migration gets its own connection, a failed one is closed instead of returned, and a test with a pool of one connection proves the next query still works.

Then the thread posted.

What X actually took

The thread had four parts: a post with an image, two replies, and a reply with a link. DotSuite records the estimate, the measured cost and the charge for every part:

Part Estimate X took Charged
Post with image $0.020 $0.020 $0.020
Reply $0.015 $0.010 $0.015
Reply $0.015 $0.010 $0.015
Reply with a link $0.200 $0.010 $0.200
Total $0.250 $0.050 $0.250

X's list price for a post containing a link is $0.20. Replies in a thread were billed $0.01 each, link or not. I'd charged five times what the thread cost, and the user in this case was me.

Could X have charged the link a few minutes later? The X Developer Console answered that. It showed $0.10 for the last 30 days across nine requests, including that thread. A late $0.20 charge couldn't fit in that total.

The first real thread: a post with an image estimated at $0.020, two replies at $0.015 and a reply with a link at $0.200. X took $0.020, $0.010, $0.010 and $0.010, $0.05 in total, but the old rule charged $0.25, five times what it cost.

Why not just lower the prices

The obvious fix is to price replies at $0.01. But I don't know every case where X charges less, and X can change its prices. If I price something low and X bills more, I pay the difference on every post. In 3.8 I made one rule: never under-charge. Lowering the prices breaks it.

What I wanted was to charge exactly what X takes, without ever risking less. Card payments already solve this. A hotel or a gas pump puts a hold on your card for the most it might cost, then settles for the real amount and releases the rest.

Hold, pending, settle

Every X post now goes through three steps.

Hold. Before anything is sent, every part is priced at the most X could charge: anything that might be a link is priced as a link post, even a reply X will bill for less. One PostgreSQL transaction holds the total against the monthly budget, the user's daily post limit and an app-wide daily spend cap. A request the budget can't cover is refused before it reaches X.

Pending. Each part is posted under a global lock, so a change in X's balance belongs to exactly one post. DotSuite reads its X credit balance before and after. If the deduction hasn't shown up yet, the part stays pending and the balance is read again, up to three times, two seconds apart.

Settle. When the deduction shows up, that's the charge, and the rest of the hold goes back to the budget. If X took more than the hold, the real amount is charged anyway.

The interesting case is when the deduction doesn't show up. Maybe the balance couldn't be read, or it only dropped by less than X's cheapest post, which means the charge hasn't arrived. Then the whole hold is charged. Not confirming is never cheaper for the user than confirming, but it's never a loss for DotSuite either.

/// A deduction counts as X's charge only when it's at least X's cheapest post.
fn confirmed(seen: Option<i64>, prices: &XPrices) -> Option<i64> {
    seen.filter(|s| *s >= prices.min_post_micros)
}

let charge = || match confirmed(seen, prices) {
    Some(actual) => actual,      // what X took, even above the hold
    None => plan.estimated,      // unconfirmed: the whole hold
};
Enter fullscreen mode Exit fullscreen mode

All amounts are integer micro-dollars, and X's cheapest post is an environment variable (X_PRICE_MIN_POST_MICROS, $0.01 by default), like every other price.

Under this rule the thread above holds $0.25 and charges $0.05. And it did: the next four-post thread, on November 23, held $0.25 and was charged $0.05.

Hold: every part is priced at the most X could charge and held against the budget. Pending: posts go out one at a time and DotSuite re-reads its X balance up to three times, two seconds apart, until the deduction shows. Settle: the measured deduction is charged and the rest of the hold is released. If X took more, the real amount is charged; if it can't be confirmed, the whole hold is charged; nothing is added later.

Nothing is added later

A card can be charged after the fact. DotSuite never does that to users. Once a post settles, its charge is final.

A charge that turns up later still needs to be noticed, though. An hourly job compares X's balance with what was charged. Posts run one at a time, so any drop between one post's final reading and the next reading wasn't charged to anyone. Those drops add up, and the job logs an error for me with the amount and a pointer to the X console. If X ever bills late, I pay for it and find out within the hour. I'd rather carry that than surprise a user.

The first version had a bug that would have reported every post as unexplained. I recorded the reading after each post as an ordinary reading, so the next check counted the post's own charge as missing. The fix was a separate "this drop was charged" reading, and a test that walks a balance through measured posts, an unmeasured drop and a top-up, and checks that only the unmeasured drop is reported.

What users see

The preview had promised an exact price. With a hold that's no longer true, so it now says:

x-cloud: up to $0.25 of your X budget will be held for 4 post(s), 1 with a link.
You pay what X actually deducts and the rest is released; at least $14.75 of this
month's X budget will be left.
Enter fullscreen mode Exit fullscreen mode

The DotSuite dashboard already showed three columns per charge: the estimate, what X deducted, and what you paid. Now the last two match whenever the deduction was confirmed. The privacy policy explains the hold in all five languages it's written in.

How it was tested

  • Core: 63 tests. The full publish flow runs against a mock X API and real PostgreSQL in Docker. New cases: a reply with a link holds $0.20 and is charged $0.01; a deduction that only shows up on a re-read is still charged correctly; a post whose deduction never shows up is charged the whole hold. The pool test above runs with a pool of one connection.
  • DotShare: 405 Jest tests, including the new preview wording.
  • Production: the migrations applied, /ready returning 200, and the thread above published, measured and compared against the X console.

Try it

DotShare 3.8.1 is on the Marketplace and Open VSX, and the CLI is on npm:

npm install -g dotshare-cli
dotshare-agent cloud login
dotshare-agent accounts connect my-x --platform x
Enter fullscreen mode Exit fullscreen mode

The billing change runs on DotSuite, so it applies to every version that posts to X through it. The changelog and the privacy policy have the details.

I used AI assistance (Claude) to build, test and write up this release. The numbers and behavior described come from the shipped code, its tests and the production ledger.

Top comments (2)

Collapse
 
aichiliai profile image
AI Chili •

Detaching and closing the connection on Err (conn.detach().close().await) instead of letting sqlx return an aborted transaction state to the pool is a great catch, and reproducing it deterministically with max_connections(1) in the test suite is a solid regression guard. On the X billing measurement side, if two users publish threads concurrently against the same app-level credit balance, do you reconcile per-post cost from individual usage ledger IDs or serialize balance snapshots around each publish call?

Collapse
 
freerave profile image
freerave •

Thanks! It's the second one: the balance snapshots are serialized. X's credits endpoint only returns a balance, with no per-request usage IDs, so there's nothing to reconcile against per post.

Every X request through DotSuite takes a PostgreSQL advisory lock (pg_advisory_xact_lock) that covers all Core instances and is held for the whole thread, so two users' threads never interleave. Each part reads the balance, posts, and re-reads (up to three times, two seconds apart) until the drop shows up, and only then does the next part go out. The hold is reserved before taking the lock, so a request the budget can't cover is refused without waiting in line.

The trade-off is throughput: a part can hold the lock for a few seconds while the balance catches up, so concurrent threads queue behind each other. At the current volume that's fine. Anything the lock can't explain, like a drop between two measured posts, is what the hourly check reports, and that's paid by me, not by a user.