okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
6.1 KiB174 linesraw
1/** Serving surface: API keys, access policy, and the request log. */
2import { randomBytes } from 'node:crypto';
3import os from 'node:os';
4import { get as getStore, update } from './store.mjs';
5import { nowIso, round, sameSecret, uid } from './util.mjs';
6
7const requests = [];
8const MAX_REQUESTS = 60;
9const cancellations = new Map();
10let revision = Date.now();
11
12let hubRef = null;
13let tunnel = { status: 'idle', mode: null, url: null, error: null, installed: false, originUrl: null };
14export function setTunnel(value) { tunnel = value; emit(); }
15const tunnelActive = () => ['starting', 'connected', 'stopping'].includes(tunnel.status);
16let sharing = { active: false, url: null };
17export function setSharing(value) { sharing = value; emit(); }
18let port = 8080;
19let running = false;
20let bindHost = '127.0.0.1';
21const isLocal = () => ['127.0.0.1', 'localhost', '::1'].includes(bindHost);
22
23export function init(hub, opts = {}) {
24  hubRef = hub;
25  port = opts.port ?? port;
26  running = true;
27  bindHost = opts.host ?? '127.0.0.1';
28}
29
30export function baseUrl() {
31  const host = isLocal() ? '127.0.0.1' : localIp();
32  return `http://${host}:${port}/v1`;
33}
34
35export function state() {
36  const s = getStore();
37  const active = requests.filter((r) => r.state === 'generating' || r.state === 'queued');
38  return {
39    revision,
40    running,
41    baseUrl: sharing.active ? sharing.url : baseUrl(),
42    // The address on this computer, the one the app's own port serves, kept apart from the sharing address (#4798).
43    localUrl: baseUrl(),
44    sharing,
45    tunnel,
46    port,
47    endpoints: { openai: '/chat/completions', anthropic: '/messages', models: '/models' },
48    access: {
49      otherDevices: !isLocal() || sharing.active || tunnelActive(),
50      apiKeySet: !!s.serving?.apiKey,
51      apiKeyHint: s.serving?.apiKey ? `Ends in ${s.serving.apiKey.slice(-4)}` : null,
52      allowOrigin: '*',
53    },
54    stats: {
55      running: active.filter((r) => r.state === 'generating').length,
56      waiting: active.filter((r) => r.state === 'queued').length,
57      completed: requests.filter((r) => r.state === 'done').length,
58      failed: requests.filter((r) => r.state === 'error').length,
59      tokensOut: requests.reduce((sum, r) => sum + (r.tokensOut || 0), 0),
60    },
61    requests: [...requests].reverse(),
62    pauseServing: !!s.serving?.pauseServing,
63  };
64}
65
66function emit() {
67  revision = Math.max(Date.now(), revision + 1);
68  hubRef?.send('serving', state());
69}
70
71export function patch(body) {
72  const s = getStore();
73  const serving = { ...(s.serving ?? {}) };
74  if (typeof body.otherDevices === 'boolean' && body.otherDevices !== !isLocal()) throw new Error('Change the host listen address and restart to update network access.');
75  // The key is optional (owner decision, 0.2.2): removing it while sharing or the tunnel runs is allowed; the app warns in plain words (local-share.mjs, cloudflare.mjs).
76  if (body.apiKey === null) serving.apiKey = null;
77  else if (typeof body.apiKey === 'string' && body.apiKey.trim()) serving.apiKey = body.apiKey.trim();
78  else if (body.generateKey) serving.apiKey = `sk-strata-${randomBytes(12).toString('hex')}`;
79  if (typeof body.pauseServing === 'boolean') serving.pauseServing = body.pauseServing;
80  update({ serving });
81  emit();
82  return state();
83}
84
85export function authorized(req) {
86  const key = getStore().serving?.apiKey;
87  if (!key) return true;
88  const header = req.headers?.authorization;
89  const bearer = typeof header === 'string' && header.startsWith('Bearer ') ? header.slice(7) : '';
90  const alt = req.headers?.['x-api-key'];
91  // #4535: constant time over fixed-length digests, and both headers are always compared so the time does not show which one was sent.
92  const viaBearer = sameSecret(bearer, key);
93  const viaHeader = sameSecret(alt, key);
94  return viaBearer || viaHeader;
95}
96
97export function open({ client, endpoint, tokensIn = null, model, instanceId, gpuIds, cancel }) {
98  const entry = {
99    id: uid('req'),
100    at: nowIso(),
101    client,
102    endpoint,
103    state: 'queued',
104    tokensIn,
105    tokensOut: null,
106    durationMs: 0,
107    model: model ?? 'local',
108    instanceId, gpuIds,
109    cancellable: typeof cancel === 'function',
110    cancelRequested: false,
111    usageSource: 'unavailable',
112  };
113  if (entry.cancellable) cancellations.set(entry.id, cancel);
114  requests.push(entry);
115  if (requests.length > MAX_REQUESTS) {
116    const oldestCompleted = requests.findIndex(r => !['generating', 'queued'].includes(r.state));
117    if (oldestCompleted >= 0) requests.splice(oldestCompleted, 1);
118  }
119  emit();
120  return entry;
121}
122
123export function mark(id, patchObj) {
124  const entry = requests.find((r) => r.id === id);
125  if (!entry) return;
126  Object.assign(entry, patchObj);
127  emit();
128  return entry;
129}
130
131export function finish(id, { tokensOut, durationMs, error }) {
132  const entry = requests.find((r) => r.id === id);
133  if (!entry) return;
134  entry.state = error ? 'error' : 'done';
135  entry.tokensOut = tokensOut ?? entry.tokensOut;
136  entry.durationMs = durationMs ?? entry.durationMs;
137  if (error) entry.error = error;
138  entry.cancellable = false;
139  cancellations.delete(id);
140  emit();
141}
142
143export function cancel(id) {
144  const entry = requests.find((r) => r.id === id);
145  if (!entry) throw new Error('This request is no longer retained.');
146  if (!['generating', 'queued'].includes(entry.state)) return state();
147  const abort = cancellations.get(id);
148  if (!abort) throw new Error('This request cannot be cancelled by this host.');
149  if (!entry.cancelRequested) { entry.cancelRequested = true; abort(); }
150  emit();
151  return state();
152}
153
154export function rateSample() {
155  const done = requests.filter((r) => r.state === 'done' && r.tokensOut > 0);
156  if (!done.length) return 0;
157  const tps = done.filter((r) => r.tps > 0).map((r) => r.tps);     // answer speeds (decode time), not tokens over the whole request
158  if (!tps.length) return 0;
159  return round(tps.reduce((a, b) => a + b, 0) / tps.length, 1);
160}
161
162function localIp() {
163  try {
164    const nets = os.networkInterfaces();
165    for (const list of Object.values(nets)) {
166      for (const net of list ?? []) {
167        if (net.family === 'IPv4' && !net.internal) return net.address;
168      }
169    }
170  } catch {
171    /* fall through */
172  }
173  return '127.0.0.1';
174}