@g9tm/app-diagnostic 0.2.0 → 0.2.2
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/package.json +20 -12
- package/src/bytes.ts +48 -48
- package/src/host.ts +124 -124
- package/src/index.ts +30 -30
- package/src/live/bundle.ts +77 -77
- package/src/live/channel.ts +496 -496
- package/src/live/handlers.ts +426 -426
- package/src/live/models.ts +366 -360
- package/src/live/upload.ts +175 -175
- package/src/recording.ts +176 -176
- package/src/store.ts +39 -39
- package/src/strings.generated.ts +242 -242
- package/src/strings.ts +37 -37
- package/src/tester/archive.ts +83 -83
- package/src/tester/compose.ts +99 -99
- package/src/tester/engine.ts +2 -0
- package/src/tester/feed.ts +182 -182
- package/src/tester/gesture.ts +61 -61
- package/src/tester/model.ts +125 -125
- package/src/tester/outbox.ts +131 -131
- package/src/tester/screen.ts +117 -117
- package/src/tester/store.ts +145 -145
- package/src/tester/timeline.ts +98 -98
- package/src/upload.ts +236 -236
- package/src/wire.ts +133 -133
package/src/live/channel.ts
CHANGED
|
@@ -1,496 +1,496 @@
|
|
|
1
|
-
// The live channel's connection (G9AppDiagnostic.Maui LiveDiagnosticClient + the presence and log pushers + consent):
|
|
2
|
-
// one SignalR connection to the gateway's device hub while a user is signed in.
|
|
3
|
-
//
|
|
4
|
-
// shadow channel always while signed in: Hello (identity, device facts, the trust-on-first-use device secret), the
|
|
5
|
-
// 60 s presence announcement, the app log pushed in batches — what support sees without a session
|
|
6
|
-
// foreground only after the user allowed it: AnnounceForeground(consented), and the commands that look INTO the
|
|
7
|
-
// device are served (live/handlers.ts); the consent lives 10 minutes, slid forward while the overlay
|
|
8
|
-
// is open, and never outlives the session
|
|
9
|
-
// fleet settings Hello's deviceSettings and OnDeviceSettingsChangedAsync go to the app (ILiveDeviceSettingsSink)
|
|
10
|
-
//
|
|
11
|
-
// The package carries; the app knows its data (diagnostic/AiGuides/04-Live-Channel.md): every product command is an
|
|
12
|
-
// extension that registers its listener with `on` and answers with `push`.
|
|
13
|
-
import { type DiagnosticLog, type DiagnosticPrefs, type DiagnosticSecrets, errorText, silentLog, type Unsubscribe } from '../host.ts';
|
|
14
|
-
import { createStore, type ReadableStore, type Store } from '../store.ts';
|
|
15
|
-
import { levelName } from '../tester/timeline.ts';
|
|
16
|
-
import { CURRENT_CAPABILITIES, currentWire, DeviceHubListeners, DeviceHubMethods, type DiagnosticWireProfile, hubUrlOf, NEUTRAL_PROTOCOL_HEADER } from '../wire.ts';
|
|
17
|
-
import type { DeviceSettingItem, HelloResponse, LogEntryPayload, PeerInfo, PresencePayload } from './models.ts';
|
|
18
|
-
|
|
19
|
-
export const CONSENT_TTL_MS = 10 * 60 * 1000;
|
|
20
|
-
const PRESENCE_EVERY_MS = 60_000;
|
|
21
|
-
const LOG_PUSH_EVERY_MS = 3000;
|
|
22
|
-
const LOG_BATCH_MAX = 200;
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* What the channel uses of a SignalR client — structural on purpose: a platform's client (G9SignalRSuperNetCore's Lynx
|
|
26
|
-
* client, @microsoft/signalr in Node) fits as it is, and tests pass a fake.
|
|
27
|
-
*/
|
|
28
|
-
export interface HubClient {
|
|
29
|
-
readonly state: { readonly phase: string; readonly connectionId?: string | null };
|
|
30
|
-
onState(callback: (state: { phase: string; connectionId?: string | null; error?: string }) => void): () => void;
|
|
31
|
-
on(method: string, handler: (...args: any[]) => void): () => void;
|
|
32
|
-
invoke<T = unknown>(method: string, ...args: unknown[]): Promise<T>;
|
|
33
|
-
start(): Promise<void>;
|
|
34
|
-
stop(): Promise<void>;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** What the live channel needs to know from the app, and nothing more (ILiveChannelHost). */
|
|
38
|
-
export interface ILiveChannelHost {
|
|
39
|
-
/** The gateway's base address, read at every (re)connect (an admin may change it at runtime). */
|
|
40
|
-
gatewayUrl(): string;
|
|
41
|
-
/** Who is signed in (the username), or null. */
|
|
42
|
-
username(): Promise<string | null>;
|
|
43
|
-
/** Close (or restart) the app after a restore was applied: the stores were replaced under the running process. */
|
|
44
|
-
closeApp(): void;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* What the device says about itself in presence (ILivePresenceSource): the app fills the fields it knows (the user's
|
|
49
|
-
* names, the page, its stores' sizes, the device facts). The channel sets the id, the capabilities, the consent flag,
|
|
50
|
-
* the build and the time.
|
|
51
|
-
*/
|
|
52
|
-
export interface ILivePresenceSource {
|
|
53
|
-
/** The heavy avatar only on Hello. */
|
|
54
|
-
capture(includeAvatar: boolean): Promise<Partial<PresencePayload>>;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** One line of the app's log. */
|
|
58
|
-
export interface LiveLogLine {
|
|
59
|
-
readonly timeMs: number;
|
|
60
|
-
/** trace | debug | info | warn | error | critical, or a .NET level name. */
|
|
61
|
-
readonly level: string;
|
|
62
|
-
readonly category: string;
|
|
63
|
-
readonly message: string;
|
|
64
|
-
readonly exception?: string | null;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** The app's log: live lines, and its log files for the operator's «log files» tab (ILiveLogSource). */
|
|
68
|
-
export interface ILiveLogSource {
|
|
69
|
-
subscribe(listener: (line: LiveLogLine) => void): Unsubscribe;
|
|
70
|
-
/** The newest lines, for the first batch after Hello. */
|
|
71
|
-
tail(max: number): readonly LiveLogLine[];
|
|
72
|
-
fileLoggingEnabled(): boolean;
|
|
73
|
-
/** The log files, newest first (only files in this list are ever served). */
|
|
74
|
-
files(): Promise<ReadonlyArray<{ readonly name: string; readonly path: string; readonly size: number; readonly modifiedMs: number }>>;
|
|
75
|
-
/** The file being written now (marked «live»), or null. */
|
|
76
|
-
currentFilePath(): string | null;
|
|
77
|
-
/** Writes what is buffered, so a read sees it. */
|
|
78
|
-
flush?(): Promise<void>;
|
|
79
|
-
/** How many files the app keeps (shown to the operator). Default 7. */
|
|
80
|
-
readonly retainedFileLimit?: number;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/** Applies the fleet settings the gateway pushes (on Hello and whenever they change) to the app's storage. */
|
|
84
|
-
export interface ILiveDeviceSettingsSink {
|
|
85
|
-
apply(items: readonly DeviceSettingItem[]): Promise<void> | void;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/** Keeps the process alive while an upload runs (an Android foreground service, an iOS background task). */
|
|
89
|
-
export interface ILiveKeepAlive {
|
|
90
|
-
begin(request: { readonly category: 'live-diagnostic' | 'backup'; readonly title: string; readonly subtitle: string | null; readonly showProgress: boolean }): Promise<{
|
|
91
|
-
progress(ratio: number, text?: string): void;
|
|
92
|
-
end(): Promise<void> | void;
|
|
93
|
-
}>;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/** An app's own command on the channel (sync control, NFC, a QA bridge): started once with the channel. */
|
|
97
|
-
export interface ILiveChannelExtension {
|
|
98
|
-
start(channel: LiveChannel): void;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
export type LivePhase = 'off' | 'connecting' | 'connected' | 'reconnecting' | 'rejected';
|
|
102
|
-
|
|
103
|
-
export interface LiveState {
|
|
104
|
-
readonly phase: LivePhase;
|
|
105
|
-
readonly rejection: string | null;
|
|
106
|
-
readonly clientId: string | null;
|
|
107
|
-
/** The user allowed the foreground channel (and it has not expired). */
|
|
108
|
-
readonly consented: boolean;
|
|
109
|
-
/** The live overlay is on screen (keeps the consent alive). */
|
|
110
|
-
readonly overlayOpen: boolean;
|
|
111
|
-
readonly operators: readonly PeerInfo[];
|
|
112
|
-
/** The last command an operator ran ("screenshot", "sql", …) and when. */
|
|
113
|
-
readonly lastCommand: { readonly name: string; readonly atMs: number } | null;
|
|
114
|
-
readonly error: string | null;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export interface LiveIdentityOptions {
|
|
118
|
-
readonly prefs: DiagnosticPrefs;
|
|
119
|
-
/** The preference that holds this installation's id (an app that had the channel before keeps its own). */
|
|
120
|
-
readonly clientIdKey: string;
|
|
121
|
-
readonly secrets: DiagnosticSecrets;
|
|
122
|
-
/** The secure-storage key of the gateway's device secret (an app that had the channel before keeps its own). */
|
|
123
|
-
readonly deviceSecretKey: string;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
export interface LiveChannelOptions {
|
|
127
|
-
readonly host: ILiveChannelHost;
|
|
128
|
-
readonly presence: ILivePresenceSource;
|
|
129
|
-
readonly identity: LiveIdentityOptions;
|
|
130
|
-
/** The platform's SignalR client for the hub URL with these headers. */
|
|
131
|
-
readonly createHubClient: (url: string, headers: Readonly<Record<string, string>>) => HubClient;
|
|
132
|
-
readonly logs?: ILiveLogSource;
|
|
133
|
-
readonly settings?: ILiveDeviceSettingsSink;
|
|
134
|
-
readonly keepAlive?: ILiveKeepAlive;
|
|
135
|
-
readonly extensions?: readonly ILiveChannelExtension[];
|
|
136
|
-
/** The wire values; default: the profile in force (useWire). */
|
|
137
|
-
readonly wire?: DiagnosticWireProfile;
|
|
138
|
-
/** The header the hub connection carries the protocol tag in (an app whose gateway predates the neutral one keeps its own). */
|
|
139
|
-
readonly protocolHeader?: string;
|
|
140
|
-
/** Extra headers on the hub connection (a test tunnel's key), by URL. */
|
|
141
|
-
readonly extraHeaders?: (url: string) => Readonly<Record<string, string>>;
|
|
142
|
-
/** The build: presence carries it, every bundle's manifest too. */
|
|
143
|
-
readonly branch?: string | null;
|
|
144
|
-
readonly commit?: string | null;
|
|
145
|
-
readonly log?: DiagnosticLog;
|
|
146
|
-
readonly onError?: (where: string, error: unknown) => void;
|
|
147
|
-
readonly now?: () => number;
|
|
148
|
-
readonly consentTtlMs?: number;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
const HEX_32 = /^[0-9a-f]{32}$/i;
|
|
152
|
-
|
|
153
|
-
/** A random version-4 GUID in .NET's "N" form (32 hex: the gateway's ids are hex). */
|
|
154
|
-
export function newClientId(random: () => number = Math.random): string {
|
|
155
|
-
const r = (n: number) => {
|
|
156
|
-
let s = '';
|
|
157
|
-
for (let i = 0; i < n; i++) s += Math.floor(random() * 16).toString(16);
|
|
158
|
-
return s;
|
|
159
|
-
};
|
|
160
|
-
return `${r(12)}4${r(3)}${'89ab'.charAt(Math.floor(random() * 4))}${r(15)}`;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* This installation's id (created on first use, kept across sign-outs). The hub's Hello and the tester report upload
|
|
165
|
-
* present the same id with the same secret. A dashed GUID (an older client wrote one; the gateway's REST refuses it) is
|
|
166
|
-
* normalised once — the gateway then sees a new device, and trust on first use issues it a new secret.
|
|
167
|
-
*/
|
|
168
|
-
export function deviceClientId(prefs: DiagnosticPrefs, key: string): string {
|
|
169
|
-
let id = prefs.get(key);
|
|
170
|
-
if (id && !HEX_32.test(id)) {
|
|
171
|
-
const hex = id.replace(/-/g, '').toLowerCase();
|
|
172
|
-
id = HEX_32.test(hex) ? hex : null;
|
|
173
|
-
if (id) prefs.set(key, id);
|
|
174
|
-
}
|
|
175
|
-
if (!id) {
|
|
176
|
-
id = newClientId();
|
|
177
|
-
prefs.set(key, id);
|
|
178
|
-
}
|
|
179
|
-
return id;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
export function toLogPayload(e: LiveLogLine): LogEntryPayload {
|
|
183
|
-
return { timestampUtc: new Date(e.timeMs).toISOString(), level: levelName(e.level), category: e.category, message: e.message, exception: e.exception ?? null };
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
export class LiveChannel {
|
|
187
|
-
readonly options: LiveChannelOptions;
|
|
188
|
-
private readonly store: Store<LiveState>;
|
|
189
|
-
private client: HubClient | null = null;
|
|
190
|
-
private consentAt: number | null = null;
|
|
191
|
-
private presenceTimer: ReturnType<typeof setInterval> | null = null;
|
|
192
|
-
private logTimer: ReturnType<typeof setInterval> | null = null;
|
|
193
|
-
private logQueue: LogEntryPayload[] = [];
|
|
194
|
-
private offLog: Unsubscribe | null = null;
|
|
195
|
-
private offs: Array<() => void> = [];
|
|
196
|
-
private helloInFlight = false;
|
|
197
|
-
private lastConnectionId: string | null = null;
|
|
198
|
-
private readonly now: () => number;
|
|
199
|
-
private readonly log: DiagnosticLog;
|
|
200
|
-
private extensionsStarted = false;
|
|
201
|
-
/** Handlers register here so they are wired on every (re)built client. */
|
|
202
|
-
private readonly listeners = new Map<string, (...args: unknown[]) => void>();
|
|
203
|
-
|
|
204
|
-
constructor(options: LiveChannelOptions) {
|
|
205
|
-
this.options = options;
|
|
206
|
-
this.now = options.now ?? Date.now;
|
|
207
|
-
this.log = options.log ?? silentLog;
|
|
208
|
-
this.store = createStore<LiveState>({ phase: 'off', rejection: null, clientId: null, consented: false, overlayOpen: false, operators: [], lastCommand: null, error: null });
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
get state(): ReadableStore<LiveState> {
|
|
212
|
-
return this.store;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/** The hub client while connected (handlers push results through it). */
|
|
216
|
-
get hub(): HubClient | null {
|
|
217
|
-
return this.client && this.store.get().phase === 'connected' ? this.client : null;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
get clientId(): string {
|
|
221
|
-
return deviceClientId(this.options.identity.prefs, this.options.identity.clientIdKey);
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
/** The device secret the gateway issued (null before the first Hello). */
|
|
225
|
-
deviceSecret(): Promise<string | null> {
|
|
226
|
-
return this.options.identity.secrets.get(this.options.identity.deviceSecretKey).catch(() => null);
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
/** Registers a gateway → device handler (wired now if connected, and on every rebuilt connection). */
|
|
230
|
-
on(listener: string, handler: (...args: unknown[]) => void): void {
|
|
231
|
-
this.listeners.set(listener, handler);
|
|
232
|
-
if (this.client) this.offs.push(this.client.on(listener, handler));
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
reportError(where: string, error: unknown): void {
|
|
236
|
-
if (this.options.onError) this.options.onError(where, error);
|
|
237
|
-
else this.log.log('error', 'live', `${where}: ${errorText(error)}`);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
info(message: string, level: 'info' | 'warn' = 'info'): void {
|
|
241
|
-
this.log.log(level, 'live', message);
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
async start(): Promise<void> {
|
|
245
|
-
if (this.client) return;
|
|
246
|
-
if (!this.extensionsStarted) {
|
|
247
|
-
this.extensionsStarted = true;
|
|
248
|
-
for (const ext of this.options.extensions ?? []) {
|
|
249
|
-
try {
|
|
250
|
-
ext.start(this);
|
|
251
|
-
} catch (error) {
|
|
252
|
-
this.reportError('live.extension', error);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
const wire = this.options.wire ?? currentWire();
|
|
257
|
-
const url = hubUrlOf(this.options.host.gatewayUrl(), wire);
|
|
258
|
-
const headers = { ...(this.options.extraHeaders?.(url) ?? {}), [this.options.protocolHeader ?? NEUTRAL_PROTOCOL_HEADER]: wire.protocolTag };
|
|
259
|
-
const client = this.options.createHubClient(url, headers);
|
|
260
|
-
this.client = client;
|
|
261
|
-
this.store.set((s) => ({ ...s, phase: 'connecting', clientId: this.clientId, error: null }));
|
|
262
|
-
this.offs.push(
|
|
263
|
-
client.onState((st) => {
|
|
264
|
-
const phase: LivePhase = st.phase === 'connected' ? 'connected' : st.phase === 'reconnecting' ? 'reconnecting' : st.phase === 'connecting' ? 'connecting' : 'off';
|
|
265
|
-
if (this.store.get().phase !== 'rejected') this.store.set((s) => ({ ...s, phase, error: st.error ?? null }));
|
|
266
|
-
if (st.phase === 'connected' && st.connectionId !== this.lastConnectionId) {
|
|
267
|
-
this.lastConnectionId = st.connectionId ?? null;
|
|
268
|
-
void this.hello();
|
|
269
|
-
}
|
|
270
|
-
}),
|
|
271
|
-
);
|
|
272
|
-
this.wireCore(client);
|
|
273
|
-
for (const [name, handler] of this.listeners) this.offs.push(client.on(name, handler));
|
|
274
|
-
const logs = this.options.logs;
|
|
275
|
-
if (logs) {
|
|
276
|
-
this.offLog = logs.subscribe((e) => {
|
|
277
|
-
this.logQueue.push(toLogPayload(e));
|
|
278
|
-
if (this.logQueue.length > LOG_BATCH_MAX * 5) this.logQueue.splice(0, this.logQueue.length - LOG_BATCH_MAX * 5);
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
this.presenceTimer = setInterval(() => void this.announcePresence(), PRESENCE_EVERY_MS);
|
|
282
|
-
this.logTimer = setInterval(() => void this.pushLogs(false), LOG_PUSH_EVERY_MS);
|
|
283
|
-
client.start().catch((e: unknown) => {
|
|
284
|
-
this.store.set((s) => ({ ...s, phase: 'off', error: errorText(e) }));
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
async stop(): Promise<void> {
|
|
289
|
-
const client = this.client;
|
|
290
|
-
this.client = null;
|
|
291
|
-
for (const off of this.offs.splice(0)) off();
|
|
292
|
-
this.offLog?.();
|
|
293
|
-
this.offLog = null;
|
|
294
|
-
if (this.presenceTimer) clearInterval(this.presenceTimer);
|
|
295
|
-
if (this.logTimer) clearInterval(this.logTimer);
|
|
296
|
-
this.presenceTimer = null;
|
|
297
|
-
this.logTimer = null;
|
|
298
|
-
this.consentAt = null;
|
|
299
|
-
this.lastConnectionId = null;
|
|
300
|
-
this.logQueue = [];
|
|
301
|
-
this.store.set({ phase: 'off', rejection: null, clientId: this.store.get().clientId, consented: false, overlayOpen: false, operators: [], lastCommand: null, error: null });
|
|
302
|
-
await client?.stop().catch(() => {});
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
// ── consent ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
306
|
-
|
|
307
|
-
/** The foreground channel is open: the user allowed it within the TTL (slid forward while the overlay is open). */
|
|
308
|
-
hasConsent(): boolean {
|
|
309
|
-
return this.consentAt !== null && this.now() - this.consentAt <= (this.options.consentTtlMs ?? CONSENT_TTL_MS);
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
grantConsent(): void {
|
|
313
|
-
this.consentAt = this.now();
|
|
314
|
-
this.info('Live diagnostic allowed by the user');
|
|
315
|
-
this.store.set((s) => ({ ...s, consented: true }));
|
|
316
|
-
void this.announceForeground(true);
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
revokeConsent(): void {
|
|
320
|
-
this.consentAt = null;
|
|
321
|
-
this.info('Live diagnostic stopped by the user');
|
|
322
|
-
this.store.set((s) => ({ ...s, consented: false, overlayOpen: false }));
|
|
323
|
-
void this.announceForeground(false);
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
setOverlayOpen(open: boolean): void {
|
|
327
|
-
if (open && this.consentAt !== null) this.consentAt = this.now();
|
|
328
|
-
this.store.set((s) => ({ ...s, overlayOpen: open }));
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
/** A command an operator sent: refused (false) without consent; recorded for the overlay. */
|
|
332
|
-
admit(name: string): boolean {
|
|
333
|
-
if (!this.hasConsent()) {
|
|
334
|
-
this.info(`Operator command '${name}' refused: live access not granted`, 'warn');
|
|
335
|
-
return false;
|
|
336
|
-
}
|
|
337
|
-
this.store.set((s) => ({ ...s, lastCommand: { name, atMs: this.now() } }));
|
|
338
|
-
return true;
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
/** Sends a result; a dropped connection is logged, never thrown at the handler. */
|
|
342
|
-
async push(method: string, ...args: unknown[]): Promise<void> {
|
|
343
|
-
const hub = this.hub;
|
|
344
|
-
if (!hub) return;
|
|
345
|
-
try {
|
|
346
|
-
await hub.invoke(method, ...args);
|
|
347
|
-
} catch (e) {
|
|
348
|
-
this.reportError(`live.${method}`, e);
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
// ── Hello / presence / logs ─────────────────────────────────────────────────────────────────────────────────────
|
|
353
|
-
|
|
354
|
-
private wireCore(client: HubClient): void {
|
|
355
|
-
this.offs.push(
|
|
356
|
-
client.on(DeviceHubListeners.ping, (pingId: unknown, serverTs: unknown) => void client.invoke(DeviceHubMethods.pong, pingId, serverTs).catch(() => {})),
|
|
357
|
-
client.on(DeviceHubListeners.peerConnected, (info: unknown) => {
|
|
358
|
-
const peer = info as PeerInfo;
|
|
359
|
-
this.info(`Operator connected: ${peer.displayLabel} (${peer.roleKind})`);
|
|
360
|
-
this.store.set((s) => ({ ...s, operators: [...s.operators.filter((p) => p.peerId !== peer.peerId), peer] }));
|
|
361
|
-
}),
|
|
362
|
-
client.on(DeviceHubListeners.peerDisconnected, (peerId: unknown, reason: unknown) => {
|
|
363
|
-
this.info(`Operator left: ${String(peerId)} (${String(reason)})`);
|
|
364
|
-
this.store.set((s) => ({ ...s, operators: s.operators.filter((p) => p.peerId !== peerId) }));
|
|
365
|
-
}),
|
|
366
|
-
client.on(DeviceHubListeners.deviceSettingsChanged, (items: unknown) => void this.applySettings(items as DeviceSettingItem[])),
|
|
367
|
-
);
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
private async hello(): Promise<void> {
|
|
371
|
-
const client = this.client;
|
|
372
|
-
if (!client || this.helloInFlight) return;
|
|
373
|
-
this.helloInFlight = true;
|
|
374
|
-
try {
|
|
375
|
-
const wire = this.options.wire ?? currentWire();
|
|
376
|
-
const token = await this.deviceSecret();
|
|
377
|
-
const response = await client.invoke<HelloResponse>(DeviceHubMethods.hello, {
|
|
378
|
-
clientId: this.clientId,
|
|
379
|
-
protocolTag: wire.protocolTag,
|
|
380
|
-
presence: await this.presence(true),
|
|
381
|
-
deviceAuthToken: token,
|
|
382
|
-
});
|
|
383
|
-
if (!response.accepted) {
|
|
384
|
-
this.info(`The gateway refused Hello: ${response.rejectionReason ?? '?'}`, 'warn');
|
|
385
|
-
this.store.set((s) => ({ ...s, phase: 'rejected', rejection: response.rejectionReason ?? 'rejected' }));
|
|
386
|
-
return;
|
|
387
|
-
}
|
|
388
|
-
if (response.deviceAuthToken) await this.options.identity.secrets.set(this.options.identity.deviceSecretKey, response.deviceAuthToken);
|
|
389
|
-
await this.applySettings(response.deviceSettings ?? []);
|
|
390
|
-
this.store.set((s) => ({ ...s, phase: 'connected', rejection: null }));
|
|
391
|
-
this.info(`Connected to the gateway as ${this.clientId}`);
|
|
392
|
-
// A consent given before a reconnect still holds: say so again (Hello resets the gateway to passive).
|
|
393
|
-
if (this.hasConsent()) await this.announceForeground(true);
|
|
394
|
-
await this.pushLogs(true);
|
|
395
|
-
} catch (e) {
|
|
396
|
-
this.reportError('live.hello', e);
|
|
397
|
-
} finally {
|
|
398
|
-
this.helloInFlight = false;
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
private async announceForeground(consented: boolean): Promise<void> {
|
|
403
|
-
await this.push(DeviceHubMethods.announceForeground, {
|
|
404
|
-
consented,
|
|
405
|
-
consentedAtUtc: new Date(this.consentAt ?? this.now()).toISOString(),
|
|
406
|
-
overlayPhase: consented ? (this.store.get().overlayOpen ? 'open' : 'minimized') : 'closed',
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
/** Every 60 s: the consent slides while the overlay is open, lapses after its TTL, and presence goes out. */
|
|
411
|
-
async announcePresence(): Promise<void> {
|
|
412
|
-
if (!this.hub) return;
|
|
413
|
-
if (this.store.get().overlayOpen && this.consentAt !== null) this.consentAt = this.now();
|
|
414
|
-
if (this.consentAt !== null && !this.hasConsent()) {
|
|
415
|
-
this.consentAt = null;
|
|
416
|
-
this.store.set((s) => ({ ...s, consented: false }));
|
|
417
|
-
void this.announceForeground(false);
|
|
418
|
-
}
|
|
419
|
-
await this.push(DeviceHubMethods.announcePresence, await this.presence(false));
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
private async pushLogs(tail: boolean): Promise<void> {
|
|
423
|
-
if (!this.hub) return;
|
|
424
|
-
const entries = tail ? (this.options.logs?.tail(LOG_BATCH_MAX) ?? []).map(toLogPayload) : this.logQueue.splice(0, LOG_BATCH_MAX);
|
|
425
|
-
if (tail) this.logQueue = [];
|
|
426
|
-
if (entries.length === 0) return;
|
|
427
|
-
await this.push(DeviceHubMethods.pushLogBatch, { entries, isTail: tail });
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
/** The presence facts: the app's, then the channel's own (id, capabilities, consent, build, time). */
|
|
431
|
-
async presence(withAvatar: boolean): Promise<PresencePayload> {
|
|
432
|
-
const app = await this.options.presence.capture(withAvatar).catch((e: unknown) => {
|
|
433
|
-
this.reportError('live.presence', e);
|
|
434
|
-
return {} as Partial<PresencePayload>;
|
|
435
|
-
});
|
|
436
|
-
const username = app.username ?? (await this.options.host.username().catch(() => null)) ?? '';
|
|
437
|
-
const base: PresencePayload = {
|
|
438
|
-
clientId: this.clientId,
|
|
439
|
-
username,
|
|
440
|
-
displayName: username,
|
|
441
|
-
firstName: '',
|
|
442
|
-
lastName: '',
|
|
443
|
-
fullName: '',
|
|
444
|
-
firstNameEn: '',
|
|
445
|
-
firstNameFa: '',
|
|
446
|
-
lastNameEn: '',
|
|
447
|
-
lastNameFa: '',
|
|
448
|
-
fullNameEn: '',
|
|
449
|
-
fullNameFa: '',
|
|
450
|
-
gender: -1,
|
|
451
|
-
deviceModel: '',
|
|
452
|
-
deviceManufacturer: '',
|
|
453
|
-
deviceIdiom: 'Phone',
|
|
454
|
-
platform: '',
|
|
455
|
-
platformVersion: '',
|
|
456
|
-
appVersion: '',
|
|
457
|
-
appBuild: '',
|
|
458
|
-
environment: '',
|
|
459
|
-
culture: '',
|
|
460
|
-
capabilities: [],
|
|
461
|
-
currentPageName: '',
|
|
462
|
-
connectivityOnline: true,
|
|
463
|
-
batteryPercent: -1,
|
|
464
|
-
powerSource: '',
|
|
465
|
-
freeDiskBytes: -1,
|
|
466
|
-
totalDiskBytes: -1,
|
|
467
|
-
managedMemoryBytes: -1,
|
|
468
|
-
sqliteDbBytes: -1,
|
|
469
|
-
geoDbBytes: -1,
|
|
470
|
-
attachmentDbBytes: -1,
|
|
471
|
-
lastSeenUtc: '',
|
|
472
|
-
foregroundConsented: false,
|
|
473
|
-
};
|
|
474
|
-
const { avatarBase64, ...rest } = app;
|
|
475
|
-
return {
|
|
476
|
-
...base,
|
|
477
|
-
...rest,
|
|
478
|
-
...(withAvatar && avatarBase64 ? { avatarBase64 } : {}),
|
|
479
|
-
clientId: this.clientId,
|
|
480
|
-
capabilities: CURRENT_CAPABILITIES.slice(),
|
|
481
|
-
...(this.options.branch ? { buildBranch: this.options.branch } : {}),
|
|
482
|
-
...(this.options.commit ? { buildCommit: this.options.commit } : {}),
|
|
483
|
-
lastSeenUtc: new Date(this.now()).toISOString(),
|
|
484
|
-
foregroundConsented: this.hasConsent(),
|
|
485
|
-
};
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
private async applySettings(items: readonly DeviceSettingItem[]): Promise<void> {
|
|
489
|
-
if (!this.options.settings || items.length === 0) return;
|
|
490
|
-
try {
|
|
491
|
-
await this.options.settings.apply(items);
|
|
492
|
-
} catch (e) {
|
|
493
|
-
this.reportError('live.settings', e);
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
}
|
|
1
|
+
// The live channel's connection (G9AppDiagnostic.Maui LiveDiagnosticClient + the presence and log pushers + consent):
|
|
2
|
+
// one SignalR connection to the gateway's device hub while a user is signed in.
|
|
3
|
+
//
|
|
4
|
+
// shadow channel always while signed in: Hello (identity, device facts, the trust-on-first-use device secret), the
|
|
5
|
+
// 60 s presence announcement, the app log pushed in batches — what support sees without a session
|
|
6
|
+
// foreground only after the user allowed it: AnnounceForeground(consented), and the commands that look INTO the
|
|
7
|
+
// device are served (live/handlers.ts); the consent lives 10 minutes, slid forward while the overlay
|
|
8
|
+
// is open, and never outlives the session
|
|
9
|
+
// fleet settings Hello's deviceSettings and OnDeviceSettingsChangedAsync go to the app (ILiveDeviceSettingsSink)
|
|
10
|
+
//
|
|
11
|
+
// The package carries; the app knows its data (diagnostic/AiGuides/04-Live-Channel.md): every product command is an
|
|
12
|
+
// extension that registers its listener with `on` and answers with `push`.
|
|
13
|
+
import { type DiagnosticLog, type DiagnosticPrefs, type DiagnosticSecrets, errorText, silentLog, type Unsubscribe } from '../host.ts';
|
|
14
|
+
import { createStore, type ReadableStore, type Store } from '../store.ts';
|
|
15
|
+
import { levelName } from '../tester/timeline.ts';
|
|
16
|
+
import { CURRENT_CAPABILITIES, currentWire, DeviceHubListeners, DeviceHubMethods, type DiagnosticWireProfile, hubUrlOf, NEUTRAL_PROTOCOL_HEADER } from '../wire.ts';
|
|
17
|
+
import type { DeviceSettingItem, HelloResponse, LogEntryPayload, PeerInfo, PresencePayload } from './models.ts';
|
|
18
|
+
|
|
19
|
+
export const CONSENT_TTL_MS = 10 * 60 * 1000;
|
|
20
|
+
const PRESENCE_EVERY_MS = 60_000;
|
|
21
|
+
const LOG_PUSH_EVERY_MS = 3000;
|
|
22
|
+
const LOG_BATCH_MAX = 200;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* What the channel uses of a SignalR client — structural on purpose: a platform's client (G9SignalRSuperNetCore's Lynx
|
|
26
|
+
* client, @microsoft/signalr in Node) fits as it is, and tests pass a fake.
|
|
27
|
+
*/
|
|
28
|
+
export interface HubClient {
|
|
29
|
+
readonly state: { readonly phase: string; readonly connectionId?: string | null };
|
|
30
|
+
onState(callback: (state: { phase: string; connectionId?: string | null; error?: string }) => void): () => void;
|
|
31
|
+
on(method: string, handler: (...args: any[]) => void): () => void;
|
|
32
|
+
invoke<T = unknown>(method: string, ...args: unknown[]): Promise<T>;
|
|
33
|
+
start(): Promise<void>;
|
|
34
|
+
stop(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** What the live channel needs to know from the app, and nothing more (ILiveChannelHost). */
|
|
38
|
+
export interface ILiveChannelHost {
|
|
39
|
+
/** The gateway's base address, read at every (re)connect (an admin may change it at runtime). */
|
|
40
|
+
gatewayUrl(): string;
|
|
41
|
+
/** Who is signed in (the username), or null. */
|
|
42
|
+
username(): Promise<string | null>;
|
|
43
|
+
/** Close (or restart) the app after a restore was applied: the stores were replaced under the running process. */
|
|
44
|
+
closeApp(): void;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* What the device says about itself in presence (ILivePresenceSource): the app fills the fields it knows (the user's
|
|
49
|
+
* names, the page, its stores' sizes, the device facts). The channel sets the id, the capabilities, the consent flag,
|
|
50
|
+
* the build and the time.
|
|
51
|
+
*/
|
|
52
|
+
export interface ILivePresenceSource {
|
|
53
|
+
/** The heavy avatar only on Hello. */
|
|
54
|
+
capture(includeAvatar: boolean): Promise<Partial<PresencePayload>>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** One line of the app's log. */
|
|
58
|
+
export interface LiveLogLine {
|
|
59
|
+
readonly timeMs: number;
|
|
60
|
+
/** trace | debug | info | warn | error | critical, or a .NET level name. */
|
|
61
|
+
readonly level: string;
|
|
62
|
+
readonly category: string;
|
|
63
|
+
readonly message: string;
|
|
64
|
+
readonly exception?: string | null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The app's log: live lines, and its log files for the operator's «log files» tab (ILiveLogSource). */
|
|
68
|
+
export interface ILiveLogSource {
|
|
69
|
+
subscribe(listener: (line: LiveLogLine) => void): Unsubscribe;
|
|
70
|
+
/** The newest lines, for the first batch after Hello. */
|
|
71
|
+
tail(max: number): readonly LiveLogLine[];
|
|
72
|
+
fileLoggingEnabled(): boolean;
|
|
73
|
+
/** The log files, newest first (only files in this list are ever served). */
|
|
74
|
+
files(): Promise<ReadonlyArray<{ readonly name: string; readonly path: string; readonly size: number; readonly modifiedMs: number }>>;
|
|
75
|
+
/** The file being written now (marked «live»), or null. */
|
|
76
|
+
currentFilePath(): string | null;
|
|
77
|
+
/** Writes what is buffered, so a read sees it. */
|
|
78
|
+
flush?(): Promise<void>;
|
|
79
|
+
/** How many files the app keeps (shown to the operator). Default 7. */
|
|
80
|
+
readonly retainedFileLimit?: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Applies the fleet settings the gateway pushes (on Hello and whenever they change) to the app's storage. */
|
|
84
|
+
export interface ILiveDeviceSettingsSink {
|
|
85
|
+
apply(items: readonly DeviceSettingItem[]): Promise<void> | void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Keeps the process alive while an upload runs (an Android foreground service, an iOS background task). */
|
|
89
|
+
export interface ILiveKeepAlive {
|
|
90
|
+
begin(request: { readonly category: 'live-diagnostic' | 'backup'; readonly title: string; readonly subtitle: string | null; readonly showProgress: boolean }): Promise<{
|
|
91
|
+
progress(ratio: number, text?: string): void;
|
|
92
|
+
end(): Promise<void> | void;
|
|
93
|
+
}>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** An app's own command on the channel (sync control, NFC, a QA bridge): started once with the channel. */
|
|
97
|
+
export interface ILiveChannelExtension {
|
|
98
|
+
start(channel: LiveChannel): void;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type LivePhase = 'off' | 'connecting' | 'connected' | 'reconnecting' | 'rejected';
|
|
102
|
+
|
|
103
|
+
export interface LiveState {
|
|
104
|
+
readonly phase: LivePhase;
|
|
105
|
+
readonly rejection: string | null;
|
|
106
|
+
readonly clientId: string | null;
|
|
107
|
+
/** The user allowed the foreground channel (and it has not expired). */
|
|
108
|
+
readonly consented: boolean;
|
|
109
|
+
/** The live overlay is on screen (keeps the consent alive). */
|
|
110
|
+
readonly overlayOpen: boolean;
|
|
111
|
+
readonly operators: readonly PeerInfo[];
|
|
112
|
+
/** The last command an operator ran ("screenshot", "sql", …) and when. */
|
|
113
|
+
readonly lastCommand: { readonly name: string; readonly atMs: number } | null;
|
|
114
|
+
readonly error: string | null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface LiveIdentityOptions {
|
|
118
|
+
readonly prefs: DiagnosticPrefs;
|
|
119
|
+
/** The preference that holds this installation's id (an app that had the channel before keeps its own). */
|
|
120
|
+
readonly clientIdKey: string;
|
|
121
|
+
readonly secrets: DiagnosticSecrets;
|
|
122
|
+
/** The secure-storage key of the gateway's device secret (an app that had the channel before keeps its own). */
|
|
123
|
+
readonly deviceSecretKey: string;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface LiveChannelOptions {
|
|
127
|
+
readonly host: ILiveChannelHost;
|
|
128
|
+
readonly presence: ILivePresenceSource;
|
|
129
|
+
readonly identity: LiveIdentityOptions;
|
|
130
|
+
/** The platform's SignalR client for the hub URL with these headers. */
|
|
131
|
+
readonly createHubClient: (url: string, headers: Readonly<Record<string, string>>) => HubClient;
|
|
132
|
+
readonly logs?: ILiveLogSource;
|
|
133
|
+
readonly settings?: ILiveDeviceSettingsSink;
|
|
134
|
+
readonly keepAlive?: ILiveKeepAlive;
|
|
135
|
+
readonly extensions?: readonly ILiveChannelExtension[];
|
|
136
|
+
/** The wire values; default: the profile in force (useWire). */
|
|
137
|
+
readonly wire?: DiagnosticWireProfile;
|
|
138
|
+
/** The header the hub connection carries the protocol tag in (an app whose gateway predates the neutral one keeps its own). */
|
|
139
|
+
readonly protocolHeader?: string;
|
|
140
|
+
/** Extra headers on the hub connection (a test tunnel's key), by URL. */
|
|
141
|
+
readonly extraHeaders?: (url: string) => Readonly<Record<string, string>>;
|
|
142
|
+
/** The build: presence carries it, every bundle's manifest too. */
|
|
143
|
+
readonly branch?: string | null;
|
|
144
|
+
readonly commit?: string | null;
|
|
145
|
+
readonly log?: DiagnosticLog;
|
|
146
|
+
readonly onError?: (where: string, error: unknown) => void;
|
|
147
|
+
readonly now?: () => number;
|
|
148
|
+
readonly consentTtlMs?: number;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const HEX_32 = /^[0-9a-f]{32}$/i;
|
|
152
|
+
|
|
153
|
+
/** A random version-4 GUID in .NET's "N" form (32 hex: the gateway's ids are hex). */
|
|
154
|
+
export function newClientId(random: () => number = Math.random): string {
|
|
155
|
+
const r = (n: number) => {
|
|
156
|
+
let s = '';
|
|
157
|
+
for (let i = 0; i < n; i++) s += Math.floor(random() * 16).toString(16);
|
|
158
|
+
return s;
|
|
159
|
+
};
|
|
160
|
+
return `${r(12)}4${r(3)}${'89ab'.charAt(Math.floor(random() * 4))}${r(15)}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* This installation's id (created on first use, kept across sign-outs). The hub's Hello and the tester report upload
|
|
165
|
+
* present the same id with the same secret. A dashed GUID (an older client wrote one; the gateway's REST refuses it) is
|
|
166
|
+
* normalised once — the gateway then sees a new device, and trust on first use issues it a new secret.
|
|
167
|
+
*/
|
|
168
|
+
export function deviceClientId(prefs: DiagnosticPrefs, key: string): string {
|
|
169
|
+
let id = prefs.get(key);
|
|
170
|
+
if (id && !HEX_32.test(id)) {
|
|
171
|
+
const hex = id.replace(/-/g, '').toLowerCase();
|
|
172
|
+
id = HEX_32.test(hex) ? hex : null;
|
|
173
|
+
if (id) prefs.set(key, id);
|
|
174
|
+
}
|
|
175
|
+
if (!id) {
|
|
176
|
+
id = newClientId();
|
|
177
|
+
prefs.set(key, id);
|
|
178
|
+
}
|
|
179
|
+
return id;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function toLogPayload(e: LiveLogLine): LogEntryPayload {
|
|
183
|
+
return { timestampUtc: new Date(e.timeMs).toISOString(), level: levelName(e.level), category: e.category, message: e.message, exception: e.exception ?? null };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export class LiveChannel {
|
|
187
|
+
readonly options: LiveChannelOptions;
|
|
188
|
+
private readonly store: Store<LiveState>;
|
|
189
|
+
private client: HubClient | null = null;
|
|
190
|
+
private consentAt: number | null = null;
|
|
191
|
+
private presenceTimer: ReturnType<typeof setInterval> | null = null;
|
|
192
|
+
private logTimer: ReturnType<typeof setInterval> | null = null;
|
|
193
|
+
private logQueue: LogEntryPayload[] = [];
|
|
194
|
+
private offLog: Unsubscribe | null = null;
|
|
195
|
+
private offs: Array<() => void> = [];
|
|
196
|
+
private helloInFlight = false;
|
|
197
|
+
private lastConnectionId: string | null = null;
|
|
198
|
+
private readonly now: () => number;
|
|
199
|
+
private readonly log: DiagnosticLog;
|
|
200
|
+
private extensionsStarted = false;
|
|
201
|
+
/** Handlers register here so they are wired on every (re)built client. */
|
|
202
|
+
private readonly listeners = new Map<string, (...args: unknown[]) => void>();
|
|
203
|
+
|
|
204
|
+
constructor(options: LiveChannelOptions) {
|
|
205
|
+
this.options = options;
|
|
206
|
+
this.now = options.now ?? Date.now;
|
|
207
|
+
this.log = options.log ?? silentLog;
|
|
208
|
+
this.store = createStore<LiveState>({ phase: 'off', rejection: null, clientId: null, consented: false, overlayOpen: false, operators: [], lastCommand: null, error: null });
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
get state(): ReadableStore<LiveState> {
|
|
212
|
+
return this.store;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The hub client while connected (handlers push results through it). */
|
|
216
|
+
get hub(): HubClient | null {
|
|
217
|
+
return this.client && this.store.get().phase === 'connected' ? this.client : null;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
get clientId(): string {
|
|
221
|
+
return deviceClientId(this.options.identity.prefs, this.options.identity.clientIdKey);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** The device secret the gateway issued (null before the first Hello). */
|
|
225
|
+
deviceSecret(): Promise<string | null> {
|
|
226
|
+
return this.options.identity.secrets.get(this.options.identity.deviceSecretKey).catch(() => null);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Registers a gateway → device handler (wired now if connected, and on every rebuilt connection). */
|
|
230
|
+
on(listener: string, handler: (...args: unknown[]) => void): void {
|
|
231
|
+
this.listeners.set(listener, handler);
|
|
232
|
+
if (this.client) this.offs.push(this.client.on(listener, handler));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
reportError(where: string, error: unknown): void {
|
|
236
|
+
if (this.options.onError) this.options.onError(where, error);
|
|
237
|
+
else this.log.log('error', 'live', `${where}: ${errorText(error)}`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
info(message: string, level: 'info' | 'warn' = 'info'): void {
|
|
241
|
+
this.log.log(level, 'live', message);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async start(): Promise<void> {
|
|
245
|
+
if (this.client) return;
|
|
246
|
+
if (!this.extensionsStarted) {
|
|
247
|
+
this.extensionsStarted = true;
|
|
248
|
+
for (const ext of this.options.extensions ?? []) {
|
|
249
|
+
try {
|
|
250
|
+
ext.start(this);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
this.reportError('live.extension', error);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const wire = this.options.wire ?? currentWire();
|
|
257
|
+
const url = hubUrlOf(this.options.host.gatewayUrl(), wire);
|
|
258
|
+
const headers = { ...(this.options.extraHeaders?.(url) ?? {}), [this.options.protocolHeader ?? NEUTRAL_PROTOCOL_HEADER]: wire.protocolTag };
|
|
259
|
+
const client = this.options.createHubClient(url, headers);
|
|
260
|
+
this.client = client;
|
|
261
|
+
this.store.set((s) => ({ ...s, phase: 'connecting', clientId: this.clientId, error: null }));
|
|
262
|
+
this.offs.push(
|
|
263
|
+
client.onState((st) => {
|
|
264
|
+
const phase: LivePhase = st.phase === 'connected' ? 'connected' : st.phase === 'reconnecting' ? 'reconnecting' : st.phase === 'connecting' ? 'connecting' : 'off';
|
|
265
|
+
if (this.store.get().phase !== 'rejected') this.store.set((s) => ({ ...s, phase, error: st.error ?? null }));
|
|
266
|
+
if (st.phase === 'connected' && st.connectionId !== this.lastConnectionId) {
|
|
267
|
+
this.lastConnectionId = st.connectionId ?? null;
|
|
268
|
+
void this.hello();
|
|
269
|
+
}
|
|
270
|
+
}),
|
|
271
|
+
);
|
|
272
|
+
this.wireCore(client);
|
|
273
|
+
for (const [name, handler] of this.listeners) this.offs.push(client.on(name, handler));
|
|
274
|
+
const logs = this.options.logs;
|
|
275
|
+
if (logs) {
|
|
276
|
+
this.offLog = logs.subscribe((e) => {
|
|
277
|
+
this.logQueue.push(toLogPayload(e));
|
|
278
|
+
if (this.logQueue.length > LOG_BATCH_MAX * 5) this.logQueue.splice(0, this.logQueue.length - LOG_BATCH_MAX * 5);
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
this.presenceTimer = setInterval(() => void this.announcePresence(), PRESENCE_EVERY_MS);
|
|
282
|
+
this.logTimer = setInterval(() => void this.pushLogs(false), LOG_PUSH_EVERY_MS);
|
|
283
|
+
client.start().catch((e: unknown) => {
|
|
284
|
+
this.store.set((s) => ({ ...s, phase: 'off', error: errorText(e) }));
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async stop(): Promise<void> {
|
|
289
|
+
const client = this.client;
|
|
290
|
+
this.client = null;
|
|
291
|
+
for (const off of this.offs.splice(0)) off();
|
|
292
|
+
this.offLog?.();
|
|
293
|
+
this.offLog = null;
|
|
294
|
+
if (this.presenceTimer) clearInterval(this.presenceTimer);
|
|
295
|
+
if (this.logTimer) clearInterval(this.logTimer);
|
|
296
|
+
this.presenceTimer = null;
|
|
297
|
+
this.logTimer = null;
|
|
298
|
+
this.consentAt = null;
|
|
299
|
+
this.lastConnectionId = null;
|
|
300
|
+
this.logQueue = [];
|
|
301
|
+
this.store.set({ phase: 'off', rejection: null, clientId: this.store.get().clientId, consented: false, overlayOpen: false, operators: [], lastCommand: null, error: null });
|
|
302
|
+
await client?.stop().catch(() => {});
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ── consent ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
306
|
+
|
|
307
|
+
/** The foreground channel is open: the user allowed it within the TTL (slid forward while the overlay is open). */
|
|
308
|
+
hasConsent(): boolean {
|
|
309
|
+
return this.consentAt !== null && this.now() - this.consentAt <= (this.options.consentTtlMs ?? CONSENT_TTL_MS);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
grantConsent(): void {
|
|
313
|
+
this.consentAt = this.now();
|
|
314
|
+
this.info('Live diagnostic allowed by the user');
|
|
315
|
+
this.store.set((s) => ({ ...s, consented: true }));
|
|
316
|
+
void this.announceForeground(true);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
revokeConsent(): void {
|
|
320
|
+
this.consentAt = null;
|
|
321
|
+
this.info('Live diagnostic stopped by the user');
|
|
322
|
+
this.store.set((s) => ({ ...s, consented: false, overlayOpen: false }));
|
|
323
|
+
void this.announceForeground(false);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
setOverlayOpen(open: boolean): void {
|
|
327
|
+
if (open && this.consentAt !== null) this.consentAt = this.now();
|
|
328
|
+
this.store.set((s) => ({ ...s, overlayOpen: open }));
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** A command an operator sent: refused (false) without consent; recorded for the overlay. */
|
|
332
|
+
admit(name: string): boolean {
|
|
333
|
+
if (!this.hasConsent()) {
|
|
334
|
+
this.info(`Operator command '${name}' refused: live access not granted`, 'warn');
|
|
335
|
+
return false;
|
|
336
|
+
}
|
|
337
|
+
this.store.set((s) => ({ ...s, lastCommand: { name, atMs: this.now() } }));
|
|
338
|
+
return true;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Sends a result; a dropped connection is logged, never thrown at the handler. */
|
|
342
|
+
async push(method: string, ...args: unknown[]): Promise<void> {
|
|
343
|
+
const hub = this.hub;
|
|
344
|
+
if (!hub) return;
|
|
345
|
+
try {
|
|
346
|
+
await hub.invoke(method, ...args);
|
|
347
|
+
} catch (e) {
|
|
348
|
+
this.reportError(`live.${method}`, e);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// ── Hello / presence / logs ─────────────────────────────────────────────────────────────────────────────────────
|
|
353
|
+
|
|
354
|
+
private wireCore(client: HubClient): void {
|
|
355
|
+
this.offs.push(
|
|
356
|
+
client.on(DeviceHubListeners.ping, (pingId: unknown, serverTs: unknown) => void client.invoke(DeviceHubMethods.pong, pingId, serverTs).catch(() => {})),
|
|
357
|
+
client.on(DeviceHubListeners.peerConnected, (info: unknown) => {
|
|
358
|
+
const peer = info as PeerInfo;
|
|
359
|
+
this.info(`Operator connected: ${peer.displayLabel} (${peer.roleKind})`);
|
|
360
|
+
this.store.set((s) => ({ ...s, operators: [...s.operators.filter((p) => p.peerId !== peer.peerId), peer] }));
|
|
361
|
+
}),
|
|
362
|
+
client.on(DeviceHubListeners.peerDisconnected, (peerId: unknown, reason: unknown) => {
|
|
363
|
+
this.info(`Operator left: ${String(peerId)} (${String(reason)})`);
|
|
364
|
+
this.store.set((s) => ({ ...s, operators: s.operators.filter((p) => p.peerId !== peerId) }));
|
|
365
|
+
}),
|
|
366
|
+
client.on(DeviceHubListeners.deviceSettingsChanged, (items: unknown) => void this.applySettings(items as DeviceSettingItem[])),
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
private async hello(): Promise<void> {
|
|
371
|
+
const client = this.client;
|
|
372
|
+
if (!client || this.helloInFlight) return;
|
|
373
|
+
this.helloInFlight = true;
|
|
374
|
+
try {
|
|
375
|
+
const wire = this.options.wire ?? currentWire();
|
|
376
|
+
const token = await this.deviceSecret();
|
|
377
|
+
const response = await client.invoke<HelloResponse>(DeviceHubMethods.hello, {
|
|
378
|
+
clientId: this.clientId,
|
|
379
|
+
protocolTag: wire.protocolTag,
|
|
380
|
+
presence: await this.presence(true),
|
|
381
|
+
deviceAuthToken: token,
|
|
382
|
+
});
|
|
383
|
+
if (!response.accepted) {
|
|
384
|
+
this.info(`The gateway refused Hello: ${response.rejectionReason ?? '?'}`, 'warn');
|
|
385
|
+
this.store.set((s) => ({ ...s, phase: 'rejected', rejection: response.rejectionReason ?? 'rejected' }));
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
if (response.deviceAuthToken) await this.options.identity.secrets.set(this.options.identity.deviceSecretKey, response.deviceAuthToken);
|
|
389
|
+
await this.applySettings(response.deviceSettings ?? []);
|
|
390
|
+
this.store.set((s) => ({ ...s, phase: 'connected', rejection: null }));
|
|
391
|
+
this.info(`Connected to the gateway as ${this.clientId}`);
|
|
392
|
+
// A consent given before a reconnect still holds: say so again (Hello resets the gateway to passive).
|
|
393
|
+
if (this.hasConsent()) await this.announceForeground(true);
|
|
394
|
+
await this.pushLogs(true);
|
|
395
|
+
} catch (e) {
|
|
396
|
+
this.reportError('live.hello', e);
|
|
397
|
+
} finally {
|
|
398
|
+
this.helloInFlight = false;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
private async announceForeground(consented: boolean): Promise<void> {
|
|
403
|
+
await this.push(DeviceHubMethods.announceForeground, {
|
|
404
|
+
consented,
|
|
405
|
+
consentedAtUtc: new Date(this.consentAt ?? this.now()).toISOString(),
|
|
406
|
+
overlayPhase: consented ? (this.store.get().overlayOpen ? 'open' : 'minimized') : 'closed',
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Every 60 s: the consent slides while the overlay is open, lapses after its TTL, and presence goes out. */
|
|
411
|
+
async announcePresence(): Promise<void> {
|
|
412
|
+
if (!this.hub) return;
|
|
413
|
+
if (this.store.get().overlayOpen && this.consentAt !== null) this.consentAt = this.now();
|
|
414
|
+
if (this.consentAt !== null && !this.hasConsent()) {
|
|
415
|
+
this.consentAt = null;
|
|
416
|
+
this.store.set((s) => ({ ...s, consented: false }));
|
|
417
|
+
void this.announceForeground(false);
|
|
418
|
+
}
|
|
419
|
+
await this.push(DeviceHubMethods.announcePresence, await this.presence(false));
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
private async pushLogs(tail: boolean): Promise<void> {
|
|
423
|
+
if (!this.hub) return;
|
|
424
|
+
const entries = tail ? (this.options.logs?.tail(LOG_BATCH_MAX) ?? []).map(toLogPayload) : this.logQueue.splice(0, LOG_BATCH_MAX);
|
|
425
|
+
if (tail) this.logQueue = [];
|
|
426
|
+
if (entries.length === 0) return;
|
|
427
|
+
await this.push(DeviceHubMethods.pushLogBatch, { entries, isTail: tail });
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** The presence facts: the app's, then the channel's own (id, capabilities, consent, build, time). */
|
|
431
|
+
async presence(withAvatar: boolean): Promise<PresencePayload> {
|
|
432
|
+
const app = await this.options.presence.capture(withAvatar).catch((e: unknown) => {
|
|
433
|
+
this.reportError('live.presence', e);
|
|
434
|
+
return {} as Partial<PresencePayload>;
|
|
435
|
+
});
|
|
436
|
+
const username = app.username ?? (await this.options.host.username().catch(() => null)) ?? '';
|
|
437
|
+
const base: PresencePayload = {
|
|
438
|
+
clientId: this.clientId,
|
|
439
|
+
username,
|
|
440
|
+
displayName: username,
|
|
441
|
+
firstName: '',
|
|
442
|
+
lastName: '',
|
|
443
|
+
fullName: '',
|
|
444
|
+
firstNameEn: '',
|
|
445
|
+
firstNameFa: '',
|
|
446
|
+
lastNameEn: '',
|
|
447
|
+
lastNameFa: '',
|
|
448
|
+
fullNameEn: '',
|
|
449
|
+
fullNameFa: '',
|
|
450
|
+
gender: -1,
|
|
451
|
+
deviceModel: '',
|
|
452
|
+
deviceManufacturer: '',
|
|
453
|
+
deviceIdiom: 'Phone',
|
|
454
|
+
platform: '',
|
|
455
|
+
platformVersion: '',
|
|
456
|
+
appVersion: '',
|
|
457
|
+
appBuild: '',
|
|
458
|
+
environment: '',
|
|
459
|
+
culture: '',
|
|
460
|
+
capabilities: [],
|
|
461
|
+
currentPageName: '',
|
|
462
|
+
connectivityOnline: true,
|
|
463
|
+
batteryPercent: -1,
|
|
464
|
+
powerSource: '',
|
|
465
|
+
freeDiskBytes: -1,
|
|
466
|
+
totalDiskBytes: -1,
|
|
467
|
+
managedMemoryBytes: -1,
|
|
468
|
+
sqliteDbBytes: -1,
|
|
469
|
+
geoDbBytes: -1,
|
|
470
|
+
attachmentDbBytes: -1,
|
|
471
|
+
lastSeenUtc: '',
|
|
472
|
+
foregroundConsented: false,
|
|
473
|
+
};
|
|
474
|
+
const { avatarBase64, ...rest } = app;
|
|
475
|
+
return {
|
|
476
|
+
...base,
|
|
477
|
+
...rest,
|
|
478
|
+
...(withAvatar && avatarBase64 ? { avatarBase64 } : {}),
|
|
479
|
+
clientId: this.clientId,
|
|
480
|
+
capabilities: CURRENT_CAPABILITIES.slice(),
|
|
481
|
+
...(this.options.branch ? { buildBranch: this.options.branch } : {}),
|
|
482
|
+
...(this.options.commit ? { buildCommit: this.options.commit } : {}),
|
|
483
|
+
lastSeenUtc: new Date(this.now()).toISOString(),
|
|
484
|
+
foregroundConsented: this.hasConsent(),
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
private async applySettings(items: readonly DeviceSettingItem[]): Promise<void> {
|
|
489
|
+
if (!this.options.settings || items.length === 0) return;
|
|
490
|
+
try {
|
|
491
|
+
await this.options.settings.apply(items);
|
|
492
|
+
} catch (e) {
|
|
493
|
+
this.reportError('live.settings', e);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|