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 — fix(server): usage refresher skips healthy OpenCode like upstream; te… · scuttletoby/t3code@75045ac

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src/usage
    • HeadlessUsageRefresher.test.ts
    • HeadlessUsageRefresher.ts
  • packages/provider-core/src/server
    • managedProvider.test.ts
    • managedProvider.ts
    • snapshot.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/usage/HeadlessUsageRefresher.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/usage/HeadlessUsageRefresher.test.ts
+144-70Lines changed: 144 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { assert, describe, it } from "@effect/vitest";
22
import {
33
AuthSessionId,
4+
type BackgroundScope,
45
DEFAULT_SERVER_SETTINGS,
56
defaultInstanceIdForDriver,
67
type HostPowerSnapshot,
@@ -86,18 +87,22 @@ const fakeTarget = (
8687
initial: ServerProvider,
8788
options?: {
8889
readonly awaitingFirstCheck?: () => boolean;
90+
readonly checksOnInterval?: () => boolean;
8991
readonly enabled?: boolean;
9092
readonly noRefreshUsage?: boolean;
9193
},
9294
) => {
9395
let snapshot = initial;
9496
let calls = 0;
97+
let interrupts = 0;
9598
let outcome: Outcome = "ok";
9699
let gate: Deferred.Deferred<void> | undefined;
97100
const refreshUsage = Effect.gen(function* () {
98101
calls += 1;
99102
if (gate !== undefined) yield* Deferred.await(gate);
100-
if (outcome === "hang") return yield* Effect.never;
103+
if (outcome === "hang") {
104+
return yield* Effect.never.pipe(Effect.onInterrupt(() => Effect.sync(() => interrupts++)));
105+
}
101106
if (outcome === "error") {
102107
return yield* new ServerSettingsError({
103108
settingsPath: "settings.json",
@@ -131,12 +136,16 @@ const fakeTarget = (
131136
snapshot: {
132137
getSnapshot: Effect.sync(() => snapshot),
133138
isAwaitingFirstCheck: Effect.sync(() => options?.awaitingFirstCheck?.() ?? false),
139+
...(options?.checksOnInterval
140+
? { checksOnInterval: Effect.sync(options.checksOnInterval) }
141+
: {}),
134142
...(options?.noRefreshUsage ? {} : { refreshUsage }),
135143
},
136144
};
137145
return {
138146
target,
139147
calls: () => calls,
148+
interrupts: () => interrupts,
140149
setOutcome: (next: Outcome) => {
141150
outcome = next;
142151
},
@@ -328,6 +337,26 @@ describe("HeadlessUsageRefresher", () => {
328337
}),
329338
);
330339

340+
it.effect("skips an instance upstream's own loop skips, such as a healthy OpenCode", () =>
341+
Effect.gen(function* () {
342+
yield* startAt(NOW_MS);
343+
const old = NOW_MS - HOUR;
344+
const opencode = { driver: ProviderDriverKind.make("opencode") };
345+
let healthy = true;
346+
// A check of a healthy OpenCode instance starts an OpenCode server; upstream skips it.
347+
const skipped = fakeTarget(provider(old, opencode), { checksOnInterval: () => !healthy });
348+
const otherDriver = fakeTarget(provider(old, {}, SECOND));
349+
const { sweep } = yield* make(deps([skipped.target, otherDriver.target]));
350+
yield* sweep;
351+
assert.equal(skipped.calls(), 0);
352+
assert.equal(otherDriver.calls(), 1);
353+
// Unhealthy (for example its usage probe failed): upstream checks it, and so does this.
354+
healthy = false;
355+
yield* sweep;
356+
assert.equal(skipped.calls(), 1);
357+
}),
358+
);
359+
331360
it.effect(
332361
"leaves the refresh to upstream while a client lease holds, and pauses on a constrained host",
333362
() =>
@@ -438,6 +467,7 @@ describe("HeadlessUsageRefresher", () => {
438467
yield* TestClock.adjust(REFRESH_TIMEOUT_MS);
439468
yield* Fiber.join(fiber);
440469
assert.equal(fake.calls(), 1);
470+
assert.equal(fake.interrupts(), 1);
441471
assert.equal(log.warnings.length, 1);
442472
// The next pass is not stuck behind the hung one; it waits out the backoff.
443473
fake.setOutcome("ok");
@@ -529,69 +559,112 @@ describe("HeadlessUsageRefresher", () => {
529559
"the server layer refreshes through the Scheduler only while no client lease holds",
530560
() =>
531561
Effect.gen(function* () {
532-
yield* startAt(NOW_MS);
533-
const fake = fakeTarget(provider(NOW_MS - HOUR));
534-
const refreshed = yield* Queue.unbounded<void>();
535-
const target = fake.target;
536-
const instance = {
537-
...target,
538-
snapshot: {
539-
...target.snapshot,
540-
refreshUsage: target.snapshot.refreshUsage!.pipe(
541-
Effect.andThen(Queue.offer(refreshed, undefined)),
542-
),
543-
},
544-
} as unknown as ProviderInstance;
545-
const registry = Layer.succeed(
546-
ProviderInstanceRegistry.ProviderInstanceRegistry,
547-
ProviderInstanceRegistry.ProviderInstanceRegistry.of({
548-
getInstance: () => Effect.succeed(instance),
549-
listInstances: Effect.succeed([instance]),
550-
listUnavailable: Effect.succeed([]),
551-
streamChanges: Stream.empty,
552-
subscribeChanges: Effect.die("unused"),
553-
}),
554-
);
555-
const policyLayer = BackgroundPolicy.layer.pipe(
556-
Layer.provide(Layer.merge(hostPowerLayer, ServerSettingsModule.layerTest())),
557-
);
558-
yield* Effect.gen(function* () {
559-
const policy = yield* BackgroundPolicy.BackgroundPolicy;
560-
// A focused client watches provider status: upstream's loop refreshes, not this job.
561-
yield* policy.reportClientActivity(AuthSessionId.make("s"), RpcClientId.make(1), {
562-
clientId: "c",
563-
clientKind: "web",
564-
visible: true,
565-
focused: true,
566-
recentlyInteracted: true,
567-
scopes: [{ type: "provider-status" }],
568-
ttlMs: 60_000,
569-
observedAt: DateTime.makeUnsafe(NOW_MS),
570-
});
571-
yield* Effect.scoped(
572-
Layer.build(
573-
HeadlessUsageRefresher.layer.pipe(
574-
Layer.provide(Layer.mergeAll(registry, ServerSettingsModule.layerTest())),
575-
),
576-
).pipe(
577-
Effect.andThen(
578-
Effect.gen(function* () {
579-
yield* TestClock.adjust("10 seconds");
580-
assert.equal(fake.calls(), 0);
581-
// The client goes away: its lease expires and the job takes over.
582-
yield* policy.removeRpcClient(AuthSessionId.make("s"), RpcClientId.make(1));
583-
yield* TestClock.adjust("5 seconds");
584-
yield* Queue.take(refreshed);
585-
assert.equal(fake.calls(), 1);
586-
}),
587-
),
588-
),
562+
// A client may watch all providers or one instance; either way upstream's loop refreshes.
563+
const scopes: ReadonlyArray<BackgroundScope> = [
564+
{ type: "provider-status" },
565+
{ type: "provider-status", instanceId: INSTANCE },
566+
];
567+
for (const scope of scopes) {
568+
yield* withServerLayer(({ fake, policy, refreshed }) =>
569+
Effect.gen(function* () {
570+
// A focused client watches provider status: upstream's loop refreshes, not this job.
571+
yield* policy.reportClientActivity(AuthSessionId.make("s"), RpcClientId.make(1), {
572+
clientId: "c",
573+
clientKind: "web",
574+
visible: true,
575+
focused: true,
576+
recentlyInteracted: true,
577+
scopes: [scope],
578+
ttlMs: 60_000,
579+
observedAt: DateTime.makeUnsafe(NOW_MS),
580+
});
581+
yield* TestClock.adjust("10 seconds");
582+
assert.equal(fake.calls(), 0, JSON.stringify(scope));
583+
// The client goes away: its lease expires and the job takes over.
584+
yield* policy.removeRpcClient(AuthSessionId.make("s"), RpcClientId.make(1));
585+
yield* TestClock.adjust("5 seconds");
586+
yield* Queue.take(refreshed);
587+
assert.equal(fake.calls(), 1);
588+
}),
589589
);
590-
}).pipe(Effect.provide(policyLayer));
590+
}
591591
}),
592592
);
593+
594+
it.effect("the server layer pauses while the host is locked or in low power", () =>
595+
Effect.gen(function* () {
596+
const constrained: ReadonlyArray<Partial<HostPowerSnapshot>> = [
597+
// Default (balanced) settings pause on these; battery pauses only in battery-saver.
598+
{ locked: "true" },
599+
{ lowPowerMode: "true" },
600+
];
601+
for (const power of constrained) {
602+
let hostPower: HostPowerSnapshot = { ...nominalHostPower, stale: false, ...power };
603+
yield* withServerLayer(
604+
({ fake, refreshed }) =>
605+
Effect.gen(function* () {
606+
yield* TestClock.adjust("10 seconds");
607+
assert.equal(fake.calls(), 0, JSON.stringify(power));
608+
hostPower = { ...nominalHostPower, stale: false };
609+
yield* TestClock.adjust("5 seconds");
610+
yield* Queue.take(refreshed);
611+
assert.equal(fake.calls(), 1);
612+
}),
613+
Effect.sync(() => hostPower),
614+
);
615+
}
616+
}),
617+
);
593618
});
594619

620+
/** Runs `body` with the refresher's server layer over one stale signed-in instance. */
621+
const withServerLayer = <A, E>(
622+
body: (ctx: {
623+
readonly fake: ReturnType<typeof fakeTarget>;
624+
readonly policy: BackgroundPolicy.BackgroundPolicy["Service"];
625+
readonly refreshed: Queue.Queue<void>;
626+
}) => Effect.Effect<A, E>,
627+
hostPower: Effect.Effect<HostPowerSnapshot> = Effect.succeed(nominalHostPower),
628+
) =>
629+
Effect.gen(function* () {
630+
yield* startAt(NOW_MS);
631+
const fake = fakeTarget(provider(NOW_MS - HOUR));
632+
const refreshed = yield* Queue.unbounded<void>();
633+
const target = fake.target;
634+
const instance = {
635+
...target,
636+
snapshot: {
637+
...target.snapshot,
638+
refreshUsage: target.snapshot.refreshUsage!.pipe(
639+
Effect.andThen(Queue.offer(refreshed, undefined)),
640+
),
641+
},
642+
} as unknown as ProviderInstance;
643+
const registry = Layer.succeed(
644+
ProviderInstanceRegistry.ProviderInstanceRegistry,
645+
ProviderInstanceRegistry.ProviderInstanceRegistry.of({
646+
getInstance: () => Effect.succeed(instance),
647+
listInstances: Effect.succeed([instance]),
648+
listUnavailable: Effect.succeed([]),
649+
streamChanges: Stream.empty,
650+
subscribeChanges: Effect.die("unused"),
651+
}),
652+
);
653+
const policyLayer = BackgroundPolicy.layer.pipe(
654+
Layer.provide(Layer.merge(hostPowerLayer(hostPower), ServerSettingsModule.layerTest())),
655+
);
656+
return yield* Effect.gen(function* () {
657+
const policy = yield* BackgroundPolicy.BackgroundPolicy;
658+
return yield* Effect.scoped(
659+
Layer.build(
660+
HeadlessUsageRefresher.layer.pipe(
661+
Layer.provide(Layer.mergeAll(registry, ServerSettingsModule.layerTest())),
662+
),
663+
).pipe(Effect.andThen(body({ fake, policy, refreshed }))),
664+
);
665+
}).pipe(Effect.provide(policyLayer));
666+
});
667+
595668
const nominalHostPower: HostPowerSnapshot = {
596669
source: "unknown",
597670
idle: "unknown",
@@ -605,14 +678,15 @@ const nominalHostPower: HostPowerSnapshot = {
605678
updatedAt: DateTime.makeUnsafe(NOW_MS),
606679
};
607680

608-
const hostPowerLayer = Layer.effect(
609-
HostPowerMonitor.HostPowerMonitor,
610-
Effect.gen(function* () {
611-
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
612-
return HostPowerMonitor.HostPowerMonitor.of({
613-
snapshot: Effect.succeed(nominalHostPower),
614-
report: () => Effect.void,
615-
streamChanges: Stream.fromPubSub(changes),
616-
});
617-
}),
618-
);
681+
const hostPowerLayer = (snapshot: Effect.Effect<HostPowerSnapshot>) =>
682+
Layer.effect(
683+
HostPowerMonitor.HostPowerMonitor,
684+
Effect.gen(function* () {
685+
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
686+
return HostPowerMonitor.HostPowerMonitor.of({
687+
snapshot,
688+
report: () => Effect.void,
689+
streamChanges: Stream.fromPubSub(changes),
690+
});
691+
}),
692+
);
Collapse file

‎apps/server/src/usage/HeadlessUsageRefresher.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/usage/HeadlessUsageRefresher.ts
+6-1Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ export interface RefreshTarget {
3838
readonly enabled: boolean;
3939
readonly snapshot: Pick<
4040
ManagedServerProvider,
41-
"getSnapshot" | "isAwaitingFirstCheck" | "refreshUsage"
41+
"getSnapshot" | "isAwaitingFirstCheck" | "checksOnInterval" | "refreshUsage"
4242
>;
4343
}
4444

@@ -172,6 +172,11 @@ export const make = Effect.fn("HeadlessUsageRefresher.make")(function* (deps: Re
172172
if (target.snapshot.isAwaitingFirstCheck && (yield* target.snapshot.isAwaitingFirstCheck)) {
173173
continue;
174174
}
175+
// Upstream's loop skips some healthy instances: a check of a healthy OpenCode one
176+
// starts an OpenCode server. Skip them too.
177+
if (target.snapshot.checksOnInterval && !(yield* target.snapshot.checksOnInterval)) {
178+
continue;
179+
}
175180
const before = yield* target.snapshot.getSnapshot;
176181
if (!canRefresh(before)) continue;
177182
const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
Collapse file

‎packages/provider-core/src/server/managedProvider.test.ts‎

Copy file name to clipboardExpand all lines: packages/provider-core/src/server/managedProvider.test.ts
+40Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,46 @@ describe("makeManagedServerProvider", () => {
413413
).pipe(Effect.provide(Layer.mergeAll(layerAlwaysRunTest, TestClock.layer()))),
414414
);
415415

416+
it.effect("tells whether the interval loop would check the instance now", () =>
417+
Effect.scoped(
418+
Effect.gen(function* () {
419+
const probe = yield* Ref.make<ServerProvider>({ ...refreshedSnapshot, status: "error" });
420+
const provider = yield* makeManagedServerProvider<TestSettings>({
421+
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
422+
getSettings: Effect.succeed({ enabled: true }),
423+
streamSettings: Stream.empty,
424+
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
425+
// Like OpenCode: only an unhealthy instance is checked again on the interval.
426+
refreshOnInterval: (snapshot) => snapshot.status === "error",
427+
initialSnapshot: () => Effect.succeed(initialSnapshot),
428+
checkProvider: Ref.get(probe),
429+
checkUsageLimits: Effect.undefined,
430+
});
431+
yield* Stream.take(provider.streamChanges, 1).pipe(Stream.runDrain);
432+
const checks = provider.checksOnInterval!;
433+
assert.isTrue(yield* checks);
434+
// Healthy: the loop skips it.
435+
yield* Ref.set(probe, refreshedSnapshot);
436+
yield* provider.refresh;
437+
assert.isFalse(yield* checks);
438+
// Healthy but its usage probe failed: the loop recovers the usage.
439+
yield* Ref.set(probe, {
440+
...refreshedSnapshot,
441+
usageLimits: {
442+
checkedAt: refreshedSnapshot.checkedAt,
443+
windows: [],
444+
unavailable: { reason: "probeFailed" },
445+
},
446+
});
447+
yield* provider.refresh;
448+
assert.isTrue(yield* checks);
449+
yield* Ref.set(probe, { ...refreshedSnapshot, status: "error" as const, enabled: false });
450+
yield* provider.refresh;
451+
assert.isFalse(yield* checks);
452+
}),
453+
).pipe(Effect.provide(layerAlwaysRunTest)),
454+
);
455+
416456
it.effect("rechecks a ready provider after one failed periodic check before publishing it", () =>
417457
Effect.scoped(
418458
Effect.gen(function* () {
Collapse file

‎packages/provider-core/src/server/managedProvider.ts‎

Copy file name to clipboardExpand all lines: packages/provider-core/src/server/managedProvider.ts
+11-10Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -357,17 +357,15 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
357357
yield* PubSub.publish(changesPubSub, next);
358358
});
359359

360+
// A disabled instance has nothing to probe; a periodic check would only
361+
// republish a snapshot that differs in checkedAt.
362+
const checksSnapshotOnInterval = (snapshot: ServerProvider) =>
363+
snapshot.enabled && (needsUsageRecovery(snapshot) || needsProviderRefresh(snapshot));
364+
360365
const shouldRefreshOnInterval = Effect.gen(function* () {
361-
const state = yield* Ref.get(snapshotStateRef);
362-
// A disabled instance has nothing to probe; a periodic check would only
363-
// republish a snapshot that differs in checkedAt.
364-
if (
365-
!state.snapshot.enabled ||
366-
(!needsUsageRecovery(state.snapshot) && !needsProviderRefresh(state.snapshot))
367-
) {
368-
return false;
369-
}
370-
const instanceId = state.snapshot.instanceId;
366+
const { snapshot } = yield* Ref.get(snapshotStateRef);
367+
if (!checksSnapshotOnInterval(snapshot)) return false;
368+
const instanceId = snapshot.instanceId;
371369
const [genericDemand, instanceDemand] = yield* Effect.all([
372370
host.shouldRunBackgroundWork({ type: "provider-status" }),
373371
host.shouldRunBackgroundWork({ type: "provider-status", instanceId }),
@@ -455,6 +453,9 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
455453
resolveMaintenance: input.resolveMaintenance,
456454
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
457455
isAwaitingFirstCheck: Ref.get(snapshotStateRef).pipe(Effect.map((state) => !state.checked)),
456+
checksOnInterval: Ref.get(snapshotStateRef).pipe(
457+
Effect.map((state) => checksSnapshotOnInterval(state.snapshot)),
458+
),
458459
refresh: input
459460
.resolveMaintenance({ fresh: true })
460461
.pipe(Effect.andThen(refreshSnapshot), Effect.tapError(Effect.logError), Effect.orDie),
Collapse file

‎packages/provider-core/src/server/snapshot.ts‎

Copy file name to clipboardExpand all lines: packages/provider-core/src/server/snapshot.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ export interface ManagedServerProvider {
2323
readonly getSnapshot: Effect.Effect<ServerProvider>;
2424
/** True while getSnapshot still returns the placeholder from before the first completed check. */
2525
readonly isAwaitingFirstCheck?: Effect.Effect<boolean>;
26+
/** False while the interval loop skips this instance, such as a healthy OpenCode one. */
27+
readonly checksOnInterval?: Effect.Effect<boolean>;
2628
readonly refresh: Effect.Effect<ServerProvider>;
2729
readonly refreshUsage?: Effect.Effect<void, ServerSettingsError>;
2830
readonly streamChanges: Stream.Stream<ServerProvider>;

0 commit comments

Comments
0 (0)
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.