PageSourceSearch

https://factlens.pro/admin-managed-health-v50.js

js factlens.pro collected 2026-10-02 02:06:03 UTC 7,675 bytes, 120 lines download raw bytes

1(() => {
2  if (window.__factlensAdminManagedHealthV50) return;
3  window.__factlensAdminManagedHealthV50 = true;
4
5  let lastProbeResult = null;
6
7  const escHealth = (value) => String(value ?? '')
8    .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
9    .replaceAll('"', '&quot;').replaceAll("'", '&#039;');
10  const fmtHealthDate = (value) => value ? new Date(value).toLocaleString() : 'Never';
11  const selectedService = () => {
12    try { return adminManagedService; } catch { return 'deepgram'; }
13  };
14  const managedRows = () => {
15    try { return Array.isArray(adminManagedRows) ? adminManagedRows : []; } catch { return []; }
16  };
17
18  function probeResultHtml(payload) {
19    if (!payload) return '';
20    const results = Array.isArray(payload.results) ? payload.results : [];
21    return `<section class="stat-card" data-managed-health-result style="margin-top:1rem;max-width:1100px">
22      <div class="data-table-header"><div><div class="data-table-title">Latest manual health check</div><div class="muted" style="font-size:.75rem">${Number(payload.healthy || 0)} healthy · ${Number(payload.failed || 0)} failed · ${Number(payload.checked || 0)} checked</div></div></div>
23      <div style="display:grid;gap:.75rem;margin-top:.8rem">${results.length ? results.map((item) => `<div style="border-top:1px solid var(--border);padding-top:.75rem">
24        <div style="display:flex;gap:.5rem;align-items:center;flex-wrap:wrap"><strong>${escHealth(item.provider || item.service || 'Provider')}</strong>${item.model ? `<code>${escHealth(item.model)}</code>` : ''}<span class="badge ${item.succeeded ? 'pro' : 'trial-ended'}">${item.succeeded ? 'Healthy' : 'Failed'}</span><span class="muted">HTTP ${escHealth(item.provider_status ?? '—')}</span></div>
25        <div class="muted" style="font-size:.72rem;margin-top:.45rem">Probe payload</div>
26        <pre style="white-space:pre-wrap;word-break:break-word;margin:.3rem 0 0;padding:.65rem;background:rgba(2,6,23,.25);border:1px solid var(--border);border-radius:8px;font-size:.72rem">${escHealth(JSON.stringify(item.probe || {}, null, 2))}</pre>
27        <div class="muted" style="font-size:.72rem;margin-top:.45rem">Resulting health: ${escHealth(item.state?.health_status || 'unknown')} · checked ${escHealth(fmtHealthDate(item.state?.last_checked_at))}${item.state?.last_error ? ` · ${escHealth(item.state.last_error)}` : ''}</div>
28      </div>`).join('') : '<div class="muted">No enabled keys matched this manual check.</div>'}</div>
29    </section>`;
30  }
31
32  async function runManagedHealthCheck(keyId = null) {
33    const service = selectedService();
34    const payload = { operation: 'admin_health_probe', ...(keyId ? { key_id: keyId } : { service }) };
35    const label = keyId ? 'provider' : service;
36    showToast(`Checking ${label} health…`);
37    try {
38      lastProbeResult = await invokeAdminFunction('factlens-managed-health', payload);
39      showToast(`Health check complete: ${Number(lastProbeResult.healthy || 0)} healthy, ${Number(lastProbeResult.failed || 0)} failed.`);
40      await renderDeepgram(document.getElementById('admin-main-content'));
41    } catch (error) {
42      showToast(error?.message || 'Health check failed.', 'error');
43    }
44  }
45
46  async function decorateManagedHealthPage() {
47    const root = document.getElementById('admin-main-content');
48    if (!root || !/Managed services/i.test(root.querySelector('.admin-page-title')?.textContent || '')) return;
49
50    let topology = [];
51    try { topology = await sbRpc('factlens_admin_managed_service_topology') || []; }
52    catch (error) { console.error('Managed topology unavailable', error); }
53    const service = selectedService();
54    const current = topology.find((item) => item.service === service) || {};
55    const capacity = Number(current.current_capacity || 0);
56    const active = Number(current.active_leases || 0);
57    const ceiling = Number(current.adaptive_ceiling || capacity);
58    const raw = Number(current.raw_key_capacity || 0);
59    const adaptive = current.adaptive_enabled === true;
60
61    const stats = [...root.querySelectorAll('.stats-grid .stat-card')];
62    if (stats[3]) {
63      const label = stats[3].querySelector('.stat-label');
64      const value = stats[3].querySelector('.stat-value');
65      const meta = stats[3].querySelector('.stat-meta');
66      if (label) label.textContent = 'Active / current capacity';
67      if (value) value.textContent = `${active.toLocaleString()} / ${capacity.toLocaleString()}`;
68      if (meta) meta.textContent = adaptive ? `Adaptive ${capacity.toLocaleString()} / ${ceiling.toLocaleString()}` : 'Configured provider slots';
69    }
70
71    root.querySelector('[data-managed-topology]')?.remove();
72    const anchor = root.querySelector('.stats-grid');
73    if (anchor) {
74      const panel = document.createElement('section');
75      panel.className = 'stat-card';
76      panel.dataset.managedTopology = 'true';
77      panel.style.cssText = 'margin-top:1rem;max-width:1100px';
78      panel.innerHTML = `<div class="data-table-header"><div><div class="data-table-title">Live pool topology</div><div class="muted" style="font-size:.75rem">Read directly from the backend, not hard-coded Admin values.</div></div><button type="button" class="action-btn" data-managed-health-all>Check all now</button></div>
79        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:.75rem;margin-top:.9rem">
80          <div><div class="stat-label">Current capacity</div><strong>${capacity.toLocaleString()}</strong></div>
81          <div><div class="stat-label">Adaptive ceiling</div><strong>${ceiling.toLocaleString()}</strong></div>
82          <div><div class="stat-label">Raw key capacity</div><strong>${raw.toLocaleString()}</strong></div>
83          <div><div class="stat-label">Enabled keys</div><strong>${Number(current.enabled_key_count || 0).toLocaleString()}</strong></div>
84          <div><div class="stat-label">Success streak</div><strong>${Number(current.adaptive_success_streak || 0).toLocaleString()}</strong></div>
85          <div><div class="stat-label">Latest health check</div><strong style="font-size:.78rem">${escHealth(fmtHealthDate(current.latest_health_check))}</strong></div>
86        </div>`;
87      anchor.insertAdjacentElement('afterend', panel);
88      panel.querySelector('[data-managed-health-all]')?.addEventListener('click', () => void runManagedHealthCheck());
89      if (lastProbeResult) panel.insertAdjacentHTML('afterend', probeResultHtml(lastProbeResult));
90    }
91
92    const rows = managedRows();
93    const tableRows = [...root.querySelectorAll('.data-table-wrap table tbody tr')];
94    rows.forEach((row, index) => {
95      const actions = tableRows[index]?.querySelector('td:last-child');
96      if (!actions || actions.querySelector('[data-managed-health-check]')) return;
97      const button = document.createElement('button');
98      button.type = 'button';
99      button.className = 'action-btn';
100      button.dataset.managedHealthCheck = row.id;
101      button.textContent = 'Check now';
102      button.addEventListener('click', () => void runManagedHealthCheck(row.id));
103      actions.prepend(button, document.createTextNode(' '));
104    });
105  }
106
107  if (typeof renderDeepgram === 'function' && !renderDeepgram.__managedHealthV50Wrapped) {
108    const original = renderDeepgram;
109    const wrapped = async function (...args) {
110      const result = await original.apply(this, args);
111      await decorateManagedHealthPage();
112      return result;
113    };
114    wrapped.__managedHealthV50Wrapped = true;
115    renderDeepgram = wrapped;
116  }
117
118  window.runManagedHealthCheck = runManagedHealthCheck;
119  setTimeout(() => void decorateManagedHealthPage(), 0);
120})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.