* wip backend optimism * another inch * make action state transitions only happen once * another inch * almost ready for testing * use interactive txs * another inch * ready for basic testing * lint fix * inches * wip item update * get item update to work * donate and downzap * inchy inch * fix territory paid actions * wip usePaidMutation * usePaidMutation error handling * PENDING_HELD and HELD transitions, gql paidAction return types * mostly working pessimism * make sure invoice field is present in optimisticResponse * inches * show optimistic values to current me * first pass at notifications and payment status reporting * fix migration to have withdrawal hash * reverse optimism on payment failure * Revert "Optimistic updates via pending sats in item context (#1229)" This reverts commit 93713b33df9bc3701dc5a692b86a04ff64e8cfb1. * add onCompleted to usePaidMutation * onPaid and onPayError for new comments * use 'IS DISTINCT FROM' for NULL invoiceActionState columns * make usePaidMutation easier to read * enhance invoice qr * prevent actions on unpaid items * allow navigation to action's invoice * retry create item * start edit window after item is paid for * fix ux of retries from notifications * refine retries * fix optimistic downzaps * remember item updates can't be retried * store reference to action item in invoice * remove invoice modal layout shift * fix destructuring * fix zap undos * make sure ItemAct is paid in aggregate queries * dont toast on long press zap undo * fix delete and remindme bots * optimistic poll votes with retries * fix retry notifications and invoice item context * fix pessimisitic typo * item mentions and mention notifications * dont show payment retry on item popover * make bios work * refactor paidAction transitions * remove stray console.log * restore docker compose nwc settings * add new todos * persist qr modal on post submission + unify item form submission * fix post edit threshold * make bounty payments work * make job posting work * remove more store procedure usage ... document serialization concerns * dont use dynamic imports for paid action modules * inline comment denormalization * create item starts with median votes * fix potential of serialization anomalies in zaps * dont trigger notification indicator on successful paid action invoices * ignore invoiceId on territory actions and add optimistic concurrency control * begin docs for paid actions * better error toasts and fix apollo cache warnings * small documentation enhancements * improve paid action docs * optimistic concurrency control for territory updates * use satsToMsats and msatsToSats helpers * explictly type raw query template parameters * improve consistency of nested relation names * complete paid action docs * useEffect for canEdit on payment * make sure invoiceId is provided when required * don't return null when expecting array * remove buy credits * move verifyPayment to paidAction * fix comments invoicePaidAt time zone * close nwc connections once * grouped logs for paid actions * stop invoiceWaitUntilPaid if not attempting to pay * allow actionState to transition directly from HELD to PAID * make paid mutation wait until pessimistic are fully paid * change button text when form submits/pays * pulsing form submit button * ignore me in notification indicator for territory subscription * filter unpaid items from more queries * fix donation stike timing * fix pending poll vote * fix recent item notifcation padding * no default form submitting button text * don't show paying on submit button on free edits * fix territory autorenew with fee credits * reorg readme * allow jobs to be editted forever * fix image uploads * more filter fixes for aggregate views * finalize paid action invoice expirations * remove unnecessary async * keep clientside cache normal/consistent * add more detail to paid action doc * improve paid action table * remove actionType guard * fix top territories * typo api/paidAction/README.md Co-authored-by: ekzyis <ek@stacker.news> * typo components/use-paid-mutation.js Co-authored-by: ekzyis <ek@stacker.news> * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> * encorporate ek feeback * more ek suggestions * fix 'cost to post' hover on items * Apply suggestions from code review Co-authored-by: ekzyis <ek@stacker.news> --------- Co-authored-by: ekzyis <ek@stacker.news>
243 lines
8.4 KiB
JavaScript
243 lines
8.4 KiB
JavaScript
import { ANON_ITEM_SPAM_INTERVAL, ITEM_SPAM_INTERVAL, USER_ID } from '@/lib/constants'
|
|
import { notifyItemMention, notifyItemParents, notifyMention, notifyTerritorySubscribers, notifyUserSubscribers } from '@/lib/webPush'
|
|
import { getItemMentions, getMentions, performBotBehavior } from './lib/item'
|
|
import { satsToMsats } from '@/lib/format'
|
|
|
|
export const anonable = true
|
|
export const supportsPessimism = true
|
|
export const supportsOptimism = true
|
|
|
|
export async function getCost ({ subName, parentId, uploadIds, boost = 0, bio }, { models, user }) {
|
|
const sub = (parentId || bio) ? null : await models.sub.findUnique({ where: { name: subName } })
|
|
const baseCost = sub ? satsToMsats(sub.baseCost) : 1000n
|
|
|
|
// cost = baseCost * 10^num_items_in_10m * 100 (anon) or 1 (user) + image fees + boost
|
|
const [{ cost }] = await models.$queryRaw`
|
|
SELECT ${baseCost}::INTEGER
|
|
* POWER(10, item_spam(${parseInt(parentId)}::INTEGER, ${user?.id || USER_ID.anon}::INTEGER,
|
|
${user?.id && !bio ? ITEM_SPAM_INTERVAL : ANON_ITEM_SPAM_INTERVAL}::INTERVAL))
|
|
* ${user ? 1 : 100}::INTEGER
|
|
+ (SELECT "nUnpaid" * "imageFeeMsats"
|
|
FROM image_fees_info(${user?.id || USER_ID.anon}::INTEGER, ${uploadIds}::INTEGER[]))
|
|
+ ${satsToMsats(boost)}::INTEGER as cost`
|
|
|
|
// sub allows freebies (or is a bio or a comment), cost is less than baseCost, not anon, and cost must be greater than user's balance
|
|
const freebie = (parentId || bio || sub?.allowFreebies) && cost <= baseCost && !!user && cost > user?.msats
|
|
|
|
return freebie ? BigInt(0) : BigInt(cost)
|
|
}
|
|
|
|
export async function perform (args, context) {
|
|
const { invoiceId, parentId, uploadIds = [], forwardUsers = [], options: pollOptions = [], boost = 0, ...data } = args
|
|
const { tx, me, cost } = context
|
|
const boostMsats = satsToMsats(boost)
|
|
|
|
let invoiceData = {}
|
|
if (invoiceId) {
|
|
invoiceData = { invoiceId, invoiceActionState: 'PENDING' }
|
|
await tx.upload.updateMany({
|
|
where: { id: { in: uploadIds } },
|
|
data: invoiceData
|
|
})
|
|
}
|
|
|
|
const itemActs = []
|
|
if (boostMsats > 0) {
|
|
itemActs.push({
|
|
msats: boostMsats, act: 'BOOST', userId: data.userId, ...invoiceData
|
|
})
|
|
}
|
|
if (cost > 0) {
|
|
itemActs.push({
|
|
msats: cost - boostMsats, act: 'FEE', userId: data.userId, ...invoiceData
|
|
})
|
|
} else {
|
|
data.freebie = true
|
|
}
|
|
|
|
const mentions = await getMentions(args, context)
|
|
const itemMentions = await getItemMentions(args, context)
|
|
|
|
// start with median vote
|
|
if (me) {
|
|
const [row] = await tx.$queryRaw`SELECT
|
|
COALESCE(percentile_cont(0.5) WITHIN GROUP(
|
|
ORDER BY "weightedVotes" - "weightedDownVotes"), 0)
|
|
AS median FROM "Item" WHERE "userId" = ${me.id}::INTEGER`
|
|
if (row?.median < 0) {
|
|
data.weightedDownVotes = -row.median
|
|
}
|
|
}
|
|
|
|
const itemData = {
|
|
parentId: parentId ? parseInt(parentId) : null,
|
|
...data,
|
|
...invoiceData,
|
|
boost,
|
|
threadSubscriptions: {
|
|
createMany: {
|
|
data: [
|
|
{ userId: data.userId },
|
|
...forwardUsers.map(({ userId }) => ({ userId }))
|
|
]
|
|
}
|
|
},
|
|
itemForwards: {
|
|
createMany: {
|
|
data: forwardUsers
|
|
}
|
|
},
|
|
pollOptions: {
|
|
createMany: {
|
|
data: pollOptions.map(option => ({ option }))
|
|
}
|
|
},
|
|
itemUploads: {
|
|
create: uploadIds.map(id => ({ uploadId: id }))
|
|
},
|
|
itemActs: {
|
|
createMany: {
|
|
data: itemActs
|
|
}
|
|
},
|
|
mentions: {
|
|
createMany: {
|
|
data: mentions
|
|
}
|
|
},
|
|
itemReferrers: {
|
|
create: itemMentions
|
|
}
|
|
}
|
|
|
|
let item
|
|
if (data.bio && me) {
|
|
item = (await tx.user.update({
|
|
where: { id: data.userId },
|
|
include: { bio: true },
|
|
data: {
|
|
bio: {
|
|
create: itemData
|
|
}
|
|
}
|
|
})).bio
|
|
} else {
|
|
item = await tx.item.create({ data: itemData })
|
|
}
|
|
|
|
// store a reference to the item in the invoice
|
|
if (invoiceId) {
|
|
await tx.invoice.update({
|
|
where: { id: invoiceId },
|
|
data: { actionId: item.id }
|
|
})
|
|
}
|
|
|
|
await performBotBehavior(item, context)
|
|
|
|
// ltree is unsupported in Prisma, so we have to query it manually (FUCK!)
|
|
return (await tx.$queryRaw`
|
|
SELECT *, ltree2text(path) AS path, created_at AS "createdAt", updated_at AS "updatedAt"
|
|
FROM "Item" WHERE id = ${item.id}::INTEGER`
|
|
)[0]
|
|
}
|
|
|
|
export async function retry ({ invoiceId, newInvoiceId }, { tx }) {
|
|
await tx.itemAct.updateMany({ where: { invoiceId }, data: { invoiceId: newInvoiceId, invoiceActionState: 'PENDING' } })
|
|
await tx.item.updateMany({ where: { invoiceId }, data: { invoiceId: newInvoiceId, invoiceActionState: 'PENDING' } })
|
|
await tx.upload.updateMany({ where: { invoiceId }, data: { invoiceId: newInvoiceId, invoiceActionState: 'PENDING' } })
|
|
return (await tx.$queryRaw`
|
|
SELECT *, ltree2text(path) AS path, created_at AS "createdAt", updated_at AS "updatedAt"
|
|
FROM "Item" WHERE "invoiceId" = ${newInvoiceId}::INTEGER`
|
|
)[0]
|
|
}
|
|
|
|
export async function onPaid ({ invoice, id }, context) {
|
|
const { models, tx } = context
|
|
let item
|
|
|
|
if (invoice) {
|
|
item = await tx.item.findFirst({
|
|
where: { invoiceId: invoice.id },
|
|
include: {
|
|
mentions: true,
|
|
itemReferrers: { include: { refereeItem: true } },
|
|
user: true
|
|
}
|
|
})
|
|
await tx.itemAct.updateMany({ where: { invoiceId: invoice.id }, data: { invoiceActionState: 'PAID' } })
|
|
await tx.item.updateMany({ where: { invoiceId: invoice.id }, data: { invoiceActionState: 'PAID', invoicePaidAt: new Date() } })
|
|
await tx.upload.updateMany({ where: { invoiceId: invoice.id }, data: { invoiceActionState: 'PAID', paid: true } })
|
|
} else if (id) {
|
|
item = await tx.item.findUnique({
|
|
where: { id },
|
|
include: {
|
|
mentions: true,
|
|
itemReferrers: { include: { refereeItem: true } },
|
|
user: true,
|
|
itemUploads: { include: { upload: true } }
|
|
}
|
|
})
|
|
await tx.upload.updateMany({
|
|
where: { id: { in: item.itemUploads.map(({ uploadId }) => uploadId) } },
|
|
data: {
|
|
paid: true
|
|
}
|
|
})
|
|
} else {
|
|
throw new Error('No item found')
|
|
}
|
|
|
|
await tx.$executeRaw`INSERT INTO pgboss.job (name, data, startafter, priority)
|
|
VALUES ('timestampItem', jsonb_build_object('id', ${item.id}::INTEGER), now() + interval '10 minutes', -2)`
|
|
await tx.$executeRaw`
|
|
INSERT INTO pgboss.job (name, data, retrylimit, retrybackoff, startafter)
|
|
VALUES ('imgproxy', jsonb_build_object('id', ${item.id}::INTEGER), 21, true, now() + interval '5 seconds')`
|
|
|
|
// TODO: referals for boost
|
|
|
|
if (item.parentId) {
|
|
// denormalize ncomments and "weightedComments" for ancestors, and insert into reply table
|
|
await tx.$executeRaw`
|
|
WITH comment AS (
|
|
SELECT *
|
|
FROM "Item"
|
|
WHERE id = ${item.id}::INTEGER
|
|
), ancestors AS (
|
|
UPDATE "Item"
|
|
SET ncomments = "Item".ncomments + 1,
|
|
"weightedComments" = "Item"."weightedComments" +
|
|
CASE WHEN comment."userId" = "Item"."userId" THEN 0 ELSE ${item.user.trust}::FLOAT END
|
|
FROM comment
|
|
WHERE "Item".path @> comment.path AND "Item".id <> comment.id
|
|
RETURNING "Item".*
|
|
)
|
|
INSERT INTO "Reply" (created_at, updated_at, "ancestorId", "ancestorUserId", "itemId", "userId", level)
|
|
SELECT comment.created_at, comment.updated_at, ancestors.id, ancestors."userId",
|
|
comment.id, comment."userId", nlevel(comment.path) - nlevel(ancestors.path)
|
|
FROM ancestors, comment
|
|
WHERE ancestors."userId" <> comment."userId"`
|
|
|
|
notifyItemParents({ item, me: item.userId, models }).catch(console.error)
|
|
}
|
|
|
|
for (const { userId } of item.mentions) {
|
|
notifyMention({ models, item, userId }).catch(console.error)
|
|
}
|
|
for (const { referee } of item.itemReferrers) {
|
|
notifyItemMention({ models, referrerItem: item, refereeItem: referee }).catch(console.error)
|
|
}
|
|
notifyUserSubscribers({ models, item }).catch(console.error)
|
|
notifyTerritorySubscribers({ models, item }).catch(console.error)
|
|
}
|
|
|
|
export async function onFail ({ invoice }, { tx }) {
|
|
await tx.itemAct.updateMany({ where: { invoiceId: invoice.id }, data: { invoiceActionState: 'FAILED' } })
|
|
await tx.item.updateMany({ where: { invoiceId: invoice.id }, data: { invoiceActionState: 'FAILED' } })
|
|
await tx.upload.updateMany({ where: { invoiceId: invoice.id }, data: { invoiceActionState: 'FAILED' } })
|
|
}
|
|
|
|
export async function describe ({ parentId }, context) {
|
|
return `SN: create ${parentId ? `reply to #${parentId}` : 'item'}`
|
|
}
|