@redditech/provider-kit 0.2.1 → 0.3.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 +44 -11
- package/dist/src/adl.d.ts +2 -2
- package/dist/src/adl.js +4 -4
- package/dist/src/capacity.d.ts +61 -0
- package/dist/src/capacity.js +67 -0
- package/dist/src/config.d.ts +18 -0
- package/dist/src/config.js +46 -3
- package/dist/src/doctor.d.ts +2 -0
- package/dist/src/doctor.js +19 -0
- package/dist/src/handler.d.ts +21 -1
- package/dist/src/handler.js +184 -57
- package/dist/src/index.d.ts +4 -0
- package/dist/src/index.js +4 -0
- package/dist/src/keys.d.ts +10 -0
- package/dist/src/keys.js +29 -4
- package/dist/src/pending.d.ts +9 -3
- package/dist/src/postgres.d.ts +78 -0
- package/dist/src/postgres.js +186 -0
- package/dist/src/server.d.ts +3 -0
- package/dist/src/server.js +21 -7
- package/dist/src/serverless.d.ts +42 -0
- package/dist/src/serverless.js +115 -0
- package/dist/src/state.d.ts +48 -0
- package/dist/src/state.js +98 -0
- package/dist/src/upstream.d.ts +30 -2
- package/dist/src/upstream.js +71 -2
- package/package.json +6 -3
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { NonceReplayStore } from "@redditech/x402-solana";
|
|
2
|
+
import type { CapacityState, CapacityStore } from "./capacity.js";
|
|
3
|
+
import type { PendingCallSettle, PendingSettleStore } from "./pending.js";
|
|
4
|
+
import { type HeldAnswerStore, type HeldCall, type LockLease } from "./state.js";
|
|
5
|
+
export interface PgQueryResult {
|
|
6
|
+
rows: Record<string, unknown>[];
|
|
7
|
+
rowCount?: number | null;
|
|
8
|
+
}
|
|
9
|
+
export interface PgQueryable {
|
|
10
|
+
query(text: string, values?: unknown[]): Promise<PgQueryResult>;
|
|
11
|
+
}
|
|
12
|
+
/** A client taken from the pool for one transaction. */
|
|
13
|
+
export interface PgClient extends PgQueryable {
|
|
14
|
+
release(): void;
|
|
15
|
+
}
|
|
16
|
+
/** A `pg` Pool, or anything with the same shape. */
|
|
17
|
+
export interface PgPool extends PgQueryable {
|
|
18
|
+
connect(): Promise<PgClient>;
|
|
19
|
+
}
|
|
20
|
+
/** One lock, one call, across every instance of the provider. */
|
|
21
|
+
export declare class PostgresReplayStore implements NonceReplayStore {
|
|
22
|
+
private readonly pool;
|
|
23
|
+
private readonly provider;
|
|
24
|
+
constructor(pool: PgPool, provider: string);
|
|
25
|
+
checkAndStore(key: string): Promise<boolean>;
|
|
26
|
+
checkAndStoreAll(keys: string[]): Promise<boolean>;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A lease per lock. A lease is the holder's until it expires or the holder
|
|
30
|
+
* releases it; a release only ever ends the releasing instance's own lease.
|
|
31
|
+
*/
|
|
32
|
+
export declare class PostgresLockLease implements LockLease {
|
|
33
|
+
private readonly pool;
|
|
34
|
+
private readonly provider;
|
|
35
|
+
private readonly tokens;
|
|
36
|
+
constructor(pool: PgPool, provider: string);
|
|
37
|
+
claim(escrow: string, ttlMs: number, nowMs: number): Promise<boolean>;
|
|
38
|
+
release(escrow: string): Promise<void>;
|
|
39
|
+
held(escrow: string, nowMs: number): Promise<boolean>;
|
|
40
|
+
}
|
|
41
|
+
/** Answers waiting for their settle, collectable from any instance. */
|
|
42
|
+
export declare class PostgresHeldAnswerStore implements HeldAnswerStore {
|
|
43
|
+
private readonly pool;
|
|
44
|
+
private readonly provider;
|
|
45
|
+
constructor(pool: PgPool, provider: string);
|
|
46
|
+
hold(call: HeldCall): Promise<void>;
|
|
47
|
+
get(escrow: string): Promise<HeldCall | undefined>;
|
|
48
|
+
drop(escrow: string): Promise<void>;
|
|
49
|
+
expire(beforeMs: number): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
/** Settles sent but not yet known to land. The last record for an escrow wins. */
|
|
52
|
+
export declare class PostgresPendingSettleStore implements PendingSettleStore {
|
|
53
|
+
private readonly pool;
|
|
54
|
+
private readonly provider;
|
|
55
|
+
constructor(pool: PgPool, provider: string);
|
|
56
|
+
/** The records still `pending`: the only ones the handler acts on. */
|
|
57
|
+
load(): Promise<PendingCallSettle[]>;
|
|
58
|
+
save(record: PendingCallSettle): Promise<void>;
|
|
59
|
+
findPending(escrow: string): Promise<PendingCallSettle | undefined>;
|
|
60
|
+
}
|
|
61
|
+
/** The model's limits, counted across every instance. One row per provider, updated under a row lock. */
|
|
62
|
+
export declare class PostgresCapacityStore implements CapacityStore {
|
|
63
|
+
private readonly pool;
|
|
64
|
+
private readonly provider;
|
|
65
|
+
constructor(pool: PgPool, provider: string);
|
|
66
|
+
update<T>(update: (state: CapacityState) => {
|
|
67
|
+
state: CapacityState;
|
|
68
|
+
result: T;
|
|
69
|
+
}): Promise<T>;
|
|
70
|
+
}
|
|
71
|
+
/** All the stores for one provider on one database. */
|
|
72
|
+
export declare function postgresProviderStores(pool: PgPool, provider: string): {
|
|
73
|
+
replayStore: PostgresReplayStore;
|
|
74
|
+
lease: PostgresLockLease;
|
|
75
|
+
heldAnswers: PostgresHeldAnswerStore;
|
|
76
|
+
pendingSettles: PostgresPendingSettleStore;
|
|
77
|
+
capacityStore: PostgresCapacityStore;
|
|
78
|
+
};
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Postgres versions of everything a provider remembers, for a host that runs
|
|
3
|
+
* several instances at once (a serverless deployment). Every instance of one
|
|
4
|
+
* provider passes the same `provider` id and the same database, so:
|
|
5
|
+
*
|
|
6
|
+
* - a lock pays for one call across all of them (the replay table);
|
|
7
|
+
* - only one request at a time settles, looks at or collects a lock (leases);
|
|
8
|
+
* - an answer held for its settle can be collected from any instance;
|
|
9
|
+
* - a settle sent but not yet known to land is found by the sweep on any one;
|
|
10
|
+
* - the model's limits count calls on all of them together.
|
|
11
|
+
*
|
|
12
|
+
* Tables are in the `provider_kit` schema (supabase/migrations). The kit does
|
|
13
|
+
* not depend on a driver: pass a `pg` Pool, or anything with the same
|
|
14
|
+
* `query` and `connect` shape. Every failure throws, and the handler treats a
|
|
15
|
+
* store it cannot use as "nothing accepted" (fail closed).
|
|
16
|
+
*/
|
|
17
|
+
import { randomUUID } from "node:crypto";
|
|
18
|
+
import { decodeState, encodeState } from "./state.js";
|
|
19
|
+
const PROVIDER_ID = /^[\x21-\x7e]{1,100}$/;
|
|
20
|
+
const KEY = /^[\x21-\x7e]{1,200}$/;
|
|
21
|
+
function checkProvider(provider) {
|
|
22
|
+
if (!PROVIDER_ID.test(provider))
|
|
23
|
+
throw new Error("provider id must be 1-100 printable characters without spaces");
|
|
24
|
+
return provider;
|
|
25
|
+
}
|
|
26
|
+
async function inTransaction(pool, work) {
|
|
27
|
+
const client = await pool.connect();
|
|
28
|
+
try {
|
|
29
|
+
await client.query("begin");
|
|
30
|
+
try {
|
|
31
|
+
const result = await work(client);
|
|
32
|
+
await client.query("commit");
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
await client.query("rollback").catch(() => undefined);
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
client.release();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const isUniqueViolation = (error) => error?.code === "23505";
|
|
45
|
+
/** One lock, one call, across every instance of the provider. */
|
|
46
|
+
export class PostgresReplayStore {
|
|
47
|
+
pool;
|
|
48
|
+
provider;
|
|
49
|
+
constructor(pool, provider) {
|
|
50
|
+
this.pool = pool;
|
|
51
|
+
this.provider = checkProvider(provider);
|
|
52
|
+
}
|
|
53
|
+
async checkAndStore(key) {
|
|
54
|
+
if (!KEY.test(key))
|
|
55
|
+
throw new Error("replay key must be 1-200 printable characters without spaces");
|
|
56
|
+
const result = await this.pool.query("insert into provider_kit.replay (provider, key) values ($1, $2) on conflict do nothing returning key", [this.provider, key]);
|
|
57
|
+
return result.rows.length === 1;
|
|
58
|
+
}
|
|
59
|
+
async checkAndStoreAll(keys) {
|
|
60
|
+
if (keys.length === 0 || new Set(keys).size !== keys.length || !keys.every((key) => KEY.test(key)))
|
|
61
|
+
throw new Error("replay keys must be distinct printable strings");
|
|
62
|
+
// Every key or none: a key already there rolls the whole insert back.
|
|
63
|
+
try {
|
|
64
|
+
await inTransaction(this.pool, (client) => client.query("insert into provider_kit.replay (provider, key) select $1, unnest($2::text[])", [this.provider, keys]));
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (isUniqueViolation(error))
|
|
69
|
+
return false;
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* A lease per lock. A lease is the holder's until it expires or the holder
|
|
76
|
+
* releases it; a release only ever ends the releasing instance's own lease.
|
|
77
|
+
*/
|
|
78
|
+
export class PostgresLockLease {
|
|
79
|
+
pool;
|
|
80
|
+
provider;
|
|
81
|
+
tokens = new Map();
|
|
82
|
+
constructor(pool, provider) {
|
|
83
|
+
this.pool = pool;
|
|
84
|
+
this.provider = checkProvider(provider);
|
|
85
|
+
}
|
|
86
|
+
async claim(escrow, ttlMs, nowMs) {
|
|
87
|
+
const token = randomUUID();
|
|
88
|
+
const result = await this.pool.query(`insert into provider_kit.leases (provider, escrow, token, until_ms) values ($1, $2, $3, $4)
|
|
89
|
+
on conflict (provider, escrow) do update set token = excluded.token, until_ms = excluded.until_ms
|
|
90
|
+
where provider_kit.leases.until_ms <= $5
|
|
91
|
+
returning token`, [this.provider, escrow, token, nowMs + ttlMs, nowMs]);
|
|
92
|
+
const claimed = result.rows.length === 1 && result.rows[0].token === token;
|
|
93
|
+
if (claimed)
|
|
94
|
+
this.tokens.set(escrow, token);
|
|
95
|
+
return claimed;
|
|
96
|
+
}
|
|
97
|
+
async release(escrow) {
|
|
98
|
+
const token = this.tokens.get(escrow);
|
|
99
|
+
if (!token)
|
|
100
|
+
return;
|
|
101
|
+
this.tokens.delete(escrow);
|
|
102
|
+
await this.pool.query("delete from provider_kit.leases where provider = $1 and escrow = $2 and token = $3", [this.provider, escrow, token]);
|
|
103
|
+
}
|
|
104
|
+
async held(escrow, nowMs) {
|
|
105
|
+
const result = await this.pool.query("select 1 from provider_kit.leases where provider = $1 and escrow = $2 and until_ms > $3", [this.provider, escrow, nowMs]);
|
|
106
|
+
return result.rows.length > 0;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** Answers waiting for their settle, collectable from any instance. */
|
|
110
|
+
export class PostgresHeldAnswerStore {
|
|
111
|
+
pool;
|
|
112
|
+
provider;
|
|
113
|
+
constructor(pool, provider) {
|
|
114
|
+
this.pool = pool;
|
|
115
|
+
this.provider = checkProvider(provider);
|
|
116
|
+
}
|
|
117
|
+
async hold(call) {
|
|
118
|
+
await this.pool.query(`insert into provider_kit.held_answers (provider, escrow, call, created_ms) values ($1, $2, $3, $4)
|
|
119
|
+
on conflict (provider, escrow) do update set call = excluded.call, created_ms = excluded.created_ms`, [this.provider, call.escrow, encodeState(call), call.createdMs]);
|
|
120
|
+
}
|
|
121
|
+
async get(escrow) {
|
|
122
|
+
const result = await this.pool.query("select call from provider_kit.held_answers where provider = $1 and escrow = $2", [this.provider, escrow]);
|
|
123
|
+
const text = result.rows[0]?.call;
|
|
124
|
+
return typeof text === "string" ? decodeState(text) : undefined;
|
|
125
|
+
}
|
|
126
|
+
async drop(escrow) {
|
|
127
|
+
await this.pool.query("delete from provider_kit.held_answers where provider = $1 and escrow = $2", [this.provider, escrow]);
|
|
128
|
+
}
|
|
129
|
+
async expire(beforeMs) {
|
|
130
|
+
await this.pool.query("delete from provider_kit.held_answers where provider = $1 and created_ms < $2", [this.provider, beforeMs]);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** Settles sent but not yet known to land. The last record for an escrow wins. */
|
|
134
|
+
export class PostgresPendingSettleStore {
|
|
135
|
+
pool;
|
|
136
|
+
provider;
|
|
137
|
+
constructor(pool, provider) {
|
|
138
|
+
this.pool = pool;
|
|
139
|
+
this.provider = checkProvider(provider);
|
|
140
|
+
}
|
|
141
|
+
/** The records still `pending`: the only ones the handler acts on. */
|
|
142
|
+
async load() {
|
|
143
|
+
const result = await this.pool.query("select record from provider_kit.pending_settles where provider = $1 and status = 'pending' order by updated_at", [this.provider]);
|
|
144
|
+
return result.rows.map((row) => decodeState(String(row.record)));
|
|
145
|
+
}
|
|
146
|
+
async save(record) {
|
|
147
|
+
await this.pool.query(`insert into provider_kit.pending_settles (provider, escrow, status, record, updated_at) values ($1, $2, $3, $4, now())
|
|
148
|
+
on conflict (provider, escrow) do update set status = excluded.status, record = excluded.record, updated_at = now()`, [this.provider, record.escrow, record.status, encodeState(record)]);
|
|
149
|
+
}
|
|
150
|
+
async findPending(escrow) {
|
|
151
|
+
const result = await this.pool.query("select record from provider_kit.pending_settles where provider = $1 and escrow = $2 and status = 'pending'", [this.provider, escrow]);
|
|
152
|
+
const text = result.rows[0]?.record;
|
|
153
|
+
return typeof text === "string" ? decodeState(text) : undefined;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** The model's limits, counted across every instance. One row per provider, updated under a row lock. */
|
|
157
|
+
export class PostgresCapacityStore {
|
|
158
|
+
pool;
|
|
159
|
+
provider;
|
|
160
|
+
constructor(pool, provider) {
|
|
161
|
+
this.pool = pool;
|
|
162
|
+
this.provider = checkProvider(provider);
|
|
163
|
+
}
|
|
164
|
+
async update(update) {
|
|
165
|
+
return inTransaction(this.pool, async (client) => {
|
|
166
|
+
const empty = { recent: [], day: "", today: 0, coolingUntil: 0 };
|
|
167
|
+
await client.query("insert into provider_kit.capacity (provider, state) values ($1, $2) on conflict do nothing", [this.provider, JSON.stringify(empty)]);
|
|
168
|
+
const read = await client.query("select state from provider_kit.capacity where provider = $1 for update", [this.provider]);
|
|
169
|
+
const raw = read.rows[0]?.state;
|
|
170
|
+
const current = (typeof raw === "string" ? JSON.parse(raw) : raw);
|
|
171
|
+
const { state, result } = update(current);
|
|
172
|
+
await client.query("update provider_kit.capacity set state = $2 where provider = $1", [this.provider, JSON.stringify(state)]);
|
|
173
|
+
return result;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** All the stores for one provider on one database. */
|
|
178
|
+
export function postgresProviderStores(pool, provider) {
|
|
179
|
+
return {
|
|
180
|
+
replayStore: new PostgresReplayStore(pool, provider),
|
|
181
|
+
lease: new PostgresLockLease(pool, provider),
|
|
182
|
+
heldAnswers: new PostgresHeldAnswerStore(pool, provider),
|
|
183
|
+
pendingSettles: new PostgresPendingSettleStore(pool, provider),
|
|
184
|
+
capacityStore: new PostgresCapacityStore(pool, provider),
|
|
185
|
+
};
|
|
186
|
+
}
|
package/dist/src/server.d.ts
CHANGED
|
@@ -13,6 +13,9 @@ export type StartResult = {
|
|
|
13
13
|
ok: false;
|
|
14
14
|
message: string;
|
|
15
15
|
};
|
|
16
|
+
/** How long a client may take to send its headers, and its whole request. */
|
|
17
|
+
export declare const HEADERS_TIMEOUT_MS = 15000;
|
|
18
|
+
export declare const REQUEST_TIMEOUT_MS = 60000;
|
|
16
19
|
/** Serves a fetch-style handler on a Node HTTP server. */
|
|
17
20
|
export declare function serve(handler: (request: Request) => Promise<Response>, origin: string): Server;
|
|
18
21
|
export declare function upstreamFor(config: ProviderConfig): Upstream;
|
package/dist/src/server.js
CHANGED
|
@@ -9,12 +9,15 @@ import { FileSessionStore } from "./sessions.js";
|
|
|
9
9
|
import { FilePendingSettleStore } from "./pending.js";
|
|
10
10
|
import { dirname, join } from "node:path";
|
|
11
11
|
import { MeteredSessionLedger } from "@redditech/x402-solana";
|
|
12
|
-
import { createMockUpstream, createOpenAiCompatibleUpstream } from "./upstream.js";
|
|
12
|
+
import { createAnthropicUpstream, createMockUpstream, createOpenAiCompatibleUpstream } from "./upstream.js";
|
|
13
13
|
/** How often sessions are checked for an idle timeout or a refund window that is about to open. */
|
|
14
14
|
export const SESSION_SWEEP_MS = 30_000;
|
|
15
|
+
/** How long a client may take to send its headers, and its whole request. */
|
|
16
|
+
export const HEADERS_TIMEOUT_MS = 15_000;
|
|
17
|
+
export const REQUEST_TIMEOUT_MS = 60_000;
|
|
15
18
|
/** Serves a fetch-style handler on a Node HTTP server. */
|
|
16
19
|
export function serve(handler, origin) {
|
|
17
|
-
|
|
20
|
+
const server = createServer(async (req, res) => {
|
|
18
21
|
try {
|
|
19
22
|
const request = new Request(new URL(req.url ?? "/", origin), {
|
|
20
23
|
method: req.method,
|
|
@@ -23,19 +26,30 @@ export function serve(handler, origin) {
|
|
|
23
26
|
duplex: "half",
|
|
24
27
|
});
|
|
25
28
|
const response = await handler(request);
|
|
26
|
-
|
|
27
|
-
|
|
29
|
+
// A body the handler stopped reading (too large) is not drained: the connection is closed instead.
|
|
30
|
+
const unread = !req.complete;
|
|
31
|
+
res.writeHead(response.status, { ...Object.fromEntries(response.headers.entries()), ...(unread ? { connection: "close" } : {}) });
|
|
32
|
+
res.end(await response.text(), () => {
|
|
33
|
+
if (unread)
|
|
34
|
+
req.destroy();
|
|
35
|
+
});
|
|
28
36
|
}
|
|
29
37
|
catch {
|
|
30
38
|
res.writeHead(500, { "content-type": "application/json" });
|
|
31
39
|
res.end(JSON.stringify({ error: { code: "internal_error", message: "The provider hit an unexpected error." } }));
|
|
32
40
|
}
|
|
33
41
|
});
|
|
42
|
+
server.headersTimeout = HEADERS_TIMEOUT_MS;
|
|
43
|
+
server.requestTimeout = REQUEST_TIMEOUT_MS;
|
|
44
|
+
return server;
|
|
34
45
|
}
|
|
35
46
|
export function upstreamFor(config) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
47
|
+
const u = config.upstream;
|
|
48
|
+
if (u.mock)
|
|
49
|
+
return createMockUpstream();
|
|
50
|
+
if (u.provider === "anthropic")
|
|
51
|
+
return createAnthropicUpstream({ apiKey: u.apiKey, timeoutMs: u.timeoutMs, ...(u.effort ? { effort: u.effort } : {}), ...(u.thinking ? { thinking: u.thinking } : {}) });
|
|
52
|
+
return u.baseUrl ? createOpenAiCompatibleUpstream({ baseUrl: u.baseUrl, apiKey: u.apiKey, timeoutMs: u.timeoutMs }) : createMockUpstream();
|
|
39
53
|
}
|
|
40
54
|
/**
|
|
41
55
|
* Refuses to start, rather than start half-working, when the key is missing or
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type ProviderChain } from "./chain.js";
|
|
2
|
+
import { type ProviderConfig, type ProviderConfigFile } from "./config.js";
|
|
3
|
+
import { type PgPool } from "./postgres.js";
|
|
4
|
+
import type { Upstream } from "./upstream.js";
|
|
5
|
+
export interface ServerlessProviderOptions {
|
|
6
|
+
/** The provider's config, as in a provider.json file. `systemPromptFile` is not read here: use `promptEnv`. */
|
|
7
|
+
file: ProviderConfigFile;
|
|
8
|
+
env: Record<string, string | undefined>;
|
|
9
|
+
pool: PgPool;
|
|
10
|
+
/** The environment variable with the wallet's keypair (a JSON array of 64 numbers). */
|
|
11
|
+
keyEnv: string;
|
|
12
|
+
/** The environment variable with the private system prompt, if the provider has one. */
|
|
13
|
+
promptEnv?: string;
|
|
14
|
+
/** Where this provider is mounted on the host, such as `/humaniser`. Stripped before routing. */
|
|
15
|
+
basePath?: string;
|
|
16
|
+
/** Keys the provider's rows in the database. Defaults to the wallet address. */
|
|
17
|
+
providerId?: string;
|
|
18
|
+
log?: (event: Record<string, unknown>) => void;
|
|
19
|
+
/** For tests. */
|
|
20
|
+
chain?: ProviderChain;
|
|
21
|
+
upstream?: Upstream;
|
|
22
|
+
}
|
|
23
|
+
export interface ServerlessProvider {
|
|
24
|
+
config: ProviderConfig;
|
|
25
|
+
handle(request: Request): Promise<Response>;
|
|
26
|
+
/** Looks again at settles whose outcome was not known and whose answers are no longer held. Call it every minute or so. */
|
|
27
|
+
sweep(): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
export type ServerlessProviderResult = {
|
|
30
|
+
ok: true;
|
|
31
|
+
provider: ServerlessProvider;
|
|
32
|
+
} | {
|
|
33
|
+
ok: false;
|
|
34
|
+
message: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* A log event with every URL in its text replaced by its scheme, so an error
|
|
38
|
+
* that quotes an endpoint (an RPC URL carries its API key) never reaches the
|
|
39
|
+
* host's logs.
|
|
40
|
+
*/
|
|
41
|
+
export declare function redactLogEvent(event: Record<string, unknown>): Record<string, unknown>;
|
|
42
|
+
export declare function createServerlessProvider(options: ServerlessProviderOptions): ServerlessProviderResult;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A provider on a serverless host (Vercel functions, or any host that runs
|
|
3
|
+
* many short-lived instances): no disk, no long-running timer, several copies
|
|
4
|
+
* at once. Everything the provider remembers lives in Postgres
|
|
5
|
+
* (`./postgres`), the wallet key and the private system prompt come from the
|
|
6
|
+
* host's environment, and the host calls `sweep()` on a schedule instead of a
|
|
7
|
+
* timer.
|
|
8
|
+
*
|
|
9
|
+
* It refuses to start without its key, its prompt (when it has one) or its
|
|
10
|
+
* model's key, so it never accepts a payment it cannot serve.
|
|
11
|
+
*
|
|
12
|
+
* Refused here, until they have shared stores of their own:
|
|
13
|
+
* - sessions (their ledger is kept in one process);
|
|
14
|
+
* - `refundAccountSubsidy` (its daily bound is counted in one process, so it
|
|
15
|
+
* would multiply with the number of instances).
|
|
16
|
+
*/
|
|
17
|
+
import { checkProviderCluster } from "@redditech/x402-solana";
|
|
18
|
+
import { createProviderChain } from "./chain.js";
|
|
19
|
+
import { Capacity } from "./capacity.js";
|
|
20
|
+
import { parseProviderConfig } from "./config.js";
|
|
21
|
+
import { createProviderHandler } from "./handler.js";
|
|
22
|
+
import { loadProviderKeyFromEnv } from "./keys.js";
|
|
23
|
+
import { postgresProviderStores } from "./postgres.js";
|
|
24
|
+
import { upstreamFor } from "./server.js";
|
|
25
|
+
const BASE_PATH = /^\/[a-z0-9][a-z0-9-]{0,62}$/;
|
|
26
|
+
const URL_TEXT = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi;
|
|
27
|
+
/**
|
|
28
|
+
* A log event with every URL in its text replaced by its scheme, so an error
|
|
29
|
+
* that quotes an endpoint (an RPC URL carries its API key) never reaches the
|
|
30
|
+
* host's logs.
|
|
31
|
+
*/
|
|
32
|
+
export function redactLogEvent(event) {
|
|
33
|
+
const redact = (value) => {
|
|
34
|
+
if (typeof value === "string")
|
|
35
|
+
return value.replace(URL_TEXT, (url) => `${url.slice(0, url.indexOf(":"))}://[redacted]`);
|
|
36
|
+
if (Array.isArray(value))
|
|
37
|
+
return value.map(redact);
|
|
38
|
+
if (value && typeof value === "object")
|
|
39
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redact(item)]));
|
|
40
|
+
return value;
|
|
41
|
+
};
|
|
42
|
+
return redact(event);
|
|
43
|
+
}
|
|
44
|
+
export function createServerlessProvider(options) {
|
|
45
|
+
const { systemPromptFile: _ignored, ...file } = options.file;
|
|
46
|
+
let promptFile = file;
|
|
47
|
+
if (options.promptEnv) {
|
|
48
|
+
const prompt = options.env[options.promptEnv]?.trim();
|
|
49
|
+
if (!prompt)
|
|
50
|
+
return { ok: false, message: `no system prompt is set: put it in ${options.promptEnv}` };
|
|
51
|
+
promptFile = { ...file, systemPrompt: prompt };
|
|
52
|
+
}
|
|
53
|
+
const parsed = parseProviderConfig(promptFile, options.env);
|
|
54
|
+
if (!parsed.ok)
|
|
55
|
+
return { ok: false, message: `config: ${parsed.errors.join("; ")}` };
|
|
56
|
+
const config = parsed.config;
|
|
57
|
+
if (config.sessions.enabled)
|
|
58
|
+
return { ok: false, message: "sessions are not offered on a serverless host yet: set sessions.enabled to false" };
|
|
59
|
+
if (config.refundAccountsPerDay > 0)
|
|
60
|
+
return { ok: false, message: "refundAccountSubsidy is not offered on a serverless host yet: its daily bound is counted per instance" };
|
|
61
|
+
if (config.upstream.mock && config.network === "solana-mainnet-beta")
|
|
62
|
+
return { ok: false, message: "mock answers cannot be sold on mainnet: set upstream.mock to false" };
|
|
63
|
+
// A serverless host has no model of its own to call without a key: a call would be accepted and then fail.
|
|
64
|
+
if (!config.upstream.mock && !options.upstream && !config.upstream.apiKey)
|
|
65
|
+
return { ok: false, message: `no model key is set: put it in ${config.upstream.apiKeyEnv}` };
|
|
66
|
+
const basePath = options.basePath ?? "";
|
|
67
|
+
if (basePath && !BASE_PATH.test(basePath))
|
|
68
|
+
return { ok: false, message: "basePath must look like /name (lowercase letters, digits and dashes)" };
|
|
69
|
+
if (basePath && !new URL(config.publicUrl).pathname.replace(/\/+$/, "").endsWith(basePath)) {
|
|
70
|
+
return { ok: false, message: `publicUrl must end with ${basePath}, where the provider is mounted, so buyers are sent to the right address` };
|
|
71
|
+
}
|
|
72
|
+
const hostLog = options.log;
|
|
73
|
+
const log = hostLog ? (event) => hostLog(redactLogEvent(event)) : undefined;
|
|
74
|
+
const key = loadProviderKeyFromEnv({ env: options.env, name: options.keyEnv, wallet: config.wallet });
|
|
75
|
+
if (!key.ok)
|
|
76
|
+
return { ok: false, message: key.message };
|
|
77
|
+
const stores = postgresProviderStores(options.pool, options.providerId ?? config.wallet);
|
|
78
|
+
const chain = options.chain ?? createProviderChain(config.rpcUrl, key.key.keypair);
|
|
79
|
+
const handler = createProviderHandler(config, {
|
|
80
|
+
chain,
|
|
81
|
+
upstream: options.upstream ?? upstreamFor(config),
|
|
82
|
+
replayStore: stores.replayStore,
|
|
83
|
+
pendingSettles: stores.pendingSettles,
|
|
84
|
+
lease: stores.lease,
|
|
85
|
+
heldAnswers: stores.heldAnswers,
|
|
86
|
+
capacity: new Capacity(config.capacity, stores.capacityStore),
|
|
87
|
+
signMessage: key.key.signMessage,
|
|
88
|
+
...(log ? { log } : {}),
|
|
89
|
+
});
|
|
90
|
+
const handle = async (request) => {
|
|
91
|
+
if (!basePath)
|
|
92
|
+
return handler(request);
|
|
93
|
+
const url = new URL(request.url);
|
|
94
|
+
if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {
|
|
95
|
+
return new Response(JSON.stringify({ error: { code: "not_found", message: "No such route." } }), { status: 404, headers: { "content-type": "application/json; charset=utf-8" } });
|
|
96
|
+
}
|
|
97
|
+
url.pathname = url.pathname.slice(basePath.length) || "/";
|
|
98
|
+
const init = { method: request.method, headers: request.headers };
|
|
99
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
100
|
+
init.body = request.body;
|
|
101
|
+
init.duplex = "half";
|
|
102
|
+
}
|
|
103
|
+
return handler(new Request(url, init));
|
|
104
|
+
};
|
|
105
|
+
const sweep = async () => {
|
|
106
|
+
// The sweep reads the chain; it never trusts one on another cluster.
|
|
107
|
+
const cluster = await checkProviderCluster(() => chain.readGenesisHash(), config.network, config.genesisHash);
|
|
108
|
+
if (!cluster.ok) {
|
|
109
|
+
log?.({ event: "cluster_check_failed", reason: cluster.reason, alert: true });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
await handler.settleDueSessions();
|
|
113
|
+
};
|
|
114
|
+
return { ok: true, provider: { config, handle, sweep } };
|
|
115
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { TokenCounts, VerifiedLock } from "@redditech/x402-solana";
|
|
2
|
+
export type HeldLock = Extract<VerifiedLock, {
|
|
3
|
+
ok: true;
|
|
4
|
+
}>;
|
|
5
|
+
/** A served single call whose answer waits for its settle. */
|
|
6
|
+
export interface HeldCall {
|
|
7
|
+
escrow: string;
|
|
8
|
+
lock: HeldLock;
|
|
9
|
+
requestId: string;
|
|
10
|
+
/** SHA-256 of the request body: only the same request may collect the answer. */
|
|
11
|
+
requestHash: string;
|
|
12
|
+
upstream: Record<string, unknown>;
|
|
13
|
+
usage: TokenCounts;
|
|
14
|
+
createdMs: number;
|
|
15
|
+
}
|
|
16
|
+
export interface LockLease {
|
|
17
|
+
/** True when this caller now holds the lease on `escrow` for `ttlMs`; false when another holds it. */
|
|
18
|
+
claim(escrow: string, ttlMs: number, nowMs: number): Promise<boolean>;
|
|
19
|
+
release(escrow: string): Promise<void>;
|
|
20
|
+
/** True while someone holds an unexpired lease on `escrow`. */
|
|
21
|
+
held(escrow: string, nowMs: number): Promise<boolean>;
|
|
22
|
+
}
|
|
23
|
+
export interface HeldAnswerStore {
|
|
24
|
+
hold(call: HeldCall): Promise<void>;
|
|
25
|
+
get(escrow: string): Promise<HeldCall | undefined>;
|
|
26
|
+
drop(escrow: string): Promise<void>;
|
|
27
|
+
/** Forgets answers held since before `beforeMs`. */
|
|
28
|
+
expire(beforeMs: number): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare class MemoryLockLease implements LockLease {
|
|
31
|
+
private readonly leases;
|
|
32
|
+
claim(escrow: string, ttlMs: number, nowMs: number): Promise<boolean>;
|
|
33
|
+
release(escrow: string): Promise<void>;
|
|
34
|
+
held(escrow: string, nowMs: number): Promise<boolean>;
|
|
35
|
+
}
|
|
36
|
+
export declare class MemoryHeldAnswerStore implements HeldAnswerStore {
|
|
37
|
+
private readonly calls;
|
|
38
|
+
hold(call: HeldCall): Promise<void>;
|
|
39
|
+
get(escrow: string): Promise<HeldCall | undefined>;
|
|
40
|
+
drop(escrow: string): Promise<void>;
|
|
41
|
+
expire(beforeMs: number): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* JSON that keeps public keys, big integers and byte arrays, so a held call
|
|
45
|
+
* (its verified lock included) can be stored as text and read back the same.
|
|
46
|
+
*/
|
|
47
|
+
export declare function encodeState(value: unknown): string;
|
|
48
|
+
export declare function decodeState<T>(text: string): T;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a provider remembers between requests about single calls, behind
|
|
3
|
+
* interfaces, so it can live in this process (the `rap-provider start`
|
|
4
|
+
* server) or in a database shared by every instance of a serverless
|
|
5
|
+
* deployment (`./postgres`).
|
|
6
|
+
*
|
|
7
|
+
* - A lease on a lock: only one request at a time sends, looks at or collects
|
|
8
|
+
* the settle of one escrow. It expires, so a crashed instance cannot hold a
|
|
9
|
+
* lock for ever.
|
|
10
|
+
* - Held answers: the answer of a call whose settle was sent but not yet known
|
|
11
|
+
* to land, kept for the buyer to collect with the same request.
|
|
12
|
+
*/
|
|
13
|
+
import { PublicKey } from "@solana/web3.js";
|
|
14
|
+
export class MemoryLockLease {
|
|
15
|
+
leases = new Map();
|
|
16
|
+
async claim(escrow, ttlMs, nowMs) {
|
|
17
|
+
const until = this.leases.get(escrow);
|
|
18
|
+
if (until !== undefined && until > nowMs)
|
|
19
|
+
return false;
|
|
20
|
+
this.leases.set(escrow, nowMs + ttlMs);
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
async release(escrow) {
|
|
24
|
+
this.leases.delete(escrow);
|
|
25
|
+
}
|
|
26
|
+
async held(escrow, nowMs) {
|
|
27
|
+
const until = this.leases.get(escrow);
|
|
28
|
+
return until !== undefined && until > nowMs;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export class MemoryHeldAnswerStore {
|
|
32
|
+
calls = new Map();
|
|
33
|
+
async hold(call) {
|
|
34
|
+
this.calls.set(call.escrow, call);
|
|
35
|
+
}
|
|
36
|
+
async get(escrow) {
|
|
37
|
+
return this.calls.get(escrow);
|
|
38
|
+
}
|
|
39
|
+
async drop(escrow) {
|
|
40
|
+
this.calls.delete(escrow);
|
|
41
|
+
}
|
|
42
|
+
async expire(beforeMs) {
|
|
43
|
+
for (const [escrow, call] of this.calls)
|
|
44
|
+
if (call.createdMs < beforeMs)
|
|
45
|
+
this.calls.delete(escrow);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* JSON that keeps public keys, big integers and byte arrays, so a held call
|
|
50
|
+
* (its verified lock included) can be stored as text and read back the same.
|
|
51
|
+
*/
|
|
52
|
+
export function encodeState(value) {
|
|
53
|
+
return JSON.stringify(toPlain(value));
|
|
54
|
+
}
|
|
55
|
+
export function decodeState(text) {
|
|
56
|
+
return fromPlain(JSON.parse(text));
|
|
57
|
+
}
|
|
58
|
+
/** A public key from any copy of @solana/web3.js (the kit and the SDK may each load their own). */
|
|
59
|
+
const isPublicKey = (value) => value instanceof PublicKey || (typeof value === "object" && value !== null && typeof value.toBase58 === "function" && typeof value.toBytes === "function" && typeof value.equals === "function");
|
|
60
|
+
function toPlain(value) {
|
|
61
|
+
if (isPublicKey(value))
|
|
62
|
+
return { $pk: value.toBase58() };
|
|
63
|
+
if (typeof value === "bigint")
|
|
64
|
+
return { $bi: value.toString() };
|
|
65
|
+
if (value instanceof Uint8Array)
|
|
66
|
+
return { $u8: Buffer.from(value).toString("hex") };
|
|
67
|
+
if (Array.isArray(value))
|
|
68
|
+
return value.map(toPlain);
|
|
69
|
+
if (value && typeof value === "object") {
|
|
70
|
+
const out = {};
|
|
71
|
+
for (const [key, item] of Object.entries(value))
|
|
72
|
+
if (item !== undefined)
|
|
73
|
+
out[key] = toPlain(item);
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
function fromPlain(value) {
|
|
79
|
+
if (Array.isArray(value))
|
|
80
|
+
return value.map(fromPlain);
|
|
81
|
+
if (value && typeof value === "object") {
|
|
82
|
+
const record = value;
|
|
83
|
+
const keys = Object.keys(record);
|
|
84
|
+
if (keys.length === 1) {
|
|
85
|
+
if (typeof record.$pk === "string")
|
|
86
|
+
return new PublicKey(record.$pk);
|
|
87
|
+
if (typeof record.$bi === "string")
|
|
88
|
+
return BigInt(record.$bi);
|
|
89
|
+
if (typeof record.$u8 === "string")
|
|
90
|
+
return Uint8Array.from(Buffer.from(record.$u8, "hex"));
|
|
91
|
+
}
|
|
92
|
+
const out = {};
|
|
93
|
+
for (const [key, item] of Object.entries(record))
|
|
94
|
+
out[key] = fromPlain(item);
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
return value;
|
|
98
|
+
}
|