Skip to content

Commit 7bf8193

Browse files
committed
Exercise D1PublicRepository against a real database
The class was never instantiated in any test. orbit-public-page-tests.ts drives an in-memory fake, so listFeed, getRecord and the whole hydration path — topic accent, reply count, reply agents, latest reply — shipped without a single query ever running in CI. That is precisely the code the feed is made of. The test worker now seeds a fixed public world: agents carrying accents and empty avatars, an active topic and a retired one, a post answered twice by the same agent and once by another, a removed reply, a deleted reply, and a second post crowded by five agents. Thirteen tests read it back through the real repository over local D1. Mutation-checked rather than assumed: reversing the reply ordering and letting retired topics through makes three of them fail. The wrangler-dev harness moves to scripts/support/d1-test-worker-harness.ts so orbit-d1-tests.ts and the new file share one copy.
1 parent 7af98b8 commit 7bf8193

5 files changed

Lines changed: 438 additions & 138 deletions

File tree

‎package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@
3838
"staging:slice5:images-cpu": "tsx scripts/orbit-slice5-images-cpu-staging-e2e.ts",
3939
"orbit:import:verify": "tsx scripts/orbit-slice3-manifest.ts",
4040
"orbit:import:local": "tsx scripts/orbit-slice3-import.ts --local --database=orbit-v6-local --config=wrangler.test.jsonc",
41-
"test:d1": "tsx --test --test-concurrency=5 scripts/orbit-agent-identity-tests.ts scripts/orbit-api-contract-tests.ts scripts/orbit-d1-tests.ts scripts/orbit-mcp-authorization-tests.ts scripts/orbit-public-page-tests.ts scripts/orbit-single-renderer-tests.ts scripts/orbit-slice1-tests.ts scripts/orbit-slice1-worker-tests.ts scripts/orbit-slice3-tests.ts scripts/orbit-slice4-tests.ts scripts/orbit-slice5-tests.ts",
42-
"test:d1:core": "tsx --test --test-concurrency=5 scripts/orbit-agent-identity-tests.ts scripts/orbit-api-contract-tests.ts scripts/orbit-d1-tests.ts scripts/orbit-public-page-tests.ts scripts/orbit-slice1-tests.ts scripts/orbit-slice1-worker-tests.ts scripts/orbit-slice3-tests.ts",
41+
"test:d1": "tsx --test --test-concurrency=5 scripts/orbit-agent-identity-tests.ts scripts/orbit-api-contract-tests.ts scripts/orbit-d1-tests.ts scripts/orbit-mcp-authorization-tests.ts scripts/orbit-public-page-tests.ts scripts/orbit-public-repository-tests.ts scripts/orbit-single-renderer-tests.ts scripts/orbit-slice1-tests.ts scripts/orbit-slice1-worker-tests.ts scripts/orbit-slice3-tests.ts scripts/orbit-slice4-tests.ts scripts/orbit-slice5-tests.ts",
42+
"test:d1:core": "tsx --test --test-concurrency=5 scripts/orbit-agent-identity-tests.ts scripts/orbit-api-contract-tests.ts scripts/orbit-d1-tests.ts scripts/orbit-public-page-tests.ts scripts/orbit-public-repository-tests.ts scripts/orbit-slice1-tests.ts scripts/orbit-slice1-worker-tests.ts scripts/orbit-slice3-tests.ts",
4343
"test:d1:publication": "tsx --test scripts/orbit-slice4-tests.ts",
4444
"test:d1:platform": "tsx --test scripts/orbit-slice5-tests.ts",
4545
"v6:check": "npm run test:d1 && npm run check && npm run worker:build",

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

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
import { createDynamicBackup } from '../src/server/backup/dynamic-backup';
66
import type { McpAuthorizationScope } from '../src/server/identity/mcp-authorization-scopes';
77
import { D1McpAuthorizationRepository } from '../src/server/repositories/d1/d1-mcp-authorization-repository';
8+
import { D1PublicRepository } from '../src/server/repositories/d1/d1-public-repository';
89

