@hogsend/engine 0.46.1 → 0.51.0
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 +6 -0
- package/package.json +13 -10
- package/src/campaigns/cohort-sql.ts +8 -9
- package/src/connectors/presets/index.ts +8 -2
- package/src/container.ts +150 -8
- package/src/destinations/define-destination.ts +2 -2
- package/src/destinations/presets/posthog.ts +7 -0
- package/src/destinations/presets/segment.ts +5 -0
- package/src/env.ts +38 -0
- package/src/flags/reconcile.ts +200 -0
- package/src/index.ts +79 -0
- package/src/journeys/authoring.ts +32 -0
- package/src/journeys/define-journey.ts +45 -40
- package/src/journeys/execute-journey-run.ts +73 -32
- package/src/journeys/journey-boundary.ts +76 -0
- package/src/journeys/journey-context.ts +128 -70
- package/src/journeys/journey-task-factory.ts +31 -0
- package/src/journeys/journey-task-runtime.ts +31 -0
- package/src/journeys/journey-version.test.ts +236 -0
- package/src/journeys/journey-version.ts +158 -0
- package/src/journeys/record-once.ts +28 -2
- package/src/lib/campaign-send-key.ts +9 -18
- package/src/lib/connector-actions.test.ts +36 -0
- package/src/lib/connector-actions.ts +42 -4
- package/src/lib/contacts.ts +49 -0
- package/src/lib/conversions.test.ts +33 -0
- package/src/lib/conversions.ts +9 -1
- package/src/lib/crm-deals.ts +1 -1
- package/src/lib/crm-ingest.ts +1 -1
- package/src/lib/email.ts +23 -2
- package/src/lib/enrollment-policy.ts +51 -0
- package/src/lib/event-names.ts +7 -1
- package/src/lib/feed.ts +55 -3
- package/src/lib/flags-registry.ts +48 -0
- package/src/lib/flags.ts +498 -0
- package/src/lib/frequency-cap.ts +4 -2
- package/src/lib/funnel-progress.ts +1 -1
- package/src/lib/fx.ts +374 -0
- package/src/lib/global-control-readout.ts +166 -0
- package/src/lib/groups.ts +362 -0
- package/src/lib/holdout.ts +1 -1
- package/src/lib/ingestion.ts +38 -0
- package/src/lib/journey-lift.ts +142 -0
- package/src/lib/journey-suppress.ts +4 -2
- package/src/lib/lift-stats.ts +2 -2
- package/src/lib/operator-settings.ts +71 -0
- package/src/lib/outbound.ts +147 -0
- package/src/lib/preferences.ts +6 -80
- package/src/lib/recipient-preferences.ts +53 -0
- package/src/lib/sms.ts +21 -2
- package/src/lib/stable-stringify.test.ts +42 -0
- package/src/lib/stable-stringify.ts +23 -0
- package/src/lib/tracked.ts +9 -2
- package/src/lib/variant.ts +99 -0
- package/src/lib/webhook-signing.ts +16 -1
- package/src/lists/registry.ts +6 -2
- package/src/lists/subscription.ts +13 -0
- package/src/routes/admin/attribution.ts +1 -2
- package/src/routes/admin/campaigns.ts +84 -45
- package/src/routes/admin/contacts.ts +53 -4
- package/src/routes/admin/conversions.ts +138 -1
- package/src/routes/admin/deals.ts +43 -34
- package/src/routes/admin/emails.ts +4 -6
- package/src/routes/admin/events.ts +128 -1
- package/src/routes/admin/flags.ts +369 -0
- package/src/routes/admin/groups.ts +900 -0
- package/src/routes/admin/impact-schemas.ts +44 -0
- package/src/routes/admin/impact-wire.test.ts +181 -0
- package/src/routes/admin/impact.ts +486 -0
- package/src/routes/admin/index.ts +12 -0
- package/src/routes/admin/journey-impact.ts +446 -0
- package/src/routes/admin/journeys.ts +70 -100
- package/src/routes/admin/settings.ts +145 -0
- package/src/routes/admin/targeting.ts +259 -0
- package/src/routes/events/index.ts +11 -0
- package/src/routes/flags/index.ts +120 -0
- package/src/routes/groups/index.ts +417 -0
- package/src/routes/index.ts +23 -1
- package/src/testing.ts +25 -0
- package/src/webhook-sources/presets/index.ts +5 -1
- package/src/webhook-sources/presets/intercom.ts +230 -0
- package/src/webhook-sources/presets/segment.ts +56 -4
- package/src/worker.ts +3 -0
- package/src/workflows/bucket-backfill.ts +1 -14
- package/src/workflows/crm-reconcile.ts +1 -1
- package/src/workflows/impact-digest.ts +761 -0
- package/src/workflows/journey-blueprint-interpreter.ts +18 -1
- package/src/middleware/auth.ts +0 -24
package/src/lib/flags.ts
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type {
|
|
3
|
+
ConditionEval,
|
|
4
|
+
ConditionSet,
|
|
5
|
+
FlagTargeting,
|
|
6
|
+
FlagVariant,
|
|
7
|
+
PropertyCondition,
|
|
8
|
+
} from "@hogsend/core";
|
|
9
|
+
import { evaluateCondition, evaluatePropertyConditions } from "@hogsend/core";
|
|
10
|
+
import {
|
|
11
|
+
bucketMemberships,
|
|
12
|
+
contacts,
|
|
13
|
+
type Database,
|
|
14
|
+
deals,
|
|
15
|
+
flags,
|
|
16
|
+
journeyStates,
|
|
17
|
+
} from "@hogsend/db";
|
|
18
|
+
import { and, eq, isNull } from "drizzle-orm";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The structural subset of a flag the evaluator reads. Both the drizzle row
|
|
22
|
+
* (`flags.$inferSelect`) and the portable `FlagDefinition` (@hogsend/core)
|
|
23
|
+
* satisfy it, so the same pure function serves the DB path and any in-memory
|
|
24
|
+
* caller. `targeting` accepts BOTH the legacy `PropertyCondition[]` (implicit
|
|
25
|
+
* AND) and the condition tree ({@link FlagTargeting}); `conditionSets` is the
|
|
26
|
+
* richer ordered form (first matching set wins) and, when present, takes
|
|
27
|
+
* precedence over `targeting`+`rollout`.
|
|
28
|
+
*/
|
|
29
|
+
export interface EvaluableFlag {
|
|
30
|
+
key: string;
|
|
31
|
+
enabled: boolean;
|
|
32
|
+
type: string;
|
|
33
|
+
variants: FlagVariant[];
|
|
34
|
+
defaultValue: unknown;
|
|
35
|
+
targeting: FlagTargeting | PropertyCondition[];
|
|
36
|
+
rollout: number;
|
|
37
|
+
conditionSets?: ConditionSet[] | null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The FIXED, snapshot of the materialized contact state the pure targeting
|
|
42
|
+
* leaves read. Loaded ONCE per flag evaluation request (never per flag), so the
|
|
43
|
+
* browser `GET /v1/flags` hot path stays O(1) in the number of flags:
|
|
44
|
+
* - `properties` — the contact's stored properties (property leaves)
|
|
45
|
+
* - `email` — the contact's email, the key `email_engagement` scan leaves
|
|
46
|
+
* look up `email_sends` on (SERVER path only; `contactKey` is
|
|
47
|
+
* NOT an email, so without this the leaf never matches)
|
|
48
|
+
* - `buckets` — the ids of the contact's ACTIVE bucket memberships
|
|
49
|
+
* - `journeys` — per journey id, whether it is live (active/waiting) and/or
|
|
50
|
+
* has completed
|
|
51
|
+
* - `deals` — the contact's CRM deal posture (won/open + furthest stage)
|
|
52
|
+
*/
|
|
53
|
+
export interface TargetingSnapshot {
|
|
54
|
+
properties: Record<string, unknown>;
|
|
55
|
+
email: string | null;
|
|
56
|
+
buckets: Set<string>;
|
|
57
|
+
journeys: Map<string, { active: boolean; completed: boolean }>;
|
|
58
|
+
deals: { won: boolean; open: boolean; stage: string | null };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** An empty snapshot (anon contact / no materialized rows). */
|
|
62
|
+
export function emptySnapshot(
|
|
63
|
+
properties: Record<string, unknown> = {},
|
|
64
|
+
): TargetingSnapshot {
|
|
65
|
+
return {
|
|
66
|
+
properties,
|
|
67
|
+
email: null,
|
|
68
|
+
buckets: new Set(),
|
|
69
|
+
journeys: new Map(),
|
|
70
|
+
deals: { won: false, open: false, stage: null },
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Load the FIXED ~4-query targeting snapshot for a contact. `contactKey` is the
|
|
76
|
+
* logical id `bucket_memberships`/`journey_states` are keyed on (their `userId`
|
|
77
|
+
* is `external_id ?? anonymous_id ?? id`); `contactId` is the trusted uuid used
|
|
78
|
+
* for the property + deal reads (see `evaluateFlagsForContact`'s security note).
|
|
79
|
+
* An anon contact with no rows yields empty sets — correct (targeting-gated
|
|
80
|
+
* flags fall to default).
|
|
81
|
+
*/
|
|
82
|
+
export async function loadTargetingSnapshot(opts: {
|
|
83
|
+
db: Database;
|
|
84
|
+
contactKey: string;
|
|
85
|
+
contactId?: string;
|
|
86
|
+
}): Promise<TargetingSnapshot> {
|
|
87
|
+
const { db, contactKey, contactId } = opts;
|
|
88
|
+
|
|
89
|
+
const [contactRows, bucketRows, journeyRows, dealRows] = await Promise.all([
|
|
90
|
+
contactId
|
|
91
|
+
? db
|
|
92
|
+
.select({ properties: contacts.properties, email: contacts.email })
|
|
93
|
+
.from(contacts)
|
|
94
|
+
.where(and(eq(contacts.id, contactId), isNull(contacts.deletedAt)))
|
|
95
|
+
.limit(1)
|
|
96
|
+
: Promise.resolve([] as { properties: unknown; email: string | null }[]),
|
|
97
|
+
db
|
|
98
|
+
.select({ bucketId: bucketMemberships.bucketId })
|
|
99
|
+
.from(bucketMemberships)
|
|
100
|
+
.where(
|
|
101
|
+
and(
|
|
102
|
+
eq(bucketMemberships.userId, contactKey),
|
|
103
|
+
eq(bucketMemberships.status, "active"),
|
|
104
|
+
isNull(bucketMemberships.deletedAt),
|
|
105
|
+
),
|
|
106
|
+
),
|
|
107
|
+
db
|
|
108
|
+
.select({
|
|
109
|
+
journeyId: journeyStates.journeyId,
|
|
110
|
+
status: journeyStates.status,
|
|
111
|
+
})
|
|
112
|
+
.from(journeyStates)
|
|
113
|
+
.where(eq(journeyStates.userId, contactKey)),
|
|
114
|
+
contactId
|
|
115
|
+
? db
|
|
116
|
+
.select({
|
|
117
|
+
soldAt: deals.soldAt,
|
|
118
|
+
canonicalStage: deals.canonicalStage,
|
|
119
|
+
stageRank: deals.stageRank,
|
|
120
|
+
})
|
|
121
|
+
.from(deals)
|
|
122
|
+
.where(eq(deals.contactId, contactId))
|
|
123
|
+
: Promise.resolve(
|
|
124
|
+
[] as {
|
|
125
|
+
soldAt: Date | null;
|
|
126
|
+
canonicalStage: string;
|
|
127
|
+
stageRank: number;
|
|
128
|
+
}[],
|
|
129
|
+
),
|
|
130
|
+
]);
|
|
131
|
+
|
|
132
|
+
const properties = (contactRows[0]?.properties ?? {}) as Record<
|
|
133
|
+
string,
|
|
134
|
+
unknown
|
|
135
|
+
>;
|
|
136
|
+
const email = (contactRows[0]?.email ?? null) as string | null;
|
|
137
|
+
|
|
138
|
+
const buckets = new Set<string>();
|
|
139
|
+
for (const row of bucketRows) buckets.add(row.bucketId);
|
|
140
|
+
|
|
141
|
+
const journeys = new Map<string, { active: boolean; completed: boolean }>();
|
|
142
|
+
for (const row of journeyRows) {
|
|
143
|
+
const entry = journeys.get(row.journeyId) ?? {
|
|
144
|
+
active: false,
|
|
145
|
+
completed: false,
|
|
146
|
+
};
|
|
147
|
+
if (row.status === "active" || row.status === "waiting") {
|
|
148
|
+
entry.active = true;
|
|
149
|
+
}
|
|
150
|
+
if (row.status === "completed") entry.completed = true;
|
|
151
|
+
journeys.set(row.journeyId, entry);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let won = false;
|
|
155
|
+
let open = false;
|
|
156
|
+
let stage: string | null = null;
|
|
157
|
+
let bestRank = -1;
|
|
158
|
+
for (const row of dealRows) {
|
|
159
|
+
if (row.soldAt != null || row.canonicalStage === "sold") won = true;
|
|
160
|
+
if (row.canonicalStage !== "sold" && row.canonicalStage !== "lost") {
|
|
161
|
+
open = true;
|
|
162
|
+
}
|
|
163
|
+
// The furthest-along deal represents the contact's stage for a `stage`
|
|
164
|
+
// predicate (denormalized `stageRank`, highest wins).
|
|
165
|
+
if (row.stageRank > bestRank) {
|
|
166
|
+
bestRank = row.stageRank;
|
|
167
|
+
stage = row.canonicalStage;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return { properties, email, buckets, journeys, deals: { won, open, stage } };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The context an async targeting evaluation runs in. `mode` gates the SERVER-
|
|
176
|
+
* ONLY scan leaves (`event`/`email_engagement`): they resolve via
|
|
177
|
+
* `evaluateCondition` ONLY when `mode==="server"` with `db`+`userId`, and
|
|
178
|
+
* short-circuit to `false` on the browser path (keeping the browser query count
|
|
179
|
+
* fixed — no per-flag DB access).
|
|
180
|
+
*/
|
|
181
|
+
export interface TargetingEvalContext {
|
|
182
|
+
snapshot: TargetingSnapshot;
|
|
183
|
+
mode: "browser" | "server";
|
|
184
|
+
db?: Database;
|
|
185
|
+
userId?: string;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* A `negate`-aware answer for the pure snapshot leaves.
|
|
190
|
+
*/
|
|
191
|
+
function applyNegate(matched: boolean, negate?: boolean): boolean {
|
|
192
|
+
return negate ? !matched : matched;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Evaluate a PURE (snapshot-backed, DB-free) targeting leaf. Returns `null` for
|
|
197
|
+
* a leaf that is NOT pure (`event`/`email_engagement`) so the caller can route
|
|
198
|
+
* it to the server-only path.
|
|
199
|
+
*/
|
|
200
|
+
function evaluatePureLeaf(
|
|
201
|
+
node: Exclude<FlagTargeting, { type: "composite" }>,
|
|
202
|
+
snapshot: TargetingSnapshot,
|
|
203
|
+
): boolean | null {
|
|
204
|
+
switch (node.type) {
|
|
205
|
+
case "property":
|
|
206
|
+
return evaluatePropertyConditions({
|
|
207
|
+
conditions: [node],
|
|
208
|
+
properties: snapshot.properties,
|
|
209
|
+
});
|
|
210
|
+
case "bucket":
|
|
211
|
+
return applyNegate(snapshot.buckets.has(node.bucketId), node.negate);
|
|
212
|
+
case "journey": {
|
|
213
|
+
const entry = snapshot.journeys.get(node.journeyId);
|
|
214
|
+
const matched =
|
|
215
|
+
node.state === "active" ? !!entry?.active : !!entry?.completed;
|
|
216
|
+
return applyNegate(matched, node.negate);
|
|
217
|
+
}
|
|
218
|
+
case "deal": {
|
|
219
|
+
let matched: boolean;
|
|
220
|
+
if (node.predicate === "won") matched = snapshot.deals.won;
|
|
221
|
+
else if (node.predicate === "open") matched = snapshot.deals.open;
|
|
222
|
+
else matched = node.stage != null && snapshot.deals.stage === node.stage;
|
|
223
|
+
return applyNegate(matched, node.negate);
|
|
224
|
+
}
|
|
225
|
+
default:
|
|
226
|
+
// event / email_engagement — not snapshot-resolvable.
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Fully evaluate a targeting node against the snapshot + mode. PURE leaves
|
|
233
|
+
* resolve from the snapshot; the SERVER-ONLY scan leaves resolve via
|
|
234
|
+
* `evaluateCondition` on the server path (else `false`); a COMPOSITE folds
|
|
235
|
+
* AND/OR (short-circuiting) over its children. A bare `PropertyCondition[]` is
|
|
236
|
+
* an implicit AND (empty ⇒ everyone); an empty COMPOSITE ⇒ everyone.
|
|
237
|
+
*/
|
|
238
|
+
export async function evaluateTargeting(
|
|
239
|
+
node: FlagTargeting | PropertyCondition[] | null | undefined,
|
|
240
|
+
ctx: TargetingEvalContext,
|
|
241
|
+
): Promise<boolean> {
|
|
242
|
+
if (node == null) return true;
|
|
243
|
+
if (Array.isArray(node)) {
|
|
244
|
+
for (const child of node) {
|
|
245
|
+
if (!(await evaluateTargeting(child, ctx))) return false;
|
|
246
|
+
}
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
if (node.type === "composite") {
|
|
250
|
+
// An empty group is "no constraint" ⇒ everyone, regardless of operator.
|
|
251
|
+
if (node.conditions.length === 0) return true;
|
|
252
|
+
if (node.operator === "or") {
|
|
253
|
+
for (const child of node.conditions) {
|
|
254
|
+
if (await evaluateTargeting(child, ctx)) return true;
|
|
255
|
+
}
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
for (const child of node.conditions) {
|
|
259
|
+
if (!(await evaluateTargeting(child, ctx))) return false;
|
|
260
|
+
}
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const pure = evaluatePureLeaf(node, ctx.snapshot);
|
|
265
|
+
if (pure !== null) return pure;
|
|
266
|
+
|
|
267
|
+
// event / email_engagement — SERVER-ONLY. Never touches the DB on the browser
|
|
268
|
+
// path (THE invariant): short-circuit to false unless server mode is armed.
|
|
269
|
+
if (ctx.mode !== "server" || !ctx.db || !ctx.userId) return false;
|
|
270
|
+
return evaluateCondition({
|
|
271
|
+
condition: node as ConditionEval,
|
|
272
|
+
ctx: {
|
|
273
|
+
db: ctx.db,
|
|
274
|
+
userId: ctx.userId,
|
|
275
|
+
// `email_engagement` leaves look up `email_sends.to_email` — key it on the
|
|
276
|
+
// contact's ACTUAL email (from the loaded snapshot), never the contactKey
|
|
277
|
+
// (which is external_id/anonymous_id/id, never an address).
|
|
278
|
+
email: ctx.snapshot.email,
|
|
279
|
+
journeyContext: {},
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Deterministic percent bucket in [0, 100) from a string. Mirrors the holdout
|
|
286
|
+
* hashing law (sha256's first 4 bytes → uniform bucket): NO RNG and NO clock,
|
|
287
|
+
* so the same input buckets identically forever. A contact is IN a set's
|
|
288
|
+
* rollout when `bucket < set.rollout` (see {@link evaluateFlag}).
|
|
289
|
+
*/
|
|
290
|
+
export function flagBucket(input: string): number {
|
|
291
|
+
const digest = createHash("sha256").update(input).digest();
|
|
292
|
+
return (digest.readUInt32BE(0) % 10000) / 100;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* The rollout admission-hash input for condition set index `i`. Set 0 — the
|
|
297
|
+
* synthesized back-compat set of a legacy flag AND the first set of any flag —
|
|
298
|
+
* keys on the bare `${contactKey}:${flagKey}` so a pre-condition-set flag keeps
|
|
299
|
+
* its EXACT pre-Phase-2 bucket across the upgrade (rollout stays STICKY, no
|
|
300
|
+
* silent re-randomization). Additional sets append `:${i}`, giving each set's
|
|
301
|
+
* rollout an INDEPENDENT dice roll (a contact that fails set 0's rollout can
|
|
302
|
+
* still pass set 1's). Used identically by the sync and async evaluators.
|
|
303
|
+
*/
|
|
304
|
+
function rolloutKey(contactKey: string, flagKey: string, i: number): string {
|
|
305
|
+
return i === 0 ? `${contactKey}:${flagKey}` : `${contactKey}:${flagKey}:${i}`;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Deterministic unit in [0, 1) from a string — the weighted-variant selector.
|
|
310
|
+
* Same sha256-first-4-bytes construction as {@link flagBucket}, normalized over
|
|
311
|
+
* the full 32-bit range so the multivariate pick is uniform.
|
|
312
|
+
*/
|
|
313
|
+
export function flagUnit(input: string): number {
|
|
314
|
+
const digest = createHash("sha256").update(input).digest();
|
|
315
|
+
return digest.readUInt32BE(0) / 0x1_0000_0000;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Pick a multivariate arm by cumulative weight over a deterministic unit-hash
|
|
320
|
+
* of `contactKey:flagKey:v`. Weights are relative (normalized by their sum);
|
|
321
|
+
* a zero/empty weight set falls back to the flag's `defaultValue`.
|
|
322
|
+
*/
|
|
323
|
+
function pickVariant(flag: EvaluableFlag, contactKey: string): unknown {
|
|
324
|
+
const total = flag.variants.reduce((s, v) => s + Math.max(0, v.weight), 0);
|
|
325
|
+
if (total <= 0) return flag.defaultValue;
|
|
326
|
+
const target = flagUnit(`${contactKey}:${flag.key}:v`) * total;
|
|
327
|
+
let cumulative = 0;
|
|
328
|
+
for (const variant of flag.variants) {
|
|
329
|
+
cumulative += Math.max(0, variant.weight);
|
|
330
|
+
if (target < cumulative) return variant.value;
|
|
331
|
+
}
|
|
332
|
+
// Floating-point tail: fall through to the last arm.
|
|
333
|
+
return flag.variants[flag.variants.length - 1]?.value ?? flag.defaultValue;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* The ordered condition sets to walk for a flag. When `conditionSets` is present
|
|
338
|
+
* and non-empty it is authoritative; otherwise a single set is synthesized from
|
|
339
|
+
* the legacy `targeting`+`rollout` columns (back-compat: a flag that predates
|
|
340
|
+
* condition sets, or an empty array ⇒ one everyone-set at the flag's rollout).
|
|
341
|
+
*/
|
|
342
|
+
function resolveConditionSets(flag: EvaluableFlag): ConditionSet[] {
|
|
343
|
+
if (flag.conditionSets && flag.conditionSets.length > 0) {
|
|
344
|
+
return flag.conditionSets;
|
|
345
|
+
}
|
|
346
|
+
return [{ targeting: flag.targeting, rollout: flag.rollout }];
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* The served value once a matching set (or none) is known. Shared by the sync
|
|
351
|
+
* (browser-pure) and async (mode-aware) entry points.
|
|
352
|
+
*/
|
|
353
|
+
function servedValue(flag: EvaluableFlag, contactKey: string): unknown {
|
|
354
|
+
if (flag.type === "boolean") return true;
|
|
355
|
+
return pickVariant(flag, contactKey);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* SYNC, browser-pure evaluation of a flag for a contact. PURE leaves
|
|
360
|
+
* (property/bucket/journey/deal) resolve from `snapshot` (or, back-compat, from
|
|
361
|
+
* bare `properties`); the SERVER-ONLY scan leaves (event/email_engagement)
|
|
362
|
+
* evaluate to `false`. STICKY by construction. Precedence — walk the ordered
|
|
363
|
+
* condition sets; the FIRST set whose targeting matches AND whose per-set
|
|
364
|
+
* rollout bucket ({@link rolloutKey}) admits the contact wins; otherwise
|
|
365
|
+
* `defaultValue`.
|
|
366
|
+
*/
|
|
367
|
+
export function evaluateFlag(
|
|
368
|
+
flag: EvaluableFlag,
|
|
369
|
+
ctx: {
|
|
370
|
+
contactKey: string;
|
|
371
|
+
properties: Record<string, unknown>;
|
|
372
|
+
snapshot?: TargetingSnapshot;
|
|
373
|
+
},
|
|
374
|
+
): unknown {
|
|
375
|
+
if (!flag.enabled) return flag.defaultValue;
|
|
376
|
+
|
|
377
|
+
const snapshot = ctx.snapshot ?? emptySnapshot(ctx.properties);
|
|
378
|
+
const sets = resolveConditionSets(flag);
|
|
379
|
+
for (let i = 0; i < sets.length; i++) {
|
|
380
|
+
const set = sets[i];
|
|
381
|
+
if (!set) continue;
|
|
382
|
+
if (!evaluateTargetingSync(set.targeting, snapshot)) continue;
|
|
383
|
+
if (flagBucket(rolloutKey(ctx.contactKey, flag.key, i)) >= set.rollout) {
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
return servedValue(flag, ctx.contactKey);
|
|
387
|
+
}
|
|
388
|
+
return flag.defaultValue;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* SYNC targeting fold used by the browser-pure {@link evaluateFlag}. Identical
|
|
393
|
+
* semantics to the async {@link evaluateTargeting} in `mode:"browser"` (the
|
|
394
|
+
* server-only scan leaves are `false`), but without the Promise machinery.
|
|
395
|
+
*/
|
|
396
|
+
function evaluateTargetingSync(
|
|
397
|
+
node: FlagTargeting | PropertyCondition[] | null | undefined,
|
|
398
|
+
snapshot: TargetingSnapshot,
|
|
399
|
+
): boolean {
|
|
400
|
+
if (node == null) return true;
|
|
401
|
+
if (Array.isArray(node)) {
|
|
402
|
+
return node.every((child) => evaluateTargetingSync(child, snapshot));
|
|
403
|
+
}
|
|
404
|
+
if (node.type === "composite") {
|
|
405
|
+
if (node.conditions.length === 0) return true;
|
|
406
|
+
return node.operator === "or"
|
|
407
|
+
? node.conditions.some((c) => evaluateTargetingSync(c, snapshot))
|
|
408
|
+
: node.conditions.every((c) => evaluateTargetingSync(c, snapshot));
|
|
409
|
+
}
|
|
410
|
+
const pure = evaluatePureLeaf(node, snapshot);
|
|
411
|
+
// event / email_engagement are server-only ⇒ false on the browser path.
|
|
412
|
+
return pure ?? false;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Async, mode-aware evaluation of one flag against a pre-loaded snapshot. On the
|
|
417
|
+
* browser path this NEVER issues a DB query (server-only leaves short-circuit to
|
|
418
|
+
* false); on the server path event/email_engagement leaves resolve via
|
|
419
|
+
* `evaluateCondition`. First matching set wins (per-set rollout keyed by index).
|
|
420
|
+
*/
|
|
421
|
+
async function evaluateFlagResolved(
|
|
422
|
+
flag: EvaluableFlag,
|
|
423
|
+
ctx: {
|
|
424
|
+
contactKey: string;
|
|
425
|
+
snapshot: TargetingSnapshot;
|
|
426
|
+
mode: "browser" | "server";
|
|
427
|
+
db?: Database;
|
|
428
|
+
userId?: string;
|
|
429
|
+
},
|
|
430
|
+
): Promise<unknown> {
|
|
431
|
+
if (!flag.enabled) return flag.defaultValue;
|
|
432
|
+
|
|
433
|
+
const evalCtx: TargetingEvalContext = {
|
|
434
|
+
snapshot: ctx.snapshot,
|
|
435
|
+
mode: ctx.mode,
|
|
436
|
+
db: ctx.db,
|
|
437
|
+
userId: ctx.userId,
|
|
438
|
+
};
|
|
439
|
+
const sets = resolveConditionSets(flag);
|
|
440
|
+
for (let i = 0; i < sets.length; i++) {
|
|
441
|
+
const set = sets[i];
|
|
442
|
+
if (!set) continue;
|
|
443
|
+
if (!(await evaluateTargeting(set.targeting, evalCtx))) continue;
|
|
444
|
+
if (flagBucket(rolloutKey(ctx.contactKey, flag.key, i)) >= set.rollout) {
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
return servedValue(flag, ctx.contactKey);
|
|
448
|
+
}
|
|
449
|
+
return flag.defaultValue;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Evaluate EVERY live (enabled, non-archived) flag for a contact and return the
|
|
454
|
+
* `{ key: value }` map. `contactKey` is the STICKY bucketing identity AND the
|
|
455
|
+
* key `bucket_memberships`/`journey_states`/`user_events` are read on; the
|
|
456
|
+
* SERVER-TRUSTED `contactId` (a resolved `contacts.id`, NEVER a re-resolved raw
|
|
457
|
+
* `contactKey`) scopes the property + deal reads — the same security boundary as
|
|
458
|
+
* before (a pk_ caller's raw `contactKey` must never load another contact's
|
|
459
|
+
* properties/deals).
|
|
460
|
+
*
|
|
461
|
+
* THE INVARIANT: the snapshot is loaded ONCE (a fixed ~4 indexed queries) and
|
|
462
|
+
* every flag evaluates against it, so the browser path issues a FIXED query
|
|
463
|
+
* count (flags query + snapshot) regardless of flag count. On `mode:"browser"`
|
|
464
|
+
* the server-only scan leaves (event/email_engagement) short-circuit to false —
|
|
465
|
+
* NO per-flag DB query runs. `mode:"server"` (the secret-key evaluate route)
|
|
466
|
+
* resolves those leaves via `evaluateCondition` keyed on `contactKey`.
|
|
467
|
+
*/
|
|
468
|
+
export async function evaluateFlagsForContact(opts: {
|
|
469
|
+
db: Database;
|
|
470
|
+
contactKey: string;
|
|
471
|
+
contactId?: string;
|
|
472
|
+
mode: "browser" | "server";
|
|
473
|
+
}): Promise<Record<string, unknown>> {
|
|
474
|
+
const { db, contactKey, contactId, mode } = opts;
|
|
475
|
+
|
|
476
|
+
const rows = await db
|
|
477
|
+
.select()
|
|
478
|
+
.from(flags)
|
|
479
|
+
.where(and(eq(flags.enabled, true), isNull(flags.archivedAt)));
|
|
480
|
+
|
|
481
|
+
const snapshot = await loadTargetingSnapshot({ db, contactKey, contactId });
|
|
482
|
+
|
|
483
|
+
const result: Record<string, unknown> = {};
|
|
484
|
+
for (const row of rows) {
|
|
485
|
+
// The jsonb `targeting`/`conditionSets` columns are typed loosely at rest
|
|
486
|
+
// (db can't import core; Zod validates on write). Narrow to the evaluated
|
|
487
|
+
// shape at this single boundary, matching `serializeFlag`.
|
|
488
|
+
const flag = row as unknown as EvaluableFlag;
|
|
489
|
+
result[flag.key] = await evaluateFlagResolved(flag, {
|
|
490
|
+
contactKey,
|
|
491
|
+
snapshot,
|
|
492
|
+
mode,
|
|
493
|
+
db: mode === "server" ? db : undefined,
|
|
494
|
+
userId: mode === "server" ? contactKey : undefined,
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
return result;
|
|
498
|
+
}
|
package/src/lib/frequency-cap.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { durationToMs } from "@hogsend/core";
|
|
2
2
|
import type { Database } from "@hogsend/db";
|
|
3
3
|
import { emailSends } from "@hogsend/db";
|
|
4
|
-
import { and, count, eq, gte,
|
|
4
|
+
import { and, count, eq, gte, notInArray } from "drizzle-orm";
|
|
5
5
|
import type { FrequencyCapConfig } from "./email-service-types.js";
|
|
6
6
|
|
|
7
7
|
const DEFAULT_EXEMPT = ["transactional"];
|
|
@@ -28,7 +28,9 @@ export async function countRecentSends(opts: {
|
|
|
28
28
|
const conditions = [
|
|
29
29
|
eq(emailSends.toEmail, to),
|
|
30
30
|
gte(emailSends.createdAt, since),
|
|
31
|
-
|
|
31
|
+
// Neither dispatch failures nor policy-suppressed rows reached the inbox,
|
|
32
|
+
// so neither consumes cap budget.
|
|
33
|
+
notInArray(emailSends.status, ["failed", "suppressed"]),
|
|
32
34
|
];
|
|
33
35
|
if (category !== undefined) {
|
|
34
36
|
conditions.push(eq(emailSends.category, category));
|
|
@@ -5,7 +5,7 @@ import { resolveFunnelTargets } from "./funnel-transitions.js";
|
|
|
5
5
|
import type { Logger } from "./logger.js";
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* Event-funnel REPORTING projection
|
|
8
|
+
* Event-funnel REPORTING projection —
|
|
9
9
|
* one first-reach row per (contact, funnel, stage), the raw material for
|
|
10
10
|
* progression counts ("how many reached activated") and velocity ("median
|
|
11
11
|
* time signed_up → activated"). Complements the deals projection the
|