Files
conversation-history/SquareMCP/2026-06-09-mysql-backed-tracking-links-eng-review.md

9.7 KiB

Engineering Review — MySQL-Backed Tracking Links

Date: 2026-06-09 Status: COMPLETE Reviews: 2026-06-09-mysql-backed-tracking-links Related: 2026-06-09-lodge-brothers-eng-review, 2026-06-09-lodge-brothers-beta-design


Verdict

The core decision — MySQL as source of truth, not Redis — is correct. The proposal is close to implementable. Three issues must be fixed before writing code: a token length mismatch that will cause a silent column truncation bug, an ambiguous async ordering that can accidentally block the redirect, and a Redis "optional fast path" that adds complexity without benefit at pilot scale. Everything else is sound.


Step 0 — Scope Check

No prior implementation of tracking_links, utm_token, or GET /t/:token exists in the codebase. Confirmed by searching the full source tree — the feature exists in planning notes only.

The proposal correctly follows the CREATE TABLE IF NOT EXISTS + initDatabase() convention used by all 5 existing tables in src/db.ts. No new dependency, no migration runner needed.

Redis is at 10.152.183.80:6379 (K8s cluster IP). No persistence config is visible in hermes-k8s.yaml. Default Redis (no AOF, no RDB snapshot) loses all keys on pod restart. The "Redis as sole source of truth is fragile" argument is valid for this deployment.


Issue 1 — Token length mismatch will silently truncate PRIMARY KEY ⚠️ HIGH

The schema says VARCHAR(43). The code example uses randomBytes(24).toString('base64url').

$ node -e "console.log(require('crypto').randomBytes(24).toString('base64url').length)"
32   # not 43
$ node -e "console.log(require('crypto').randomBytes(32).toString('base64url').length)"
43   # matches VARCHAR(43)

These must match. A 32-char token inserted into VARCHAR(43) works fine, but a 43-char token inserted into VARCHAR(32) is silently truncated in MySQL's default mode, turning every insert into a partial key and breaking uniqueness. The collision is subtle — the token stored in post_drafts.utm_token must also match.

The prior engineering review defined utm_token VARCHAR(32) NULL on post_drafts. Use that as the anchor:

// ✅ Consistent with post_drafts.utm_token VARCHAR(32)
const token = crypto.randomBytes(24).toString('base64url');  // 32 chars
-- ✅ Match the code
token VARCHAR(32) PRIMARY KEY,

If the decision is to use 43-char tokens instead, change both the tracking_links schema AND add ensureColumn(db, 'post_drafts', 'utm_token', 'VARCHAR(43) NULL') to handle the existing column definition.


Issue 2 — Async click recording must send the redirect FIRST ⚠️ HIGH

The proposal says "return 302 immediately… record the click without making redirect success depend on analytics." This is correct in intent but the implementation ordering matters in Express. The redirect must be sent before any async work begins — not just "don't await it."

// ❌ Dangerous: analytics error path can accidentally block before redirect
const link = await getTrackingLink(token);
if (!link) return res.status(404).send('Not found');

await recordClick(token);          // ← if this throws, redirect never happens
res.redirect(302, link.destination_url);

// ✅ Correct: redirect sent first, analytics is fire-and-forget after
const link = await getTrackingLink(token);
if (!link) return res.status(404).send('Not found');

res.redirect(302, link.destination_url);  // ← visitor is gone

// Fire-and-forget after response is sent
pool.query(
  'UPDATE tracking_links SET click_count = click_count + 1 WHERE token = ?',
  [token]
).catch(err => console.error('[tracking] click record failed:', err));

The await placement is the bug. Express does not prevent further code execution after res.redirect() — the redirect is sent to the client but the handler continues. Place the analytics write after res.redirect() with no await.

Add an explicit test for this: mock pool.query to reject, confirm the test still receives a 302.


Issue 3 — Drop the Redis "optional fast path" for v1 ⚠️ MEDIUM

The proposal mentions: "Redis may increment a fast counter, but the redirect should still work if Redis is down."

This path is never actually specced. Implementing MySQL primary + Redis cache layer introduces:

  • A cache-invalidation problem (Redis counter drifts from MySQL click_count)
  • Two code paths to test (Redis up, Redis down)
  • No benefit at Lodge Brothers pilot volume (dozens of clicks/day)

The MySQL UPDATE click_count + 1 is sufficient. Remove all Redis references from src/tracking-links.ts. The dashboard query already reads directly from MySQL. The original Lodge Brothers eng review's Redis pipeline suggestion for the dashboard was about batching Redis reads — that's independent of link storage and can be dropped now that click counts live in MySQL.