910
interface TestStatement {
1011
bind(...values: unknown[]): TestStatement;
@@ -38,6 +39,11 @@ function stringValue(data: Record<string, unknown>, key: string): string {
3839
return value;
3940
}
4041

42+
function optionalString(data: Record<string, unknown>, key: string): string | null {
43+
const value = data[key];
44+
return typeof value === 'string' && value.length > 0 ? value : null;
45+
}
46+
4147
function numberValue(data: Record<string, unknown>, key: string): number {
4248
const value = data[key];
4349
if (typeof value !== 'number' || !Number.isFinite(value)) {
@@ -127,10 +133,107 @@ async function seedAgent(
127133
`).bind(credentialId, agentId, credentialDigest, sponsorId, now).run();
128134
}
129135

136+
/**
137+
* Public okuma testleri için sabit bir dünya kurar: accent'li ajanlar, biri
138+
* emekli iki konu, bir gönderi ve görünürlük durumları farklı yanıtlar.
139+
* Amaç D1PublicRepository'nin hidrasyon SQL'ini gerçek veritabanında koşturmak.
140+
*/
141+
async function seedPublicWorld(
142+
db: TestDatabase,
143+
repository: D1FoundationRepository,
144+
now: number,
145+
): Promise<void> {
146+
await seedOwner(db, 'public-owner', now);
147+
148+
const agents: Array<[handle: string, avatar: string, accent: string]> = [
149+
['alfa', '/agents/alfa.webp', '#a891ff'],
150+
['beta', '/agents/beta.webp', '#f0bd68'],
151+
['gama', '', '#69cfe3'],
152+
['delta', '/agents/delta.webp', '#ff4fd8'],
153+
['epsilon', '', '#5fbf7a'],
154+
['zeta', '', '#c76a3d'],
155+
['eta', '', '#3d7ac7'],
156+
];
157+
for (const [handle, avatar, accent] of agents) {
158+
await db.prepare(`
159+
INSERT INTO agents (
160+
id, handle, handle_normalized, display_name, bio, avatar_asset,
161+
accent, publication_mode, status, created_at, updated_at
162+
) VALUES (?, ?, ?, ?, '', ?, ?, 'direct_publish', 'active', ?, ?)
163+
`).bind(handle, handle, handle, handle, avatar, accent, now, now).run();
164+
}
165+
166+
await db.prepare(`
167+
INSERT INTO topics (id, slug, label, status, accent)
168+
VALUES ('topic-live', 'yorunge', 'Yörünge', 'active', '#3aa0d8')
169+
`).run();
170+
await db.prepare(`
171+
INSERT INTO topics (id, slug, label, status, accent)
172+
VALUES ('topic-retired', 'arsiv', 'Arşiv', 'retired', '#999999')
173+
`).run();
174+
175+
const publish = async (
176+
id: string,
177+
authorAgentId: string,
178+
publishedAt: number,
179+
parent: { parentId: string; rootId: string } | null,
180+
): Promise<void> => {
181+
await repository.createRecordWithRevision({
182+
record: {
183+
id,
184+
kind: parent ? 'reply' : 'post',
185+
authorAgentId,
186+
slug: `slug-${id}`,
187+
parentId: parent?.parentId,
188+
rootId: parent?.rootId ?? id,
189+
lifecycleState: 'published',
190+
createdAt: publishedAt,
191+
publishedAt,
192+
},
193+
revision: {
194+
id: `rev-${id}`,
195+
bodyMarkdown: `${id} gövdesi`,
196+
summary: `${id} özeti`,
197+
state: 'published',
198+
createdByAgentId: authorAgentId,
199+
createdAt: publishedAt,
200+
publishedAt,
201+
},
202+
});
203+
};
204+
205+
// Ana gönderi: iki konu, biri emekli.
206+
await publish('post-main', 'alfa', now, null);
207+
for (const topicId of ['topic-live', 'topic-retired']) {
208+
await db.prepare(`
209+
INSERT INTO record_topics (record_id, topic_id, created_at) VALUES (?, ?, ?)
210+
`).bind('post-main', topicId, now).run();
211+
}
212+
213+
const thread = { parentId: 'post-main', rootId: 'post-main' };
214+
await publish('reply-beta-1', 'beta', now + 10, thread);
215+
await publish('reply-gama', 'gama', now + 20, thread);
216+
await publish('reply-beta-2', 'beta', now + 30, thread);
217+
// Kaldırılan ve silinen yanıt: ne sayıya ne avatar yığınına girmeli.
218+
await publish('reply-removed', 'delta', now + 40, thread);
219+
await db.prepare(`UPDATE records SET moderation_state = 'removed' WHERE id = 'reply-removed'`).run();
220+
await publish('reply-deleted', 'delta', now + 50, thread);
221+
await db.prepare(`UPDATE records SET deleted_at = ? WHERE id = 'reply-deleted'`).bind(now + 51).run();
222+
223+
// İkinci gönderi: beş farklı ajan yanıtlıyor, avatar yığını dörtte kesilmeli.
224+
await publish('post-crowded', 'alfa', now + 100, null);
225+
const crowd = { parentId: 'post-crowded', rootId: 'post-crowded' };
226+
const crowdAgents = ['beta', 'gama', 'delta', 'epsilon', 'zeta'];
227+
for (const [index, handle] of crowdAgents.entries()) {
228+
await publish(`reply-crowd-${handle}`, handle, now + 101 + index, crowd);
229+
}
230+
}
231+
130232
async function handleAction(body: ActionRequest, env: Environment): Promise<Response> {
131233
const data = body.data ?? {};
132234
const repository = new D1FoundationRepository(env.DB);
133235
const mcpRepository = new D1McpAuthorizationRepository(env.DB);
236+
const publicRepository = new D1PublicRepository(env.DB);
134237

135238
switch (body.action) {
136239
case 'health':
@@ -531,6 +634,32 @@ async function handleAction(body: ActionRequest, env: Environment): Promise<Resp
531634
return json({ row });
532635
}
533636

637+
case 'seedPublicWorld': {
638+
await seedPublicWorld(env.DB, repository, numberValue(data, 'now'));
639+
return json({ ok: true });
640+
}
641+
642+
case 'publicFeed': {
643+
const page = await publicRepository.listFeed({
644+
limit: numberValue(data, 'limit'),
645+
cursor: null,
646+
agentHandle: optionalString(data, 'agentHandle'),
647+
projectSlug: null,
648+
topicSlug: optionalString(data, 'topicSlug'),
649+
});
650+
return json(page);
651+
}
652+
653+
case 'publicRecord': {
654+
const record = await publicRepository.getRecord(stringValue(data, 'idOrSlug'));
655+
return json({ record });
656+
}
657+
658+
case 'publicThreadReplies': {
659+
const replies = await publicRepository.listThreadReplies(stringValue(data, 'rootId'));
660+
return json({ replies });
661+
}
662+
534663
default:
535664
return json({ error: 'unknown_action' }, 404);
536665
}

‎scripts/orbit-d1-tests.ts‎

Lines changed: 10 additions & 136 deletions
Original file line numberDiff line numberDiff line change
@@ -1,113 +1,22 @@
11
import assert from 'node:assert/strict';
2-
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from 'node:child_process';
3-
import { mkdtemp, rm } from 'node:fs/promises';
4-
import { createServer } from 'node:net';
5-
import { tmpdir } from 'node:os';
6-
import path from 'node:path';
72
import { after, before, describe, test } from 'node:test';
3+
import { startTestWorker, type TestWorker } from './support/d1-test-worker-harness';
84
import { createEntityId, createRequestId, isUuidV7 } from '../src/server/foundation/ids';
95
import { createErrorEnvelope } from '../src/server/foundation/errors';
106
import { redactSecrets } from '../src/server/foundation/redaction';
117

12-
const ROOT = process.cwd();
13-
const WRANGLER = path.join(ROOT, 'node_modules', 'wrangler', 'bin', 'wrangler.js');
14-
const CONFIG = 'wrangler.test.jsonc';
15-
16-
let persistDirectory = '';
17-
let baseUrl = '';
18-
let worker: ChildProcessWithoutNullStreams | undefined;
8+
let harness: TestWorker | undefined;
199
let firstMigrationOutput = '';
2010
let secondMigrationOutput = '';
2111

22-
function runMigrations(): string {
23-
const result = spawnSync(
24-
process.execPath,
25-
[
26-
WRANGLER,
27-
'd1',
28-
'migrations',
29-
'apply',
30-
'orbit-v6-local',
31-
'--config',
32-
CONFIG,
33-
'--local',
34-
`--persist-to=${persistDirectory}`,
35-
],
36-
{
37-
cwd: ROOT,
38-
encoding: 'utf8',
39-
env: { ...process.env, CI: '1', NO_COLOR: '1' },
40-
},
41-
);
42-
43-
if (result.status !== 0) {
44-
throw new Error(`Migration command failed:\n${result.stdout}\n${result.stderr}`);
45-
}
46-
47-
return `${result.stdout}\n${result.stderr}`;
48-
}
49-
50-
async function availablePort(): Promise<number> {
51-
return await new Promise((resolve, reject) => {
52-
const server = createServer();
53-
server.once('error', reject);
54-
server.listen(0, '127.0.0.1', () => {
55-
const address = server.address();
56-
if (!address || typeof address === 'string') {
57-
server.close();
58-
reject(new Error('Could not allocate a local test port.'));
59-
return;
60-
}
61-
const { port } = address;
62-
server.close((error) => (error ? reject(error) : resolve(port)));
63-
});
64-
});
65-
}
66-
67-
async function waitForWorker(process: ChildProcessWithoutNullStreams): Promise<void> {
68-
const deadline = Date.now() + 20_000;
69-
let output = '';
70-
process.stdout.on('data', (chunk) => { output += String(chunk); });
71-
process.stderr.on('data', (chunk) => { output += String(chunk); });
72-
73-
while (Date.now() < deadline) {
74-
if (process.exitCode !== null) {
75-
throw new Error(`Wrangler exited before becoming ready:\n${output}`);
76-
}
77-
try {
78-
const response = await fetch(baseUrl, {
79-
method: 'POST',
80-
headers: { 'content-type': 'application/json' },
81-
body: JSON.stringify({ action: 'health' }),
82-
});
83-
if (response.ok) return;
84-
} catch {
85-
// Wrangler has not bound the local port yet.
86-
}
87-
await new Promise((resolve) => setTimeout(resolve, 100));
88-
}
89-
90-
throw new Error(`Wrangler did not become ready within 20 seconds:\n${output}`);
91-
}
92-
93-
async function callAction<T>(
12+
const callAction = async <T>(
9413
action: string,
9514
data: Record<string, unknown> = {},
9615
expectedStatus = 200,
97-
): Promise<T> {
98-
const response = await fetch(baseUrl, {
99-
method: 'POST',
100-
headers: { 'content-type': 'application/json' },
101-
body: JSON.stringify({ action, data }),
102-
});
103-
const body = await response.json() as T;
104-
assert.equal(
105-
response.status,
106-
expectedStatus,
107-
`${action} returned ${response.status}: ${JSON.stringify(body)}`,
108-
);
109-
return body;
110-
}
16+
): Promise<T> => {
17+
if (!harness) throw new Error('Test worker is not running.');
18+
return await harness.callAction<T>(action, data, expectedStatus);
19+
};
11120

11221
function registrationData(prefix: string, invitationId: string, githubUserId: string, now: number) {
11322
return {
@@ -128,47 +37,12 @@ function registrationData(prefix: string, invitationId: string, githubUserId: st
12837
}
12938

13039
before(async () => {
131-
persistDirectory = await mkdtemp(path.join(tmpdir(), 'orbit-v6-d1-'));
132-
firstMigrationOutput = runMigrations();
133-
secondMigrationOutput = runMigrations();
134-
135-
const port = await availablePort();
136-
let inspectorPort = await availablePort();
137-
while (inspectorPort === port) inspectorPort = await availablePort();
138-
baseUrl = `http://127.0.0.1:${port}`;
139-
worker = spawn(
140-
process.execPath,
141-
[
142-
WRANGLER,
143-
'dev',
144-
'--config',
145-
CONFIG,
146-
'--local',
147-
`--port=${port}`,
148-
`--inspector-port=${inspectorPort}`,
149-
`--persist-to=${persistDirectory}`,
150-
],
151-
{
152-
cwd: ROOT,
153-
env: { ...process.env, CI: '1', NO_COLOR: '1' },
154-
stdio: ['pipe', 'pipe', 'pipe'],
155-
},
156-
);
157-
await waitForWorker(worker);
40+
harness = await startTestWorker();
41+
[firstMigrationOutput, secondMigrationOutput] = harness.migrationOutputs;
15842
});
15943

16044
after(async () => {
161-
if (worker && worker.exitCode === null) {
162-
worker.kill('SIGTERM');
163-
await Promise.race([
164-
new Promise<void>((resolve) => worker?.once('exit', () => resolve())),
165-
new Promise<void>((resolve) => setTimeout(resolve, 3_000)),
166-
]);
167-
if (worker.exitCode === null) worker.kill('SIGKILL');
168-
}
169-
if (persistDirectory) {
170-
await rm(persistDirectory, { recursive: true, force: true });
171-
}
45+
await harness?.stop();
17246
});
17347

17448
describe('Orbit V6 Slice 0 local-D1 foundation', { concurrency: false }, () => {

0 commit comments

Comments
 (0)