@blamejs/blamejs-shop 0.4.63 → 0.4.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.4.x
10
10
 
11
+ - v0.4.64 (2026-06-19) — **A failed side-effect can no longer strand a claimed record.** Hardens the atomic-claim concurrency fixes (shipped over the previous releases) against the case where the side-effect fails or the worker crashes AFTER a record was claimed. Each claim now restores or recovers the record so a transient failure can't leave it permanently stuck. A scheduled payment retry that is claimed out of the due set but then fails to advance (a malformed policy or a database write error) restores its next-retry time, so the retry isn't silently dropped. Approving a seller application that crashes between claiming the approval and persisting the vendor is now recoverable — an application left approved with no vendor can be approved again rather than being stranded in a terminal state. A survey response whose insert fails after the invitation was claimed reverts the invitation to issued so it can be answered. A reorder reminder or wishlist digest whose send fails defers the retry to a later tick on a distinct cursor, so a concurrent overlapping tick can't pick up the rolled-back row and send a duplicate in the same window. No API change. **Fixed:** *Payment retry restores its schedule on a failed advance* — The retry scheduler claims an enrollment out of the due set by clearing its next-retry time before doing processor work. If advancing the enrollment then throws (a malformed retry policy, or a database write failure while recording the attempt), the next-retry time is restored to the value the tick observed, so a later tick re-attempts the retry. Previously the enrollment was left active with no next-retry time, and the due query (which requires a next-retry time) would never pick it up again, silently stopping the customer's recovery retries. · *Seller approval is recoverable after a mid-approval crash* — Approving a seller application claims the in-review-to-approved transition before registering the vendor. If the worker crashes or times out between the claim and persisting the vendor, the application is left approved with no vendor — a terminal state the rest of the primitive could never move out of. Approval now treats an approved application that has no vendor attached as re-approvable, so the registration can be retried and the application recovered instead of stranded. · *Survey response keeps the invitation retryable on insert failure* — Submitting a survey response claims the invitation (issued to responded) before inserting the response row. If that insert fails (a transient write error), the invitation is reverted to issued so the response can be submitted again, rather than being stuck responded with no response recorded and every retry rejected as already-responded. · *Reorder reminder and wishlist digest defer a failed send instead of re-firing it* — When a reorder reminder or a wishlist digest send fails after the row was claimed, the schedule cursor is rolled to a value distinct from the one the tick observed (still due, so a later tick retries) rather than back to the exact observed value. A concurrent overlapping tick that read the same cursor was waiting to claim it; restoring the exact value let it match and send a duplicate in the same window. The retry is now deferred to a later tick with no duplicate.
12
+
11
13
  - v0.4.63 (2026-06-19) — **Fulfillment and customer-data actions can't double-fire under concurrent calls.** Closes a further set of concurrency races where a fulfillment or customer-data action read a row, checked its status in application code, and then performed an irreversible side-effect (open an inventory hold, create shipments, restock received stock, create an order, reparent customer records, requeue a print job, mint child carts) before an unconditional update committed — so two concurrent calls could both pass the check and both perform the side-effect. Each now claims the transition with a single conditional update and performs the side-effect only when that claim wins, reverting the claim if the side-effect then fails so a row is never stranded. Approving an exchange opens its replacement hold once; executing a split-shipment plan creates the parcels once; recording a partial purchase-order receipt restocks each line once (claimed per line); completing a pick list creates its shipment once; converting or launching a pre-order creates the order once and a reservation can't oversell its cap; merging or rolling back a customer reparents the records once; an impersonation notice, a duplicate-suggestion link, a print-job retry, and a cart split each happen once. Behavior for a single sequential caller is unchanged. **Fixed:** *Fulfillment transitions claim before their side-effect* — Approving an exchange now claims pending-to-approved (WHERE id = ? AND status = 'pending') before opening the replacement inventory hold, reverting to pending if the hold fails. Executing a split-shipment plan claims proposed-to-executed before creating any shipment. Recording a partial purchase-order receipt claims each receipt line by advancing its received quantity conditionally before restocking, rolling the claimed lines back if a later line fails. Completing a pick list claims its completion before creating the shipment. In each case two concurrent calls can no longer both create the holds / shipments / restock for one row. · *Pre-order conversion, launch, cancel, and reserve are atomic* — Converting a reservation to an order claims active-to-converted before creating the order (reverting on failure), so a reservation can't spawn two orders; launching a campaign claims active-to-launched before walking reservations; cancelling claims active-to-cancelled before decrementing the reserved counter. Reserving now enforces the campaign cap inside the increment itself (units_reserved + qty <= max_units_available in the update's WHERE), so concurrent reservations can't oversell the pool; a reservation that loses the cap is compensated. · *Customer merge/rollback, impersonation notice, suggestion dedup, print retry, and cart split run once* — Executing or rolling back a customer merge claims the transition before reparenting records, reverting if the reparent fails. Sending the 'an operator viewed your account' notice claims the notified stamp (WHERE customer_notified_at IS NULL) before enqueuing, so it's sent once. Linking a duplicate suggestion claims the source before migrating its votes to the canonical row. Marking a print job failed claims the transition before inserting the retry job, so a job isn't reprinted twice. Splitting a cart claims the source's abandon before minting the child carts, so a concurrent split can't create two sets of children.
