Files
Termix/src/backend/sync/server/feed.ts
T
f90621a54e v26.10.6 (#1739)
* feat: let the login page send the token back to the mobile app

* feat: add host-scripts entry to the plugin sdk

* feat: let plugins say how they show in the mobile app

* feat: frame host for running one plugin view outside the shell

* fix: build the SDK host modules in production mode

* chore: note the SDK host build fix in the changelog

* feat: list plugin engine ranges for the mobile app

* feat: host color and icon columns that sync

* chore: update translations and plugin pins

* fix: test

* fix: show source address when rejecting proxy auth

* fix: deleting your own account removes all of its data

* fix(deps): update body-parser to 2.4.0 (#1736)

* fix: body-parser 보안 패치 반영

* chore: 자동 검사를 막던 기존 JSON 서식 정리

---------

Co-authored-by: renovys <180682734+renovys@users.noreply.github.com>

* fix(sdk): decode command output as GBK when it is not valid UTF-8 (#1735)

* fix: honor shared credentials on shared hosts (#1730)

* fix: honor shared credentials on shared hosts and in personal SSH auth

* fix: snapshot shared SSH auth from a credential shared with the host owner

* fix: size DataView list columns by the table's own width (#1713)

* fix: size DataView list columns by the table's own width

The list grid was built from every column, so columns hidden below md/lg
left empty tracks and the visible cells landed under the wrong headers.
Each width now gets a template of only its visible columns (CSS variables
+ container queries on the table, so a narrow panel counts, not the window),
the header uses the same gap as the rows, and rows use a minimum height so
wrapped cells no longer overlap.

* test: wait for the title bar offset effect before asserting

The bar shows once getTitleBarVisible resolves, but --termix-titlebar-height
is set in a later passive effect, so reading it right after findByText raced
(3-5 of 40 runs under load, on main too).

* chore: rerun CI against dev-26.10.6

* fix: unlock passphrase keys once per connect burst (#1737)

* feat: give ssh transports the host origin and sync id (#1717)

* fix: wake other clients after a sync push (Plugin-Sync#1)

* feat: look up local row ids by sync id for the sync plugin (Plugin-Sync#4)

* feat: rail items can show a status dot (Plugin-Sync#5)

* fix: add the desktop shared copy banner text (#1709)

* feat: sidebar preference for alternating rows (#1712)

* fix: striped rows text

* feat: shell can open a saved host's editor for plugins (Plugin-SSH-Terminal#36)

* fix: show the logo in the macos menu bar (#1728)

* fix: number shortcuts skip the home tab (#1724)

* fix: show plugins that could not be downloaded as failed (#1714)

* fix: pass the host id as text when opening its editor

* fix: retry a plugin bundle that was not ready yet (#1708)

* fix: let commonjs plugins fall back to core packages on the desktop

* fix: let non docker installs switch nginx to https (#1711)

* feat: remove a folder share from its hosts too (#1719)

* chore: changelog for merged pull requests

* fix: accept the release .sig when installing a plugin from a file

* feat: folder logins for shared hosts, read only plugin sync, full desktop builds

* fix: test

* fix: stop dev runner restart loops and narrow plugin watchers

* chore: update translations and plugin pins

* chore: lint, format, and bump version to 26.10.6

---------

Co-authored-by: renovys <renovy@gmail.com>
Co-authored-by: renovys <180682734+renovys@users.noreply.github.com>
Co-authored-by: Sebastian Cao <cycsmail@gmail.com>
Co-authored-by: Jonathan Rehuel Lewerissa <jonathan.rehuel16@gmail.com>
Co-authored-by: Rhiz3K <33246262+Rhiz3K@users.noreply.github.com>
2026-10-29 17:59:55 -05:00

216 lines
6.1 KiB
TypeScript

/**
* The server's change feed.
*
* Nothing records a change as it happens. Instead the reconciler compares
* every synced row a user owns with sync_records and bumps the record of
* anything new, changed or gone. That catches every write path, including
* plugin tables, bulk routes and background jobs, without each of them having
* to remember to report it.
*/
import type { Response } from "express";
import type { SyncRow } from "@termix-ssh/plugin-sdk/backend";
import { listEntities } from "../../plugins/sync-registry.js";
import { syncLogger } from "../../utils/logger.js";
import { registerCoreSyncEntities } from "../entities.js";
import { createResolvers, loadWireRows } from "../store.js";
import { allocateSeq, listRecords, putRecord, recordKey } from "../records.js";
const locks = new Map<string, Promise<unknown>>();
/** Runs one user's sync work at a time: reconcile and push must not interleave. */
export async function withUserLock<T>(
userId: string,
fn: () => Promise<T>,
): Promise<T> {
const previous = locks.get(userId) ?? Promise.resolve();
const run = previous.catch(() => {}).then(fn);
locks.set(userId, run);
try {
return await run;
} finally {
if (locks.get(userId) === run) locks.delete(userId);
}
}
interface Snapshot {
at: number;
generation: number;
wire: Map<string, SyncRow>;
}
const snapshots = new Map<string, Snapshot>();
const SNAPSHOT_TTL_MS = 60_000;
let generation = 0;
export interface ReconcileResult {
changed: boolean;
/** Every live row on the wire, by recordKey. */
wire: Map<string, SyncRow>;
}
/**
* Brings the user's records up to date. Call inside withUserLock. Skipped
* when nothing was written since the last run and it is recent, unless
* forced.
*/
export async function reconcileUser(
userId: string,
options: { force?: boolean } = {},
): Promise<ReconcileResult> {
const snapshot = snapshots.get(userId);
if (
!options.force &&
snapshot &&
snapshot.generation === generation &&
Date.now() - snapshot.at < SNAPSHOT_TTL_MS
) {
return { changed: false, wire: snapshot.wire };
}
registerCoreSyncEntities();
const startedAt = generation;
const records = await listRecords(userId);
const resolvers = createResolvers(userId);
const wire = new Map<string, SyncRow>();
let changed = false;
for (const entity of listEntities()) {
let loaded;
try {
loaded = await loadWireRows(entity, userId, resolvers);
} catch (error) {
// An entity that cannot load right now is left alone rather than read
// as every row deleted.
syncLogger.warn("Could not read a sync entity", {
operation: "sync_reconcile",
entityType: entity.type,
userId,
error: error instanceof Error ? error.message : String(error),
});
continue;
}
for (const row of loaded.rows.values()) {
const key = recordKey(entity.type, row.syncId);
wire.set(key, row.wire);
const record = records.get(key);
if (record && !record.deleted && record.hash === row.hash) continue;
await putRecord(userId, entity.type, row.syncId, {
revision: (record?.revision ?? 0) + 1,
seq: await allocateSeq(),
hash: row.hash,
deleted: false,
});
changed = true;
}
for (const record of records.values()) {
if (record.entityType !== entity.type || record.deleted) continue;
if (loaded.rows.has(record.syncId) || loaded.failed.has(record.syncId)) {
continue;
}
if (entity.covers && !entity.covers(record.syncId)) continue;
await putRecord(userId, entity.type, record.syncId, {
revision: record.revision + 1,
seq: await allocateSeq(),
hash: null,
deleted: true,
});
changed = true;
}
}
snapshots.set(userId, { at: Date.now(), generation: startedAt, wire });
if (changed) notifyListeners(userId);
return { changed, wire };
}
const listeners = new Map<string, Set<Response>>();
let debounce: NodeJS.Timeout | null = null;
let heartbeat: NodeJS.Timeout | null = null;
let sweep: NodeJS.Timeout | null = null;
/**
* Something was written. Desktops listening for changes get their
* account reconciled shortly after, since a write by one user (an owner
* editing a shared host) can change what another one sees.
*/
export function markChanged(): void {
generation++;
if (listeners.size === 0) return;
if (debounce) clearTimeout(debounce);
debounce = setTimeout(() => {
debounce = null;
void reconcileListeners();
}, 1500);
debounce.unref?.();
}
async function reconcileListeners(): Promise<void> {
for (const userId of [...listeners.keys()]) {
try {
await withUserLock(userId, () => reconcileUser(userId));
} catch (error) {
syncLogger.warn("Background sync reconcile failed", {
operation: "sync_reconcile_background",
userId,
error: error instanceof Error ? error.message : String(error),
});
}
}
}
export function notifyListeners(userId: string): void {
const set = listeners.get(userId);
if (!set) return;
for (const res of set) {
res.write(`event: change\ndata: {}\n\n`);
}
}
export function addListener(userId: string, res: Response): () => void {
let set = listeners.get(userId);
if (!set) {
set = new Set();
listeners.set(userId, set);
}
set.add(res);
ensureTimers();
return () => {
set!.delete(res);
if (set!.size === 0) listeners.delete(userId);
};
}
function ensureTimers(): void {
if (!heartbeat) {
heartbeat = setInterval(() => {
for (const set of listeners.values()) {
for (const res of set) res.write(`: ping\n\n`);
}
}, 25_000);
heartbeat.unref?.();
}
if (!sweep) {
// Background jobs write without a request; this catches them.
sweep = setInterval(() => {
generation++;
void reconcileListeners();
}, 60_000);
sweep.unref?.();
}
}
/** Test seam. */
export function resetFeed(): void {
snapshots.clear();
listeners.clear();
locks.clear();
generation = 0;
for (const timer of [debounce, heartbeat, sweep]) {
if (timer) clearTimeout(timer);
}
debounce = heartbeat = sweep = null;
}