@delmaredigital/payload-experiments 0.4.0-rc.7 → 0.4.0-rc.9

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.
Files changed (221) hide show
  1. package/README.md +12 -12
  2. package/dist/admin/blocks/model.js +2 -2
  3. package/dist/admin/copy/blocks.js +1 -1
  4. package/dist/admin/surface/ResultsRoute.js +17 -11
  5. package/dist/admin/surface/TestsHome.js +53 -20
  6. package/dist/admin/surface/newTest/PageWizard.js +8 -2
  7. package/dist/admin/surface/results/ResultsHeader.js +11 -6
  8. package/dist/admin/surface/test/TestPage.js +3 -3
  9. package/dist/blocks/formState.js +1 -1
  10. package/dist/collections/experiments/config.js +8 -3
  11. package/dist/collections/experiments/deleteGuard.js +2 -2
  12. package/dist/collections/experiments/lockHook.js +21 -2
  13. package/dist/collections/experiments/pickSlug.js +2 -0
  14. package/dist/collections/metricsGuards.js +2 -0
  15. package/dist/collections/serialize.js +5 -4
  16. package/dist/constants.d.ts +1 -0
  17. package/dist/constants.js +1 -0
  18. package/dist/db/adapter.d.ts +9 -1
  19. package/dist/db/adapter.js +77 -1
  20. package/dist/db/delete.d.ts +1 -1
  21. package/dist/db/delete.js +2 -4
  22. package/dist/db/events.d.ts +9 -0
  23. package/dist/db/events.js +42 -8
  24. package/dist/db/executor.d.ts +7 -1
  25. package/dist/db/executor.js +7 -3
  26. package/dist/db/results.d.ts +5 -1
  27. package/dist/db/results.js +21 -5
  28. package/dist/db/snapshots.d.ts +1 -0
  29. package/dist/endpoints/deleteImpact.js +2 -1
  30. package/dist/endpoints/events.js +103 -39
  31. package/dist/endpoints/index.js +2 -8
  32. package/dist/endpoints/placementStatus.js +7 -4
  33. package/dist/endpoints/results.d.ts +1 -1
  34. package/dist/endpoints/results.js +6 -2
  35. package/dist/endpoints/routeId.d.ts +2 -2
  36. package/dist/endpoints/routeId.js +11 -5
  37. package/dist/endpoints/summary.js +46 -12
  38. package/dist/endpoints/transitions.js +37 -24
  39. package/dist/errors.d.ts +4 -0
  40. package/dist/errors.js +6 -0
  41. package/dist/events/request.d.ts +6 -2
  42. package/dist/events/request.js +35 -8
  43. package/dist/events/rows.d.ts +1 -1
  44. package/dist/events/rows.js +24 -8
  45. package/dist/events/writable.d.ts +9 -0
  46. package/dist/events/writable.js +13 -0
  47. package/dist/exports/index.d.ts +1 -1
  48. package/dist/exports/rsc.d.ts +1 -0
  49. package/dist/exports/rsc.js +1 -0
  50. package/dist/goals/fairness.js +2 -2
  51. package/dist/hooks/hostHook.js +6 -2
  52. package/dist/hooks/pageGuard.js +4 -0
  53. package/dist/lib/fetchAllDocs.d.ts +1 -1
  54. package/dist/manifest/compile.js +8 -5
  55. package/dist/onInit.js +14 -0
  56. package/dist/options.js +5 -0
  57. package/dist/proxy/pageNavigation.d.ts +4 -0
  58. package/dist/proxy/pageNavigation.js +28 -0
  59. package/dist/proxy/resolve.js +52 -25
  60. package/dist/puck/editor/ConfigureTestDrawer.js +5 -4
  61. package/dist/puck/editor/ExperimentSlotEditor.js +182 -58
  62. package/dist/puck/editor/QuickTestActions.d.ts +5 -2
  63. package/dist/puck/editor/QuickTestActions.js +16 -4
  64. package/dist/puck/editor/ResultsReadout.d.ts +2 -1
  65. package/dist/puck/editor/ResultsReadout.js +2 -1
  66. package/dist/puck/editor/VersionBuilder.d.ts +13 -2
  67. package/dist/puck/editor/VersionBuilder.js +133 -49
  68. package/dist/puck/editor/armWrites.js +1 -1
  69. package/dist/puck/editor/armsCache.js +1 -3
  70. package/dist/puck/editor/copy.d.ts +4 -1
  71. package/dist/puck/editor/copy.js +4 -1
  72. package/dist/puck/editor/editor.chrome.css +1 -0
  73. package/dist/puck/editor/editor.css +1 -0
  74. package/dist/puck/editor/editor.model.d.ts +1 -0
  75. package/dist/puck/editor/placementsCache.d.ts +5 -1
  76. package/dist/puck/editor/placementsCache.js +17 -9
  77. package/dist/puck/editor/usePageSaveReadiness.d.ts +9 -0
  78. package/dist/puck/editor/usePageSaveReadiness.js +34 -0
  79. package/dist/puck/editor/usePlacementNotice.d.ts +2 -2
  80. package/dist/puck/editor/usePlacementNotice.js +5 -4
  81. package/dist/results/aggregate.d.ts +6 -3
  82. package/dist/results/aggregate.js +9 -9
  83. package/dist/results/health.d.ts +8 -0
  84. package/dist/results/health.js +28 -0
  85. package/dist/results/identityCredit.d.ts +1 -0
  86. package/dist/results/identityCredit.js +4 -1
  87. package/dist/results/verdict.js +2 -1
  88. package/dist/runtime/cookie.d.ts +10 -2
  89. package/dist/runtime/cookie.js +38 -6
  90. package/dist/runtime/cookieOptions.d.ts +6 -0
  91. package/dist/runtime/cookieOptions.js +14 -0
  92. package/dist/runtime/proxyRuntime.d.ts +1 -0
  93. package/dist/runtime/proxyRuntime.js +18 -8
  94. package/dist/runtime/signing.d.ts +1 -0
  95. package/dist/runtime/signing.js +5 -0
  96. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  97. package/dist/sanitizeReadinessDetail.js +20 -2
  98. package/dist/server/getAssignments.js +11 -10
  99. package/dist/server/recordContentChange.d.ts +1 -1
  100. package/dist/server/recordContentChange.js +11 -2
  101. package/dist/server/resolveExperimentBlocks.js +2 -4
  102. package/dist/server/resolveExperimentData.js +2 -5
  103. package/dist/server/runResults.js +52 -14
  104. package/dist/server/startExperiment.d.ts +20 -0
  105. package/dist/server/startExperiment.js +70 -0
  106. package/dist/server/trackConversion.js +10 -13
  107. package/dist/testSurface/actions/DecideDialog.d.ts +4 -1
  108. package/dist/testSurface/actions/DecideDialog.js +32 -14
  109. package/dist/testSurface/actions/MakeContentResult.d.ts +4 -3
  110. package/dist/testSurface/actions/MakeContentResult.js +9 -1
  111. package/dist/testSurface/api.d.ts +5 -5
  112. package/dist/testSurface/api.js +21 -9
  113. package/dist/testSurface/copy/actions.d.ts +1 -0
  114. package/dist/testSurface/copy/actions.js +1 -0
  115. package/dist/testSurface/copy/common.d.ts +3 -1
  116. package/dist/testSurface/copy/common.js +4 -2
  117. package/dist/testSurface/copy/languages.d.ts +1 -0
  118. package/dist/testSurface/copy/languages.js +1 -0
  119. package/dist/testSurface/copy/metrics.d.ts +1 -0
  120. package/dist/testSurface/copy/metrics.js +1 -0
  121. package/dist/testSurface/copy/readiness.d.ts +12 -1
  122. package/dist/testSurface/copy/readiness.js +18 -1
  123. package/dist/testSurface/copy/results.d.ts +5 -2
  124. package/dist/testSurface/copy/results.js +5 -2
  125. package/dist/testSurface/copy/testPage.d.ts +20 -2
  126. package/dist/testSurface/copy/testPage.js +34 -3
  127. package/dist/testSurface/readPreflight.d.ts +5 -0
  128. package/dist/testSurface/readPreflight.js +7 -0
  129. package/dist/testSurface/readinessRead.d.ts +3 -0
  130. package/dist/testSurface/readinessRead.js +4 -0
  131. package/dist/testSurface/results/VerdictHero.d.ts +2 -1
  132. package/dist/testSurface/results/VerdictHero.js +5 -1
  133. package/dist/testSurface/results/results.model.d.ts +1 -1
  134. package/dist/testSurface/results/results.model.js +6 -2
  135. package/dist/testSurface/surface/contracts.d.ts +8 -1
  136. package/dist/testSurface/surface/editorPlacement.d.ts +2 -2
  137. package/dist/testSurface/surface/editorPlacement.js +1 -1
  138. package/dist/testSurface/surface/pageBlock/pageBlock.model.js +2 -2
  139. package/dist/testSurface/surface/pagePicker/PageCombobox.js +20 -6
  140. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +4 -2
  141. package/dist/testSurface/surface/readiness/ActionDialogs.js +39 -34
  142. package/dist/testSurface/surface/readiness/Banner.js +23 -12
  143. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +4 -3
  144. package/dist/testSurface/surface/readiness/SaveStatus.js +15 -15
  145. package/dist/testSurface/surface/readiness/readiness.model.d.ts +6 -1
  146. package/dist/testSurface/surface/readiness/readiness.model.js +108 -11
  147. package/dist/testSurface/surface/readiness/useTransition.d.ts +4 -4
  148. package/dist/testSurface/surface/readiness/useTransition.js +12 -10
  149. package/dist/testSurface/surface/results/ReleasePages.d.ts +4 -2
  150. package/dist/testSurface/surface/results/ReleasePages.js +5 -4
  151. package/dist/testSurface/surface/results/ResultsBody.d.ts +4 -2
  152. package/dist/testSurface/surface/results/ResultsBody.js +86 -43
  153. package/dist/testSurface/surface/results/useResults.d.ts +7 -6
  154. package/dist/testSurface/surface/results/useResults.js +3 -2
  155. package/dist/testSurface/surface/setting/parts.js +58 -18
  156. package/dist/testSurface/surface/test/AdvancedSection.js +1 -0
  157. package/dist/testSurface/surface/test/DeleteTest.d.ts +6 -2
  158. package/dist/testSurface/surface/test/DeleteTest.js +145 -54
  159. package/dist/testSurface/surface/test/GoalSection.js +7 -3
  160. package/dist/testSurface/surface/test/LengthSection.js +3 -0
  161. package/dist/testSurface/surface/test/PageHoldout.js +4 -1
  162. package/dist/testSurface/surface/test/ReadinessBar.js +1 -1
  163. package/dist/testSurface/surface/test/TargetingSection.js +77 -12
  164. package/dist/testSurface/surface/test/TestSurface.js +81 -19
  165. package/dist/testSurface/surface/test/VersionsSection.js +56 -29
  166. package/dist/testSurface/surface/test/fields.d.ts +29 -4
  167. package/dist/testSurface/surface/test/fields.js +159 -39
  168. package/dist/testSurface/surface/test/pageParts.js +14 -5
  169. package/dist/testSurface/surface/test/testPage.model.d.ts +1 -0
  170. package/dist/testSurface/surface/test/testPage.model.js +6 -0
  171. package/dist/testSurface/surface/testDocument.model.d.ts +3 -0
  172. package/dist/testSurface/surface/testDocument.model.js +4 -1
  173. package/dist/testSurface/surface/useTestDocument.d.ts +22 -4
  174. package/dist/testSurface/surface/useTestDocument.js +407 -160
  175. package/dist/testSurface/useApi.d.ts +5 -5
  176. package/dist/testSurface/useOnTestReturn.d.ts +2 -0
  177. package/dist/testSurface/useOnTestReturn.js +27 -0
  178. package/dist/testSurface/useReadinessPolling.js +3 -1
  179. package/dist/transitions/addMetric.d.ts +1 -4
  180. package/dist/transitions/allocate.d.ts +2 -2
  181. package/dist/transitions/allocate.js +3 -1
  182. package/dist/transitions/archive.d.ts +1 -1
  183. package/dist/transitions/archive.js +3 -2
  184. package/dist/transitions/checkStart.d.ts +1 -0
  185. package/dist/transitions/checkStart.js +17 -6
  186. package/dist/transitions/decide.d.ts +1 -1
  187. package/dist/transitions/decide.js +5 -3
  188. package/dist/transitions/deleteExperiment.d.ts +2 -2
  189. package/dist/transitions/deleteExperiment.js +17 -7
  190. package/dist/transitions/kernel.d.ts +2 -0
  191. package/dist/transitions/kernel.js +9 -4
  192. package/dist/transitions/makeContent.d.ts +2 -1
  193. package/dist/transitions/makeContent.js +12 -8
  194. package/dist/transitions/nestedPlacementNames.d.ts +2 -2
  195. package/dist/transitions/nestedPlacementNames.js +4 -5
  196. package/dist/transitions/phaseRecord.d.ts +2 -0
  197. package/dist/transitions/phaseRecord.js +5 -0
  198. package/dist/transitions/placementInteractions.d.ts +3 -3
  199. package/dist/transitions/placementInteractions.js +8 -7
  200. package/dist/transitions/placements.d.ts +2 -0
  201. package/dist/transitions/placements.js +5 -5
  202. package/dist/transitions/preflightData.d.ts +3 -2
  203. package/dist/transitions/preflightData.js +67 -41
  204. package/dist/transitions/releaseHoldout.d.ts +2 -1
  205. package/dist/transitions/releaseHoldout.js +3 -1
  206. package/dist/transitions/releasePages.d.ts +2 -1
  207. package/dist/transitions/releasePages.js +3 -1
  208. package/dist/transitions/resolveCaps.d.ts +2 -4
  209. package/dist/transitions/start.d.ts +6 -8
  210. package/dist/transitions/start.js +67 -34
  211. package/dist/transitions/startReads.d.ts +7 -0
  212. package/dist/transitions/startReads.js +28 -0
  213. package/dist/transitions/stop.d.ts +2 -1
  214. package/dist/transitions/stop.js +3 -2
  215. package/dist/types/contracts.d.ts +6 -3
  216. package/dist/types/endpoints.d.ts +52 -9
  217. package/dist/types/runtime.d.ts +15 -9
  218. package/dist/types/snapshot.d.ts +2 -0
  219. package/dist/ui/ChipsInput.d.ts +8 -1
  220. package/dist/ui/ChipsInput.js +17 -4
  221. package/package.json +2 -2
