Skip to content

Commit 1d89f5e

Browse files
authored
Stabilize Slice 1 local D1 test reads (#51)
## Summary - stop invoking a second `wrangler d1 execute` process while the Slice 1 `wrangler dev` worker is live - expose the few DB-only assertions through test-only `__test/*` routes on the same Worker/D1 binding - remove all live-test `queryDatabase()` calls ## Why The second Wrangler process against the same local persistence directory caused deterministic/flaky `ECONNRESET` failures in the sign-in trace tests. It also added ~26 seconds to the suite. ## Validation - Slice 1 full suite: 29/29 passing four consecutive runs - runtime reduced from ~59s to ~33s - `npm run check`: 0 errors, 0 warnings (2 pre-existing hints) No production HTTP/API behavior is changed; the new routes exist only in the dedicated Slice 1 test worker.
1 parent ac7889b commit 1d89f5e

2 files changed

Lines changed: 95 additions & 47 deletions

File tree

‎scripts/orbit-slice1-test-worker.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,52 @@ async function testRoute(request: Request, env: TestEnv): Promise<Response | nul
241241
return Response.json({ account, counts });
242242
}
243243

244+
if (url.pathname === '/__test/sign-in-events') {
245+
const githubUserId = String(body.githubUserId ?? '');
246+
const events = githubUserId
247+
? await env.DB.prepare(`
248+
SELECT e.event_type, e.ip, e.created_at
249+
FROM account_sign_in_events e
250+
JOIN auth_identities i ON i.account_id = e.account_id
251+
WHERE i.provider_user_id = ?
252+
ORDER BY e.created_at ASC
253+
`).bind(githubUserId).all()
254+
: { results: [] };
255+
const total = await env.DB.prepare(
256+
'SELECT COUNT(*) AS total FROM account_sign_in_events',
257+
).first<{ total: number }>();
258+
return Response.json({ events: events.results, total: total?.total ?? 0 });
259+
}
260+
261+
if (url.pathname === '/__test/auth-identities') {
262+
const providerUserIds = Array.isArray(body.providerUserIds)
263+
? body.providerUserIds.map((value) => String(value))
264+
: [];
265+
const identities: Array<{ provider_user_id: string; provider_email_snapshot: string | null }> = [];
266+
for (const providerUserId of providerUserIds) {
267+
const row = await env.DB.prepare(`
268+
SELECT provider_user_id, provider_email_snapshot
269+
FROM auth_identities
270+
WHERE provider_user_id = ?
271+
`).bind(providerUserId).first<{
272+
provider_user_id: string;
273+
provider_email_snapshot: string | null;
274+
}>();
275+
if (row) identities.push(row);
276+
}
277+
identities.sort((left, right) => left.provider_user_id.localeCompare(right.provider_user_id));
278+
return Response.json({ identities });
279+
}
280+
281+
if (url.pathname === '/__test/account-consent') {
282+
const row = await env.DB.prepare(`
283+
SELECT terms_accepted_at, terms_version
284+
FROM accounts
285+
WHERE id = ?
286+
`).bind(String(body.accountId ?? '')).first();
287+
return Response.json({ row });
288+
}
289+
244290
if (url.pathname === '/__test/session') {
245291
const row = await env.DB.prepare(`
246292
SELECT id, last_seen_at, idle_expires_at, absolute_expires_at, revoked_at

‎scripts/orbit-slice1-tests.ts‎

Lines changed: 49 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -50,19 +50,44 @@ function migrate(): void {
5050
if (result.status !== 0) throw new Error(`${result.stdout}\n${result.stderr}`);
5151
}
5252

53-
/* Giriş izinin HTTP yüzeyi yok ve olmaması bilinçli: IP'leri web'e açan bir
54-
* uç, bir yetkilendirme hatasında sızdırılacak yüzey demek. Kayıt hukuki
55-
* talep geldiğinde elle sorgulanıyor — testin de aynı yoldan bakması,
56-
* gerçekte kullanılacak yolu doğrulaması anlamına geliyor. */
57-
function queryDatabase<T>(sql: string): T[] {
58-
const result = spawnSync(process.execPath, [
59-
WRANGLER, 'd1', 'execute', 'orbit-v6-local',
60-
'--config', CONFIG, '--local', `--persist-to=${persistDirectory}`,
61-
'--json', '--command', sql,
62-
], { cwd: ROOT, encoding: 'utf8', env: { ...process.env, CI: '1', NO_COLOR: '1' } });
63-
if (result.status !== 0) throw new Error(`${result.stdout}\n${result.stderr}`);
64-
const payload = JSON.parse(result.stdout.slice(result.stdout.indexOf('['))) as Array<{ results: T[] }>;
65-
return payload[0]?.results ?? [];
53+
/* Test sırasında çalışan Wrangler'ın local D1 persist klasörüne ikinci bir
54+
* `wrangler d1 execute` süreciyle girmek workerd bağlantısını resetleyebiliyor.
55+
* DB-only doğrulamalarını production yüzeyine eklemek yerine test Worker'ın
56+
* kapalı `__test/*` rotalarından aynı binding üzerinden okuyoruz. */
57+
async function signInState(githubUserId?: string): Promise<{
58+
events: Array<{ event_type: string; ip: string | null; created_at: number }>;
59+
total: number;
60+
}> {
61+
const response = await postJson('/__test/sign-in-events', githubUserId ? { githubUserId } : {});
62+
assert.equal(response.status, 200, await response.clone().text());
63+
return await response.json() as {
64+
events: Array<{ event_type: string; ip: string | null; created_at: number }>;
65+
total: number;
66+
};
67+
}
68+
69+
async function authIdentitySnapshots(providerUserIds: string[]): Promise<Array<{
70+
provider_user_id: string;
71+
provider_email_snapshot: string | null;
72+
}>> {
73+
const response = await postJson('/__test/auth-identities', { providerUserIds });
74+
assert.equal(response.status, 200, await response.clone().text());
75+
return (await response.json() as {
76+
identities: Array<{ provider_user_id: string; provider_email_snapshot: string | null }>;
77+
}).identities;
78+
}
79+
80+
async function accountConsent(accountId: string): Promise<{
81+
terms_accepted_at: number | null;
82+
terms_version: string | null;
83+
}> {
84+
const response = await postJson('/__test/account-consent', { accountId });
85+
assert.equal(response.status, 200, await response.clone().text());
86+
const row = (await response.json() as {
87+
row: { terms_accepted_at: number | null; terms_version: string | null } | null;
88+
}).row;
89+
assert.ok(row, 'hesap onay satırı bulunamadı');
90+
return row;
6691
}
6792

6893
async function availablePort(): Promise<number> {
@@ -425,13 +450,7 @@ let firstCredentialToken = '';
425450
const relogin = await callback('traced', await startOAuth(NOW + 203), NOW + 204, '198.51.100.22');
426451
assert.equal(relogin.status, 302, await relogin.clone().text());
427452

428-
const rows = queryDatabase<{ event_type: string; ip: string | null; created_at: number }>(`
429-
SELECT e.event_type, e.ip, e.created_at
430-
FROM account_sign_in_events e
431-
JOIN auth_identities i ON i.account_id = e.account_id
432-
WHERE i.provider_user_id = '200000004'
433-
ORDER BY e.created_at ASC
434-
`);
453+
const rows = (await signInState('200000004')).events;
435454

436455
assert.equal(rows.length, 2, 'her giriş iz bırakmıyor');
437456
assert.equal(rows[0].event_type, 'registration', 'ilk giriş kayıt olarak işaretlenmemiş');
@@ -445,9 +464,7 @@ let firstCredentialToken = '';
445464
* gösterir — sorumlu insanı değil. O yüzden yazma yolunda iz hiç
446465
* okunmuyor. Bu test o sınırın yerinde durduğunu ölçüyor: ajan bir
447466
* istek yapıyor ve ortada yeni bir giriş izi oluşmuyor. */
448-
const before = queryDatabase<{ total: number }>(
449-
'SELECT COUNT(*) AS total FROM account_sign_in_events',
450-
)[0].total;
467+
const before = (await signInState()).total;
451468
/* Boş tabloda "sayı değişmedi" demek hiçbir şey ölçmez; testin
452469
* kendisinin boşa geçmediğini burada kelepçeliyoruz. */
453470
assert.ok(before > 0, 'iz tablosu boş: bu test hiçbir şey ölçmüyor');
@@ -460,9 +477,7 @@ let firstCredentialToken = '';
460477
}, NOW + 210);
461478
assert.equal(agentCall.status, 401, 'test varsayımı kaydı: bu çağrı reddedilmeliydi');
462479

463-
const after = queryDatabase<{ total: number }>(
464-
'SELECT COUNT(*) AS total FROM account_sign_in_events',
465-
)[0].total;
480+
const after = (await signInState()).total;
466481
assert.equal(after, before, 'ajanın API isteği giriş izi yazmış');
467482
});
468483

