@delmaredigital/payload-experiments 0.4.1 → 0.5.1
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/README.md +9 -5
- package/dist/admin/blocks/model.js +2 -0
- package/dist/admin/copy/blocks.d.ts +1 -0
- package/dist/admin/copy/blocks.js +1 -0
- package/dist/admin/copy/status.d.ts +3 -0
- package/dist/admin/copy/status.js +3 -0
- package/dist/admin/placementStatus.model.js +3 -0
- package/dist/admin/status.model.d.ts +3 -2
- package/dist/admin/status.model.js +9 -3
- package/dist/admin/surface/ResultsRoute.js +2 -1
- package/dist/admin/surface/TestsHome.d.ts +2 -1
- package/dist/admin/surface/TestsHome.js +31 -11
- package/dist/admin/surface/TestsSurface.js +4 -0
- package/dist/admin/surface/home.model.d.ts +11 -6
- package/dist/admin/surface/home.model.js +19 -8
- package/dist/admin/surface/newTest/PageWizard.js +13 -3
- package/dist/admin/surface/results/ResultsHeader.js +43 -9
- package/dist/admin/surface/test/TestPage.js +11 -1
- package/dist/admin/useLayerUsage.d.ts +1 -1
- package/dist/admin/views/buildSurfaceProps.js +3 -0
- package/dist/blocks/placementLocale.d.ts +14 -0
- package/dist/blocks/placementLocale.js +80 -13
- package/dist/blocks/placementPublication.d.ts +14 -0
- package/dist/blocks/placementPublication.js +24 -0
- package/dist/cohorts/build.d.ts +35 -0
- package/dist/cohorts/build.js +134 -0
- package/dist/cohorts/key.d.ts +12 -0
- package/dist/cohorts/key.js +15 -0
- package/dist/cohorts/maintenance.d.ts +10 -0
- package/dist/cohorts/maintenance.js +70 -0
- package/dist/cohorts/readiness.d.ts +30 -0
- package/dist/cohorts/readiness.js +54 -0
- package/dist/cohorts/readinessData.d.ts +29 -0
- package/dist/cohorts/readinessData.js +123 -0
- package/dist/cohorts/rule.d.ts +33 -0
- package/dist/cohorts/rule.js +50 -0
- package/dist/collections/cohortMembers.d.ts +4 -0
- package/dist/collections/cohortMembers.js +95 -0
- package/dist/collections/experiments/config.js +157 -7
- package/dist/collections/experiments/editability.js +10 -6
- package/dist/collections/experiments/lockHook.js +39 -20
- package/dist/collections/index.js +4 -1
- package/dist/collections/phases.js +4 -1
- package/dist/constants.d.ts +2 -0
- package/dist/constants.js +2 -0
- package/dist/db/adapter.d.ts +2 -1
- package/dist/db/adapter.js +17 -4
- package/dist/db/appends.d.ts +2 -1
- package/dist/db/appends.js +3 -2
- package/dist/db/bulkPlacementRemoval.d.ts +5 -0
- package/dist/db/bulkPlacementRemoval.js +7 -2
- package/dist/db/cohortMembership.d.ts +11 -0
- package/dist/db/cohortMembership.js +31 -0
- package/dist/db/cohortPool.d.ts +9 -0
- package/dist/db/cohortPool.js +53 -0
- package/dist/db/cohortTransactions.d.ts +3 -0
- package/dist/db/cohortTransactions.js +52 -0
- package/dist/db/cohorts.d.ts +72 -0
- package/dist/db/cohorts.js +280 -0
- package/dist/db/erase.d.ts +2 -0
- package/dist/db/erase.js +21 -2
- package/dist/db/events.d.ts +2 -0
- package/dist/db/events.js +8 -0
- package/dist/db/executor.d.ts +2 -0
- package/dist/db/executor.js +8 -0
- package/dist/db/locks.d.ts +7 -0
- package/dist/db/locks.js +13 -1
- package/dist/db/names.d.ts +95 -1
- package/dist/db/names.js +95 -1
- package/dist/db/occupancy.d.ts +21 -0
- package/dist/db/occupancy.js +46 -0
- package/dist/db/pageBindings.d.ts +2 -2
- package/dist/db/pageBindings.js +3 -3
- package/dist/db/pageOccupancy.d.ts +4 -4
- package/dist/db/pageOccupancy.js +13 -10
- package/dist/db/pgExecutor.d.ts +4 -0
- package/dist/db/pgExecutor.js +1 -1
- package/dist/db/placements.d.ts +6 -1
- package/dist/db/placements.js +27 -1
- package/dist/db/results.d.ts +5 -2
- package/dist/db/results.js +32 -5
- package/dist/db/slices.d.ts +9 -2
- package/dist/db/slices.js +15 -8
- package/dist/db/snapshots.d.ts +16 -1
- package/dist/db/snapshots.js +27 -2
- package/dist/db/sql.d.ts +2 -2
- package/dist/db/sql.js +1 -2
- package/dist/endpoints/cohortSources.d.ts +16 -0
- package/dist/endpoints/cohortSources.js +335 -0
- package/dist/endpoints/contentLocale.d.ts +1 -1
- package/dist/endpoints/duplicateOriginal.d.ts +1 -0
- package/dist/endpoints/events.js +82 -18
- package/dist/endpoints/index.js +45 -1
- package/dist/endpoints/pausedBy.d.ts +14 -0
- package/dist/endpoints/pausedBy.js +94 -0
- package/dist/endpoints/preflight.js +4 -1
- package/dist/endpoints/previewToken.js +2 -0
- package/dist/endpoints/results.d.ts +2 -2
- package/dist/endpoints/results.js +111 -3
- package/dist/endpoints/routeId.d.ts +2 -1
- package/dist/endpoints/routeId.js +6 -2
- package/dist/endpoints/summary.js +24 -1
- package/dist/endpoints/transitions.d.ts +7 -0
- package/dist/endpoints/transitions.js +50 -1
- package/dist/events/rows.d.ts +1 -1
- package/dist/events/rows.js +5 -3
- package/dist/exports/index.d.ts +2 -0
- package/dist/exports/index.js +1 -0
- package/dist/exports/runtimeProxy.d.ts +1 -0
- package/dist/exports/runtimeProxy.js +1 -0
- package/dist/hooks/blockRemovalRule.d.ts +1 -1
- package/dist/hooks/blockRemovalRule.js +12 -8
- package/dist/hooks/pageGuard.d.ts +7 -1
- package/dist/hooks/pageGuard.js +177 -4
- package/dist/hooks/puckNestedTests.d.ts +1 -1
- package/dist/hooks/puckNestedTests.js +3 -1
- package/dist/labels/status.d.ts +15 -0
- package/dist/labels/status.js +12 -0
- package/dist/manifest/compile.d.ts +15 -4
- package/dist/manifest/compile.js +91 -3
- package/dist/onInit.js +4 -6
- package/dist/options.d.ts +1 -0
- package/dist/options.js +10 -0
- package/dist/proxy/consentFallback.d.ts +1 -1
- package/dist/proxy/consentFallback.js +4 -4
- package/dist/proxy/control.d.ts +1 -1
- package/dist/proxy/control.js +2 -2
- package/dist/proxy/pageRewrite.d.ts +1 -1
- package/dist/proxy/pageRewrite.js +3 -2
- package/dist/proxy/resolve.js +76 -17
- package/dist/puck/ExperimentPicker.js +2 -1
- package/dist/puck/copy.d.ts +6 -5
- package/dist/puck/copy.js +3 -7
- package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
- package/dist/puck/editor/QuickTestActions.js +7 -1
- package/dist/puck/editor/armWrites.js +6 -1
- package/dist/puck/editor/copy.d.ts +3 -0
- package/dist/puck/editor/copy.js +3 -0
- package/dist/puck/editor/editor.css +2 -1
- package/dist/puck/editor/editor.model.d.ts +2 -1
- package/dist/puck/editor/editor.model.js +2 -0
- package/dist/puck/editor/placementsCache.d.ts +1 -1
- package/dist/puck/editor/placementsCache.js +6 -3
- package/dist/results/analyse.d.ts +3 -1
- package/dist/results/analyse.js +20 -3
- package/dist/results/health.d.ts +11 -0
- package/dist/results/health.js +38 -0
- package/dist/results/power.d.ts +1 -1
- package/dist/results/power.js +1 -1
- package/dist/results/snapshot.d.ts +8 -2
- package/dist/results/snapshot.js +23 -1
- package/dist/results/unitValues.d.ts +48 -0
- package/dist/results/unitValues.js +166 -0
- package/dist/runtime/assign.d.ts +7 -3
- package/dist/runtime/assign.js +12 -4
- package/dist/runtime/cohortCookie.d.ts +15 -0
- package/dist/runtime/cohortCookie.js +72 -0
- package/dist/runtime/cohortLookup.d.ts +9 -0
- package/dist/runtime/cohortLookup.js +25 -0
- package/dist/runtime/eligibility.d.ts +11 -5
- package/dist/runtime/eligibility.js +33 -7
- package/dist/runtime/header.d.ts +1 -0
- package/dist/runtime/header.js +1 -1
- package/dist/runtime/proxyRuntime.js +5 -1
- package/dist/runtime/targeting.d.ts +3 -2
- package/dist/runtime/targeting.js +2 -1
- package/dist/sanitizeReadinessDetail.d.ts +2 -2
- package/dist/sanitizeReadinessDetail.js +41 -4
- package/dist/schedule/activeTime.d.ts +28 -0
- package/dist/schedule/activeTime.js +322 -0
- package/dist/schedule/ranges.d.ts +13 -0
- package/dist/schedule/ranges.js +11 -0
- package/dist/schedule/roundTime.d.ts +10 -0
- package/dist/schedule/roundTime.js +45 -0
- package/dist/schedule/types.d.ts +29 -0
- package/dist/schedule/types.js +1 -0
- package/dist/server/cohortLookup.d.ts +3 -0
- package/dist/server/cohortLookup.js +7 -0
- package/dist/server/eraseUser.d.ts +1 -0
- package/dist/server/getAssignments.js +63 -40
- package/dist/server/previewDraft.d.ts +1 -1
- package/dist/server/previewDraft.js +3 -2
- package/dist/server/recordContentChange.d.ts +1 -1
- package/dist/server/recordContentChange.js +42 -20
- package/dist/server/recordExposures.js +4 -2
- package/dist/server/runResults.js +97 -150
- package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
- package/dist/testSurface/actions/LifecycleAction.js +15 -5
- package/dist/testSurface/actions/actions.model.d.ts +13 -2
- package/dist/testSurface/actions/actions.model.js +38 -5
- package/dist/testSurface/api.d.ts +13 -1
- package/dist/testSurface/api.js +19 -0
- package/dist/testSurface/copy/actions.d.ts +13 -0
- package/dist/testSurface/copy/actions.js +13 -0
- package/dist/testSurface/copy/cohorts.d.ts +68 -0
- package/dist/testSurface/copy/cohorts.js +81 -0
- package/dist/testSurface/copy/common.d.ts +2 -3
- package/dist/testSurface/copy/common.js +4 -4
- package/dist/testSurface/copy/inputs.d.ts +3 -0
- package/dist/testSurface/copy/inputs.js +3 -0
- package/dist/testSurface/copy/readiness.d.ts +20 -6
- package/dist/testSurface/copy/readiness.js +42 -9
- package/dist/testSurface/copy/results.d.ts +1 -0
- package/dist/testSurface/copy/results.js +1 -0
- package/dist/testSurface/copy/schedule.d.ts +58 -0
- package/dist/testSurface/copy/schedule.js +150 -0
- package/dist/testSurface/copy/surface.d.ts +2 -0
- package/dist/testSurface/copy/surface.js +2 -0
- package/dist/testSurface/copy/testPage.d.ts +12 -2
- package/dist/testSurface/copy/testPage.js +17 -2
- package/dist/testSurface/format/roundProgress.d.ts +13 -1
- package/dist/testSurface/format/roundProgress.js +34 -5
- package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
- package/dist/testSurface/format/scheduleStatus.js +93 -0
- package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
- package/dist/testSurface/format/useScheduleClock.js +20 -0
- package/dist/testSurface/labels.d.ts +4 -9
- package/dist/testSurface/labels.js +2 -7
- package/dist/testSurface/lockedNotice.model.d.ts +2 -2
- package/dist/testSurface/lockedNotice.model.js +16 -3
- package/dist/testSurface/readPreflight.d.ts +3 -0
- package/dist/testSurface/readPreflight.js +14 -0
- package/dist/testSurface/readinessRead.d.ts +2 -2
- package/dist/testSurface/results/DataQualityPanel.js +7 -7
- package/dist/testSurface/results/results.model.d.ts +1 -1
- package/dist/testSurface/results/results.model.js +34 -6
- package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
- package/dist/testSurface/review/cohortEstimate.js +32 -0
- package/dist/testSurface/surface/contracts.d.ts +2 -1
- package/dist/testSurface/surface/contracts.js +1 -0
- package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
- package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
- package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
- package/dist/testSurface/surface/readiness/Banner.js +29 -11
- package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
- package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
- package/dist/testSurface/surface/readiness/useTransition.js +17 -5
- package/dist/testSurface/surface/results/ResultsBody.js +44 -8
- package/dist/testSurface/surface/results/useResults.d.ts +16 -1
- package/dist/testSurface/surface/results/useResults.js +17 -6
- package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
- package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
- package/dist/testSurface/surface/test/LengthSection.js +26 -6
- package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
- package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
- package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
- package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
- package/dist/testSurface/surface/test/Section.js +1 -1
- package/dist/testSurface/surface/test/TargetingSection.js +306 -182
- package/dist/testSurface/surface/test/TestSurface.js +9 -0
- package/dist/testSurface/surface/test/fields.d.ts +2 -1
- package/dist/testSurface/surface/test/fields.js +3 -3
- package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
- package/dist/testSurface/surface/test/jumpToSection.js +4 -4
- package/dist/testSurface/surface/test/testPage.css +26 -0
- package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
- package/dist/testSurface/surface/testDocument.model.js +2 -1
- package/dist/testSurface/surface/useTestDocument.js +11 -4
- package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
- package/dist/testSurface/targeting/targeting.model.js +1 -1
- package/dist/testSurface/useApi.d.ts +12 -0
- package/dist/transitions/addMetric.js +5 -2
- package/dist/transitions/allocate.js +6 -1
- package/dist/transitions/assertNoOverlap.d.ts +9 -0
- package/dist/transitions/assertNoOverlap.js +24 -0
- package/dist/transitions/buildCohorts.d.ts +10 -0
- package/dist/transitions/buildCohorts.js +68 -0
- package/dist/transitions/cancelSchedule.d.ts +4 -0
- package/dist/transitions/cancelSchedule.js +42 -0
- package/dist/transitions/checkStart.d.ts +17 -3
- package/dist/transitions/checkStart.js +20 -7
- package/dist/transitions/decide.js +40 -13
- package/dist/transitions/kernel.d.ts +3 -1
- package/dist/transitions/kernel.js +5 -2
- package/dist/transitions/pause.d.ts +4 -0
- package/dist/transitions/pause.js +35 -0
- package/dist/transitions/phaseRecord.d.ts +19 -2
- package/dist/transitions/phaseRecord.js +50 -11
- package/dist/transitions/placementInteractions.d.ts +7 -2
- package/dist/transitions/placementInteractions.js +9 -7
- package/dist/transitions/placements.d.ts +4 -3
- package/dist/transitions/placements.js +28 -14
- package/dist/transitions/preflightData.d.ts +11 -3
- package/dist/transitions/preflightData.js +134 -81
- package/dist/transitions/reschedule.d.ts +4 -0
- package/dist/transitions/reschedule.js +58 -0
- package/dist/transitions/resume.d.ts +4 -0
- package/dist/transitions/resume.js +32 -0
- package/dist/transitions/scheduledRound.d.ts +18 -0
- package/dist/transitions/scheduledRound.js +42 -0
- package/dist/transitions/start.d.ts +4 -0
- package/dist/transitions/start.js +139 -56
- package/dist/transitions/startReads.d.ts +14 -0
- package/dist/transitions/startReads.js +27 -0
- package/dist/transitions/stop.d.ts +10 -0
- package/dist/transitions/stop.js +35 -22
- package/dist/types/admin.d.ts +1 -1
- package/dist/types/contracts.d.ts +7 -1
- package/dist/types/endpoints.d.ts +72 -3
- package/dist/types/manifest.d.ts +9 -0
- package/dist/types/runtime.d.ts +5 -0
- package/dist/types/snapshot.d.ts +10 -0
- package/dist/types/status.d.ts +1 -0
- package/dist/types/status.js +1 -0
- package/dist/types/surface.d.ts +1 -0
- package/dist/ui/Feedback.d.ts +9 -6
- package/dist/ui/Feedback.js +10 -9
- package/dist/ui/SelectControl.js +1 -1
- package/dist/ui/ui.css +2 -1
- package/package.json +2 -2
package/dist/db/snapshots.d.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
|
+
import type { FrozenCohortRule } from '../cohorts/rule.js';
|
|
2
|
+
import type { TargetingRule } from '../types/contracts.js';
|
|
1
3
|
import type { Payload } from 'payload';
|
|
2
4
|
import type { Arm, DocId, ExperimentKind, Status, UnitType } from '../types/contracts.js';
|
|
3
5
|
import type { PlacementDoc } from './placements.js';
|
|
4
6
|
import type { Snapshot } from '../types/snapshot.js';
|
|
5
7
|
import type { AnalysisPhase, FrozenMetric } from '../results/analyse.js';
|
|
6
8
|
import { type Executor } from './executor.js';
|
|
9
|
+
import type { RoundTiming } from '../schedule/types.js';
|
|
7
10
|
export interface ResultsPhase extends AnalysisPhase {
|
|
8
11
|
arms: Array<AnalysisPhase['arms'][number] & Pick<Arm, 'pageTarget'>>;
|
|
12
|
+
targeting?: Array<TargetingRule | FrozenCohortRule>;
|
|
9
13
|
seed: string;
|
|
10
14
|
allocation: number;
|
|
11
15
|
metricDefinitions: Array<FrozenMetric & {
|
|
@@ -27,7 +31,7 @@ export interface ResultsCandidate {
|
|
|
27
31
|
currentPhase?: number;
|
|
28
32
|
winnerArm?: string | null;
|
|
29
33
|
unitType: UnitType;
|
|
30
|
-
status:
|
|
34
|
+
status: Exclude<Status, 'draft'>;
|
|
31
35
|
latestComputedAt: string | null;
|
|
32
36
|
testArms: Array<{
|
|
33
37
|
key: string;
|
|
@@ -42,6 +46,12 @@ export interface ResultsCandidate {
|
|
|
42
46
|
/** Each query gets its own pooled connection and timeout transaction. A failed
|
|
43
47
|
* metric query cannot poison the next metric's transaction. */
|
|
44
48
|
export declare function resultsExecutor(payload: Payload, timeoutMs: () => number): Executor;
|
|
49
|
+
export declare const LATE_BEACON_GRACE_MS: number;
|
|
50
|
+
/** The claim end mirrors the frozen schedule. Stop verifies the phase under its locks. */
|
|
51
|
+
export declare function dueScheduledStops(exec: Executor, now: string, experimentId?: DocId): Promise<{
|
|
52
|
+
id: DocId;
|
|
53
|
+
phase: number;
|
|
54
|
+
}[]>;
|
|
45
55
|
/** Scheduling and immutable assignment metadata only; metric/config data comes
|
|
46
56
|
* from the phase JSON, never from live metric or experiment analysis fields. */
|
|
47
57
|
export declare function resultsCandidates(exec: Executor, { cutoff, experimentId }: {
|
|
@@ -55,6 +65,11 @@ export declare function writeSnapshots(exec: Executor, snapshots: Snapshot[]): P
|
|
|
55
65
|
/** Fetch pointers only, then the endpoint reads the bounded set through Payload
|
|
56
66
|
* with req/overrideAccess:false. Called behind the readResults/manage gate. */
|
|
57
67
|
export declare function newestSnapshotIds(exec: Executor, ids: DocId[], per: 'phase' | 'experiment'): Promise<DocId[]>;
|
|
68
|
+
/** Current timing for the bounded results summary, even before the first snapshot. */
|
|
69
|
+
export declare function currentRoundTiming(exec: Executor, ids: DocId[]): Promise<(RoundTiming & {
|
|
70
|
+
experiment: DocId;
|
|
71
|
+
phase: number;
|
|
72
|
+
})[]>;
|
|
58
73
|
type ResultsMetadata = {
|
|
59
74
|
name: string | null;
|
|
60
75
|
kind: ExperimentKind;
|
package/dist/db/snapshots.js
CHANGED
|
@@ -16,7 +16,21 @@ import { qualifiedTable, quoteIdentifier as q } from './sql.js';
|
|
|
16
16
|
}
|
|
17
17
|
// CORE-16 README: allow late beacons for 24 hours after a phase ends, then keep
|
|
18
18
|
// its final snapshot frozen. This is internal scheduling policy, not public API.
|
|
19
|
-
const LATE_BEACON_GRACE_MS = 24 * 60 * 60 * 1000;
|
|
19
|
+
export const LATE_BEACON_GRACE_MS = 24 * 60 * 60 * 1000;
|
|
20
|
+
/** The claim end mirrors the frozen schedule. Stop verifies the phase under its locks. */ export async function dueScheduledStops(exec, now, experimentId) {
|
|
21
|
+
const e = COLUMNS.experiments;
|
|
22
|
+
const { rows } = await exec.query(`SELECT ${q(e.id)} AS "id", ${q(e.phase)} AS "phase"
|
|
23
|
+
FROM ${qualifiedTable(exec, TABLES.experiments)}
|
|
24
|
+
WHERE ${q(e.status)} = 'running' AND ${q(e.claimTo)} <= $1
|
|
25
|
+
${experimentId === undefined ? '' : `AND ${q(e.id)} = $2`}
|
|
26
|
+
ORDER BY ${q(e.claimTo)}, ${q(e.id)}`, experimentId === undefined ? [
|
|
27
|
+
now
|
|
28
|
+
] : [
|
|
29
|
+
now,
|
|
30
|
+
experimentId
|
|
31
|
+
]);
|
|
32
|
+
return rows;
|
|
33
|
+
}
|
|
20
34
|
/** Scheduling and immutable assignment metadata only; metric/config data comes
|
|
21
35
|
* from the phase JSON, never from live metric or experiment analysis fields. */ export async function resultsCandidates(exec, { cutoff, experimentId }) {
|
|
22
36
|
const p = COLUMNS.phases, e = COLUMNS.experiments, s = COLUMNS.resultsSnapshots, l = COLUMNS.layers;
|
|
@@ -30,7 +44,8 @@ const LATE_BEACON_GRACE_MS = 24 * 60 * 60 * 1000;
|
|
|
30
44
|
jsonb_build_object('experiment', p.${q(p.experimentId)}, 'phase', p.${q(p.phase)}, 'phaseKind', p.${q(p.phaseKind)},
|
|
31
45
|
'startedAt', p.${q(p.startedAt)}, 'endedAt', p.${q(p.endedAt)}, 'seed', p.${q(p.seed)},
|
|
32
46
|
'arms', p.${q(p.arms)}, 'allocation', p.${q(p.allocation)}, 'metricDefinitions', p.${q(p.metricDefinitions)},
|
|
33
|
-
'analysis', p.${q(p.analysis)}, 'contentChanges', p.${q(p.contentChanges)}
|
|
47
|
+
'analysis', p.${q(p.analysis)}, 'targeting', p.${q(p.targeting)}, 'contentChanges', p.${q(p.contentChanges)},
|
|
48
|
+
'schedule', p.${q(p.schedule)}, 'pauses', p.${q(p.pauses)}) AS "phase",
|
|
34
49
|
e.${q(e.slug)} AS "slug",
|
|
35
50
|
(SELECT t.${q(p.placementDocs)} FROM ${phases} t WHERE t.${q(p.experimentId)} = p.${q(p.experimentId)} AND t.${q(p.phaseKind)} = 'test' AND t.${q(p.phase)} <= p.${q(p.phase)} ORDER BY t.${q(p.phase)} DESC LIMIT 1) AS "testPlacementDocs",
|
|
36
51
|
e.${q(e.pageCollection)} AS "pageCollection", e.${q(e.kind)} AS "kind", e.${q(e.phase)} AS "currentPhase", e.${q(e.unitType)} AS "unitType", e.${q(e.status)} AS "status", e.${q(e.decisionWinnerArm)} AS "winnerArm",
|
|
@@ -99,6 +114,16 @@ export async function writeSnapshot(exec, snapshot) {
|
|
|
99
114
|
const { rows } = await exec.query(`SELECT DISTINCT ON (${partition}) ${q(c.id)} AS "id" FROM ${qualifiedTable(exec, TABLES.resultsSnapshots)} WHERE ${q(c.experimentId)} IN (${placeholders.join(', ')}) ORDER BY ${partition}, ${q(c.computedAt)} DESC, ${q(c.id)} DESC`, params);
|
|
100
115
|
return rows.map((row)=>row.id);
|
|
101
116
|
}
|
|
117
|
+
/** Current timing for the bounded results summary, even before the first snapshot. */ export async function currentRoundTiming(exec, ids) {
|
|
118
|
+
if (!ids.length) return [];
|
|
119
|
+
const p = COLUMNS.phases, e = COLUMNS.experiments;
|
|
120
|
+
const { rows } = await exec.query(`SELECT p.${q(p.experimentId)} AS "experiment", p.${q(p.phase)} AS "phase", p.${q(p.schedule)} AS "schedule", p.${q(p.pauses)} AS "pauses"
|
|
121
|
+
FROM ${qualifiedTable(exec, TABLES.phases)} p JOIN ${qualifiedTable(exec, TABLES.experiments)} e
|
|
122
|
+
ON e.${q(e.id)} = p.${q(p.experimentId)} AND e.${q(e.phase)} = p.${q(p.phase)}
|
|
123
|
+
WHERE p.${q(p.experimentId)} IN (${ids.map((_, index)=>`$${index + 1}`).join(', ')}) AND p.${q(p.endedAt)} IS NULL
|
|
124
|
+
AND (p.${q(p.schedule)} IS NOT NULL OR p.${q(p.pauses)} <> '[]'::jsonb)`, ids);
|
|
125
|
+
return rows;
|
|
126
|
+
}
|
|
102
127
|
/** Called only behind the endpoint's readResults gate. Experiment collection
|
|
103
128
|
* reads require manage, so read only the identity and decision metadata needed by results. */ export async function resultsMetadata(exec, id) {
|
|
104
129
|
const c = COLUMNS.experiments;
|
package/dist/db/sql.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { Executor } from './
|
|
1
|
+
import type { Executor } from './pgExecutor.js';
|
|
2
2
|
/** Quote schema/table/column identifiers; data values still use parameters. */
|
|
3
3
|
export declare const quoteIdentifier: (name: string) => string;
|
|
4
4
|
/** Preserve the schema carried by the request's executor for raw plugin SQL. */
|
|
5
|
-
export declare function qualifiedTable(
|
|
5
|
+
export declare function qualifiedTable({ schemaName }: Partial<Executor>, name: string): string;
|
package/dist/db/sql.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
/** Quote schema/table/column identifiers; data values still use parameters. */ export const quoteIdentifier = (name)=>`"${name.replaceAll('"', '""')}"`;
|
|
2
|
-
/** Preserve the schema carried by the request's executor for raw plugin SQL. */ export function qualifiedTable(
|
|
3
|
-
const schemaName = exec.schemaName;
|
|
2
|
+
/** Preserve the schema carried by the request's executor for raw plugin SQL. */ export function qualifiedTable({ schemaName }, name) {
|
|
4
3
|
return `${schemaName ? `${quoteIdentifier(schemaName)}.` : ''}${quoteIdentifier(name)}`;
|
|
5
4
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
import type { DocId } from '../types/contracts.js';
|
|
3
|
+
import type { CohortSourceRound, EndpointContext } from '../types/endpoints.js';
|
|
4
|
+
/** Load saved choices directly so a previously chosen source is available even outside the search cap. */
|
|
5
|
+
export declare function savedCohortSources<TUser extends {
|
|
6
|
+
id: DocId;
|
|
7
|
+
}>(req: PayloadRequest, options: EndpointContext<TUser>['options'], ids: string[]): Promise<{
|
|
8
|
+
id: DocId;
|
|
9
|
+
name: string;
|
|
10
|
+
status: "running" | "decided" | "draft" | "paused" | "stopped" | "archived" | "scheduled";
|
|
11
|
+
unitType: import("../types/contracts.js").UnitType;
|
|
12
|
+
rounds: CohortSourceRound[];
|
|
13
|
+
}[]>;
|
|
14
|
+
export declare function handleCohortSources<TUser extends {
|
|
15
|
+
id: DocId;
|
|
16
|
+
}>(req: PayloadRequest, { options }: EndpointContext<TUser>): Promise<Response>;
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import { latestCohortRounds } from '../db/cohorts.js';
|
|
2
|
+
import { reachesTarget } from '../cohorts/readinessData.js';
|
|
3
|
+
import { cohortRelationshipId } from '../cohorts/rule.js';
|
|
4
|
+
import { pooledExecutor } from '../db/executor.js';
|
|
5
|
+
import { LATE_BEACON_GRACE_MS } from '../db/snapshots.js';
|
|
6
|
+
import { timestampMs } from '../results/aggregate.js';
|
|
7
|
+
import { COHORT_EDITOR } from '../testSurface/copy/cohorts.js';
|
|
8
|
+
import { displayStatus } from '../testSurface/labels.js';
|
|
9
|
+
import { experimentId } from './routeId.js';
|
|
10
|
+
import { phasesCollection } from '../collections/phases.js';
|
|
11
|
+
import { readSnapshots, resultsError } from './results.js';
|
|
12
|
+
const PAGE_SIZE = 20;
|
|
13
|
+
/** Round numbers and dates follow xp-phases read access exactly: the collection's own access function
|
|
14
|
+
* (built from the same options), called with the manager's req. */ async function canReadPhases(req, options) {
|
|
15
|
+
// phasesCollection reads only options.access.
|
|
16
|
+
const read = phasesCollection(options).access?.read;
|
|
17
|
+
if (typeof read !== 'function') return false;
|
|
18
|
+
try {
|
|
19
|
+
return await read({
|
|
20
|
+
req
|
|
21
|
+
}) === true;
|
|
22
|
+
} catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const LIVE = [
|
|
27
|
+
'running',
|
|
28
|
+
'paused'
|
|
29
|
+
];
|
|
30
|
+
const PAST = [
|
|
31
|
+
'draft',
|
|
32
|
+
'stopped',
|
|
33
|
+
'decided',
|
|
34
|
+
'archived'
|
|
35
|
+
];
|
|
36
|
+
function roundDates(start, end) {
|
|
37
|
+
return {
|
|
38
|
+
startedAt: new Date(timestampMs(start)).toISOString(),
|
|
39
|
+
endedAt: end == null ? null : new Date(timestampMs(end)).toISOString(),
|
|
40
|
+
closedAt: end == null ? null : new Date(timestampMs(end) + LATE_BEACON_GRACE_MS).toISOString()
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function roundVersions(arms) {
|
|
44
|
+
return arms.map(({ key, label, kind })=>({
|
|
45
|
+
key: key,
|
|
46
|
+
label,
|
|
47
|
+
kind
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
function snapshotEstimate({ computedAt, snapshot }, round) {
|
|
51
|
+
return {
|
|
52
|
+
computedAt,
|
|
53
|
+
perArm: Object.fromEntries(round.arms.map(({ key })=>[
|
|
54
|
+
key,
|
|
55
|
+
{
|
|
56
|
+
exposed: snapshot.exposures.perArm[key] ?? 0,
|
|
57
|
+
converters: Object.fromEntries(snapshot.metrics.flatMap((metric)=>{
|
|
58
|
+
const count = metric.unavailable === undefined ? metric.perArm.find((arm)=>arm.arm === key)?.converters : undefined;
|
|
59
|
+
return count === undefined ? [] : [
|
|
60
|
+
[
|
|
61
|
+
String(metric.metricId),
|
|
62
|
+
count
|
|
63
|
+
]
|
|
64
|
+
];
|
|
65
|
+
}))
|
|
66
|
+
}
|
|
67
|
+
]))
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
async function frozenRounds(req, ids) {
|
|
71
|
+
const { docs } = await req.payload.find({
|
|
72
|
+
collection: 'xp-phases',
|
|
73
|
+
req,
|
|
74
|
+
overrideAccess: false,
|
|
75
|
+
depth: 0,
|
|
76
|
+
pagination: false,
|
|
77
|
+
limit: 0,
|
|
78
|
+
where: {
|
|
79
|
+
and: [
|
|
80
|
+
{
|
|
81
|
+
experiment: {
|
|
82
|
+
in: ids
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
phaseKind: {
|
|
87
|
+
equals: 'test'
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
]
|
|
91
|
+
},
|
|
92
|
+
sort: '-phase'
|
|
93
|
+
});
|
|
94
|
+
const roundsByTest = new Map();
|
|
95
|
+
for (const record of docs.sort((a, b)=>b.phase - a.phase)){
|
|
96
|
+
const key = String(record.experiment);
|
|
97
|
+
const rounds = roundsByTest.get(key) ?? [];
|
|
98
|
+
rounds.push({
|
|
99
|
+
phase: record.phase,
|
|
100
|
+
...roundDates(record.startedAt, record.endedAt),
|
|
101
|
+
arms: roundVersions(record.arms),
|
|
102
|
+
goals: record.metricDefinitions.map(({ metricId, name })=>({
|
|
103
|
+
metricId,
|
|
104
|
+
name
|
|
105
|
+
}))
|
|
106
|
+
});
|
|
107
|
+
roundsByTest.set(key, rounds);
|
|
108
|
+
}
|
|
109
|
+
return roundsByTest;
|
|
110
|
+
}
|
|
111
|
+
function metricIds(metrics) {
|
|
112
|
+
return [
|
|
113
|
+
metrics?.primary,
|
|
114
|
+
...metrics?.secondary ?? [],
|
|
115
|
+
...metrics?.guardrails ?? []
|
|
116
|
+
].flatMap((value)=>{
|
|
117
|
+
const id = cohortRelationshipId(value);
|
|
118
|
+
return id == null ? [] : [
|
|
119
|
+
id
|
|
120
|
+
];
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/** Without xp-phases read access, show no round number or dates: only the test document's own fields. */ async function currentRounds(req, candidates) {
|
|
124
|
+
const goals = [
|
|
125
|
+
...new Set(candidates.flatMap((doc)=>metricIds(doc.metrics)))
|
|
126
|
+
];
|
|
127
|
+
const names = new Map();
|
|
128
|
+
if (goals.length) {
|
|
129
|
+
const { docs } = await req.payload.find({
|
|
130
|
+
collection: 'xp-metrics',
|
|
131
|
+
req,
|
|
132
|
+
overrideAccess: false,
|
|
133
|
+
depth: 0,
|
|
134
|
+
pagination: false,
|
|
135
|
+
limit: 0,
|
|
136
|
+
where: {
|
|
137
|
+
id: {
|
|
138
|
+
in: goals
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
select: {
|
|
142
|
+
name: true
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
for (const doc of docs)names.set(String(doc.id), String(doc.name));
|
|
146
|
+
}
|
|
147
|
+
const roundsByTest = new Map();
|
|
148
|
+
for (const doc of candidates){
|
|
149
|
+
roundsByTest.set(String(doc.id), [
|
|
150
|
+
{
|
|
151
|
+
phase: null,
|
|
152
|
+
startedAt: null,
|
|
153
|
+
endedAt: null,
|
|
154
|
+
closedAt: null,
|
|
155
|
+
arms: roundVersions(doc.arms),
|
|
156
|
+
goals: metricIds(doc.metrics).flatMap((metricId)=>{
|
|
157
|
+
const name = names.get(String(metricId));
|
|
158
|
+
return name === undefined ? [] : [
|
|
159
|
+
{
|
|
160
|
+
metricId,
|
|
161
|
+
name
|
|
162
|
+
}
|
|
163
|
+
];
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
]);
|
|
167
|
+
}
|
|
168
|
+
return roundsByTest;
|
|
169
|
+
}
|
|
170
|
+
async function optionsFor(req, candidates, phasesReadable, now) {
|
|
171
|
+
if (!candidates.length) return [];
|
|
172
|
+
const rounds = phasesReadable ? await frozenRounds(req, candidates.map((doc)=>doc.id)) : await currentRounds(req, candidates);
|
|
173
|
+
return candidates.flatMap((doc)=>{
|
|
174
|
+
const available = rounds.get(String(doc.id));
|
|
175
|
+
return available?.length ? [
|
|
176
|
+
{
|
|
177
|
+
id: doc.id,
|
|
178
|
+
name: doc.name,
|
|
179
|
+
status: displayStatus(doc, now),
|
|
180
|
+
unitType: doc.unitType,
|
|
181
|
+
rounds: available
|
|
182
|
+
}
|
|
183
|
+
] : [];
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
async function addEstimates(req, sources) {
|
|
187
|
+
if (!sources.length) return;
|
|
188
|
+
const snapshots = await readSnapshots(req, sources.map((source)=>source.id));
|
|
189
|
+
const byRound = new Map(snapshots.map((snapshot)=>[
|
|
190
|
+
JSON.stringify([
|
|
191
|
+
String(cohortRelationshipId(snapshot.experiment)),
|
|
192
|
+
snapshot.phase
|
|
193
|
+
]),
|
|
194
|
+
snapshot
|
|
195
|
+
]));
|
|
196
|
+
for (const source of sources){
|
|
197
|
+
for (const round of source.rounds){
|
|
198
|
+
const snapshot = byRound.get(JSON.stringify([
|
|
199
|
+
String(source.id),
|
|
200
|
+
round.phase
|
|
201
|
+
]));
|
|
202
|
+
if (snapshot) round.estimate = snapshotEstimate(snapshot, round);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const selectCandidate = {
|
|
207
|
+
name: true,
|
|
208
|
+
status: true,
|
|
209
|
+
unitType: true,
|
|
210
|
+
startedAt: true,
|
|
211
|
+
arms: {
|
|
212
|
+
key: true,
|
|
213
|
+
label: true,
|
|
214
|
+
kind: true
|
|
215
|
+
},
|
|
216
|
+
metrics: true
|
|
217
|
+
};
|
|
218
|
+
/** Load saved choices directly so a previously chosen source is available even outside the search cap. */ export async function savedCohortSources(req, options, ids) {
|
|
219
|
+
const wanted = ids.flatMap((id)=>{
|
|
220
|
+
const stored = experimentId(req, id);
|
|
221
|
+
return stored === undefined ? [] : [
|
|
222
|
+
stored
|
|
223
|
+
];
|
|
224
|
+
});
|
|
225
|
+
if (!wanted.length) return [];
|
|
226
|
+
const canRead = await (options.access.readResults ?? options.access.manage)({
|
|
227
|
+
req
|
|
228
|
+
}) === true;
|
|
229
|
+
const { docs } = await req.payload.find({
|
|
230
|
+
collection: 'xp-experiments',
|
|
231
|
+
req,
|
|
232
|
+
overrideAccess: false,
|
|
233
|
+
depth: 0,
|
|
234
|
+
pagination: false,
|
|
235
|
+
limit: 0,
|
|
236
|
+
where: {
|
|
237
|
+
id: {
|
|
238
|
+
in: wanted
|
|
239
|
+
}
|
|
240
|
+
},
|
|
241
|
+
select: selectCandidate
|
|
242
|
+
});
|
|
243
|
+
const phasesReadable = await canReadPhases(req, options);
|
|
244
|
+
const sources = await optionsFor(req, docs, phasesReadable, Date.now());
|
|
245
|
+
if (canRead && phasesReadable) await addEstimates(req, sources);
|
|
246
|
+
return sources;
|
|
247
|
+
}
|
|
248
|
+
export async function handleCohortSources(req, { options }) {
|
|
249
|
+
const url = new URL(req.url ?? 'http://localhost');
|
|
250
|
+
const q = url.searchParams.get('q') ?? '';
|
|
251
|
+
const rawExclude = url.searchParams.get('exclude');
|
|
252
|
+
const exclude = rawExclude == null ? undefined : experimentId(req, rawExclude, 'query');
|
|
253
|
+
if (url.searchParams.getAll('q').length > 1 || url.searchParams.getAll('exclude').length > 1 || q.length > 100 || /[\x00-\x1f\x7f\ufffd]/.test(q) || rawExclude != null && (!rawExclude.trim() || rawExclude !== rawExclude.trim() || rawExclude.length > 128 || /[\x00-\x20\x7f\ufffd,]/.test(rawExclude) || exclude === undefined)) {
|
|
254
|
+
return resultsError(400, 'invalid-body', COHORT_EDITOR.invalidSearch);
|
|
255
|
+
}
|
|
256
|
+
const term = q.trim().replace(/[\\%_]/g, '\\$&');
|
|
257
|
+
const canRead = await (options.access.readResults ?? options.access.manage)({
|
|
258
|
+
req
|
|
259
|
+
}) === true;
|
|
260
|
+
const now = Date.now();
|
|
261
|
+
const phasesReadable = await canReadPhases(req, options);
|
|
262
|
+
const dependencies = new Map();
|
|
263
|
+
const exec = pooledExecutor(req.payload);
|
|
264
|
+
const selected = [];
|
|
265
|
+
for (const statuses of [
|
|
266
|
+
LIVE,
|
|
267
|
+
PAST
|
|
268
|
+
]){
|
|
269
|
+
if (selected.length === PAGE_SIZE) break;
|
|
270
|
+
const and = [
|
|
271
|
+
{
|
|
272
|
+
status: {
|
|
273
|
+
in: statuses
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
];
|
|
277
|
+
if (term) and.push({
|
|
278
|
+
or: [
|
|
279
|
+
{
|
|
280
|
+
name: {
|
|
281
|
+
contains: term
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
{
|
|
285
|
+
slug: {
|
|
286
|
+
contains: term
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
]
|
|
290
|
+
});
|
|
291
|
+
if (exclude !== undefined) and.push({
|
|
292
|
+
id: {
|
|
293
|
+
not_equals: exclude
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
const { docs } = await req.payload.find({
|
|
297
|
+
collection: 'xp-experiments',
|
|
298
|
+
req,
|
|
299
|
+
overrideAccess: false,
|
|
300
|
+
depth: 0,
|
|
301
|
+
pagination: false,
|
|
302
|
+
limit: 0,
|
|
303
|
+
where: {
|
|
304
|
+
and
|
|
305
|
+
},
|
|
306
|
+
select: selectCandidate
|
|
307
|
+
});
|
|
308
|
+
const candidates = docs;
|
|
309
|
+
// Only tests with a test round are listed. Without xp-phases access the phase rows decide existence
|
|
310
|
+
// only; nothing from them is returned, and ordering uses the test document's own start time.
|
|
311
|
+
const latestRounds = await latestCohortRounds(exec, candidates.map((doc)=>doc.id));
|
|
312
|
+
const started = new Map(latestRounds.map((round)=>[
|
|
313
|
+
String(round.id),
|
|
314
|
+
phasesReadable ? timestampMs(round.startedAt) : (()=>{
|
|
315
|
+
const doc = candidates.find((candidate)=>String(candidate.id) === String(round.id));
|
|
316
|
+
return doc?.startedAt ? timestampMs(doc.startedAt) : 0;
|
|
317
|
+
})()
|
|
318
|
+
]));
|
|
319
|
+
const ordered = candidates.filter((doc)=>started.has(String(doc.id))).sort((a, b)=>started.get(String(b.id)) - started.get(String(a.id)) || String(a.id).localeCompare(String(b.id)));
|
|
320
|
+
for (const doc of ordered){
|
|
321
|
+
if (selected.length === PAGE_SIZE) break;
|
|
322
|
+
if (exclude !== undefined && await reachesTarget(exec, String(doc.id), String(exclude), dependencies)) continue;
|
|
323
|
+
selected.push(doc);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const docs = await optionsFor(req, selected, phasesReadable, now);
|
|
327
|
+
if (canRead && phasesReadable) await addEstimates(req, docs);
|
|
328
|
+
return Response.json({
|
|
329
|
+
docs
|
|
330
|
+
}, {
|
|
331
|
+
headers: {
|
|
332
|
+
'Cache-Control': 'private, no-store'
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
}
|
|
@@ -2,5 +2,5 @@ import { type PayloadRequest } from 'payload';
|
|
|
2
2
|
/** Validate advisory-read metadata language; placement discovery still scans all languages. */
|
|
3
3
|
export declare function contentLocale(req: PayloadRequest): {
|
|
4
4
|
locale: string | null | undefined;
|
|
5
|
-
fallbackLocale: false | "
|
|
5
|
+
fallbackLocale: false | "false" | "none" | "null" | ({} & string) | ({} & string)[] | null | undefined;
|
|
6
6
|
};
|
|
@@ -24,6 +24,7 @@ export declare function preparePageCopy<TUser extends {
|
|
|
24
24
|
reader: {
|
|
25
25
|
views: import("../blocks/placementLocale.js").PlacementLocaleView[];
|
|
26
26
|
documentViews: import("../blocks/placementLocale.js").PlacementLocaleView[];
|
|
27
|
+
isPublished(doc: Record<string, unknown> | null | undefined, view: import("../blocks/placementLocale.js").PlacementLocaleView): boolean;
|
|
27
28
|
read(doc: Record<string, unknown> | null | undefined, input: import("../blocks/placementLocale.js").PlacementInput, view?: import("../blocks/placementLocale.js").PlacementLocaleView): {
|
|
28
29
|
view: import("../blocks/placementLocale.js").PlacementLocaleView;
|
|
29
30
|
readonly doc: Record<string, unknown> | undefined;
|
package/dist/endpoints/events.js
CHANGED
|
@@ -5,19 +5,23 @@ import { NextRequest } from 'next/server.js';
|
|
|
5
5
|
import { DEFAULT_MAX_BODY_BYTES } from '../constants.js';
|
|
6
6
|
import { pooledExecutor } from '../db/executor.js';
|
|
7
7
|
import { insertEvents } from '../db/events.js';
|
|
8
|
+
import { readManifestRow } from '../db/manifest.js';
|
|
8
9
|
import { EventsBodyError, readEvents } from '../events/body.js';
|
|
9
10
|
import { isPreview } from '../events/preview.js';
|
|
10
11
|
import { eventRequestContext, publicEventOrigin } from '../events/request.js';
|
|
11
12
|
import { eventRows } from '../events/rows.js';
|
|
12
13
|
import { assign } from '../runtime/assign.js';
|
|
14
|
+
import { cohortKeysToResolve, isEntryActive } from '../runtime/eligibility.js';
|
|
13
15
|
import { isBot } from '../runtime/bot.js';
|
|
14
16
|
import { readSignedUnit } from '../runtime/cookie.js';
|
|
15
17
|
import { requestAttributes } from '../runtime/normalisePath.js';
|
|
16
18
|
import { serverManifest } from '../server/context.js';
|
|
19
|
+
import { resolveServerCohorts } from '../server/cohortLookup.js';
|
|
17
20
|
const accepted = ()=>Response.json({}, {
|
|
18
21
|
status: 202
|
|
19
22
|
});
|
|
20
23
|
const originDrops = new WeakMap();
|
|
24
|
+
const inactiveDrops = new WeakMap();
|
|
21
25
|
function logSessionLookupError(payload, error) {
|
|
22
26
|
try {
|
|
23
27
|
payload.logger.error({
|
|
@@ -25,25 +29,40 @@ function logSessionLookupError(payload, error) {
|
|
|
25
29
|
}, 'Experiments: events session lookup failed');
|
|
26
30
|
} catch {}
|
|
27
31
|
}
|
|
28
|
-
function
|
|
29
|
-
const drops =
|
|
32
|
+
function countDrop(payload, counts, now) {
|
|
33
|
+
const drops = counts.get(payload) ?? {
|
|
30
34
|
count: 0,
|
|
31
35
|
nextLogAt: 0
|
|
32
36
|
};
|
|
33
|
-
|
|
34
|
-
drops.count
|
|
37
|
+
counts.set(payload, drops);
|
|
38
|
+
drops.count += 1;
|
|
35
39
|
if (now < drops.nextLogAt) return;
|
|
36
40
|
drops.nextLogAt = now + 60_000;
|
|
37
41
|
try {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
42
|
+
if (counts === originDrops) {
|
|
43
|
+
payload.logger.warn({
|
|
44
|
+
droppedRequests: drops.count
|
|
45
|
+
}, 'Experiments: browser event requests dropped by origin check');
|
|
46
|
+
} else {
|
|
47
|
+
payload.logger.warn({
|
|
48
|
+
droppedRequests: drops.count
|
|
49
|
+
}, 'Experiments: browser event requests with exposures dropped for inactive or unavailable tests');
|
|
50
|
+
}
|
|
41
51
|
drops.count = 0;
|
|
42
52
|
} catch {}
|
|
43
53
|
}
|
|
54
|
+
function isExposure(event) {
|
|
55
|
+
return event !== null && typeof event === 'object' && 'type' in event && event.type === 'exposure' && 'experiment' in event && typeof event.experiment === 'string' && 'phase' in event && typeof event.phase === 'number' && 'arm' in event && typeof event.arm === 'string' && 'policy' in event && typeof event.policy === 'string' && [
|
|
56
|
+
'manual',
|
|
57
|
+
'viewport',
|
|
58
|
+
'pageview'
|
|
59
|
+
].includes(event.policy);
|
|
60
|
+
}
|
|
44
61
|
export async function handleEvents(req, { options }) {
|
|
45
|
-
const receivedAt = Date.now();
|
|
46
62
|
const runtime = options.runtime, proxy = runtime.proxyRuntime;
|
|
63
|
+
const clock = proxy.now ?? (()=>new Date(Date.now()));
|
|
64
|
+
const receipt = clock();
|
|
65
|
+
const receivedAt = receipt.getTime();
|
|
47
66
|
const unitCookie = readSignedUnit(req.headers, proxy, receivedAt);
|
|
48
67
|
const visitorId = unitCookie?.unitId;
|
|
49
68
|
const issuedAtMs = unitCookie?.issuedAtMs;
|
|
@@ -55,7 +74,7 @@ export async function handleEvents(req, { options }) {
|
|
|
55
74
|
});
|
|
56
75
|
const { allowed, source } = eventRequestContext(request, options.events?.origin ?? publicEventOrigin(req.payload.config?.serverURL));
|
|
57
76
|
if (!allowed) {
|
|
58
|
-
|
|
77
|
+
countDrop(req.payload, originDrops, receivedAt);
|
|
59
78
|
return accepted();
|
|
60
79
|
}
|
|
61
80
|
// API paths bypass the proxy: re-check consent even when a stale signed cookie exists.
|
|
@@ -113,8 +132,8 @@ export async function handleEvents(req, { options }) {
|
|
|
113
132
|
}) !== true) return accepted();
|
|
114
133
|
}
|
|
115
134
|
const events = await readEvents(req.body, options.events?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
|
|
116
|
-
const
|
|
117
|
-
if (!
|
|
135
|
+
const cached = await serverManifest(proxy);
|
|
136
|
+
if (!cached) return accepted();
|
|
118
137
|
const unit = source || !useProxySession ? await proxy.getUnit?.(source ?? request) : requestUnit;
|
|
119
138
|
// The beacon URL is an API route, not the page whose content was rendered.
|
|
120
139
|
// A referrer supplies page context only, never an identity or an assigned arm.
|
|
@@ -126,13 +145,58 @@ export async function handleEvents(req, { options }) {
|
|
|
126
145
|
...serverAttributes
|
|
127
146
|
}, source?.nextUrl.pathname);
|
|
128
147
|
const unresolvedStaff = Boolean(options.attributeKeys?.staff && !user && (sessionUnresolved || unit?.sessionUnknown || requestUnit?.sessionUnknown));
|
|
129
|
-
const
|
|
148
|
+
const exec = events.some(isExposure) ? pooledExecutor(req.payload) : undefined;
|
|
149
|
+
// A manual pause removes the entry at commit. Recheck committed routing state
|
|
150
|
+
// before accepting exposures even while the request caches still serve it.
|
|
151
|
+
const committed = exec && await readManifestRow(exec).then((row)=>row?.manifest, (error)=>{
|
|
152
|
+
try {
|
|
153
|
+
req.payload.logger.error({
|
|
154
|
+
err: safeError(error)
|
|
155
|
+
}, 'Experiments: committed exposure state unavailable');
|
|
156
|
+
} catch {}
|
|
157
|
+
return undefined;
|
|
158
|
+
});
|
|
159
|
+
const manifest = committed ?? cached;
|
|
160
|
+
const validatedAt = clock();
|
|
161
|
+
const sessionUnknown = sessionUnresolved || requestUnit?.sessionUnknown === true;
|
|
162
|
+
let droppedInactiveExposure = false;
|
|
163
|
+
const cohortEntries = new Set();
|
|
164
|
+
const eligibleEvents = events.filter((event)=>{
|
|
165
|
+
if (!isExposure(event)) return true;
|
|
166
|
+
const entry = committed && committed.experiments.find((exp)=>exp.slug === event.experiment);
|
|
167
|
+
if (entry && isEntryActive(entry, receipt) && isEntryActive(entry, validatedAt)) {
|
|
168
|
+
if (entry.cohorts?.length && event.phase === entry.phase && event.policy === entry.exposurePolicy) cohortEntries.add(entry);
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
droppedInactiveExposure = true;
|
|
172
|
+
return false;
|
|
173
|
+
});
|
|
174
|
+
if (droppedInactiveExposure) countDrop(req.payload, inactiveDrops, receivedAt);
|
|
175
|
+
const ids = {
|
|
130
176
|
visitorId,
|
|
131
177
|
userId
|
|
132
|
-
}
|
|
133
|
-
|
|
178
|
+
};
|
|
179
|
+
const keysToResolve = cohortEntries.size ? cohortKeysToResolve({
|
|
180
|
+
...manifest,
|
|
181
|
+
experiments: [
|
|
182
|
+
...cohortEntries
|
|
183
|
+
]
|
|
184
|
+
}, ids, attributes, {
|
|
185
|
+
now: validatedAt,
|
|
186
|
+
sessionUnknown
|
|
187
|
+
}) : [];
|
|
188
|
+
const cohorts = keysToResolve.length ? await resolveServerCohorts(req.payload, {
|
|
189
|
+
...ids,
|
|
190
|
+
keys: keysToResolve
|
|
191
|
+
}) : undefined;
|
|
192
|
+
const assignmentAt = keysToResolve.length ? clock() : validatedAt;
|
|
193
|
+
const cohortRejected = new Set();
|
|
194
|
+
const assignments = assign(manifest, ids, attributes, {
|
|
195
|
+
now: assignmentAt,
|
|
134
196
|
method: req.method,
|
|
135
|
-
sessionUnknown
|
|
197
|
+
sessionUnknown,
|
|
198
|
+
cohorts,
|
|
199
|
+
onCohortIneligible: (slug)=>cohortRejected.add(slug),
|
|
136
200
|
staff: requestUnit?.attributes.staff === true || unit?.attributes.staff === true || attributes.staff === true,
|
|
137
201
|
bot: isBot(req.headers.get('user-agent')),
|
|
138
202
|
preview: isPreview(request)
|
|
@@ -140,10 +204,10 @@ export async function handleEvents(req, { options }) {
|
|
|
140
204
|
if (unresolvedStaff) for (const assignment of Object.values(assignments.bySlug))assignment.exposable = false;
|
|
141
205
|
const keys = events.some((event)=>event && typeof event === 'object' && 'eventName' in event && validClickSource(event.eventName)) ? await clickKeys(req.payload) : undefined;
|
|
142
206
|
// Age measures arrival. Keep attribution at the time the round was validated.
|
|
143
|
-
const rows = eventRows(
|
|
144
|
-
// §7.8 events insert / assignment lookup exception: pooled SQL
|
|
207
|
+
const rows = eventRows(eligibleEvents, manifest, assignments, options, visitorId, userId, validatedAt.toISOString(), unitAgeMs, attributes, keys, unresolvedStaff ? undefined : cohortRejected);
|
|
208
|
+
// §7.8 events insert / assignment lookup exception: pooled SQL,
|
|
145
209
|
// no Local API calls (and hence no implicit overrideAccess defaults).
|
|
146
|
-
if (rows.length) await insertEvents(pooledExecutor(req.payload), rows, (message)=>req.payload.logger.error(message));
|
|
210
|
+
if (rows.length) await insertEvents(exec ?? pooledExecutor(req.payload), rows, (message)=>req.payload.logger.error(message));
|
|
147
211
|
} catch (error) {
|
|
148
212
|
if (error instanceof EventsBodyError) return Response.json({
|
|
149
213
|
errors: [
|