12
14
 
13
15
  - v0.4.62 (2026-06-19) — **Money and approval actions can't double-fire under concurrent calls.** Closes a set of concurrency races in money- and approval-critical paths where the action read a row, checked its status in application code, and then performed an irreversible side-effect (retry a card, execute an approved action, register a vendor, bill a subscription change) before an unconditional update committed — so two concurrent calls could both pass the check and both perform the side-effect. Each now claims the transition with a single conditional update and performs the side-effect only when that claim wins. A scheduled payment retry is claimed out of the due set before the processor is called, so an overlapping scheduler tick can't retry the same card twice; a payment outcome is claimed by its attempt number before the attempt is recorded, so a redelivered webhook can't double-count it. Executing an approved operator request claims the approved-to-executed transition before returning success, so the underlying money move runs once. Approving a seller application claims the in-review-to-approved transition before registering the vendor (rolling back to in-review if registration fails), so one application can't create two vendors. Applying scheduled subscription plan changes claims each pending change before updating the plan and recording its proration invoice, and stamps a deterministic idempotency key on the invoice, so an overlapping or retried scheduler run can't bill the proration twice. Behavior for a single sequential caller is unchanged. **Fixed:** *Scheduled payment retries and recorded outcomes claim before acting* — The retry scheduler now claims each due enrollment (nulling its next-retry time, conditional on the value the tick observed) before composing the processor retry, so two overlapping ticks can't both retry the same card for one scheduled slot — only the claim winner calls the processor. Recording a retry outcome claims the enrollment by bumping its attempt count conditionally on the observed value before writing the attempt row, so a redelivered webhook (or a manual record racing it) can't write a duplicate attempt or double-count toward the cap; the loser returns the already-advanced row. · *Executing an approved request runs the action once* — markExecuted now flips the request from approved to executed with a conditional update (WHERE id = ? AND status = 'approved') and returns success only when that update changes one row; a concurrent second call is refused with a typed error before the application runs the underlying action (a large refund, vendor payout, or bulk operation) a second time. · *Approving a seller application creates one vendor* — approveApplication now claims the in-review-to-approved transition first and registers the vendor only when the claim wins, so two concurrent approvals can't both register a vendor for one application. If vendor registration fails after the claim, the application is rolled back to in-review so it can be approved again rather than stranded as approved with no vendor. · *Applying scheduled plan changes bills the proration once* — applyScheduledChanges now claims each pending change (WHERE id = ? AND status = 'pending') before updating the subscription plan and recording the proration invoice, so an overlapping or retried scheduler run skips an already-applied change instead of billing it twice. Both the scheduled and the immediate plan-change paths now stamp a deterministic idempotency key on the proration invoice, so even a re-run that reached the billing call would dedupe against the unique invoice id rather than write a second charge. A regression test asserts a second apply pass records no additional invoice.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.4.63",