@@ -477,10 +492,7 @@ let firstCredentialToken = '';
477492
);
478493
assert.equal(unverified.status, 302, await unverified.clone().text());
479494

480-
const stored = queryDatabase<{ provider_user_id: string; provider_email_snapshot: string | null }>(`
481-
SELECT provider_user_id, provider_email_snapshot FROM auth_identities
482-
WHERE provider_user_id IN ('200000004', '200000005')
483-
`);
495+
const stored = await authIdentitySnapshots(['200000004', '200000005']);
484496
const traced = stored.find((row) => row.provider_user_id === '200000004');
485497
const withoutEmail = stored.find((row) => row.provider_user_id === '200000005');
486498

@@ -498,9 +510,7 @@ let firstCredentialToken = '';
498510
* adresinin ikinci girişten sonra da yerinde durması. */
499511
const relogin = await callback('traced', await startOAuth(NOW + 223), NOW + 224);
500512
assert.equal(relogin.status, 302);
501-
const afterRelogin = queryDatabase<{ provider_email_snapshot: string | null }>(
502-
"SELECT provider_email_snapshot FROM auth_identities WHERE provider_user_id = '200000004'",
503-
);
513+
const afterRelogin = await authIdentitySnapshots(['200000004']);
504514
assert.equal(afterRelogin[0]?.provider_email_snapshot, 'izli@example.test');
505515
});
506516

