Skip to content

Commit 57e99cf

Browse files
fix: one opt-out event without the account; no polling of a rejected key
- claim the opt-out send with an in-flight file, so two inits send once - the event carries the machine id and source only - retry identity only after a transient failure - refresh identity on TUI /logout - create ~/.altimate owner-only Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X
1 parent f751255 commit 57e99cf

7 files changed

Lines changed: 220 additions & 35 deletions

File tree

‎packages/opencode/src/altimate/telemetry/identity.ts‎

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import fs from "fs"
22
import path from "path"
3-
import { rm } from "node:fs/promises"
3+
import fsp, { rm } from "node:fs/promises"
44
import { createHash } from "crypto"
55
import { Global } from "../../global"
66
import { Filesystem } from "../../util/filesystem"
@@ -38,11 +38,6 @@ export function cachePath(): string {
3838
return path.join(Global.Path.home, ".altimate", "telemetry-identity.json")
3939
}
4040

41-
/** True when a credential is in use (file or auth store), whatever its validity. */
42-
export async function hasCredential(): Promise<boolean> {
43-
return (await loadCredential()) !== undefined
44-
}
45-
4641
/** The credential the Altimate provider would use, or undefined when signed out. */
4742
export async function loadCredential(): Promise<Credential | undefined> {
4843
try {
@@ -69,7 +64,8 @@ export async function loadCredential(): Promise<Credential | undefined> {
6964
/**
7065
* A cheap stamp of the two credential files (mtime and size), so a flush can notice that a
7166
* sign-in, sign-out or key change happened on disk, in this thread or another, without
72-
* reading or parsing anything.
67+
* reading or parsing anything. Synchronous on purpose: two `stat` calls on small local files,
68+
* once per flush (every 5 s at most), cost less than the async round trips would.
7369
*/
7470
export function credentialStamp(): string {
7571
const stamp = (p: string) => {
@@ -83,6 +79,9 @@ export function credentialStamp(): string {
8379
return `${stamp(AltimateApi.credentialsPath())}|${stamp(Auth.filepath())}`
8480
}
8581

82+
/** A cache key, not a secret: 64 bits of SHA-256 over a high-entropy API key leave no realistic
83+
* collision between the credentials one machine sees, and the cache holds nothing the key's
84+
* owner could not already read. */
8685
function fingerprint(c: Credential): string {
8786
return createHash("sha256")
8887
.update(`${c.altimateUrl}\n${c.altimateInstanceName}\n${c.altimateApiKey}`)
@@ -124,36 +123,53 @@ export async function cached(): Promise<Identity | undefined> {
124123
* keeps it. The answer is written and returned only if the same credential is still in use.
125124
*/
126125
export async function resolve(opts: { refresh?: boolean } = {}): Promise<Identity | undefined> {
126+
return (await resolveWithOutcome(opts)).identity
127+
}
128+
129+
/**
130+
* How a resolution ended: `ok` with an identity; `none` when no credential is stored (or it
131+
* changed during the request); `rejected` when the backend refused the credential (401/403),
132+
* which only a new credential can change; `error` for a transient failure worth retrying.
133+
*/
134+
export type Outcome = "ok" | "none" | "rejected" | "error"
135+
136+
/** {@link resolve}, also saying how it ended, so a caller retries only a transient failure. */
137+
export async function resolveWithOutcome(
138+
opts: { refresh?: boolean } = {},
139+
): Promise<{ identity?: Identity; outcome: Outcome }> {
127140
try {
128141
const creds = await loadCredential()
129142
if (!creds) {
130143
await clear()
131-
return undefined
144+
return { outcome: "none" }
132145
}
133146
const fp = fingerprint(creds)
134147
if (!opts.refresh) {
135148
const hit = await readCache()
136-
if (hit && hit.fingerprint === fp) return { user_id: hit.user_id, tenant: hit.tenant }
149+
if (hit && hit.fingerprint === fp)
150+
return { identity: { user_id: hit.user_id, tenant: hit.tenant }, outcome: "ok" }
137151
}
138152
const answer = await fetchMe(creds)
139153
if (answer.kind === "rejected") {
140154
const hit = await readCache()
141155
if (hit && hit.fingerprint === fp) await clear()
142-
return undefined
156+
return { outcome: "rejected" }
143157
}
144-
if (answer.kind !== "ok") return undefined
158+
if (answer.kind !== "ok") return { outcome: "error" }
145159
const now = await loadCredential()
146-
if (!now || fingerprint(now) !== fp) return undefined
147-
const identity: Identity = { user_id: answer.uuid, tenant: creds.altimateInstanceName }
160+
if (!now || fingerprint(now) !== fp) return { outcome: "none" }
161+
const identity: Identity = { user_id: answer.uuid, tenant: now.altimateInstanceName }
148162
try {
163+
// The directory holds the machine id and this cache: owner-only when this creates it.
164+
await fsp.mkdir(path.dirname(cachePath()), { recursive: true, mode: 0o700 })
149165
await Filesystem.writeJson(cachePath(), { ...identity, fingerprint: fp } satisfies Cached, 0o600)
150166
} catch (err) {
151167
log.warn("telemetry identity cache not written", { err: String(err) })
152168
}
153-
return identity
169+
return { identity, outcome: "ok" }
154170
} catch (err) {
155171
log.warn("telemetry identity unresolved", { err: String(err) })
156-
return undefined
172+
return { outcome: "error" }
157173
}
158174
}
159175

‎packages/opencode/src/altimate/telemetry/index.ts‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2206,14 +2206,13 @@ export namespace Telemetry {
22062206
const generation = ++identityGeneration
22072207
identityStamp = TelemetryIdentity.credentialStamp()
22082208
identityRetryAt = 0
2209-
return TelemetryIdentity.resolve(opts)
2210-
.then(async (resolved) => {
2209+
return TelemetryIdentity.resolveWithOutcome(opts)
2210+
.then(({ identity: resolved, outcome }) => {
22112211
if (generation !== identityGeneration) return
22122212
identity = resolved
2213-
if (resolved === undefined && (await TelemetryIdentity.hasCredential())) {
2214-
// Signed in but unresolved: a transient failure. Retry at a later flush.
2215-
if (generation === identityGeneration) identityRetryAt = Date.now() + IDENTITY_RETRY_MS
2216-
}
2213+
// Only a transient failure is retried, at a later flush. A rejected credential (401/403)
2214+
// stays rejected until it changes, which the stamp comparison notices without polling.
2215+
if (outcome === "error") identityRetryAt = Date.now() + IDENTITY_RETRY_MS
22172216
})
22182217
.catch(() => {})
22192218
}
@@ -2243,10 +2242,11 @@ export namespace Telemetry {
22432242

22442243
// altimate_change start — the final event of an opted-out machine. Sent once, only from a
22452244
// machine that has sent telemetry before (a machine id exists; none is minted here), under the
2246-
// same sink rules as doInit(), with the identity cached by an earlier signed-in run (no request
2247-
// to resolve it). The marker is written only once the ingest endpoint accepted the event, so an
2248-
// offline launch tries again next time; after the marker, nothing is sent until telemetry is
2249-
// re-enabled. Not awaited: an opted-out launch must not wait on the network.
2245+
// same sink rules as doInit(). It carries the machine id and the opt-out source, never the account,
2246+
// project or launch. One send at a time across threads and processes (OptOutMarker.claim). The
2247+
// marker is written only once the ingest endpoint accepted the event, so an offline launch tries
2248+
// again next time; after the marker, nothing is sent until telemetry is re-enabled. Not awaited:
2249+
// an opted-out launch must not wait on the network.
22502250
const OPT_OUT_TIMEOUT_MS = 3_000
22512251
let optOutUnderTestRunner = false
22522252
/** Test seam: let a suite that redirects the home directory exercise recordOptOut(). */
@@ -2270,14 +2270,21 @@ export namespace Telemetry {
22702270
const envelopes = toAppInsightsEnvelopes(
22712271
[{ type: "telemetry_opted_out", timestamp: Date.now(), opt_out_source: source }],
22722272
cfg,
2273-
{ machineId: id, identity: await TelemetryIdentity.cached() },
2274-
)
2273+
{ machineId: id, identity: undefined },
2274+
) as Array<{ data: { baseData: { properties: Record<string, string> } } }>
2275+
for (const envelope of envelopes) {
2276+
delete envelope.data.baseData.properties.project_id
2277+
delete envelope.data.baseData.properties.launch_id
2278+
}
22752279
// A shutdown since this task started means a later init may own the marker now: do not
22762280
// send, and let the next disabled init start over.
22772281
if (lifecycle !== lifecycleGeneration) return
2282+
if (!OptOutMarker.claim()) return
22782283
const controller = new AbortController()
22792284
const timeout = setTimeout(() => controller.abort(), OPT_OUT_TIMEOUT_MS)
22802285
try {
2286+
// Another send may have finished between the marker check above and the claim.
2287+
if (OptOutMarker.exists()) return
22812288
const res = await fetch(cfg.endpoint, {
22822289
method: "POST",
22832290
headers: { "Content-Type": "application/json" },
@@ -2288,6 +2295,7 @@ export namespace Telemetry {
22882295
if (res.ok && marker === markerGeneration) OptOutMarker.write()
22892296
} finally {
22902297
clearTimeout(timeout)
2298+
OptOutMarker.release()
22912299
}
22922300
} catch {
22932301
// The opt-out path never surfaces: a missed marker only means one more attempt next launch.

‎packages/opencode/src/altimate/telemetry/opt-out.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,53 @@ export function exists(): boolean {
3535
}
3636

3737
export function write(): void {
38-
fs.mkdirSync(dir(), { recursive: true })
38+
fs.mkdirSync(dir(), { recursive: true, mode: 0o700 })
3939
// Exclusive create: never follow a planted symlink; an existing entry fails the write.
4040
fs.writeFileSync(markerPath(), `${new Date().toISOString()}\n`, { mode: 0o600, flag: "wx" })
4141
}
4242

43+
/** A send older than this is a process that died mid-send; its claim no longer holds. The send
44+
* itself is capped at 3 s. */
45+
const CLAIM_STALE_MS = 30_000
46+
47+
function claimPath(): string {
48+
return path.join(dir(), "telemetry-opted-out.sending")
49+
}
50+
51+
/**
52+
* Claim the one opt-out send, across threads and processes: an exclusive create of an in-flight
53+
* file next to the marker. The TUI's main thread and its worker both init telemetry, so without
54+
* this the first opted-out launch sent the event twice. False when another send holds a fresh
55+
* claim (or the file cannot be created); a claim left by a process that died is taken over.
56+
*/
57+
export function claim(): boolean {
58+
const create = () => fs.writeFileSync(claimPath(), `${process.pid}\n`, { mode: 0o600, flag: "wx" })
59+
try {
60+
create()
61+
return true
62+
} catch (err) {
63+
if ((err as NodeJS.ErrnoException)?.code !== "EEXIST") return false
64+
}
65+
try {
66+
const age = Date.now() - fs.lstatSync(claimPath()).mtimeMs
67+
if (age < CLAIM_STALE_MS) return false
68+
fs.rmSync(claimPath(), { force: true })
69+
create()
70+
return true
71+
} catch {
72+
return false
73+
}
74+
}
75+
76+
/** Give the claim back: after the marker is written, or when the send failed so a later launch tries. */
77+
export function release(): void {
78+
try {
79+
fs.rmSync(claimPath(), { force: true })
80+
} catch {
81+
// a leftover claim goes stale and is taken over
82+
}
83+
}
84+
4385
/** Best effort: an unremovable marker (read-only directory) must never fail an init. */
4486
export function clear(): void {
4587
try {

‎packages/opencode/src/plugin/tui/altimate/provider-credentials.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import type { TuiPlugin, TuiPluginApi } from "@opencode-ai/plugin/tui"
1515
import type { BuiltinTuiPlugin } from "@opencode-ai/tui/builtins"
1616
import { createSignal, Show } from "solid-js"
1717
import { AltimateApi } from "@/altimate/api/client"
18+
import { Telemetry } from "@/altimate/telemetry"
1819

1920
const id = "altimate:provider-credentials"
2021

@@ -87,6 +88,8 @@ function show(api: TuiPluginApi) {
8788
async function logout(api: TuiPluginApi) {
8889
try {
8990
await AltimateApi.clearCredentials()
91+
// Rows from here on carry no account; the batch already buffered keeps the one it was tracked under.
92+
void Telemetry.refreshIdentity().catch(() => {})
9093
await api.client.instance.dispose()
9194
api.ui.toast({ variant: "success", message: "Signed out of Altimate LLM Gateway" })
9295
} catch (err) {

‎packages/opencode/test/altimate/telemetry/identity.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,30 @@ describe("telemetry identity", () => {
284284
expect(Telemetry.identityForTest()).toBeUndefined()
285285
})
286286

287+
test("a rejected key is not polled; only a new credential is looked up again", async () => {
288+
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING =
289+
"InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/"
290+
writeCreds("key-revoked")
291+
meStatus = 401
292+
await Telemetry.shutdown()
293+
await Telemetry.init()
294+
expect(await until(() => meCalls().length === 1)).toBe(true)
295+
await new Promise((r) => setTimeout(r, 50)) // let the rejection settle
296+
for (let i = 0; i < 3; i++) {
297+
Telemetry.retryIdentityNowForTest() // a pending backoff would end here; there is none
298+
await Telemetry.flush()
299+
}
300+
await new Promise((r) => setTimeout(r, 50))
301+
expect(meCalls()).toHaveLength(1)
302+
303+
meStatus = 200
304+
await new Promise((r) => setTimeout(r, 15))
305+
writeCreds("key-new-and-longer")
306+
await Telemetry.flush()
307+
expect(await until(() => Telemetry.identityForTest()?.user_id !== undefined)).toBe(true)
308+
expect(meCalls()).toHaveLength(2)
309+
})
310+
287311
test("a transient failure at startup is retried at a later flush, not on every flush", async () => {
288312
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING =
289313
"InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://ingest.example.invalid/"

0 commit comments

Comments
 (0)