@jini-ai/platform 0.7.3-next.1 → 0.7.3-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +13 -0
- package/dist/download-lock.d.ts +3 -1
- package/dist/download-lock.js +4 -4
- package/dist/download-maintenance.js +6 -6
- package/dist/download-state.js +17 -14
- package/dist/download-store.d.ts +34 -10
- package/dist/download-store.js +24 -20
- package/dist/download-target.d.ts +6 -2
- package/dist/download-target.js +7 -7
- package/dist/download-transfer.js +18 -12
- package/dist/download.js +4 -4
- package/dist/fetch-with-timeout.d.ts +0 -53
- package/dist/fetch-with-timeout.js +56 -6
- package/dist/fs/directory-running-lock.d.ts +4 -0
- package/dist/fs/directory-running-lock.js +8 -1
- package/dist/fs/directory-workspace.d.ts +2 -1
- package/dist/fs/directory-workspace.js +2 -2
- package/dist/fs/durable-json.d.ts +3 -16
- package/dist/fs/durable-json.js +4 -2
- package/dist/fs/guarded-reader.d.ts +10 -0
- package/dist/fs/guarded-reader.js +34 -1
- package/dist/fs/index.d.ts +4 -0
- package/dist/fs/index.js +4 -0
- package/dist/fs/leased-directory-move.d.ts +49 -0
- package/dist/fs/leased-directory-move.js +31 -0
- package/dist/fs/owned-temp-root.d.ts +74 -0
- package/dist/fs/owned-temp-root.js +203 -0
- package/dist/fs/recent-directories.d.ts +2 -1
- package/dist/fs/resolve-directory-target.d.ts +33 -0
- package/dist/fs/resolve-directory-target.js +58 -0
- package/dist/fs/staged-file.d.ts +40 -0
- package/dist/fs/staged-file.js +75 -0
- package/dist/fs/strict-containment.d.ts +14 -0
- package/dist/fs/strict-containment.js +14 -0
- package/dist/image/png-encode.d.ts +41 -0
- package/dist/image/png-encode.js +96 -0
- package/dist/index.d.ts +3 -1
- package/dist/mail/email-template-agent-tools.d.ts +150 -0
- package/dist/mail/email-template-agent-tools.js +86 -0
- package/dist/mail/email-template-tool-registrations.d.ts +73 -0
- package/dist/mail/email-template-tool-registrations.js +66 -0
- package/dist/mail/feedback-route.d.ts +50 -0
- package/dist/mail/feedback-route.js +46 -0
- package/dist/mail/feedback-setup.d.ts +44 -0
- package/dist/mail/feedback-setup.js +53 -0
- package/dist/mail/feedback-sources.d.ts +67 -0
- package/dist/mail/feedback-sources.js +42 -0
- package/dist/mail/index.d.ts +10 -1
- package/dist/mail/index.js +4 -0
- package/dist/mail/mail-status.d.ts +32 -0
- package/dist/mail/mail-status.js +2 -0
- package/dist/mail/positional-purpose-gate.d.ts +14 -0
- package/dist/mail/positional-purpose-gate.js +18 -0
- package/dist/mail/purpose-gate-probe.d.ts +18 -0
- package/dist/mail/purpose-gate-probe.js +22 -0
- package/dist/mail/resolve-mailer.d.ts +13 -1
- package/dist/mail/resolve-mailer.js +11 -5
- package/dist/mail/sql/activity.repo.d.ts +20 -0
- package/dist/mail/sql/activity.repo.js +133 -0
- package/dist/mail/sql/attempts.repo.d.ts +17 -0
- package/dist/mail/sql/attempts.repo.js +32 -0
- package/dist/mail/sql/capture.repo.d.ts +69 -0
- package/dist/mail/sql/capture.repo.js +119 -0
- package/dist/mail/sql/feedback-inbox.repo.d.ts +12 -0
- package/dist/mail/sql/feedback-inbox.repo.js +32 -0
- package/dist/mail/sql/index.d.ts +12 -0
- package/dist/mail/sql/index.js +12 -0
- package/dist/mail/sql/ledger.repo.d.ts +29 -0
- package/dist/mail/sql/ledger.repo.js +57 -0
- package/dist/mail/sql/retention.d.ts +23 -0
- package/dist/mail/sql/retention.js +53 -0
- package/dist/mail/sql/site-feedback-route.d.ts +18 -0
- package/dist/mail/sql/site-feedback-route.js +22 -0
- package/dist/mail/sql/suppression-admin.repo.d.ts +11 -0
- package/dist/mail/sql/suppression-admin.repo.js +76 -0
- package/dist/mail/sql/suppression.repo.d.ts +10 -0
- package/dist/mail/sql/suppression.repo.js +33 -0
- package/dist/mail/test-send.d.ts +147 -0
- package/dist/mail/test-send.js +201 -0
- package/dist/mail/use-readiness.d.ts +104 -0
- package/dist/mail/use-readiness.js +140 -0
- package/dist/object-store/local-fs.js +34 -1
- package/dist/object-store/site/artifact-provider.d.ts +65 -0
- package/dist/object-store/site/artifact-provider.js +37 -0
- package/dist/object-store/site/registry.d.ts +110 -0
- package/dist/object-store/site/registry.js +93 -0
- package/dist/object-store/site/setting.d.ts +34 -0
- package/dist/object-store/site/setting.js +32 -0
- package/dist/process-probes.d.ts +11 -4
- package/dist/process-probes.js +3 -3
- package/dist/process-top-footprint.d.ts +1 -1
- package/dist/process.d.ts +3 -17
- package/dist/process.js +3 -2
- package/dist/retention/index.d.ts +6 -0
- package/dist/retention/index.js +6 -0
- package/dist/retention/measure-tree.d.ts +68 -0
- package/dist/retention/measure-tree.js +205 -0
- package/dist/retention/preview-store.d.ts +10 -0
- package/dist/retention/preview-store.js +26 -0
- package/dist/retention/routes.d.ts +23 -0
- package/dist/retention/routes.js +24 -0
- package/dist/retention/runner.d.ts +103 -0
- package/dist/retention/runner.js +164 -0
- package/dist/secrets/credential-sets/index.d.ts +1 -0
- package/dist/secrets/credential-sets/index.js +1 -0
- package/dist/secrets/credential-sets/store-vault-guards.d.ts +26 -0
- package/dist/secrets/credential-sets/store-vault-guards.js +30 -0
- package/dist/secrets/credential-sets/vault.service.d.ts +1 -1
- package/dist/secrets/index.d.ts +1 -1
- package/dist/secrets/index.js +1 -1
- package/dist/secrets/keyring.env.d.ts +1 -1
- package/dist/secrets/keyring.env.js +3 -5
- package/dist/secrets/keyring.memory.d.ts +4 -1
- package/dist/secrets/keyring.memory.js +4 -1
- package/dist/secrets/legacy-codecs.d.ts +381 -0
- package/dist/secrets/legacy-codecs.js +468 -0
- package/dist/secrets/legacy-owner.d.ts +3 -11
- package/dist/secrets/root-key/ensure.d.ts +154 -0
- package/dist/secrets/root-key/ensure.js +328 -0
- package/dist/secrets/root-key/files.d.ts +104 -0
- package/dist/secrets/root-key/files.js +166 -0
- package/dist/secrets/root-key/material.d.ts +132 -0
- package/dist/secrets/root-key/material.js +116 -0
- package/dist/secrets/root-key/ordered-keyring.d.ts +157 -0
- package/dist/secrets/root-key/ordered-keyring.js +104 -0
- package/dist/secrets/root-key/reconcile.d.ts +50 -0
- package/dist/secrets/root-key/reconcile.js +147 -0
- package/dist/secrets/root-key/site-keyring-errors.d.ts +78 -0
- package/dist/secrets/root-key/site-keyring-errors.js +37 -0
- package/dist/secrets/root-key/sources.d.ts +79 -0
- package/dist/secrets/root-key/sources.js +119 -0
- package/dist/secrets/secret-sealer.aesgcm.d.ts +50 -2
- package/dist/secrets/secret-sealer.aesgcm.js +107 -19
- package/dist/web/tool-registrations.d.ts +67 -0
- package/dist/web/tool-registrations.js +44 -0
- package/package.json +139 -7
|
@@ -84,6 +84,7 @@ async function consoleMailer({ state, catalog }) {
|
|
|
84
84
|
const provider = catalog.registry.get({ id: "console" }).provider;
|
|
85
85
|
const mailer = state.wrap({ providerId: "console", provider, mailer: state.deps.createProviderMailer({ provider, credential: { token: "" } }) });
|
|
86
86
|
state.resolved.set("console", { mailer, fingerprint: "" });
|
|
87
|
+
state.consoleFallbacks.add(mailer);
|
|
87
88
|
return mailer;
|
|
88
89
|
}
|
|
89
90
|
/** Local mode keeps working through console; production refuses and logs safe host copy once. */
|
|
@@ -173,19 +174,23 @@ async function currentMailer({ state, id }) {
|
|
|
173
174
|
state.resolved.delete(id);
|
|
174
175
|
return resolveOnce({ state, id });
|
|
175
176
|
}
|
|
176
|
-
/** Fresh lane selection precedes every resolution and updates the synchronous transactional projection.
|
|
177
|
-
|
|
177
|
+
/** Fresh lane selection precedes every resolution and updates the synchronous transactional projection.
|
|
178
|
+
* The reported id comes from this same pass, so a settings change mid-flight cannot split id from mailer. */
|
|
179
|
+
async function resolveLane({ state, lane }) {
|
|
178
180
|
const id = (await currentSetting(state))[lane];
|
|
179
181
|
const mailer = id === null
|
|
180
182
|
? await fallback({ state, catalog: await state.deps.loadCatalog({}), errorCode: "MAIL_UNCONFIGURED", message: state.deps.unconfiguredMessage({ lane }) })
|
|
181
183
|
: await currentMailer({ state, id });
|
|
182
184
|
if (lane === "transactional")
|
|
183
185
|
state.lastTransactional = mailer;
|
|
184
|
-
return mailer;
|
|
186
|
+
return { mailer, providerId: id !== null && state.consoleFallbacks.has(mailer) ? "console" : id };
|
|
185
187
|
}
|
|
186
188
|
/** Settings/catalog faults become a refusal rather than throwing across the routing boundary. */
|
|
189
|
+
function laneResolution(required) {
|
|
190
|
+
return resolveLane(required).catch(() => ({ mailer: refusingMailer({ errorCode: "MAIL_PROVIDER_UNAVAILABLE", message: "Mail provider selection failed; check configuration." }), providerId: null }));
|
|
191
|
+
}
|
|
187
192
|
function forLane(required) {
|
|
188
|
-
return
|
|
193
|
+
return laneResolution(required).then(resolution => resolution.mailer);
|
|
189
194
|
}
|
|
190
195
|
/** The public mailer preserves synchronous capability reporting and awaits the proper lane for sends. */
|
|
191
196
|
function createRouter(state) {
|
|
@@ -330,7 +335,7 @@ function invalidate(state) {
|
|
|
330
335
|
export function createResolvedMailer(required, optional = {}) {
|
|
331
336
|
const state = { deps: required, options: optional, nowMs: () => (optional.clock ?? { nowMs: () => Date.now() }).nowMs(),
|
|
332
337
|
warn: optional.warn ?? (message => createConsoleLogger({ prefix: '' }).warn({ message })),
|
|
333
|
-
wrap: optional.wrapProviderMailer ?? (({ mailer }) => mailer), resolved: new Map(), inFlight: new Map(), warned: new Set(), generation: 0,
|
|
338
|
+
wrap: optional.wrapProviderMailer ?? (({ mailer }) => mailer), consoleFallbacks: new WeakSet(), resolved: new Map(), inFlight: new Map(), warned: new Set(), generation: 0,
|
|
334
339
|
initialization: undefined, lastTransactional: undefined, lastError: undefined };
|
|
335
340
|
const ready = forLane({ state, lane: "transactional" }).then(() => undefined);
|
|
336
341
|
const mailer = createRouter(state);
|
|
@@ -344,6 +349,7 @@ export function createResolvedMailer(required, optional = {}) {
|
|
|
344
349
|
describeProviders: () => describeProviders({ state, deps: required }),
|
|
345
350
|
invalidate: () => { invalidate(state); statusCache.invalidate(); },
|
|
346
351
|
laneReady: async ({ lane }) => (await forLane({ state, lane })).capabilities({}).driver !== "console",
|
|
352
|
+
effectiveProviderId: async ({ lane }) => (await laneResolution({ state, lane })).providerId,
|
|
347
353
|
checkProvider: input => checkProvider({ state, ...input }),
|
|
348
354
|
domainRequirements: input => domainRequirements({ state, ...input, resolveDomainReadCredential }),
|
|
349
355
|
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { MailActivityRepo } from "../activity/ports.js";
|
|
2
|
+
import type { MailActivityUse } from "../activity/vocabulary.js";
|
|
3
|
+
import type { MailRepoDeps } from "./ledger.repo.js";
|
|
4
|
+
/** Classify an observation once, before writing it; unknown keys stay explicitly unknown. */
|
|
5
|
+
export declare function mailActivityUse({ idempotencyKey }: {
|
|
6
|
+
idempotencyKey: string;
|
|
7
|
+
}, _optional?: Record<string, never>): MailActivityUse;
|
|
8
|
+
/**
|
|
9
|
+
* The activity reads. Newest first by creation, ties broken by the opaque activity id, so a page boundary
|
|
10
|
+
* inside one timestamp is resumed by its keyset position without exposing a key or address in the cursor.
|
|
11
|
+
* @complexity Ordinary lists merge at most two limit-sized indexed candidate pages, then probe
|
|
12
|
+
* feedback at most three times per candidate. The legacy branch can scan the recent 30-day window
|
|
13
|
+
* for purpose/duplicate exclusion. Outcome filters evaluate candidates in that window before LIMIT;
|
|
14
|
+
* they are not constant-time indexed reads. Detail uses indexed identity/recipient predicates.
|
|
15
|
+
* @example createMailActivityRepo({ db: kernel }).list({ workspaceId, limit: 26 }, { outcome: "bounced" })
|
|
16
|
+
*/
|
|
17
|
+
export declare function createMailActivityRepo<DB>({ db }: MailRepoDeps<DB>, optional?: {
|
|
18
|
+
now?: () => number;
|
|
19
|
+
}): MailActivityRepo;
|
|
20
|
+
//# sourceMappingURL=activity.repo.d.ts.map
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Read projection over the send ledger joined with provider feedback (email phase 4): the
|
|
3
|
+
* Email page's **Recent sends and failures** and `mail_list_activity`/`mail_get_activity`. One SQL
|
|
4
|
+
* body for SQLite and Postgres; migrations 0029 and 0031 add the source and lookup indexes.
|
|
5
|
+
*
|
|
6
|
+
* Only body-free metadata leaves here: the ledger stores no subject, body or link, and this never
|
|
7
|
+
* reads `mail_capture`. Outcomes are derived, never stored:
|
|
8
|
+
*
|
|
9
|
+
* - `sent` rows are `accepted` until feedback says more; the most severe event wins
|
|
10
|
+
* (complained > bounced > delivered), joined by the provider's message id.
|
|
11
|
+
* - `failed` rows keep the policy's reason: `MAIL_RECIPIENT_SUPPRESSED` is `suppressed`,
|
|
12
|
+
* `MAIL_RATE_LIMITED` is `deferred`, anything else `failed`.
|
|
13
|
+
* - `reserved` (in flight, or a crash mid-send) and `unknown` are `unknown`: the provider may have
|
|
14
|
+
* taken it, which is exactly why there is no general Resend.
|
|
15
|
+
*
|
|
16
|
+
* The observer persists use (purpose) from the idempotency key prefix each owner already writes
|
|
17
|
+
* (`members:signin:`, `newsletter:confirm-email:`, `forms:notify:`, `newsletter:`, `mail:test:`).
|
|
18
|
+
* Historical ledgers derive it within the recent window; any other key is `unknown` rather than
|
|
19
|
+
* guessed.
|
|
20
|
+
*/
|
|
21
|
+
import { sql } from "kysely";
|
|
22
|
+
import { MAIL_ACTIVITY_RETENTION_MS } from "./retention.js";
|
|
23
|
+
const USE_PREFIXES = [
|
|
24
|
+
["members:signin:", "sign_in"], ["newsletter:confirm-email:", "newsletter_confirmation"],
|
|
25
|
+
["forms:notify:", "form_notification"], ["mail:test:", "test"], ["newsletter:", "newsletter"],
|
|
26
|
+
];
|
|
27
|
+
/** Classify an observation once, before writing it; unknown keys stay explicitly unknown. */
|
|
28
|
+
export function mailActivityUse({ idempotencyKey }, _optional = {}) {
|
|
29
|
+
return USE_PREFIXES.find(([prefix]) => idempotencyKey.startsWith(prefix))?.[1] ?? "unknown";
|
|
30
|
+
}
|
|
31
|
+
/** Historical ledgers predate the purpose column. Only their recent window is projected. */
|
|
32
|
+
function legacyUse(_required = {}, _optional = {}) {
|
|
33
|
+
const clauses = USE_PREFIXES.map(([prefix, use]) => {
|
|
34
|
+
const pattern = `${prefix}%`;
|
|
35
|
+
return sql `WHEN old.idempotency_key LIKE ${pattern} THEN ${use}`;
|
|
36
|
+
});
|
|
37
|
+
const joined = sql.join(clauses, sql ` `);
|
|
38
|
+
return sql `CASE ${joined} ELSE 'unknown' END`;
|
|
39
|
+
}
|
|
40
|
+
const feedbackExists = (kind) => sql `EXISTS (SELECT 1 FROM mail_feedback_inbox f
|
|
41
|
+
WHERE f.workspace_id = l.workspace_id AND f.provider_message_id = l.provider_message_id AND f.provider_id = l.provider_id AND f.recipient = l.effective_recipient AND f.kind = ${kind} AND f.processed_at IS NOT NULL)`;
|
|
42
|
+
/** Push non-derived predicates into each indexed source; outcome is resolved after feedback. */
|
|
43
|
+
function sourceConditions(required, _optional = {}) {
|
|
44
|
+
const { filter, legacy } = required;
|
|
45
|
+
const alias = legacy ? "old" : "a";
|
|
46
|
+
const col = ({ name }, _optional = {}) => sql.ref(`${alias}.${name}`);
|
|
47
|
+
const where = [sql `${col({ name: "workspace_id" })} = ${required.workspaceId}`, sql `${col({ name: "created_at" })} >= ${required.cutoff}`];
|
|
48
|
+
if (filter.use)
|
|
49
|
+
where.push(sql `${legacy ? legacyUse() : col({ name: "use_id" })} = ${filter.use}`);
|
|
50
|
+
if (required.idempotencyKey)
|
|
51
|
+
where.push(sql `${col({ name: "idempotency_key" })} = ${required.idempotencyKey}`);
|
|
52
|
+
if (filter.recipient)
|
|
53
|
+
where.push(recipientCondition({ ...required, recipient: filter.recipient }));
|
|
54
|
+
if (filter.before)
|
|
55
|
+
where.push(sql `(${col({ name: "created_at" })} < ${filter.before.createdAt} OR (${col({ name: "created_at" })} = ${filter.before.createdAt} AND ${col({ name: legacy ? "activity_id" : "id" })} < ${filter.before.key}))`);
|
|
56
|
+
return sql.join(where, sql ` AND `);
|
|
57
|
+
}
|
|
58
|
+
/** Exact effective-recipient lookup for details; list filters also match the original address. */
|
|
59
|
+
function recipientCondition(required, _optional = {}) {
|
|
60
|
+
const address = required.recipient.trim().toLowerCase();
|
|
61
|
+
const original = sql.ref(required.legacy ? "old.recipient" : "a.recipient");
|
|
62
|
+
const effective = sql.ref(required.legacy ? "old.recipient" : "a.effective_recipient");
|
|
63
|
+
return required.effectiveOnly ? sql `${effective} = ${address}` : sql `(${original} = ${address} OR ${effective} = ${address})`;
|
|
64
|
+
}
|
|
65
|
+
/** Limit each ordered source before the UNION/feedback work on ordinary page reads. */
|
|
66
|
+
function activitySources(required, _optional = {}) {
|
|
67
|
+
const limit = required.limit === undefined ? sql `` : sql `LIMIT ${required.limit}`;
|
|
68
|
+
return sql `SELECT * FROM (
|
|
69
|
+
SELECT a.id AS activity_id, a.workspace_id, a.idempotency_key, a.recipient, a.effective_recipient, a.delivery_mode,
|
|
70
|
+
a.lane, a.provider_id, a.outcome, a.provider_message_id, a.error_code, a.message, a.created_at, a.updated_at, a.use_id
|
|
71
|
+
FROM mail_activity_attempts a WHERE ${sourceConditions({ ...required, legacy: false })}
|
|
72
|
+
ORDER BY a.created_at DESC, a.id DESC ${limit}
|
|
73
|
+
) attempts
|
|
74
|
+
UNION ALL SELECT * FROM (
|
|
75
|
+
SELECT old.activity_id, old.workspace_id, old.idempotency_key, old.recipient, old.recipient AS effective_recipient, 'off' AS delivery_mode,
|
|
76
|
+
old.lane, old.provider_id, old.outcome, old.provider_message_id, old.error_code, NULL AS message, old.created_at, old.updated_at, ${legacyUse()} AS use_id
|
|
77
|
+
FROM mail_send_ledger old WHERE ${sourceConditions({ ...required, legacy: true })}
|
|
78
|
+
AND old.activity_retained = 1 AND NOT EXISTS (SELECT 1 FROM mail_activity_attempts a
|
|
79
|
+
WHERE a.workspace_id = old.workspace_id AND a.idempotency_key = old.idempotency_key AND a.recipient = old.recipient)
|
|
80
|
+
ORDER BY old.created_at DESC, old.activity_id DESC ${limit}
|
|
81
|
+
) legacy`;
|
|
82
|
+
}
|
|
83
|
+
/** Feedback is probed only for candidate rows; the attempts' stored purpose remains indexable. */
|
|
84
|
+
function projection(required, _optional = {}) {
|
|
85
|
+
return sql `SELECT l.*,
|
|
86
|
+
CASE WHEN l.outcome = 'captured' THEN 'captured' WHEN l.outcome = 'sent' THEN
|
|
87
|
+
CASE WHEN ${feedbackExists("complained")} THEN 'complained' WHEN ${feedbackExists("bounced")} THEN 'bounced'
|
|
88
|
+
WHEN ${feedbackExists("delivered")} THEN 'delivered' ELSE 'accepted' END
|
|
89
|
+
WHEN l.outcome = 'failed' THEN
|
|
90
|
+
CASE WHEN l.error_code = 'MAIL_RECIPIENT_SUPPRESSED' THEN 'suppressed' WHEN l.error_code = 'MAIL_RATE_LIMITED' THEN 'deferred' ELSE 'failed' END
|
|
91
|
+
ELSE 'unknown' END AS activity_outcome
|
|
92
|
+
FROM (${activitySources(required)}) l`;
|
|
93
|
+
}
|
|
94
|
+
function toRecord(row) {
|
|
95
|
+
return {
|
|
96
|
+
cursorKey: row.activity_id, idempotencyKey: row.idempotency_key, recipient: row.effective_recipient,
|
|
97
|
+
...(row.delivery_mode === "off" ? {} : { originalRecipient: row.recipient, deliveryMode: row.delivery_mode }), lane: row.lane, providerId: row.provider_id, use: row.use_id,
|
|
98
|
+
outcome: row.activity_outcome, providerMessageId: row.provider_message_id, errorCode: row.error_code, message: row.message, createdAt: row.created_at, updatedAt: row.updated_at,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The activity reads. Newest first by creation, ties broken by the opaque activity id, so a page boundary
|
|
103
|
+
* inside one timestamp is resumed by its keyset position without exposing a key or address in the cursor.
|
|
104
|
+
* @complexity Ordinary lists merge at most two limit-sized indexed candidate pages, then probe
|
|
105
|
+
* feedback at most three times per candidate. The legacy branch can scan the recent 30-day window
|
|
106
|
+
* for purpose/duplicate exclusion. Outcome filters evaluate candidates in that window before LIMIT;
|
|
107
|
+
* they are not constant-time indexed reads. Detail uses indexed identity/recipient predicates.
|
|
108
|
+
* @example createMailActivityRepo({ db: kernel }).list({ workspaceId, limit: 26 }, { outcome: "bounced" })
|
|
109
|
+
*/
|
|
110
|
+
export function createMailActivityRepo({ db }, optional = {}) {
|
|
111
|
+
const cutoff = () => new Date((optional.now ?? Date.now)() - MAIL_ACTIVITY_RETENTION_MS).toISOString();
|
|
112
|
+
return {
|
|
113
|
+
async list(required, optional = {}) {
|
|
114
|
+
const source = { workspaceId: required.workspaceId, cutoff: cutoff(), filter: optional, ...(optional.outcome ? {} : { limit: required.limit }) };
|
|
115
|
+
const outcome = optional.outcome ? sql `WHERE a.activity_outcome = ${optional.outcome}` : sql ``;
|
|
116
|
+
const rows = await db.query(sql `SELECT * FROM (${projection(source)}) a ${outcome}
|
|
117
|
+
ORDER BY a.created_at DESC, a.activity_id DESC LIMIT ${required.limit}`);
|
|
118
|
+
return rows.map(toRecord);
|
|
119
|
+
},
|
|
120
|
+
async get({ workspaceId, idempotencyKey, recipient }) {
|
|
121
|
+
const [row] = await db.query(sql `SELECT * FROM (${projection({ workspaceId, cutoff: cutoff(), filter: { recipient }, idempotencyKey, effectiveOnly: true, limit: 1 })}) a LIMIT 1`);
|
|
122
|
+
if (!row)
|
|
123
|
+
return null;
|
|
124
|
+
const feedback = row.provider_message_id === null ? [] : await db.query(sql `SELECT kind, hard_bounce, provider_id, occurred_at, received_at FROM mail_feedback_inbox
|
|
125
|
+
WHERE workspace_id = ${workspaceId} AND provider_message_id = ${row.provider_message_id} AND provider_id = ${row.provider_id} AND recipient = ${row.effective_recipient} AND processed_at IS NOT NULL ORDER BY occurred_at, event_id`);
|
|
126
|
+
return {
|
|
127
|
+
record: toRecord(row),
|
|
128
|
+
feedback: feedback.map((event) => ({ kind: event.kind, hardBounce: Number(event.hard_bounce) === 1, providerId: event.provider_id, occurredAt: event.occurred_at, receivedAt: event.received_at })),
|
|
129
|
+
};
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
//# sourceMappingURL=activity.repo.js.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { MailRepoDeps, MailRepoOptions } from "./ledger.repo.js";
|
|
2
|
+
import type { MailTestModeSetting } from "@jini-ai/core/contracts/mail";
|
|
3
|
+
import type { MailerSendOptions, MailerSendResult, OutboundEmail } from "../ports.js";
|
|
4
|
+
/** The delivery policy's per-result observer. Declared here (not in server/) so features never import server code. */
|
|
5
|
+
export type MailAttemptObserver = (required: {
|
|
6
|
+
message: OutboundEmail;
|
|
7
|
+
options: MailerSendOptions;
|
|
8
|
+
providerId: string;
|
|
9
|
+
mode: MailTestModeSetting;
|
|
10
|
+
result: MailerSendResult;
|
|
11
|
+
}) => Promise<void>;
|
|
12
|
+
/** Upsert one request's latest result without changing its original position in activity history.
|
|
13
|
+
* @complexity One indexed write; no subject, body or authentication link is stored; only a scrubbed failure diagnostic. */
|
|
14
|
+
export declare function createMailAttemptObserver<DB>({ db }: MailRepoDeps<DB>, options?: MailRepoOptions & {
|
|
15
|
+
newId?: () => string;
|
|
16
|
+
}): MailAttemptObserver;
|
|
17
|
+
//# sourceMappingURL=attempts.repo.d.ts.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Body-free observation of every policy result, including preflight refusals and captures. */
|
|
2
|
+
import { safeMailProviderText } from "../provider-error.js";
|
|
3
|
+
import { laneForPurpose } from "../policy.js";
|
|
4
|
+
import { mailActivityUse } from "./activity.repo.js";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { sql } from "kysely";
|
|
7
|
+
/** Upsert one request's latest result without changing its original position in activity history.
|
|
8
|
+
* @complexity One indexed write; no subject, body or authentication link is stored; only a scrubbed failure diagnostic. */
|
|
9
|
+
export function createMailAttemptObserver({ db }, options = {}) {
|
|
10
|
+
const nowIso = options.nowIso ?? (() => new Date().toISOString());
|
|
11
|
+
const newId = options.newId ?? randomUUID;
|
|
12
|
+
return async ({ message, options: send, providerId, mode, result }) => {
|
|
13
|
+
const at = nowIso();
|
|
14
|
+
const recipient = message.to.email.trim().toLowerCase();
|
|
15
|
+
const effective = mode.mode === "redirect" ? mode.to.trim().toLowerCase() : recipient;
|
|
16
|
+
let outcome;
|
|
17
|
+
if (result.ok) {
|
|
18
|
+
outcome = result.providerMessageId.startsWith("captured:") || providerId === "console" ? "captured" : "sent";
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
outcome = result.unknown ? "unknown" : "failed";
|
|
22
|
+
}
|
|
23
|
+
await db.execute(sql `INSERT INTO mail_activity_attempts
|
|
24
|
+
(id, workspace_id, idempotency_key, recipient, effective_recipient, delivery_mode, use_id, lane, provider_id, outcome, provider_message_id, error_code, message, created_at, updated_at)
|
|
25
|
+
VALUES (${newId()}, ${send.workspaceId}, ${send.idempotencyKey}, ${recipient}, ${effective}, ${mode.mode}, ${mailActivityUse({ idempotencyKey: send.idempotencyKey })}, ${laneForPurpose({ purpose: send.purpose })}, ${providerId}, ${outcome}, ${result.ok ? result.providerMessageId : null}, ${result.ok ? null : safeMailProviderText({ text: result.errorCode })}, ${result.ok ? null : safeMailProviderText({ text: result.message })}, ${at}, ${at})
|
|
26
|
+
ON CONFLICT (workspace_id, idempotency_key, recipient) DO UPDATE SET
|
|
27
|
+
effective_recipient = excluded.effective_recipient, delivery_mode = excluded.delivery_mode, use_id = excluded.use_id,
|
|
28
|
+
provider_id = excluded.provider_id, outcome = excluded.outcome, provider_message_id = excluded.provider_message_id,
|
|
29
|
+
error_code = excluded.error_code, message = excluded.message, updated_at = excluded.updated_at`);
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=attempts.repo.js.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { type OriginRegistryPort } from "@jini-ai/core/contracts/server/verified-origin";
|
|
2
|
+
import type { MailCaptureClearPlan } from "@jini-ai/core/contracts/mail";
|
|
3
|
+
import type { MailCapturePort, MailDeliveryLane, OutboundEmail } from "../ports.js";
|
|
4
|
+
import type { MailRepoDeps, MailRepoOptions } from "./ledger.repo.js";
|
|
5
|
+
export interface CapturedMail {
|
|
6
|
+
id: string;
|
|
7
|
+
lane: MailDeliveryLane;
|
|
8
|
+
idempotencyKey: string;
|
|
9
|
+
to: string;
|
|
10
|
+
subject: string;
|
|
11
|
+
message: OutboundEmail;
|
|
12
|
+
createdAt: string;
|
|
13
|
+
}
|
|
14
|
+
export interface MailCaptureRepo extends MailCapturePort {
|
|
15
|
+
/** Newest first. `limit` is clamped to 1..{@link MAX_CAPTURE_LIST}; default {@link DEFAULT_CAPTURE_LIST}. */
|
|
16
|
+
listCaptured(required: {
|
|
17
|
+
workspaceId: string;
|
|
18
|
+
}, optional?: {
|
|
19
|
+
limit?: number;
|
|
20
|
+
}): Promise<readonly CapturedMail[]>;
|
|
21
|
+
/**
|
|
22
|
+
* The owner's review of a clear: this workspace's stored captures plus the activity rows the Email
|
|
23
|
+
* Activity list shows as kept locally (`outcome = 'captured'`, which includes console-driver sends that
|
|
24
|
+
* never store a copy), their summary, and the revision naming exactly that set. `plan.count` counts
|
|
25
|
+
* distinct test emails (a test-mode capture and its activity row are one email).
|
|
26
|
+
*/
|
|
27
|
+
reviewCaptured(required: {
|
|
28
|
+
workspaceId: string;
|
|
29
|
+
}): Promise<CapturedMailReview>;
|
|
30
|
+
/**
|
|
31
|
+
* Deletes, in one transaction, only the reviewed `captureIds` and still-captured `attemptIds` of this
|
|
32
|
+
* workspace, and retires the matching send-ledger rows from the activity projection so a cleared send
|
|
33
|
+
* cannot resurface there. A capture that arrived after the review, or another workspace's, is never
|
|
34
|
+
* deleted; the ledger rows themselves (duplicate protection) and real sends are untouched.
|
|
35
|
+
* @returns `deleted`: the distinct test emails removed, counted like `plan.count`.
|
|
36
|
+
*/
|
|
37
|
+
clearReviewedCaptures(required: {
|
|
38
|
+
workspaceId: string;
|
|
39
|
+
captureIds: readonly string[];
|
|
40
|
+
attemptIds: readonly string[];
|
|
41
|
+
}): Promise<{
|
|
42
|
+
deleted: number;
|
|
43
|
+
}>;
|
|
44
|
+
}
|
|
45
|
+
/** A reviewed set of captured test emails; `revision` changes whenever the set does (not only its count or newest time). */
|
|
46
|
+
export interface CapturedMailReview {
|
|
47
|
+
plan: MailCaptureClearPlan;
|
|
48
|
+
captureIds: readonly string[];
|
|
49
|
+
attemptIds: readonly string[];
|
|
50
|
+
revision: string;
|
|
51
|
+
}
|
|
52
|
+
export declare const DEFAULT_CAPTURE_LIST = 50;
|
|
53
|
+
export declare const MAX_CAPTURE_LIST = 200;
|
|
54
|
+
/**
|
|
55
|
+
* Stores sign-in captures whole only for trusted loopback origins, so local/desktop operators
|
|
56
|
+
* can click their links. Public or missing origins retain routing metadata only: subject, body,
|
|
57
|
+
* headers, names and attachments may all contain credentials and must never reach storage.
|
|
58
|
+
* @complexity capture O(payload size); listCaptured O(returned payload size), with a bounded indexed row limit;
|
|
59
|
+
* reviewCaptured O(workspace captures + captured attempts), two workspace-scoped reads; clearReviewedCaptures
|
|
60
|
+
* O(reviewed ids) primary-key deletes in ceil(ids / 500) statements per table plus one indexed ledger
|
|
61
|
+
* update per deleted attempt, one transaction.
|
|
62
|
+
* @example createMailCaptureRepo({ db: kernel }).capture({ message, lane: "transactional", idempotencyKey })
|
|
63
|
+
*/
|
|
64
|
+
export declare function createMailCaptureRepo<DB>({ db, origin }: MailRepoDeps<DB> & {
|
|
65
|
+
origin?: OriginRegistryPort;
|
|
66
|
+
}, optional?: MailRepoOptions & {
|
|
67
|
+
newId?: () => string;
|
|
68
|
+
}): MailCaptureRepo;
|
|
69
|
+
//# sourceMappingURL=capture.repo.d.ts.map
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/** @file SQL adapter for Jini's `MailCapturePort` (migration 0023): test/capture mode's message sink. */
|
|
2
|
+
import { isLoopbackHostname } from "@jini-ai/core/net";
|
|
3
|
+
import { OriginNotVerifiedError, } from "@jini-ai/core/contracts/server/verified-origin";
|
|
4
|
+
import { mailActivityUse } from "./activity.repo.js";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { sql } from "kysely";
|
|
7
|
+
export const DEFAULT_CAPTURE_LIST = 50;
|
|
8
|
+
export const MAX_CAPTURE_LIST = 200;
|
|
9
|
+
/** Ids per `DELETE ... IN (...)`, under every dialect's bound-parameter limit. */
|
|
10
|
+
const CLEAR_CHUNK = 500;
|
|
11
|
+
const clampLimit = ({ limit }, _optional = {}) => Math.min(MAX_CAPTURE_LIST, Math.max(1, Math.trunc(limit ?? DEFAULT_CAPTURE_LIST)));
|
|
12
|
+
/**
|
|
13
|
+
* Stores sign-in captures whole only for trusted loopback origins, so local/desktop operators
|
|
14
|
+
* can click their links. Public or missing origins retain routing metadata only: subject, body,
|
|
15
|
+
* headers, names and attachments may all contain credentials and must never reach storage.
|
|
16
|
+
* @complexity capture O(payload size); listCaptured O(returned payload size), with a bounded indexed row limit;
|
|
17
|
+
* reviewCaptured O(workspace captures + captured attempts), two workspace-scoped reads; clearReviewedCaptures
|
|
18
|
+
* O(reviewed ids) primary-key deletes in ceil(ids / 500) statements per table plus one indexed ledger
|
|
19
|
+
* update per deleted attempt, one transaction.
|
|
20
|
+
* @example createMailCaptureRepo({ db: kernel }).capture({ message, lane: "transactional", idempotencyKey })
|
|
21
|
+
*/
|
|
22
|
+
export function createMailCaptureRepo({ db, origin }, optional = {}) {
|
|
23
|
+
const nowIso = optional.nowIso ?? (() => new Date().toISOString());
|
|
24
|
+
const newId = optional.newId ?? randomUUID;
|
|
25
|
+
return {
|
|
26
|
+
async capture({ message, lane, idempotencyKey }) {
|
|
27
|
+
const stored = await capturePayload({ message, idempotencyKey, origin });
|
|
28
|
+
const id = newId();
|
|
29
|
+
await db.execute(sql `INSERT INTO mail_capture (id, workspace_id, lane, idempotency_key, to_address, subject, payload_json, created_at)
|
|
30
|
+
VALUES (${id}, ${message.workspaceId}, ${lane}, ${idempotencyKey}, ${stored.to.email}, ${stored.subject}, ${JSON.stringify(stored)}, ${nowIso()})`);
|
|
31
|
+
return { id };
|
|
32
|
+
},
|
|
33
|
+
async listCaptured({ workspaceId }, options = {}) {
|
|
34
|
+
const rows = await db.query(sql `SELECT id, lane, idempotency_key, to_address, subject, payload_json, created_at FROM mail_capture
|
|
35
|
+
WHERE workspace_id = ${workspaceId} ORDER BY created_at DESC, id DESC LIMIT ${clampLimit({ limit: options.limit })}`);
|
|
36
|
+
return rows.map((row) => ({
|
|
37
|
+
id: row.id, lane: row.lane, idempotencyKey: row.idempotency_key, to: row.to_address, subject: row.subject,
|
|
38
|
+
message: JSON.parse(row.payload_json), createdAt: row.created_at,
|
|
39
|
+
}));
|
|
40
|
+
},
|
|
41
|
+
async reviewCaptured({ workspaceId }) {
|
|
42
|
+
const captures = await db.query(sql `SELECT id, created_at, idempotency_key, to_address AS recipient FROM mail_capture WHERE workspace_id = ${workspaceId} ORDER BY id`);
|
|
43
|
+
const attempts = await db.query(sql `SELECT id, created_at, idempotency_key, recipient FROM mail_activity_attempts
|
|
44
|
+
WHERE workspace_id = ${workspaceId} AND outcome = 'captured' ORDER BY id`);
|
|
45
|
+
const captureIds = captures.map((row) => row.id);
|
|
46
|
+
const attemptIds = attempts.map((row) => row.id);
|
|
47
|
+
const newestAt = [...captures, ...attempts].reduce((max, row) => (max === null || row.created_at > max ? row.created_at : max), null);
|
|
48
|
+
return { plan: { count: distinctEmails({ rows: [...captures, ...attempts] }), newestAt }, captureIds, attemptIds, revision: captureSetRevision({ workspaceId, captureIds, attemptIds }) };
|
|
49
|
+
},
|
|
50
|
+
clearReviewedCaptures: ({ workspaceId, captureIds, attemptIds }) => db.transaction(() => deleteReviewedCaptureRows({ db, workspaceId, captureIds, attemptIds })),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
async function deleteReviewedCaptureRows({ db, workspaceId, captureIds, attemptIds }) {
|
|
54
|
+
const removed = [];
|
|
55
|
+
for (let at = 0; at < captureIds.length; at += CLEAR_CHUNK) {
|
|
56
|
+
const ids = captureIds.slice(at, at + CLEAR_CHUNK);
|
|
57
|
+
// RETURNING reads deleted rows the same way on SQLite and Postgres.
|
|
58
|
+
removed.push(...await db.query(sql `DELETE FROM mail_capture WHERE workspace_id = ${workspaceId} AND id IN (${sql.join(ids)})
|
|
59
|
+
RETURNING id, created_at, idempotency_key, to_address AS recipient`));
|
|
60
|
+
}
|
|
61
|
+
for (let at = 0; at < attemptIds.length; at += CLEAR_CHUNK) {
|
|
62
|
+
const ids = attemptIds.slice(at, at + CLEAR_CHUNK);
|
|
63
|
+
// `outcome = 'captured'` again: an attempt upserted into a real send since the review is not a test email.
|
|
64
|
+
const rows = await db.query(sql `DELETE FROM mail_activity_attempts WHERE workspace_id = ${workspaceId} AND outcome = 'captured' AND id IN (${sql.join(ids)})
|
|
65
|
+
RETURNING id, created_at, idempotency_key, recipient`);
|
|
66
|
+
// The activity list falls back to a retained ledger row when its attempt is missing; retire it (as retention does) so the cleared send stays gone.
|
|
67
|
+
for (const row of rows) {
|
|
68
|
+
await db.execute(sql `UPDATE mail_send_ledger SET activity_retained = 0 WHERE workspace_id = ${workspaceId} AND idempotency_key = ${row.idempotency_key} AND recipient = ${row.recipient}`);
|
|
69
|
+
}
|
|
70
|
+
removed.push(...rows);
|
|
71
|
+
}
|
|
72
|
+
return { deleted: distinctEmails({ rows: removed }) };
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The revision of one workspace's reviewed capture set: a digest of its sorted ids, so two different
|
|
76
|
+
* sets with the same count and newest time never share a revision. @complexity O(ids log ids).
|
|
77
|
+
*/
|
|
78
|
+
function captureSetRevision(required, _optional = {}) {
|
|
79
|
+
const { workspaceId, captureIds, attemptIds } = required;
|
|
80
|
+
const digest = createHash("sha256").update(workspaceId);
|
|
81
|
+
for (const id of [...captureIds].sort())
|
|
82
|
+
digest.update("\nc:").update(id);
|
|
83
|
+
for (const id of [...attemptIds].sort())
|
|
84
|
+
digest.update("\na:").update(id);
|
|
85
|
+
return `captures-v2:${captureIds.length}:${attemptIds.length}:${digest.digest("base64url")}`;
|
|
86
|
+
}
|
|
87
|
+
/** One test email per (idempotency key, recipient): a test-mode capture and its activity row count once. @complexity O(rows). */
|
|
88
|
+
function distinctEmails({ rows }, _optional = {}) {
|
|
89
|
+
return new Set(rows.map((row) => `${row.idempotency_key}\n${row.recipient.trim().toLowerCase()}`)).size;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Redacts sign-in captures at the persistence boundary, before serialization. The activity owner
|
|
93
|
+
* classifies the host's purpose keys; Jini owns loopback detection. Missing evidence fails closed.
|
|
94
|
+
* @returns The original local/non-auth message, or an allowlisted public sign-in envelope.
|
|
95
|
+
* @throws Unexpected origin/storage failures propagate; no unredacted fallback is persisted.
|
|
96
|
+
* @complexity O(1), at most one origin read; redaction does not scan credential-bearing content.
|
|
97
|
+
*/
|
|
98
|
+
async function capturePayload(required, _options = {}) {
|
|
99
|
+
const { message, idempotencyKey, origin } = required;
|
|
100
|
+
if (mailActivityUse({ idempotencyKey }) !== "sign_in")
|
|
101
|
+
return message;
|
|
102
|
+
try {
|
|
103
|
+
const canonical = await origin?.canonicalOrigin({ workspaceId: message.workspaceId });
|
|
104
|
+
if (canonical && isLoopbackHostname({ hostname: canonical.host }))
|
|
105
|
+
return message;
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
if (!(err instanceof OriginNotVerifiedError))
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
workspaceId: message.workspaceId,
|
|
113
|
+
to: { email: message.to.email },
|
|
114
|
+
from: { email: message.from.email },
|
|
115
|
+
subject: "Sign-in email (content redacted)",
|
|
116
|
+
text: "Authentication content is not stored on public sites.",
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=capture.repo.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { MailFeedbackInboxPort } from "../feedback.js";
|
|
2
|
+
import type { MailRepoDeps, MailRepoOptions } from "./ledger.repo.js";
|
|
3
|
+
/**
|
|
4
|
+
* Provider feedback events, insert-if-absent on (provider, event id): a provider's replay of an
|
|
5
|
+
* event it already delivered is reported `duplicate`, so suppression is written once.
|
|
6
|
+
* Only a row whose `processed_at` is set (by `complete`, after suppression succeeded) counts as
|
|
7
|
+
* delivered: a replay of an unprocessed row is reported `inserted` so the ingest re-applies it.
|
|
8
|
+
* @complexity O(1) per event.
|
|
9
|
+
* @example createMailFeedbackInboxRepo({ db: kernel }).record({ providerId: "<mail-provider-id>", event })
|
|
10
|
+
*/
|
|
11
|
+
export declare function createMailFeedbackInboxRepo<DB>({ db }: MailRepoDeps<DB>, optional?: MailRepoOptions): MailFeedbackInboxPort;
|
|
12
|
+
//# sourceMappingURL=feedback-inbox.repo.d.ts.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** @file SQL adapter for Jini's `MailFeedbackInboxPort` (migrations 0023, 0025), one body for SQLite and Postgres. */
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
/**
|
|
4
|
+
* Provider feedback events, insert-if-absent on (provider, event id): a provider's replay of an
|
|
5
|
+
* event it already delivered is reported `duplicate`, so suppression is written once.
|
|
6
|
+
* Only a row whose `processed_at` is set (by `complete`, after suppression succeeded) counts as
|
|
7
|
+
* delivered: a replay of an unprocessed row is reported `inserted` so the ingest re-applies it.
|
|
8
|
+
* @complexity O(1) per event.
|
|
9
|
+
* @example createMailFeedbackInboxRepo({ db: kernel }).record({ providerId: "<mail-provider-id>", event })
|
|
10
|
+
*/
|
|
11
|
+
export function createMailFeedbackInboxRepo({ db }, optional = {}) {
|
|
12
|
+
const nowIso = optional.nowIso ?? (() => new Date().toISOString());
|
|
13
|
+
return {
|
|
14
|
+
async record({ providerId, event }) {
|
|
15
|
+
const inserted = await db.query(sql `INSERT INTO mail_feedback_inbox
|
|
16
|
+
(provider_id, event_id, workspace_id, recipient, kind, hard_bounce, provider_message_id, occurred_at, received_at)
|
|
17
|
+
VALUES (${providerId}, ${event.eventId}, ${event.workspaceId}, ${event.recipient}, ${event.kind}, ${event.hardBounce ? 1 : 0},
|
|
18
|
+
${event.providerMessageId}, ${event.occurredAt}, ${nowIso()})
|
|
19
|
+
ON CONFLICT (provider_id, event_id) DO NOTHING RETURNING event_id`);
|
|
20
|
+
if (inserted.length > 0)
|
|
21
|
+
return "inserted";
|
|
22
|
+
const [row] = await db.query(sql `SELECT processed_at FROM mail_feedback_inbox
|
|
23
|
+
WHERE provider_id = ${providerId} AND event_id = ${event.eventId}`);
|
|
24
|
+
// The INSERT conflicted, so the row exists; a workspace delete cascading in between is not retried.
|
|
25
|
+
return row.processed_at === null ? "inserted" : "duplicate";
|
|
26
|
+
},
|
|
27
|
+
async complete({ providerId, eventId }) {
|
|
28
|
+
await db.execute(sql `UPDATE mail_feedback_inbox SET processed_at = ${nowIso()} WHERE provider_id = ${providerId} AND event_id = ${eventId}`);
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=feedback-inbox.repo.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** @file `@jini-ai/platform/mail/sql`: Kysely SQL adapters for the mail ports (ledgers, suppression,
|
|
2
|
+
* capture, activity, feedback inbox, retention). Opt-in: importing this subpath needs `kysely`. */
|
|
3
|
+
export { createMailSendLedgerRepo, type MailRepoDeps, type MailRepoOptions, type MailSqlKernel } from "./ledger.repo.js";
|
|
4
|
+
export { createMailSuppressionRepo } from "./suppression.repo.js";
|
|
5
|
+
export { createMailSuppressionAdminRepo } from "./suppression-admin.repo.js";
|
|
6
|
+
export { createMailFeedbackInboxRepo } from "./feedback-inbox.repo.js";
|
|
7
|
+
export { createMailCaptureRepo, DEFAULT_CAPTURE_LIST, MAX_CAPTURE_LIST, type CapturedMail, type MailCaptureRepo } from "./capture.repo.js";
|
|
8
|
+
export { createMailActivityRepo, mailActivityUse } from "./activity.repo.js";
|
|
9
|
+
export { createMailAttemptObserver, type MailAttemptObserver } from "./attempts.repo.js";
|
|
10
|
+
export { purgeExpiredMail, startMailRetention, type MailRetentionOptions, MAIL_ACTIVITY_RETENTION_MS, MAIL_CAPTURE_RETENTION_MS, MAIL_RETENTION_INTERVAL_MS } from "./retention.js";
|
|
11
|
+
export { createSiteMailFeedbackRoute } from "./site-feedback-route.js";
|
|
12
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** @file `@jini-ai/platform/mail/sql`: Kysely SQL adapters for the mail ports (ledgers, suppression,
|
|
2
|
+
* capture, activity, feedback inbox, retention). Opt-in: importing this subpath needs `kysely`. */
|
|
3
|
+
export { createMailSendLedgerRepo } from "./ledger.repo.js";
|
|
4
|
+
export { createMailSuppressionRepo } from "./suppression.repo.js";
|
|
5
|
+
export { createMailSuppressionAdminRepo } from "./suppression-admin.repo.js";
|
|
6
|
+
export { createMailFeedbackInboxRepo } from "./feedback-inbox.repo.js";
|
|
7
|
+
export { createMailCaptureRepo, DEFAULT_CAPTURE_LIST, MAX_CAPTURE_LIST } from "./capture.repo.js";
|
|
8
|
+
export { createMailActivityRepo, mailActivityUse } from "./activity.repo.js";
|
|
9
|
+
export { createMailAttemptObserver } from "./attempts.repo.js";
|
|
10
|
+
export { purgeExpiredMail, startMailRetention, MAIL_ACTIVITY_RETENTION_MS, MAIL_CAPTURE_RETENTION_MS, MAIL_RETENTION_INTERVAL_MS } from "./retention.js";
|
|
11
|
+
export { createSiteMailFeedbackRoute } from "./site-feedback-route.js";
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Kysely, RawBuilder } from "kysely";
|
|
2
|
+
import type { StorageKernel } from "@jini-ai/core/contracts/storage";
|
|
3
|
+
import type { MailSendLedgerPort } from "../ports.js";
|
|
4
|
+
/** The content database kernel. Generic so a typed `ContentKernel` fits: these tables are raw SQL,
|
|
5
|
+
* outside the generated Kysely types, so only `query`/`execute`/`transaction`/`lockKey` are used. */
|
|
6
|
+
export interface MailRepoDeps<DB = unknown> {
|
|
7
|
+
db: MailSqlKernel<DB>;
|
|
8
|
+
}
|
|
9
|
+
/** Core's storage kernel over a Kysely handle, plus raw `sql` statements: `query` returns rows,
|
|
10
|
+
* `execute` returns none. A host's Kysely-bound kernel (`@jini-ai/db/kernel`) fits structurally. */
|
|
11
|
+
export interface MailSqlKernel<DB = unknown> extends StorageKernel<Kysely<DB>, DB> {
|
|
12
|
+
query<Row>(statement: RawBuilder<Row>): Promise<Row[]>;
|
|
13
|
+
execute(statement: RawBuilder<unknown>): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export interface MailRepoOptions {
|
|
16
|
+
/** Injected ISO clock; defaults to the wall clock. */
|
|
17
|
+
nowIso?: () => string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Reserve → send → mark ledger. `reserve` inserts-if-absent, then flips a `failed` row (or, with
|
|
21
|
+
* `reclaimUnknown`, a same-content `unknown` row) back to `reserved` in one conditional UPDATE (a
|
|
22
|
+
* definitive failure sent nothing, so a retry under the same identity is safe), else returns the
|
|
23
|
+
* stored row. Both run under the identity's `lockKey`, so a
|
|
24
|
+
* concurrent `mark` cannot turn the row `failed` between the flip and the read.
|
|
25
|
+
* @complexity O(1) primary-key statements per call.
|
|
26
|
+
* @example createMailSendLedgerRepo({ db: kernel }).reserve({ workspaceId, idempotencyKey, recipient, payloadHash, lane: "transactional", providerId: "smtp" })
|
|
27
|
+
*/
|
|
28
|
+
export declare function createMailSendLedgerRepo<DB>({ db }: MailRepoDeps<DB>, optional?: MailRepoOptions): MailSendLedgerPort;
|
|
29
|
+
//# sourceMappingURL=ledger.repo.d.ts.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** @file SQL adapter for Jini's `MailSendLedgerPort` (migration 0023), one body for SQLite and Postgres. */
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { sql } from "kysely";
|
|
4
|
+
/** One advisory lock per ledger identity: reserve's read-after-write and mark never interleave. */
|
|
5
|
+
function lockName({ workspaceId, idempotencyKey, recipient }) {
|
|
6
|
+
return `mail-ledger:${workspaceId}:${idempotencyKey}:${recipient}`;
|
|
7
|
+
}
|
|
8
|
+
function existingOf(row) {
|
|
9
|
+
return {
|
|
10
|
+
status: "existing", outcome: row.outcome, payloadHash: row.payload_hash,
|
|
11
|
+
...(row.provider_message_id === null ? {} : { providerMessageId: row.provider_message_id }),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Reserve → send → mark ledger. `reserve` inserts-if-absent, then flips a `failed` row (or, with
|
|
16
|
+
* `reclaimUnknown`, a same-content `unknown` row) back to `reserved` in one conditional UPDATE (a
|
|
17
|
+
* definitive failure sent nothing, so a retry under the same identity is safe), else returns the
|
|
18
|
+
* stored row. Both run under the identity's `lockKey`, so a
|
|
19
|
+
* concurrent `mark` cannot turn the row `failed` between the flip and the read.
|
|
20
|
+
* @complexity O(1) primary-key statements per call.
|
|
21
|
+
* @example createMailSendLedgerRepo({ db: kernel }).reserve({ workspaceId, idempotencyKey, recipient, payloadHash, lane: "transactional", providerId: "smtp" })
|
|
22
|
+
*/
|
|
23
|
+
export function createMailSendLedgerRepo({ db }, optional = {}) {
|
|
24
|
+
const nowIso = optional.nowIso ?? (() => new Date().toISOString());
|
|
25
|
+
const where = ({ workspaceId, idempotencyKey, recipient }) => sql `workspace_id = ${workspaceId} AND idempotency_key = ${idempotencyKey} AND recipient = ${recipient}`;
|
|
26
|
+
const reserve = async (required, _optional = {}) => {
|
|
27
|
+
const { workspaceId, idempotencyKey, recipient, payloadHash, lane, providerId, reclaimUnknown } = required;
|
|
28
|
+
await db.lockKey(lockName(required));
|
|
29
|
+
const at = nowIso();
|
|
30
|
+
const inserted = await db.query(sql `INSERT INTO mail_send_ledger (workspace_id, idempotency_key, recipient, payload_hash, lane, provider_id, outcome, created_at, updated_at, activity_id)
|
|
31
|
+
VALUES (${workspaceId}, ${idempotencyKey}, ${recipient}, ${payloadHash}, ${lane}, ${providerId}, 'reserved', ${at}, ${at}, ${randomUUID()})
|
|
32
|
+
ON CONFLICT (workspace_id, idempotency_key, recipient) DO NOTHING RETURNING outcome`);
|
|
33
|
+
if (inserted.length > 0)
|
|
34
|
+
return { status: "reserved" };
|
|
35
|
+
// A corrected retry after a definitive failure may carry new content, so the hash moves with it.
|
|
36
|
+
// A resendable `unknown` row is claimed only for the same content: the flip to `reserved` is the
|
|
37
|
+
// claim, so of two concurrent retries exactly one re-sends and the other sees `reserved`.
|
|
38
|
+
const unknown = reclaimUnknown ? sql `OR (outcome = 'unknown' AND payload_hash = ${payloadHash})` : sql ``;
|
|
39
|
+
const flipped = await db.query(sql `UPDATE mail_send_ledger SET outcome = 'reserved', payload_hash = ${payloadHash}, lane = ${lane},
|
|
40
|
+
provider_id = ${providerId}, provider_message_id = NULL, error_code = NULL, updated_at = ${at}
|
|
41
|
+
WHERE ${where(required)} AND (outcome = 'failed' ${unknown}) RETURNING outcome`);
|
|
42
|
+
if (flipped.length > 0)
|
|
43
|
+
return { status: "reserved" };
|
|
44
|
+
const [row] = await db.query(sql `SELECT outcome, payload_hash, provider_message_id FROM mail_send_ledger WHERE ${where(required)}`);
|
|
45
|
+
// The INSERT conflicted under the identity lock, so the row exists and is not `failed`.
|
|
46
|
+
return existingOf(row);
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
reserve: (required, optional = {}) => db.transaction(async () => reserve({ ...required, reclaimUnknown: optional.reclaimUnknown === true })),
|
|
50
|
+
mark: (required) => db.transaction(async () => {
|
|
51
|
+
await db.lockKey(lockName(required));
|
|
52
|
+
await db.execute(sql `UPDATE mail_send_ledger SET outcome = ${required.outcome}, provider_message_id = ${required.providerMessageId ?? null},
|
|
53
|
+
error_code = ${required.errorCode ?? null}, updated_at = ${nowIso()} WHERE ${where(required)}`);
|
|
54
|
+
}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=ledger.repo.js.map
|