GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — opencode-mobile/shared/observability/core.ts at main · drpr/opencode-mobile

Expand file tree

/

core.ts

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
331 lines (306 loc) · 12 KB
/

core.ts

Copy path

File metadata and controls

331 lines (306 loc) · 12 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import { context, trace, SpanStatusCode, type Attributes, type Counter, type Gauge, type Histogram, type Span as OtelSpan, type Tracer } from '@opentelemetry/api';
import { DEFAULT_OBSERVABILITY_PREFERENCES, readBuildMetadata, readRemoteOtlpConfig } from '@/shared/observability/config';
import { createOtelPipeline, type EmittedLog, type OtelPipeline } from '@/shared/observability/otel';
import { sanitizeAttributes, sanitizeError, sanitizeLevel, sanitizeName } from '@/shared/observability/sanitize';
import { DIAGNOSTICS_MAX_BYTES, DIAGNOSTICS_RETENTION_DAYS, DiagnosticsStore } from '@/shared/observability/storage/jsonl-store';
import { writeDiagnosticReport } from '@/shared/observability/storage/report';
import type {
BuildMetadata,
ExportOptions,
Observability,
ObservabilityLevel,
ObservabilityPreferences,
ObservabilitySnapshot,
ObservabilityStatus,
SafeAttributes,
Span,
} from '@/shared/observability/types';
type Options = {
build?: BuildMetadata;
preferences?: ObservabilityPreferences;
store?: DiagnosticsStore;
pipeline?: OtelPipeline;
remoteAvailable?: boolean;
forceRemoteDisabled?: boolean;
startedAt?: number;
};
function otelAttributes(attrs: SafeAttributes | undefined): Attributes {
return Object.fromEntries(Object.entries(sanitizeAttributes(attrs) ?? {}).filter(([, value]) => value !== undefined)) as Attributes;
}
function emptySnapshot(preferences: ObservabilityPreferences, remoteAvailable: boolean): ObservabilitySnapshot {
return {
enabled: preferences.diagnosticsEnabled,
level: preferences.diagnosticsLevel,
remoteAvailable,
remoteTelemetryEnabled: preferences.remoteTelemetryEnabled,
remoteCrashReports: preferences.remoteCrashReports,
remotePerformance: preferences.remotePerformance,
storage: {
bytes: 0,
files: 0,
retentionDays: DIAGNOSTICS_RETENTION_DAYS,
maxBytes: DIAGNOSTICS_MAX_BYTES,
corruptFiles: 0,
},
metrics: [],
recent: { logs: [], errors: [], spans: [] },
};
}
class WrappedSpan implements Span {
readonly traceId: string;
readonly spanId: string;
readonly parentSpanId?: string;
readonly name: string;
readonly startedAt = Date.now();
private attributes: SafeAttributes;
constructor(
readonly otelSpan: OtelSpan,
private readonly tracer: Tracer,
spanName: string,
attrs?: SafeAttributes,
parentSpanId?: string,
) {
const spanContext = otelSpan.spanContext();
this.traceId = spanContext.traceId;
this.spanId = spanContext.spanId;
this.parentSpanId = parentSpanId;
this.name = spanName;
this.attributes = sanitizeAttributes(attrs) ?? {};
}
setAttribute(key: string, value: string | number | boolean) {
const next = sanitizeAttributes({ ...this.attributes, [key]: value });
this.attributes = next ?? {};
this.otelSpan.setAttribute(key, value);
}
setAttributes(attrs: SafeAttributes) {
const next = sanitizeAttributes({ ...this.attributes, ...attrs }) ?? {};
this.attributes = next;
for (const [key, value] of Object.entries(next)) {
if (value !== undefined) this.otelSpan.setAttribute(key, value);
}
}
end(status: ObservabilityStatus = 'ok', attrs?: SafeAttributes) {
const merged = sanitizeAttributes({ ...this.attributes, ...attrs });
if (merged) {
for (const [key, value] of Object.entries(merged)) {
if (value !== undefined) this.otelSpan.setAttribute(key, value);
}
}
this.otelSpan.setStatus({
code: status === 'error' ? SpanStatusCode.ERROR : status === 'ok' ? SpanStatusCode.OK : SpanStatusCode.UNSET,
});
this.otelSpan.end();
}
child(name: string, attrs?: SafeAttributes) {
const parentContext = trace.setSpan(context.active(), this.otelSpan);
const child = this.tracer.startSpan(sanitizeName(name), { attributes: otelAttributes(attrs) }, parentContext);
return new WrappedSpan(child, this.tracer, sanitizeName(name), attrs, this.spanId);
}
}
export function createObservability(options: Options = {}): Observability {
const build = options.build ?? readBuildMetadata();
let preferences = options.preferences ?? DEFAULT_OBSERVABILITY_PREFERENCES;
const remoteConfig = options.forceRemoteDisabled ? undefined : readRemoteOtlpConfig();
const remoteAvailable = options.remoteAvailable ?? Boolean(remoteConfig || options.pipeline);
const store = options.store ?? new DiagnosticsStore();
const listeners = new Set<() => void>();
const startedAt = options.startedAt ?? Date.now();
const startupMarks = new Set<string>();
let snapshot = emptySnapshot(preferences, remoteAvailable);
let initialized = false;
let refreshInFlight: Promise<ObservabilitySnapshot> | undefined;
let closed = false;
const pipeline = options.pipeline ?? createOtelPipeline({
build,
remote: remoteConfig,
append: (record) => store.append(record),
getConsent: () => ({
telemetry: preferences.remoteTelemetryEnabled,
crash: preferences.remoteCrashReports,
performance: preferences.remotePerformance,
}),
});
const counters = new Map<string, Counter>();
const gauges = new Map<string, Gauge>();
const histograms = new Map<string, Histogram>();
const emitLocal = (record: EmittedLog) => {
if (closed || !preferences.diagnosticsEnabled) return;
pipeline.emitLocal({ ...record, name: sanitizeName(record.name), attrs: sanitizeAttributes(record.attrs) });
};
const captureError = (error: unknown, attrs?: SafeAttributes, remote = true) => {
const details = sanitizeError(error);
const record: EmittedLog = {
level: 'error',
name: 'app.error',
message: details.message,
stack: details.stack,
attrs: sanitizeAttributes({
...attrs,
errorName: details.name,
...(details.code !== undefined ? { reason: String(details.code) } : {}),
}),
kind: 'error',
};
emitLocal(record);
if (remote) pipeline.emitRemoteError(record);
};
const startSpan = (name: string, attrs?: SafeAttributes) => {
const parent = trace.getSpan(context.active());
const span = pipeline.tracer.startSpan(sanitizeName(name), { attributes: otelAttributes(attrs) }, context.active());
return new WrappedSpan(span, pipeline.tracer, sanitizeName(name), attrs, parent?.spanContext().spanId);
};
const span = async <T,>(name: string, attrs: SafeAttributes | undefined, run: (value: Span) => T | Promise<T>): Promise<T> => {
const active = startSpan(name, attrs) as WrappedSpan;
const activeContext = trace.setSpan(context.active(), active.otelSpan);
return context.with(activeContext, async () => {
try {
const result = await run(active);
active.end('ok');
return result;
} catch (error) {
active.end('error');
captureError(error, { operation: sanitizeName(name) });
throw error;
}
});
};
const markStartup = (phase: string, attrs?: SafeAttributes) => {
const safePhase = sanitizeName(phase);
if (startupMarks.has(safePhase)) return;
startupMarks.add(safePhase);
const durationMs = Math.max(0, Date.now() - startedAt);
emitLocal({ level: 'info', name: 'app.startup', attrs: { ...attrs, phase: safePhase, durationMs }, message: `startup ${safePhase}` });
};
const refreshSnapshot = () => {
if (refreshInFlight) return refreshInFlight;
refreshInFlight = (async () => {
await store.flush();
const [storage, records] = await Promise.all([store.usage(), store.read(300)]);
const errors = records.filter((record) => record.kind === 'error');
const next: ObservabilitySnapshot = {
enabled: preferences.diagnosticsEnabled,
level: preferences.diagnosticsLevel,
remoteAvailable,
remoteTelemetryEnabled: preferences.remoteTelemetryEnabled,
remoteCrashReports: preferences.remoteCrashReports,
remotePerformance: preferences.remotePerformance,
storage,
metrics: records.filter((record) => record.kind === 'metric').slice(0, 120),
recent: {
logs: records.filter((record) => record.kind === 'log').slice(0, 120),
errors: errors.slice(0, 40),
spans: records.filter((record) => record.kind === 'span').slice(0, 80),
},
...(errors[0] ? { lastFailure: errors[0] } : {}),
};
snapshot = next;
for (const listener of listeners) listener();
return next;
})().finally(() => { refreshInFlight = undefined; });
return refreshInFlight;
};
const configure = (next: ObservabilityPreferences) => {
const previous = preferences;
preferences = next;
if (preferences.remoteTelemetryEnabled !== previous.remoteTelemetryEnabled
|| preferences.remoteCrashReports !== previous.remoteCrashReports
|| preferences.remotePerformance !== previous.remotePerformance) {
pipeline.setRemoteEnabled(
preferences.remoteTelemetryEnabled && (preferences.remoteCrashReports || preferences.remotePerformance),
);
}
snapshot = {
...snapshot,
enabled: preferences.diagnosticsEnabled,
level: preferences.diagnosticsLevel,
remoteAvailable,
remoteTelemetryEnabled: preferences.remoteTelemetryEnabled,
remoteCrashReports: preferences.remoteCrashReports,
remotePerformance: preferences.remotePerformance,
};
for (const listener of listeners) listener();
if (initialized) void refreshSnapshot();
};
const initialize = async () => {
if (initialized) return;
initialized = true;
pipeline.setRemoteEnabled(
preferences.remoteTelemetryEnabled && (preferences.remoteCrashReports || preferences.remotePerformance),
);
await store.initialize();
await refreshSnapshot();
};
const flush = async () => {
await pipeline.forceFlush();
await refreshSnapshot();
};
const clearLocal = async () => {
await store.clear();
await refreshSnapshot();
};
const exportReport = async (exportOptions: ExportOptions) => {
await store.flush();
return writeDiagnosticReport({ store, build, preferences, options: exportOptions });
};
return {
log(level: ObservabilityLevel, name: string, attrs?: SafeAttributes) {
emitLocal({ level: sanitizeLevel(level), name, attrs });
},
logWithSpan(activeSpan: Span, level: ObservabilityLevel, name: string, attrs?: SafeAttributes) {
emitLocal({ level: sanitizeLevel(level), name, attrs, traceId: activeSpan.traceId, spanId: activeSpan.spanId });
},
debug: (name, attrs) => emitLocal({ level: 'debug', name, attrs }),
info: (name, attrs) => emitLocal({ level: 'info', name, attrs }),
warn: (name, attrs) => emitLocal({ level: 'warn', name, attrs }),
error: (name, attrs) => emitLocal({ level: 'error', name, attrs }),
startSpan,
span,
counter(name, value = 1, labels) {
const key = sanitizeName(name);
let counter = counters.get(key);
if (!counter) {
counter = pipeline.meter.createCounter(key);
counters.set(key, counter);
}
counter.add(value, otelAttributes(labels));
},
gauge(name, value, labels) {
const key = sanitizeName(name);
let gauge = gauges.get(key);
if (!gauge) {
gauge = pipeline.meter.createGauge(key);
gauges.set(key, gauge);
}
gauge.record(value, otelAttributes(labels));
},
histogram(name, value, unit, labels) {
const key = sanitizeName(name);
let histogram = histograms.get(key);
if (!histogram) {
histogram = pipeline.meter.createHistogram(key, unit ? { unit } : undefined);
histograms.set(key, histogram);
}
histogram.record(value, otelAttributes(labels));
},
captureError,
markStartup,
configure,
getSnapshot: () => snapshot,
refreshSnapshot,
subscribe(listener) {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
initialize,
shutdown: async () => {
closed = true;
await flush();
pipeline.setRemoteEnabled(false);
await pipeline.shutdown();
await store.close();
},
clearLocal,
exportReport,
flush,
} as Observability;
}
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.