forked from ezedike-evan/stellar-intel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite.ts
More file actions
204 lines (187 loc) · 6.63 KB
/
Copy pathsqlite.ts
File metadata and controls
204 lines (187 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import Database from 'better-sqlite3';
import type { OutcomeLogRow, OutcomeStatus, ProbeLedgerRow } from '@/types/reputation';
import type {
DeliveredUpdate,
DisputedUpdate,
OutcomeQuery,
ProbeSampleQuery,
ReputationStore,
} from './store';
// ─── SQLite backend (Issue #128 / #219) — local/dev ────────────────────────────
type DbInstance = InstanceType<typeof Database>;
const CREATE_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS outcome_log (
intentHash TEXT NOT NULL PRIMARY KEY,
anchorId TEXT NOT NULL,
corridor TEXT NOT NULL,
quotedRate TEXT NOT NULL,
deliveredRate TEXT,
quotedAmount TEXT NOT NULL,
deliveredAmount TEXT,
settleSeconds REAL,
outcome TEXT NOT NULL,
createdAt TEXT NOT NULL,
stellarTransactionId TEXT,
reconciledAt TEXT,
disputed INTEGER NOT NULL DEFAULT 0,
disputed_reason TEXT,
publishedAt TEXT,
oracleTxHash TEXT
);
CREATE INDEX IF NOT EXISTS idx_outcome_log_anchor ON outcome_log (anchorId);
CREATE TABLE IF NOT EXISTS probe_samples (
domain TEXT NOT NULL,
kind TEXT NOT NULL DEFAULT 'uptime',
corridor TEXT,
reachable INTEGER NOT NULL,
latencyMs REAL NOT NULL,
failureType TEXT,
error TEXT,
probedAt TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_probe_samples_domain ON probe_samples (domain);
CREATE INDEX IF NOT EXISTS idx_probe_samples_domain_corridor ON probe_samples (domain, corridor);
`;
interface OutcomeLogRowDb {
intentHash: string;
anchorId: string;
corridor: string;
quotedRate: string;
deliveredRate: string | null;
quotedAmount: string;
deliveredAmount: string | null;
settleSeconds: number | null;
outcome: string;
createdAt: string;
stellarTransactionId: string | null;
reconciledAt: string | null;
disputed: number;
disputed_reason: string | null;
publishedAt: string | null;
oracleTxHash: string | null;
}
function fromDb(r: OutcomeLogRowDb): OutcomeLogRow {
return {
...r,
outcome: r.outcome as OutcomeStatus,
disputed: r.disputed !== 0,
disputedReason: r.disputed_reason,
};
}
function fromProbeDb(r: Record<string, unknown>): ProbeLedgerRow {
return {
domain: String(r['domain']),
kind: (r['kind'] as ProbeLedgerRow['kind']) ?? 'uptime',
corridor: (r['corridor'] as string) ?? null,
reachable: Boolean(r['reachable']),
latencyMs: Number(r['latencyMs']),
failureType: (r['failureType'] as ProbeLedgerRow['failureType']) ?? null,
error: (r['error'] as string) ?? null,
probedAt: String(r['probedAt']),
};
}
export class SqliteReputationStore implements ReputationStore {
private readonly db: DbInstance;
constructor(path: string = ':memory:') {
this.db = new Database(path);
this.db.pragma('journal_mode = WAL');
this.db.exec(CREATE_TABLE_SQL);
}
async append(row: OutcomeLogRow): Promise<void> {
this.db
.prepare(
`INSERT OR REPLACE INTO outcome_log
(intentHash, anchorId, corridor, quotedRate, deliveredRate, quotedAmount,
deliveredAmount, settleSeconds, outcome, createdAt, stellarTransactionId, reconciledAt,
disputed, disputed_reason, publishedAt, oracleTxHash)
VALUES
(@intentHash, @anchorId, @corridor, @quotedRate, @deliveredRate, @quotedAmount,
@deliveredAmount, @settleSeconds, @outcome, @createdAt, @stellarTransactionId, @reconciledAt,
@disputed, @disputedReason, @publishedAt, @oracleTxHash)`
)
.run({ ...row, disputed: row.disputed ? 1 : 0 });
}
async query(filter: OutcomeQuery = {}): Promise<OutcomeLogRow[]> {
const where: string[] = [];
const params: Record<string, unknown> = {};
if (filter.anchorId) {
where.push('anchorId = @anchorId');
params['anchorId'] = filter.anchorId;
}
if (filter.corridor) {
where.push('corridor = @corridor');
params['corridor'] = filter.corridor;
}
if (filter.pendingReconciliationOnly) {
where.push(
'deliveredAmount IS NULL AND reconciledAt IS NULL AND stellarTransactionId IS NOT NULL'
);
}
const sql = `SELECT * FROM outcome_log ${
where.length ? `WHERE ${where.join(' AND ')}` : ''
} ORDER BY createdAt ASC`;
return (this.db.prepare(sql).all(params) as OutcomeLogRowDb[]).map(fromDb);
}
async markDelivered(intentHash: string, update: DeliveredUpdate): Promise<void> {
this.db
.prepare(
`UPDATE outcome_log
SET deliveredAmount = @deliveredAmount,
deliveredRate = @deliveredRate,
reconciledAt = @reconciledAt
WHERE intentHash = @intentHash`
)
.run({ ...update, intentHash });
}
async markDisputed(intentHash: string, update: DisputedUpdate): Promise<void> {
this.db
.prepare(
`UPDATE outcome_log
SET disputed = @disputed,
disputed_reason = @disputedReason
WHERE intentHash = @intentHash`
)
.run({
disputed: update.disputed ? 1 : 0,
disputedReason: update.disputedReason,
intentHash,
});
}
async recordProbeSample(row: ProbeLedgerRow): Promise<void> {
this.db
.prepare(
`INSERT INTO probe_samples (domain, kind, corridor, reachable, latencyMs, failureType, error, probedAt)
VALUES (@domain, @kind, @corridor, @reachable, @latencyMs, @failureType, @error, @probedAt)`
)
.run({ ...row, reachable: row.reachable ? 1 : 0 });
}
async queryProbeSamples(domain?: string, filter: ProbeSampleQuery = {}): Promise<ProbeLedgerRow[]> {
const where: string[] = [];
const params: Record<string, unknown> = {};
if (domain) {
where.push('domain = @domain');
params['domain'] = domain;
}
if (filter.corridor) {
where.push('corridor = @corridor');
params['corridor'] = filter.corridor;
}
if (filter.kind) {
where.push('kind = @kind');
params['kind'] = filter.kind;
}
const sql = `SELECT * FROM probe_samples ${
where.length ? `WHERE ${where.join(' AND ')}` : ''
} ORDER BY probedAt ASC`;
return (this.db.prepare(sql).all(params) as Array<Record<string, unknown>>).map(fromProbeDb);
}
async compactProbes(cutoff: Date): Promise<number> {
const result = this.db
.prepare(`DELETE FROM probe_samples WHERE probedAt < @cutoff`)
.run({ cutoff: cutoff.toISOString() });
return result.changes;
}
async close(): Promise<void> {
this.db.close();
}
}