@@ -1,3 +1,72 @@
1
+ import { APIError } from 'payload';
2
+ import { XpNoTransactionError } from '../errors.js';
3
+ import { API_MESSAGES } from '../testSurface/copy/common.js';
4
+ import { transactionSession, txExecutor } from './executor.js';
5
+ const transitionIsolation = 'read committed';
6
+ const isolationMessage = 'Experiments requires PostgreSQL READ COMMITTED so it can see changes committed while waiting for locks. Set the Postgres adapter\'s transactionOptions.isolationLevel to "read committed" or remove the override.';
7
+ const checkedSessions = new WeakMap();
8
+ export class XpTransactionIsolationError extends APIError {
9
+ constructor(){
10
+ super(API_MESSAGES.transactionIsolation, 500, null, true);
11
+ }
12
+ }
13
+ /** Payload's initTransaction cannot pass options to the adapter. Like that
14
+ * helper, publish the pending transaction on the request before awaiting it.
15
+ */ export async function initTransitionTransaction(req) {
16
+ if (req.transactionID != null) {
17
+ await req.transactionID;
18
+ return false;
19
+ }
20
+ const db = req.payload.db;
21
+ const pending = db.beginTransaction({
22
+ ...db.transactionOptions || {},
23
+ isolationLevel: transitionIsolation
24
+ }).then((id)=>{
25
+ if (id == null) throw new XpNoTransactionError();
26
+ const session = db.sessions?.[id];
27
+ if (session) checkedSessions.set(session, Promise.resolve());
28
+ req.transactionID = id;
29
+ return id;
30
+ });
31
+ req.transactionID = pending;
32
+ try {
33
+ await pending;
34
+ return true;
35
+ } catch (error) {
36
+ if (req.transactionID === pending) delete req.transactionID;
37
+ throw error;
38
+ }
39
+ }
40
+ /** A borrowed transaction may already have taken its snapshot. Check the
41
+ * effective isolation on that session before relying on a post-lock read.
42
+ */ async function isReadCommitted(exec) {
43
+ const { rows } = await exec.query('SHOW transaction_isolation');
44
+ const level = rows[0]?.transaction_isolation;
45
+ // PostgreSQL implements READ UNCOMMITTED as READ COMMITTED (docs §13.2).
46
+ return level === transitionIsolation || level === 'read uncommitted';
47
+ }
48
+ export async function assertReadCommitted(req) {
49
+ const transaction = {
50
+ payload: req.payload,
51
+ transactionID: await req.transactionID
52
+ };
53
+ // The adapter resolves the ID to a unique session object until commit or
54
+ // rollback. Cache the pending check so concurrent hooks share the same query.
55
+ const session = await transactionSession(transaction);
56
+ let checked = checkedSessions.get(session);
57
+ if (!checked) {
58
+ checked = isReadCommitted(txExecutor(transaction)).then((valid)=>{
59
+ if (!valid) {
60
+ try {
61
+ console.error('Experiments requires PostgreSQL READ COMMITTED so it can see changes committed while waiting for locks. Set the Postgres adapter\'s transactionOptions.isolationLevel to "read committed" or remove the override.');
62
+ } catch {}
63
+ throw new XpTransactionIsolationError();
64
+ }
65
+ });
66
+ checkedSessions.set(session, checked);
67
+ }
68
+ await checked;
69
+ }
1
70
  export function assertPostgresAdapter(payload) {
2
71
  // @payloadcms/db-postgres/dist/index.js:133 declares this package marker.
3
72
  if (payload.db.packageName !== '@payloadcms/db-postgres') throw new Error('Experiments requires @payloadcms/db-postgres');
@@ -5,5 +74,12 @@ export function assertPostgresAdapter(payload) {
5
74
  export async function probeTransactions(payload) {
6
75
  const id = await payload.db.beginTransaction();
7
76
  if (id == null) throw new Error('Experiments transactions are disabled');
8
- await payload.db.rollbackTransaction(id);
77
+ try {
78
+ if (!await isReadCommitted(txExecutor({
79
+ payload,
80
+ transactionID: id
81
+ }))) throw new Error(isolationMessage);
82
+ } finally{
83
+ await payload.db.rollbackTransaction(id);
84
+ }
9
85
  }
@@ -1,6 +1,6 @@
1
1
  import type { PayloadRequest } from 'payload';
2
2
  import type { DocId } from '../types/contracts.js';
3
- import type { Executor } from './executor.js';
3
+ import { type Executor } from './executor.js';
4
4
  interface DeleteState {
5
5
  tail: Promise<void>;
6
6
  retiredSlugs: Set<string>;
package/dist/db/delete.js CHANGED
@@ -1,4 +1,4 @@
1
- import { XpNoTransactionError } from '../errors.js';
1
+ import { transactionSession } from './executor.js';
2
2
  import { COLUMNS, TABLES } from './names.js';
3
3
  import { qualifiedTable, quoteIdentifier as quote } from './sql.js';
4
4
  // Key by the actual session: borrowed requests in one transaction share a queue,
@@ -9,9 +9,7 @@ const transactions = new WeakMap();
9
9
  * Successful beforeDelete bodies retain exclusions until the transaction ends:
10
10
  * another row can be between hooks with its children gone but its row present.
11
11
  */ export async function serializeDelete(req, fn) {
12
- const id = await req.transactionID;
13
- const session = id == null ? undefined : req.payload.db.sessions?.[id];
14
- if (!session) throw new XpNoTransactionError();
12
+ const session = await transactionSession(req);
15
13
  let state = transactions.get(session);
16
14
  if (!state) {
17
15
  state = {
@@ -17,5 +17,14 @@ export interface EventRow {
17
17
  attributes?: Record<string, unknown>;
18
18
  dedupeKey: string;
19
19
  }
20
+ type ServerConversion = Pick<EventRow, 'unitId' | 'unitType' | 'userId' | 'ts'> & {
21
+ eventName: string;
22
+ value: number;
23
+ idempotencyKey: string;
24
+ };
25
+ /** A retained legacy row suppresses retries for its event name. The scoped key's
26
+ * unique index handles concurrent writes after the old writers have been drained. */
27
+ export declare function insertServerConversion(exec: Executor, event: ServerConversion, log: (message: string) => void): Promise<void>;
20
28
  /** Pooled/autocommit executor required: an FK failure must not poison a caller's transaction. */
21
29
  export declare function insertEvents(exec: Executor, rows: EventRow[], log?: (message: string) => void): Promise<number>;
30
+ export {};
package/dist/db/events.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { exposureDimensions } from '../events/dimensions.js';
2
3
  import { COLUMNS, TABLES } from './names.js';
3
4
  import { qualifiedTable, quoteIdentifier } from './sql.js';
@@ -6,7 +7,7 @@ import { qualifiedTable, quoteIdentifier } from './sql.js';
6
7
  experimentId
7
8
  ]);
8
9
  }
9
- const quote = (name)=>`"${name.replaceAll('"', '""')}"`;
10
+ const quote = quoteIdentifier;
10
11
  const c = COLUMNS.events;
11
12
  function foreignKeyViolation(error) {
12
13
  const seen = new Set();
@@ -28,15 +29,48 @@ function foreignKeyViolation(error) {
28
29
  return null;
29
30
  }
30
31
  }
32
+ function hasFiniteValue(value, log) {
33
+ if (value === undefined || Number.isFinite(value)) return true;
34
+ log('Experiments: dropped event with non-finite value');
35
+ return false;
36
+ }
37
+ /** A retained legacy row suppresses retries for its event name. The scoped key's
38
+ * unique index handles concurrent writes after the old writers have been drained. */ export async function insertServerConversion(exec, event, log) {
39
+ if (!hasFiniteValue(event.value, log)) return;
40
+ const table = qualifiedTable(exec, TABLES.events);
41
+ const digest = createHash('sha256').update(JSON.stringify([
42
+ event.eventName,
43
+ event.idempotencyKey
44
+ ])).digest('hex');
45
+ await exec.query(`INSERT INTO ${table} (${[
46
+ c.type,
47
+ c.unitId,
48
+ c.unitType,
49
+ c.userId,
50
+ c.eventName,
51
+ c.value,
52
+ c.ts,
53
+ c.dedupeKey,
54
+ c.createdAt,
55
+ c.updatedAt
56
+ ].map(quote).join(', ')})
57
+ SELECT 'conversion', $1, $2, $3, $4, $5, $6, $7, now(), now()
58
+ WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE ${quote(c.dedupeKey)} = $8 AND ${quote(c.eventName)} = $4)
59
+ ON CONFLICT (${quote(c.dedupeKey)}) DO NOTHING`, [
60
+ event.unitId,
61
+ event.unitType,
62
+ event.userId ?? null,
63
+ event.eventName,
64
+ event.value,
65
+ event.ts,
66
+ `conversion:s2:${digest}`,
67
+ `conversion:s:${event.idempotencyKey}`
68
+ ]);
69
+ }
31
70
  /** Pooled/autocommit executor required: an FK failure must not poison a caller's transaction. */ export async function insertEvents(exec, rows, log = console.error) {
32
- const valid = rows.filter((row)=>{
33
- if (row.value === undefined || Number.isFinite(row.value)) return true;
34
- log('Experiments: dropped event with non-finite value');
35
- return false;
36
- });
71
+ const valid = rows.filter((row)=>hasFiniteValue(row.value, log));
37
72
  if (!valid.length) return 0;
38
- const schema = exec.schemaName;
39
- const table = `${schema ? `${quote(schema)}.` : ''}${quote(TABLES.events)}`;
73
+ const table = qualifiedTable(exec, TABLES.events);
40
74
  async function insert(batch) {
41
75
  const params = [];
42
76
  const values = batch.map((row)=>{
@@ -2,7 +2,13 @@ import type { Payload, PayloadRequest } from 'payload';
2
2
  import type { Executor } from './pgExecutor.js';
3
3
  export type { Executor } from './pgExecutor.js';
4
4
  export { pgPoolExecutor, ownConnection, withStatementTimeout, raceDeadline, ResultsBudgetError, RESULTS_TIMEOUT_MARGIN_MS } from './pgExecutor.js';
5
- export declare function txExecutor(req: PayloadRequest): Executor & {
5
+ type TransactionRequest = Pick<PayloadRequest, 'payload' | 'transactionID'>;
6
+ export declare function transactionSession(req: TransactionRequest): Promise<{
7
+ db: unknown;
8
+ reject: () => Promise<void>;
9
+ resolve: () => Promise<void>;
10
+ }>;
11
+ export declare function txExecutor(req: TransactionRequest): Executor & {
6
12
  schemaName?: string;
7
13
  };
8
14
  export declare function pooledExecutor(payload: Payload): Executor & {
@@ -14,14 +14,18 @@ export { pgPoolExecutor, ownConnection, withStatementTimeout, raceDeadline, Resu
14
14
  chunks.push(sql.raw(text.slice(start)));
15
15
  return sql.join(chunks, sql.raw(''));
16
16
  }
17
+ export async function transactionSession(req) {
18
+ const id = await req.transactionID;
19
+ const session = id == null ? undefined : req.payload.db.sessions?.[id];
20
+ if (!session) throw new XpNoTransactionError();
21
+ return session;
22
+ }
17
23
  export function txExecutor(req) {
18
24
  const db = req.payload.db;
19
25
  return {
20
26
  schemaName: db.schemaName,
21
27
  async query (text, params = []) {
22
- const id = await req.transactionID;
23
- const session = id == null ? undefined : db.sessions?.[id];
24
- if (!session) throw new XpNoTransactionError();
28
+ const session = await transactionSession(req);
25
29
  return normalise(await session.db.execute(bind(text, params)));
26
30
  }
27
31
  };
@@ -5,6 +5,7 @@ export interface PhaseExposureRow {
5
5
  unitId: string;
6
6
  arm: string;
7
7
  ts: number;
8
+ unitAgeMs?: number;
8
9
  }
9
10
  export interface RolloutExposureRow {
10
11
  unitId: string;
@@ -16,6 +17,7 @@ export interface MetricEventRow {
16
17
  userId: string | null;
17
18
  value: number;
18
19
  ts: number;
20
+ unitAgeMs?: number;
19
21
  }
20
22
  export interface IdentityRow {
21
23
  anonymousId: string;
@@ -41,12 +43,14 @@ export declare function rolloutExposureRows(exec: Executor, { experimentId, resp
41
43
  * or userIds for stored user_id (user units and visitor identity credit). Each distinct
42
44
  * ID occurs in one ANY array of at most 10,000, so batching cannot duplicate rows.
43
45
  */
44
- export declare function metricEventRows(exec: Executor, { eventName, unitIds, userIds, from, to }: {
46
+ export declare function metricEventRows(exec: Executor, { eventName, unitIds, userIds, from, to, readAge, forVisitors }: {
45
47
  eventName: string;
46
48
  unitIds?: readonly string[];
47
49
  userIds?: readonly string[];
48
50
  from: Timestamp;
49
51
  to: Timestamp;
52
+ readAge?: boolean;
53
+ forVisitors?: boolean;
50
54
  }): Promise<MetricEventRow[]>;
51
55
  /** Linked visitors for creditUserEvents; disjoint ANY batches of ≤ 10,000 IDs. */
52
56
  export declare function identityRows(exec: Executor, { anonymousIds }: {
@@ -1,11 +1,22 @@
1
1
  import { timestampMs } from '../results/aggregate.js';
2
2
  import { COLUMNS, TABLES } from './names.js';
3
+ import { USER_BROWSER_CONVERSION_PREFIX } from '../constants.js';
3
4
  import { qualifiedTable, quoteIdentifier as q } from './sql.js';
4
5
  const c = COLUMNS.events;
5
6
  const batchSize = 10_000;
6
7
  const iso = (ts)=>new Date(timestampMs(ts)).toISOString();
7
8
  // round()::bigint keeps exact milliseconds on servers where extract() returns a float (PG ≤ 13).
8
9
  const epochMs = `round(extract(epoch from ${q(c.ts)}) * 1000)::bigint`;
10
+ const signedAge = `${q(c.attributes)}->'_xp'->'unitAgeMs' AS "unitAgeMs"`;
11
+ function knownAge(unitAgeMs) {
12
+ // A reissued legacy ID counts as known and older than the rapid activity window.
13
+ if (unitAgeMs === 'legacy') return {
14
+ unitAgeMs: Infinity
15
+ };
16
+ return typeof unitAgeMs === 'number' && Number.isSafeInteger(unitAgeMs) && unitAgeMs >= 0 ? {
17
+ unitAgeMs
18
+ } : {};
19
+ }
9
20
  function phaseFilter({ experimentId, phase, endedAt }, type) {
10
21
  const params = [
11
22
  experimentId,
@@ -24,11 +35,12 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
24
35
  }
25
36
  /** All phase exposures, including multi-arm rows for firstExposures to exclude. */ export async function phaseExposureRows(exec, opts) {
26
37
  const filter = phaseFilter(opts, 'exposure');
27
- const { rows } = await exec.query(`SELECT ${q(c.unitId)} AS "unitId", ${q(c.arm)} AS "arm", ${epochMs} AS "ts" FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${filter.text} ORDER BY ${q(c.ts)}, ${q(c.unitId)}`, filter.params);
38
+ const { rows } = await exec.query(`SELECT ${q(c.unitId)} AS "unitId", ${q(c.arm)} AS "arm", ${epochMs} AS "ts", ${signedAge} FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${filter.text} ORDER BY ${q(c.ts)}, ${q(c.unitId)}`, filter.params);
28
39
  return rows.map((row)=>({
29
40
  unitId: row.unitId,
30
41
  arm: row.arm,
31
- ts: Number(row.ts)
42
+ ts: Number(row.ts),
43
+ ...knownAge(row.unitAgeMs)
32
44
  }));
33
45
  }
34
46
  /** Diagnostic distinct units only; this never contributes to multi-arm exclusion. */ export async function armMismatchCount(exec, opts) {
@@ -52,7 +64,7 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
52
64
  /** events:<name> conversion rows in [from, to). Choose unitIds for stored unit_id,
53
65
  * or userIds for stored user_id (user units and visitor identity credit). Each distinct
54
66
  * ID occurs in one ANY array of at most 10,000, so batching cannot duplicate rows.
55
- */ export async function metricEventRows(exec, { eventName, unitIds, userIds, from, to }) {
67
+ */ export async function metricEventRows(exec, { eventName, unitIds, userIds, from, to, readAge = false, forVisitors = false }) {
56
68
  if (unitIds !== undefined && userIds !== undefined) throw new RangeError('Choose unitIds or userIds');
57
69
  const params = [
58
70
  'conversion',
@@ -60,7 +72,10 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
60
72
  iso(from),
61
73
  iso(to)
62
74
  ];
63
- const text = `SELECT ${q(c.unitId)} AS "unitId", ${q(c.userId)} AS "userId", ${q(c.value)} AS "value", ${epochMs} AS "ts" FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${q(c.type)} = $1 AND ${q(c.eventName)} = $2 AND ${q(c.ts)} >= $3 AND ${q(c.ts)} < $4`;
75
+ // A browser conversion without a visitor cookie cannot count for a visitor,
76
+ // even through the separate linked-user lookup.
77
+ const visitorFilter = forVisitors ? ` AND ${q(c.dedupeKey)} NOT LIKE '${USER_BROWSER_CONVERSION_PREFIX}%'` : '';
78
+ const text = `SELECT ${q(c.unitId)} AS "unitId", ${q(c.userId)} AS "userId", ${q(c.value)} AS "value", ${epochMs} AS "ts"${readAge ? `, ${signedAge}` : ''} FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${q(c.type)} = $1 AND ${q(c.eventName)} = $2 AND ${q(c.ts)} >= $3 AND ${q(c.ts)} < $4${visitorFilter}`;
64
79
  const filterIds = userIds ?? unitIds;
65
80
  const column = userIds === undefined ? c.unitId : c.userId;
66
81
  const ids = filterIds === undefined ? undefined : [
@@ -77,7 +92,8 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
77
92
  unitId: row.unitId,
78
93
  userId: row.userId == null ? null : String(row.userId),
79
94
  value: Number(row.value),
80
- ts: Number(row.ts)
95
+ ts: Number(row.ts),
96
+ ...knownAge(row.unitAgeMs)
81
97
  });
82
98
  }
83
99
  if (ids === undefined) break;
@@ -13,6 +13,7 @@ export interface ResultsPhase extends AnalysisPhase {
13
13
  addedAt?: string;
14
14
  keyedBy?: UnitType;
15
15
  capNotice?: 'no-history';
16
+ browserWritable?: boolean;
16
17
  }>;
17
18
  }
18
19
  export interface ResultsCandidate {
@@ -5,6 +5,7 @@ import { Forbidden } from 'payload';
5
5
  import { XpRefusal } from '../errors.js';
6
6
  import { compileManifest, loadManifestInputs } from '../manifest/compile.js';
7
7
  import { publishedBlockPlacementPages } from '../transitions/placements.js';
8
+ import { API_MESSAGES } from '../testSurface/copy/common.js';
8
9
  import { routeId } from './routeId.js';
9
10
  /** Advisory read only. Delete keeps its own access check, status guard and transaction. */ export async function handleDeleteImpact(req, { options }) {
10
11
  const headers = {
@@ -39,7 +40,7 @@ import { routeId } from './routeId.js';
39
40
  });
40
41
  const experiment = docs[0];
41
42
  if (!experiment) throw new XpRefusal('not-found', 'Experiment not found', undefined, 404);
42
- if (experiment.status !== 'draft' && experiment.status !== 'archived') throw new XpRefusal('invalid-status', 'This test cannot be deleted in its current status.', undefined, 409);
43
+ if (experiment.status !== 'draft' && experiment.status !== 'archived') throw new XpRefusal('invalid-status', API_MESSAGES.deleteInvalidStatus, undefined, 409);
43
44
  const { decision, kind } = experiment;
44
45
  if (experiment.status === 'draft' || !decision?.winnerArm || decision.discardedAt || kind !== 'block' && kind !== 'page' || kind === 'page' && decision.pagesReleasedAt || kind === 'block' && decision.winnerArm === 'control') return reply({
45
46
  effect: 'none'
@@ -7,90 +7,154 @@ import { pooledExecutor } from '../db/executor.js';
7
7
  import { insertEvents } from '../db/events.js';
8
8
  import { EventsBodyError, readEvents } from '../events/body.js';
9
9
  import { isPreview } from '../events/preview.js';
10
- import { sourceRequest } from '../events/request.js';
10
+ import { eventRequestContext, publicEventOrigin } from '../events/request.js';
11
11
  import { eventRows } from '../events/rows.js';
12
12
  import { assign } from '../runtime/assign.js';
13
13
  import { isBot } from '../runtime/bot.js';
14
- import { readUnitCookie } from '../runtime/cookie.js';
14
+ import { readSignedUnit } from '../runtime/cookie.js';
15
15
  import { requestAttributes } from '../runtime/normalisePath.js';
16
16
  import { serverManifest } from '../server/context.js';
17
17
  const accepted = ()=>Response.json({}, {
18
18
  status: 202
19
19
  });
20
+ const originDrops = new WeakMap();
21
+ function logSessionLookupError(payload, error) {
22
+ try {
23
+ payload.logger.error({
24
+ err: safeError(error)
25
+ }, 'Experiments: events session lookup failed');
26
+ } catch {}
27
+ }
28
+ function countOriginDrop(payload, now) {
29
+ const drops = originDrops.get(payload) ?? {
30
+ count: 0,
31
+ nextLogAt: 0
32
+ };
33
+ originDrops.set(payload, drops);
34
+ drops.count++;
35
+ if (now < drops.nextLogAt) return;
36
+ drops.nextLogAt = now + 60_000;
37
+ try {
38
+ payload.logger.warn({
39
+ droppedRequests: drops.count
40
+ }, 'Experiments: browser event requests dropped by origin check');
41
+ drops.count = 0;
42
+ } catch {}
43
+ }
20
44
  export async function handleEvents(req, { options }) {
45
+ const receivedAt = Date.now();
21
46
  const runtime = options.runtime, proxy = runtime.proxyRuntime;
22
- const visitorId = readUnitCookie(req.headers, proxy);
23
- if (!visitorId) return Response.json({
24
- errors: [
25
- {
26
- code: 'unauthenticated',
27
- message: 'Invalid unit cookie'
28
- }
29
- ]
30
- }, {
31
- status: 401
32
- });
33
- let events;
34
- try {
35
- events = await readEvents(req.body, options.events?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
36
- } catch (error) {
37
- if (error instanceof EventsBodyError) return Response.json({
38
- errors: [
39
- {
40
- code: error.code,
41
- message: error.message
42
- }
43
- ]
44
- }, {
45
- status: error.status
46
- });
47
- throw error;
48
- }
47
+ const unitCookie = readSignedUnit(req.headers, proxy, receivedAt);
48
+ const visitorId = unitCookie?.unitId;
49
+ const issuedAtMs = unitCookie?.issuedAtMs;
50
+ const unitAgeMs = typeof issuedAtMs === 'number' ? receivedAt >= issuedAtMs ? receivedAt - issuedAtMs : null : issuedAtMs ?? null;
49
51
  try {
50
52
  const request = new NextRequest(req.url ?? 'https://xp.invalid/', {
51
53
  headers: req.headers,
52
54
  method: req.method
53
55
  });
56
+ const { allowed, source } = eventRequestContext(request, options.events?.origin ?? publicEventOrigin(req.payload.config?.serverURL));
57
+ if (!allowed) {
58
+ countOriginDrop(req.payload, receivedAt);
59
+ return accepted();
60
+ }
54
61
  // API paths bypass the proxy: re-check consent even when a stale signed cookie exists.
55
62
  try {
56
63
  if (proxy.cookie.consent?.(request) === false) return accepted();
57
64
  } catch {
58
65
  return accepted();
59
66
  }
60
- if (options.events?.rateLimit && await options.events.rateLimit({
67
+ const limit = options.events?.rateLimit;
68
+ if (visitorId && limit !== false && await limit?.({
61
69
  req,
62
- unitId: visitorId
70
+ unitId: visitorId,
71
+ unitType: 'visitor'
63
72
  }) !== true) return accepted();
73
+ // Payload and the host runtime verify sessions server-side. The page URL below
74
+ // supplies targeting attributes only, so it can never select a user identity.
75
+ let user = req.user ?? null;
76
+ let sessionUnresolved = false;
77
+ if (!user && runtime.getUser) {
78
+ try {
79
+ user = await runtime.getUser();
80
+ } catch (error) {
81
+ if (!visitorId) throw error;
82
+ sessionUnresolved = true;
83
+ logSessionLookupError(req.payload, error);
84
+ }
85
+ }
86
+ const useProxySession = !user && !runtime.getUser;
87
+ let requestUnit;
88
+ if (useProxySession) {
89
+ try {
90
+ requestUnit = await proxy.getUnit?.(request);
91
+ } catch (error) {
92
+ if (!visitorId) throw error;
93
+ sessionUnresolved = true;
94
+ logSessionLookupError(req.payload, error);
95
+ }
96
+ }
97
+ const userId = user ? runtime.userIdOf(user) : requestUnit?.sessionUnknown ? undefined : requestUnit?.userId;
98
+ if (!visitorId) {
99
+ if (!userId) return Response.json({
100
+ errors: [
101
+ {
102
+ code: 'unauthenticated',
103
+ message: 'A valid visitor cookie or signed-in session is required'
104
+ }
105
+ ]
106
+ }, {
107
+ status: 401
108
+ });
109
+ if (limit !== false && await limit?.({
110
+ req,
111
+ unitId: userId,
112
+ unitType: 'user'
113
+ }) !== true) return accepted();
114
+ }
115
+ const events = await readEvents(req.body, options.events?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
64
116
  const manifest = await serverManifest(proxy);
65
117
  if (!manifest) return accepted();
66
- const source = sourceRequest(request);
67
- const unit = await proxy.getUnit?.(source ?? request);
68
- const user = req.user ?? null;
69
- const userId = user ? runtime.userIdOf(user) : undefined;
118
+ const unit = source || !useProxySession ? await proxy.getUnit?.(source ?? request) : requestUnit;
70
119
  // The beacon URL is an API route, not the page whose content was rendered.
71
120
  // A referrer supplies page context only, never an identity or an assigned arm.
121
+ const serverAttributes = userId && !user ? {
122
+ loggedIn: true
123
+ } : runtime.attributesOf(user);
72
124
  const attributes = requestAttributes({
73
125
  ...unit?.attributes,
74
- ...runtime.attributesOf(user)
126
+ ...serverAttributes
75
127
  }, source?.nextUrl.pathname);
76
- const unresolvedStaff = Boolean(options.attributeKeys?.staff && unit?.sessionUnknown && !user);
128
+ const unresolvedStaff = Boolean(options.attributeKeys?.staff && !user && (sessionUnresolved || unit?.sessionUnknown || requestUnit?.sessionUnknown));
77
129
  const assignments = assign(manifest, {
78
130
  visitorId,
79
131
  userId
80
132
  }, attributes, {
81
133
  now: Math.floor(Date.now() / 1000),
82
134
  method: req.method,
83
- staff: unit?.attributes.staff === true || attributes.staff === true,
135
+ sessionUnknown: sessionUnresolved,
136
+ staff: requestUnit?.attributes.staff === true || unit?.attributes.staff === true || attributes.staff === true,
84
137
  bot: isBot(req.headers.get('user-agent')),
85
138
  preview: isPreview(request)
86
139
  });
87
140
  if (unresolvedStaff) for (const assignment of Object.values(assignments.bySlug))assignment.exposable = false;
88
141
  const keys = events.some((event)=>event && typeof event === 'object' && 'eventName' in event && validClickSource(event.eventName)) ? await clickKeys(req.payload) : undefined;
89
- const rows = eventRows(events, manifest, assignments, options, visitorId, userId, new Date().toISOString(), attributes, keys);
142
+ // Age measures arrival. Keep attribution at the time the round was validated.
143
+ const rows = eventRows(events, manifest, assignments, options, visitorId, userId, new Date().toISOString(), unitAgeMs, attributes, keys);
90
144
  // §7.8 events insert / assignment lookup exception: pooled SQL and cached manifest,
91
145
  // no Local API calls (and hence no implicit overrideAccess defaults).
92
146
  if (rows.length) await insertEvents(pooledExecutor(req.payload), rows, (message)=>req.payload.logger.error(message));
93
147
  } catch (error) {
148
+ if (error instanceof EventsBodyError) return Response.json({
149
+ errors: [
150
+ {
151
+ code: error.code,
152
+ message: error.message
153
+ }
154
+ ]
155
+ }, {
156
+ status: error.status
157
+ });
94
158
  try {
95
159
  req.payload.logger.error({
96
160
  err: safeError(error)
@@ -4,7 +4,6 @@ import { handleClickKeys } from './clickKeys.js';
4
4
  import { createHmac, timingSafeEqual } from 'node:crypto';
5
5
  import { XP_MANIFEST_KEY_HEADER } from '../constants.js';
6
6
  import { XpNotImplemented, XpRefusal } from '../errors.js';
7
- import { readUnitCookie } from '../runtime/cookie.js';
8
7
  import { handleManifest } from './manifest.js';
9
8
  import { handleEvents } from './events.js';
10
9
  import { handleStart, handleAllocate, handleAddMetric, handleStop, handleDecide, handleReleaseHoldout, handleReleasePages, handleMakeContent, handleDismissContentEntry, handleRestoreContentEntry, handleArchive } from './transitions.js';
@@ -26,7 +25,7 @@ export const ROUTES = [
26
25
  {
27
26
  method: 'post',
28
27
  path: '/xp/events',
29
- access: 'signedCookie',
28
+ access: 'browserEvents',
30
29
  handler: handleEvents
31
30
  },
32
31
  {
@@ -222,13 +221,8 @@ export function buildEndpoints(ctx) {
222
221
  if (!supplied || Buffer.byteLength(supplied) !== Buffer.byteLength(expected) || !timingSafeEqual(Buffer.from(supplied), Buffer.from(expected))) {
223
222
  return error(401, 'unauthenticated', 'Invalid manifest key');
224
223
  }
225
- } else {
226
- const visitorId = readUnitCookie(req.headers, options.runtime.proxyRuntime);
227
- if (!visitorId) return error(401, 'unauthenticated', 'Invalid unit cookie');
228
- handlerContext.unit = {
229
- visitorId
230
- };
231
224
  }
225
+ // The browser events handler checks consent, origin and both possible credentials.
232
226
  return await route.handler(req, handlerContext);
233
227
  } catch (cause) {
234
228
  if (cause instanceof XpRefusal) return error(cause.status, cause.code, cause.message, cause.detail);
@@ -134,13 +134,16 @@ export async function handlePlacementStatus(req, { options }) {
134
134
  name: test.name,
135
135
  status: test.status,
136
136
  kind: test.kind,
137
- arms: round.arms.map(({ key, label, slot })=>({
137
+ arms: round.arms.map(({ key, kind, label, slot })=>{
138
+ const contentSlot = test.kind === 'block' ? kind !== 'holdout' && key !== 'holdout' ? key : undefined : slot;
139
+ return {
138
140
  key,
139
141
  label,
140
- ...slot ? {
141
- slot
142
+ ...contentSlot ? {
143
+ slot: contentSlot
142
144
  } : {}
143
- })),
145
+ };
146
+ }),
144
147
  ...test.decision?.winnerArm ? {
145
148
  winnerArm: test.decision.winnerArm
146
149
  } : {},
@@ -21,4 +21,4 @@ export declare function handleResults<TUser extends {
21
21
  id: string | number;
22
22
  } = {
23
23
  id: string | number;
24
- }>(req: PayloadRequest, _ctx: EndpointContext<TUser>): Promise<Response>;
24
+ }>(req: PayloadRequest, { options }: EndpointContext<TUser>): Promise<Response>;
@@ -2,6 +2,7 @@ import { resultsMetadata, newestSnapshotIds } from '../db/snapshots.js';
2
2
  import { pooledExecutor } from '../db/executor.js';
3
3
  import { routeId } from './routeId.js';
4
4
  import { isClickSource } from '../goals/key.js';
5
+ import { browserWritableMetric } from '../events/writable.js';
5
6
  const headers = {
6
7
  'Cache-Control': 'no-store'
7
8
  };
@@ -53,7 +54,7 @@ export async function readSnapshots(req, ids, { per = 'phase', decisionId, serie
53
54
  numeric: true
54
55
  }));
55
56
  }
56
- export async function handleResults(req, _ctx) {
57
+ export async function handleResults(req, { options }) {
57
58
  const id = routeId(req);
58
59
  if (id === undefined) return resultsError(404, 'not-found', 'Experiment not found');
59
60
  const params = new URL(req.url ?? 'http://localhost').searchParams;
@@ -86,7 +87,7 @@ export async function handleResults(req, _ctx) {
86
87
  label,
87
88
  kind
88
89
  })),
89
- metrics: record.metricDefinitions.map(({ metricId, name, kind, role, source, resolvedCap, historyUnits, capNotice })=>({
90
+ metrics: record.metricDefinitions.map(({ metricId, name, kind, role, source, browserWritable, resolvedCap, historyUnits, capNotice })=>({
90
91
  metricId,
91
92
  name,
92
93
  kind,
@@ -94,6 +95,9 @@ export async function handleResults(req, _ctx) {
94
95
  ...isClickSource(source) ? {
95
96
  clickGoal: true
96
97
  } : {},
98
+ ...browserWritable === true || browserWritableMetric(source, options) ? {
99
+ browserWritable: true
100
+ } : {},
97
101
  ...resolvedCap === undefined ? {} : {
98
102
  resolvedCap
99
103
  },