One place Redis still belongs: the getTokenCustomer OAuth cache and the existing wa_phone_id routing. Those are separate and unaffected.


Issue 4 — expires_at should default to NULL for the pilot ⚠️ MEDIUM

The proposal doesn't specify what value to set for expires_at at creation time. For the Lodge Brothers pilot this must be NULL (no expiry).

Mortgage clients have 45-90 day sales cycles. A homebuyer who saw Alex's Facebook post in January and comes back in April to click the "Book a call" link should still reach Alex's Calendly. A 90-day expiry — the value inherited from the Redis TTL thinking — breaks this.

// ✅ For Lodge Brothers beta
await createTrackingLink({
  token,
  customerId: customer.id,
  draftId: draft.id,
  destinationUrl: alex.calendlyUrl,
  expiresAt: null,   // links live indefinitely
});

The expires_at column is the right schema design for future use (promotional campaigns with hard end dates). For v1, always pass null.


What the Proposal Gets Right

MySQL as source of truth — correct call. The K8s Redis has no visible persistence config; a pod restart drops all keys. A tracking link in a Facebook post that dies after the next Redis rollout is a product failure, not a monitoring issue.

"Do not publish unless tracking-link insert succeeds" — critical. The proposal is explicit: if the INSERT fails, don't call createPost(). This prevents dead links from going live on Alex's Page. Implement this as a hard gate in the approval flow:

await createTrackingLink(...);     // throws on failure
const utmUrl = `${SERVER_URL}/t/${token}`;
await createPost({ message: `${draft.draft_text_social}\n\n${utmUrl}` }, customer);

Destination URL validation — the validation section is solid: new URL(), http:/https: only, reject credentials, max length. Add the domain allowlist for beta. Alex's destinations will be a small set of known URLs (Calendly, Lodge Brothers website). Allowlisting eliminates the open-redirect risk entirely for the pilot.

GET /t/:token outside requireAuth — correct and explicitly stated. Visitors clicking Alex's Facebook posts won't have a session cookie.

src/tracking-links.ts as a separate module — clean. Keeps src/index.ts from growing further and makes the module unit-testable in isolation.

Token format validation before DB query — the proposal correctly says to reject malformed tokens without hitting MySQL. Implementation:

const TOKEN_RE = /^[A-Za-z0-9_-]{32}$/;  // base64url, 32 chars
if (!TOKEN_RE.test(req.params.token)) {
  return res.status(404).send('Not found');
}

Revised Schema

After resolving Issue 1 and Issue 3:

CREATE TABLE IF NOT EXISTS tracking_links (
  token           VARCHAR(32) PRIMARY KEY,           -- randomBytes(24).toString('base64url')
  customer_id     VARCHAR(255) NOT NULL,
  draft_id        INT NULL,
  destination_url VARCHAR(2048) NOT NULL,
  click_count     BIGINT UNSIGNED NOT NULL DEFAULT 0,
  expires_at      TIMESTAMP NULL,                    -- NULL = no expiry (use for all pilot links)
  created_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_customer_created (customer_id, created_at),
  INDEX idx_draft (draft_id)
)

No Redis. click_count is the single source of truth.


Required Tests (additions to the proposal's list)

The proposal's test list is comprehensive. Two additions:

Async ordering (new):

  • Mock pool.query to reject on the click-count UPDATE. Assert response is still 302 and visitor reached the destination. This directly tests Issue 2.

expires_at = NULL never expires (new):

  • Create a link with expires_at = NULL, confirm redirect works. Regression guard against a future code change that incorrectly treats NULL as "expired immediately."

Implementation Order

Follows the same structure as the Lodge Brothers eng review Day 1:

1. Schema: add tracking_links in initDatabase()  [15 min]
2. src/tracking-links.ts:
   - createTrackingLink()
   - getTrackingLink()     (SELECT + expiry check)
   - recordClick()         (fire-and-forget UPDATE)
   - validateDestinationUrl()
   [1 h]
3. GET /t/:token in index.ts  [30 min]
4. Wire into approval flow (gate: insert before publish)  [30 min]
5. Tests  [1.5 h]
6. Deploy + end-to-end test against hermes.squaremcp.com/t/{token}  [30 min]

Total: ~4 hours. The proposal's half-day estimate is accurate.


Summary

Issue Severity Fix
VARCHAR(43) vs. 32-char token output HIGH Use randomBytes(24) → VARCHAR(32) throughout
Async click blocks redirect if awaited HIGH res.redirect() first, then fire-and-forget
Redis fast-path unspecced, adds complexity MEDIUM Drop entirely for v1
expires_at undefined — pilot links should never expire MEDIUM Always pass null for Lodge Brothers beta