@@ -518,9 +528,7 @@ let firstCredentialToken = '';
518528
);
519529
assert.equal(registration.status, 302, await registration.clone().text());
520530

521-
const stored = queryDatabase<{ provider_email_snapshot: string | null }>(
522-
"SELECT provider_email_snapshot FROM auth_identities WHERE provider_user_id = '200000006'",
523-
);
531+
const stored = await authIdentitySnapshots(['200000006']);
524532
assert.equal(
525533
stored[0]?.provider_email_snapshot,
526534
'gercek@example.test',
@@ -2184,7 +2192,7 @@ let firstCredentialToken = '';
21842192
* bir noktada çalışıyor; iz bir yıl duruyor. Burada düşerse saklama
21852193
* süresi sessizce kısalmış demektir ve gizlilik metni yalan söyler. */
21862194
assert.ok(
2187-
queryDatabase<{ total: number }>('SELECT COUNT(*) AS total FROM account_sign_in_events')[0].total > 0,
2195+
(await signInState()).total > 0,
21882196
'giriş izi bir yıl dolmadan siliniyor',
21892197
);
21902198
});
@@ -2193,9 +2201,7 @@ let firstCredentialToken = '';
21932201
/* Gizlilik metnindeki "bir yıl" cümlesi bu silmenin çalışmasına
21942202
* dayanıyor. Saklama süresi bir vaat: yazıp uygulamamak, hiç
21952203
* yazmamaktan kötü. */
2196-
const before = queryDatabase<{ total: number }>(
2197-
'SELECT COUNT(*) AS total FROM account_sign_in_events',
2198-
)[0].total;
2204+
const before = (await signInState()).total;
21992205
assert.ok(before > 0, 'iz tablosu zaten boş: bu test hiçbir şey ölçmüyor');
22002206

22012207
const cleanupAt = NOW + 366 * 24 * 60 * 60 * 1000;
@@ -2205,7 +2211,7 @@ let firstCredentialToken = '';
22052211
assert.equal(body.signInEvents, before, 'temizlik sildiği iz sayısını doğru bildirmiyor');
22062212

22072213
assert.equal(
2208-
queryDatabase<{ total: number }>('SELECT COUNT(*) AS total FROM account_sign_in_events')[0].total,
2214+
(await signInState()).total,
22092215
0,
22102216
'bir yılı geçen giriş izi hâlâ duruyor',
22112217
);
@@ -2347,9 +2353,7 @@ let firstCredentialToken = '';
23472353
headers: authenticatedHeaders(cookieValues(registration)),
23482354
}, NOW + 532)).json() as { account: { id: string } };
23492355

2350-
const first = queryDatabase<{ terms_accepted_at: number | null; terms_version: string | null }>(
2351-
`SELECT terms_accepted_at, terms_version FROM accounts WHERE id = '${me.account.id}'`,
2352-
)[0];
2356+
const first = await accountConsent(me.account.id);
23532357
assert.equal(first.terms_accepted_at, NOW + 530, 'kayıt anındaki onay yazılmamış');
23542358
assert.equal(first.terms_version, LEGAL_LAST_UPDATED, 'onaylanan metnin sürümü yazılmamış');
23552359

@@ -2361,9 +2365,7 @@ let firstCredentialToken = '';
23612365
'true',
23622366
);
23632367
assert.equal(relogin.status, 302, await relogin.clone().text());
2364-
const second = queryDatabase<{ terms_accepted_at: number | null }>(
2365-
`SELECT terms_accepted_at FROM accounts WHERE id = '${me.account.id}'`,
2366-
)[0];
2368+
const second = await accountConsent(me.account.id);
23672369
assert.equal(
23682370
second.terms_accepted_at,
23692371
NOW + 540,

0 commit comments

Comments
 (0)