2
+ "version": "0.4.64",
3
3
  "assets": {
4
4
  "css/admin.css": {
5
5
  "integrity": "sha384-imfe0otYErcB8rr2h6KLSGTtStirysptpXETSPY4zLv3bZoIT75Lo1dOvkOav+xL",
@@ -749,11 +749,26 @@ function create(opts) {
749
749
  }
750
750
 
751
751
  var responseId = b.uuid.v7();
752
- await query(
753
- "INSERT INTO survey_responses (id, invitation_id, answers_json, occurred_at) " +
754
- "VALUES (?1, ?2, ?3, ?4)",
755
- [responseId, invitation.id, JSON.stringify(canonicalAnswers), occurredAt],
756
- );
752
+ try {
753
+ await query(
754
+ "INSERT INTO survey_responses (id, invitation_id, answers_json, occurred_at) " +
755
+ "VALUES (?1, ?2, ?3, ?4)",
756
+ [responseId, invitation.id, JSON.stringify(canonicalAnswers), occurredAt],
757
+ );
758
+ } catch (insErr) {
759
+ // The claim above already flipped the invitation to 'responded'. If
760
+ // the response insert fails (a transient D1/SQLite write error),
761
+ // revert the claim to 'issued' so the invitation stays retryable —
762
+ // otherwise it is stranded 'responded' with no response row and
763
+ // every retry is rejected as ALREADY_RESPONDED, so the response can
764
+ // never be recorded.
765
+ await query(
766
+ "UPDATE survey_invitations SET status = 'issued', responded_at = NULL " +
767
+ "WHERE id = ?1 AND status = 'responded'",
768
+ [invitation.id],
769
+ );
770
+ throw insErr;
771
+ }
757
772
 
758
773
  return {
759
774
  response_id: responseId,
@@ -604,19 +604,50 @@ function create(opts) {
604
604
  );
605
605
  if (Number(claim.rowCount || 0) !== 1) continue; // another tick claimed it
606
606
 
607
- var policy = await _getPolicy(enrollment.policy_slug);
608
- if (!policy) {
609
- // Policy went missing between enrollment + tick close
610
- // as abandoned so the row doesn't spin forever.
607
+ // Pre-charge prep. The claim above nulled next_retry_at to take
608
+ // the row out of the due set; a throw HERE (a missing policy /
609
+ // malformed retry schedule) is BEFORE any processor work, so it is
610
+ // safe to restore the observed next_retry_at (only while still
611
+ // NULL, so a partial re-stamp isn't clobbered) and let a later
612
+ // tick re-attempt — otherwise the enrollment is stranded active
613
+ // with next_retry_at NULL and the due SELECT (next_retry_at IS NOT
614
+ // NULL) never picks it up again.
615
+ var policy, schedule;
616
+ try {
617
+ policy = await _getPolicy(enrollment.policy_slug);
618
+ if (!policy) {
619
+ // Policy went missing between enrollment + tick — close
620
+ // as abandoned so the row doesn't spin forever.
621
+ await query(
622
+ "UPDATE payment_retry_enrollments SET status = 'abandoned', next_retry_at = NULL, " +
623
+ "ended_at = ?1, end_reason = 'policy_missing' WHERE id = ?2",
624
+ [now, enrollment.id],
625
+ );
626
+ advanced.push(await _refetchEnrollment(enrollment.id));
627
+ continue;
628
+ }
629
+ schedule = _parseSchedule(policy.retry_schedule_json);
630
+ } catch (prepErr) {
611
631
  await query(
612
- "UPDATE payment_retry_enrollments SET status = 'abandoned', next_retry_at = NULL, " +
613
- "ended_at = ?1, end_reason = 'policy_missing' WHERE id = ?2",
614
- [now, enrollment.id],
632
+ "UPDATE payment_retry_enrollments SET next_retry_at = ?1 " +
633
+ "WHERE id = ?2 AND status = 'active' AND next_retry_at IS NULL",
634
+ [enrollment.next_retry_at, enrollment.id],
615
635
  );
616
- advanced.push(await _refetchEnrollment(enrollment.id));
617
- continue;
636
+ throw prepErr;
618
637
  }
619
- var schedule = _parseSchedule(policy.retry_schedule_json);
638
+
639
+ // _tickAdvance composes paymentHandle.retryIntent — the real
640
+ // card-charge retry — which runs BEFORE the attempt-ledger and
641
+ // status writes. By the time any throw escapes _tickAdvance the
642
+ // charge has already been submitted, so DO NOT restore
643
+ // next_retry_at on such a throw: re-stamping it would let a later
644
+ // or overlapping tick call retryIntent AGAIN for the same attempt
645
+ // and double-move money. The enrollment is left active with
646
+ // next_retry_at NULL for a recovery sweep / operator to advance;
647
+ // retryIntent is passed attempt_number as its idempotency
648
+ // dimension, so a conformant handle de-dupes a deliberate
649
+ // re-attempt at the same number. (Not stranding without a charge
650
+ // is the prep branch above; not double-charging is here.)
620
651
  var refreshed = await _tickAdvance(enrollment, policy, schedule, now);
621
652
  advanced.push(refreshed);
622
653
  }
@@ -561,16 +561,20 @@ function create(opts) {
561
561
  fail_reason: null,
562
562
  }));
563
563
  } else {
564
- // The send failed after we won the claim. Roll the cursor
565
- // back to the observed value so the retry sweep picks this
566
- // row up on the next tick (failed rows stay due — matching
567
- // the single-caller contract). The rollback is guarded on
568
- // the value we set so a concurrent re-enrolment that moved
569
- // the cursor forward in the meantime isn't clobbered.
564
+ // The send failed after we won the claim. Roll the cursor to a
565
+ // value DISTINCT from the one this tick observed (observed + 1ms),
566
+ // NOT back to the exact observed value: a concurrent overlapping
567
+ // tick that read the same observed cursor is waiting to claim
568
+ // `next_remind_at = observed`, and restoring the exact observed
569
+ // value would let it match and re-send in the same overlap.
570
+ // observed+1 is still <= now, so the row stays due and a LATER
571
+ // tick retries it (deferred, not re-fired in this overlap). The
572
+ // guard on the value we set means a concurrent re-enrolment that
573
+ // moved the cursor forward isn't clobbered.
570
574
  await query(
571
575
  "UPDATE reorder_enrollments SET next_remind_at = ?1 " +
572
576
  "WHERE id = ?2 AND next_remind_at = ?3",
573
- [enrollment.next_remind_at, enrollment.id, nextRemindAt],
577
+ [enrollment.next_remind_at + 1, enrollment.id, nextRemindAt],
574
578
  );
575
579
  await query(
576
580
  "INSERT INTO reorder_dispatches (id, enrollment_id, status, occurred_at, fail_reason) " +
@@ -826,14 +826,21 @@ function create(opts) {
826
826
  miss.code = "APPLICATION_NOT_FOUND";
827
827
  throw miss;
828
828
  }
829
- if (TERMINAL_APPLICATION_STATUSES.indexOf(app.status) !== -1) {
829
+ // A stranded approval: a prior approve claimed 'approved' but the
830
+ // vendor was never persisted (the worker died / timed out between
831
+ // the status claim and the vendor_slug stamp). 'approved' is
832
+ // terminal, so without this the application could never be approved,
833
+ // rejected, or revised again. Treat an 'approved' row with no
834
+ // vendor_slug as re-approvable so the registration can be retried.
835
+ var recoverable = app.status === "approved" && app.vendor_slug == null;
836
+ if (TERMINAL_APPLICATION_STATUSES.indexOf(app.status) !== -1 && !recoverable) {
830
837
  var term = new Error(
831
838
  "seller-signup.approveApplication: refused — application is " + app.status + " (terminal)"
832
839
  );
833
840
  term.code = "APPLICATION_TERMINAL";
834
841
  throw term;
835
842
  }
836
- if (app.status !== "in_review") {
843
+ if (app.status !== "in_review" && !recoverable) {
837
844
  var notReady = new Error(
838
845
  "seller-signup.approveApplication: refused — application is " + app.status +
839
846
  "; approve requires status='in_review' (all requested documents uploaded)"
@@ -851,15 +858,25 @@ function create(opts) {
851
858
  // the loser is refused before registering anything. vendor_slug is
852
859
  // stamped in a second UPDATE after the (winner-only) registration.
853
860
  var ts = _now();
861
+ // The recovery branch (re-approving a stranded 'approved' row with
862
+ // no vendor) must be EXCLUSIVE. Without gating on the observed
863
+ // approved_at, two concurrent recovery approvals would BOTH match
864
+ // (the UPDATE changes nothing that makes the recoverable predicate
865
+ // false) and both call registerVendor — the duplicate-vendor race
866
+ // the claim exists to prevent. Gating the recovery branch on
867
+ // `approved_at = <observed>` (while the UPDATE bumps approved_at to
868
+ // a fresh ts) makes a second concurrent caller's predicate no longer
869
+ // match. The in_review branch stays exclusive via the status flip.
854
870
  var claim = await query(
855
871
  "UPDATE seller_applications " +
856
872
  "SET status = 'approved', approved_at = ?1, approved_by = ?2, updated_at = ?1 " +
857
- "WHERE id = ?3 AND status = 'in_review'",
858
- [ts, approvedBy, applicationId],
873
+ "WHERE id = ?3 AND (status = 'in_review' " +
874
+ "OR (status = 'approved' AND vendor_slug IS NULL AND approved_at = ?4))",
875
+ [ts, approvedBy, applicationId, app.approved_at],
859
876
  );
860
877
  if (Number(claim.rowCount || 0) !== 1) {
861
878
  var raced = new Error(
862
- "seller-signup.approveApplication: refused — application is no longer in_review (concurrent approval)"
879
+ "seller-signup.approveApplication: refused — application is not in an approvable state (concurrent approval)"
863
880
  );
864
881
  raced.code = "APPLICATION_NOT_READY";
865
882
  throw raced;
@@ -883,15 +900,17 @@ function create(opts) {
883
900
  status: "active",
884
901
  });
885
902
  } catch (e) {
886
- // Roll the claim back so the application returns to in_review and
887
- // can be re-approved the winning claim must not strand the app
888
- // in 'approved' with no vendor behind it.
903
+ // Roll back ONLY the claim THIS call won, to in_review so it can be
904
+ // re-approved. Gate on `approved_at = ts` (our claim's stamp, never
905
+ // a subsequent re-claim's) AND `vendor_slug IS NULL` (no vendor was
906
+ // stamped) so a delayed rollback can't clobber another caller's
907
+ // successful approval.
889
908
  try {
890
909
  await query(
891
910
  "UPDATE seller_applications " +
892
911
  "SET status = 'in_review', approved_at = NULL, approved_by = NULL, updated_at = ?1 " +
893
- "WHERE id = ?2 AND status = 'approved'",
894
- [_now(), applicationId],
912
+ "WHERE id = ?2 AND status = 'approved' AND approved_at = ?3 AND vendor_slug IS NULL",
913
+ [_now(), applicationId, ts],
895
914
  );
896
915
  } catch (_e2) { /* drop-silent — the registerVendor error is the caller's signal */ }
897
916
  // Surface the vendors error with our typed-code wrapper so
@@ -941,10 +941,19 @@ function create(opts) {
941
941
  // the cursor back to observedNext, guarded on the value we claimed
942
942
  // so a concurrent winner's advance is never clobbered.
943
943
  var _unclaim = async function () {
944
+ // Roll the cursor to a value DISTINCT from the one this tick
945
+ // observed (observedNext + 1ms), NOT back to the exact observed
946
+ // value: a concurrent overlapping tick that read the same cursor
947
+ // is waiting to claim `next_dispatch_at = observedNext`, and
948
+ // restoring the exact value would let it match and re-send the
949
+ // digest in the same overlap. observedNext+1 stays due, so a LATER
950
+ // tick re-attempts (deferred, not re-fired in this overlap); the
951
+ // guard on the claimed value means a concurrent winner's advance
952
+ // is never clobbered.
944
953
  await query(
945
954
  "UPDATE wishlist_digest_enrollments SET next_dispatch_at = ?1 " +
946
955
  "WHERE id = ?2 AND next_dispatch_at = ?3",
947
- [observedNext, enrollment.id, nextDispatchAt],
956
+ [observedNext + 1, enrollment.id, nextDispatchAt],
948
957
  );
949
958
  };
950
959
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/blamejs-shop",
3
- "version": "0.4.63",
3
+ "version": "0.4.64",
4
4
  "description": "Open-source framework built on blamejs. Vendored stack, zero npm runtime deps, PQC-first crypto, security-on by default.",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {