fix(connect): refresh authorization without disconnecting (#9582)
Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
1 parent
57832803ee
commit
39abb9d1d6
2 files changed
+414
-62
No files matched your search
@@ -1097,9 +1097,85 @@ describe("EnvironmentSupervisor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("renews a relay connection before its DPoP access token expires", () =>
|
||||
it.effect("hands off relay authorization after the replacement session is ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const tokenLifetimeMs = DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS * 2;
|
||||
const replacementStarted = yield* Deferred.make<void>();
|
||||
const releaseReplacement = yield* Deferred.make<void>();
|
||||
const harness = yield* makeHarness({
|
||||
prepare: (attempt) =>
|
||||
attempt === 2
|
||||
? Effect.fail(transient("Authorization refresh failed."))
|
||||
: Effect.succeed({
|
||||
...PREPARED_CONNECTION,
|
||||
target: RELAY_TARGET,
|
||||
httpAuthorization: {
|
||||
_tag: "Dpop",
|
||||
accessToken: `access-token-${attempt}`,
|
||||
expiresAtEpochMs: tokenLifetimeMs * attempt,
|
||||
},
|
||||
}),
|
||||
ready: (attempt) =>
|
||||
attempt === 2
|
||||
? Deferred.succeed(replacementStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseReplacement)),
|
||||
)
|
||||
: Effect.void,
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
const firstSession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
|
||||
const firstPrepared = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared));
|
||||
yield* TestClock.adjust(DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - 1);
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
|
||||
|
||||
yield* TestClock.adjust(1);
|
||||
expect(yield* Ref.get(harness.prepareCount)).toBe(2);
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(0);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* TestClock.adjust("2999 millis");
|
||||
expect(yield* Ref.get(harness.prepareCount)).toBe(2);
|
||||
yield* TestClock.adjust("1 milli");
|
||||
yield* Deferred.await(replacementStarted);
|
||||
|
||||
expect(yield* Ref.get(harness.prepareCount)).toBe(3);
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(2);
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(0);
|
||||
expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
|
||||
phase: "connected",
|
||||
generation: 1,
|
||||
});
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(firstSession);
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared))).toBe(
|
||||
firstPrepared,
|
||||
);
|
||||
|
||||
yield* Deferred.succeed(releaseReplacement, undefined);
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 2,
|
||||
);
|
||||
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(1);
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).not.toBe(
|
||||
firstSession,
|
||||
);
|
||||
expect(
|
||||
Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).httpAuthorization,
|
||||
).toMatchObject({ accessToken: "access-token-3" });
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("cleans up timed-out replacements and an interrupted retry", () =>
|
||||
Effect.gen(function* () {
|
||||
const tokenLifetimeMs = DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS * 2;
|
||||
const replacementStarted = yield* Deferred.make<void>();
|
||||
const retryStarted = yield* Deferred.make<void>();
|
||||
const harness = yield* makeHarness({
|
||||
prepare: (attempt) =>
|
||||
Effect.succeed({
|
||||
@@ -1111,26 +1187,93 @@ describe("EnvironmentSupervisor", () => {
|
||||
expiresAtEpochMs: tokenLifetimeMs * attempt,
|
||||
},
|
||||
}),
|
||||
ready: (attempt) => {
|
||||
if (attempt === 2) {
|
||||
return Deferred.succeed(replacementStarted, undefined).pipe(
|
||||
Effect.andThen(Effect.never),
|
||||
);
|
||||
}
|
||||
if (attempt === 3) {
|
||||
return Deferred.succeed(retryStarted, undefined).pipe(Effect.andThen(Effect.never));
|
||||
}
|
||||
return Effect.void;
|
||||
},
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
yield* TestClock.adjust(DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - 1);
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
|
||||
const firstSession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
|
||||
yield* TestClock.adjust(DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS);
|
||||
yield* Deferred.await(replacementStarted);
|
||||
|
||||
yield* TestClock.adjust(1);
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 2,
|
||||
);
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(firstSession);
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(0);
|
||||
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(2);
|
||||
yield* TestClock.adjust("15 seconds");
|
||||
yield* Effect.yieldNow;
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(1);
|
||||
expect(
|
||||
Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).httpAuthorization,
|
||||
).toMatchObject({ accessToken: "access-token-2" });
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(firstSession);
|
||||
expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
|
||||
phase: "connected",
|
||||
generation: 1,
|
||||
});
|
||||
|
||||
yield* TestClock.adjust("3 seconds");
|
||||
yield* Deferred.await(retryStarted);
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(3);
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(1);
|
||||
expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session))).toBe(firstSession);
|
||||
|
||||
yield* supervisor.disconnect;
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "available");
|
||||
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(3);
|
||||
expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
|
||||
expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("does not keep a relay session past its authorization expiry", () =>
|
||||
Effect.gen(function* () {
|
||||
const tokenLifetimeMs = DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS * 2;
|
||||
const harness = yield* makeHarness({
|
||||
prepare: (attempt) =>
|
||||
attempt === 1
|
||||
? Effect.succeed({
|
||||
...PREPARED_CONNECTION,
|
||||
target: RELAY_TARGET,
|
||||
httpAuthorization: {
|
||||
_tag: "Dpop",
|
||||
accessToken: "access-token-1",
|
||||
expiresAtEpochMs: tokenLifetimeMs,
|
||||
},
|
||||
})
|
||||
: Effect.fail(transient("Authorization refresh failed.")),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
yield* TestClock.adjust(DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS);
|
||||
yield* Effect.yieldNow;
|
||||
for (const delay of [3_000, 4_000, 8_000, 16_000, 16_000, 13_000]) {
|
||||
yield* TestClock.adjust(delay);
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
|
||||
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(1);
|
||||
expect(yield* SubscriptionRef.get(supervisor.state)).toMatchObject({
|
||||
phase: "backoff",
|
||||
generation: 1,
|
||||
});
|
||||
expect(Option.isNone(yield* SubscriptionRef.get(supervisor.session))).toBe(true);
|
||||
expect(Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))).toBe(true);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
|
||||
@@ -60,16 +60,24 @@ interface TracedAttemptFailure {
|
||||
readonly attemptSpan: Option.Option<Tracer.Span>;
|
||||
}
|
||||
|
||||
interface ScopedConnection {
|
||||
readonly attemptSpan: Option.Option<Tracer.Span>;
|
||||
readonly lease: ConnectionDriver.EnvironmentConnectionLease;
|
||||
readonly scope: Scope.Closeable;
|
||||
}
|
||||
|
||||
type AttemptOutcome =
|
||||
| {
|
||||
readonly _tag: "Interrupted";
|
||||
readonly established: boolean;
|
||||
readonly generation: number;
|
||||
readonly stable: boolean;
|
||||
readonly resetRetry: boolean;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "Failure";
|
||||
readonly established: boolean;
|
||||
readonly generation: number;
|
||||
readonly stable: boolean;
|
||||
readonly failure: TracedAttemptFailure;
|
||||
};
|
||||
@@ -77,17 +85,26 @@ type AttemptOutcome =
|
||||
type EstablishmentEvent =
|
||||
| {
|
||||
readonly _tag: "Completed";
|
||||
readonly exit: Exit.Exit<
|
||||
{
|
||||
readonly attemptSpan: Option.Option<Tracer.Span>;
|
||||
readonly lease: ConnectionDriver.EnvironmentConnectionLease;
|
||||
},
|
||||
TracedAttemptFailure
|
||||
>;
|
||||
readonly exit: Exit.Exit<ScopedConnection, TracedAttemptFailure>;
|
||||
}
|
||||
| { readonly _tag: "Interrupted"; readonly resetRetry: boolean }
|
||||
| { readonly _tag: "TimedOut" };
|
||||
|
||||
type ReplacementPreparationEvent =
|
||||
| { readonly _tag: "Completed"; readonly exit: Exit.Exit<ScopedConnection, TracedAttemptFailure> }
|
||||
| { readonly _tag: "TimedOut" }
|
||||
| { readonly _tag: "AuthorizationExpired" };
|
||||
|
||||
type ConnectedLeaseEvent =
|
||||
| {
|
||||
readonly _tag: "ActiveCompleted";
|
||||
readonly exit: Exit.Exit<boolean, TracedAttemptFailure>;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ReplacementCompleted";
|
||||
readonly exit: Exit.Exit<Option.Option<ScopedConnection>, TracedAttemptFailure>;
|
||||
};
|
||||
|
||||
function exitUnlessInterrupted<A, E, R>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<Exit.Exit<A, E>, never, R> {
|
||||
@@ -168,16 +185,18 @@ function failureFromExit<A>(
|
||||
target: ConnectionTarget,
|
||||
exit: Exit.Exit<A, TracedAttemptFailure>,
|
||||
established: boolean,
|
||||
generation: number,
|
||||
stable: boolean,
|
||||
): AttemptOutcome {
|
||||
if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
|
||||
return { _tag: "Interrupted", established, stable, resetRetry: false };
|
||||
return { _tag: "Interrupted", established, generation, stable, resetRetry: false };
|
||||
}
|
||||
const typedFailure = exit.cause.reasons.find(Cause.isFailReason);
|
||||
if (typedFailure) {
|
||||
return {
|
||||
_tag: "Failure",
|
||||
established,
|
||||
generation,
|
||||
stable,
|
||||
failure: typedFailure.error,
|
||||
};
|
||||
@@ -185,6 +204,7 @@ function failureFromExit<A>(
|
||||
return {
|
||||
_tag: "Failure",
|
||||
established,
|
||||
generation,
|
||||
stable,
|
||||
failure: {
|
||||
error: new ConnectionTransientError({
|
||||
@@ -289,9 +309,10 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
attempt: number,
|
||||
generation: number,
|
||||
lastFailure: ConnectionAttemptError | null,
|
||||
publishProgress: boolean,
|
||||
) {
|
||||
return yield* driver.connect(entry, (progress) =>
|
||||
reportProgress(attempt, generation, lastFailure, progress),
|
||||
publishProgress ? reportProgress(attempt, generation, lastFailure, progress) : Effect.void,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -342,16 +363,17 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
generation: number,
|
||||
lastFailure: ConnectionAttemptError | null,
|
||||
pendingRetry: Option.Option<PendingRetryTrace>,
|
||||
publishProgress: boolean,
|
||||
) {
|
||||
if (target._tag === "RelayConnectionTarget") {
|
||||
return yield* traceRelayEstablishment(
|
||||
establishConnection(attempt, generation, lastFailure),
|
||||
establishConnection(attempt, generation, lastFailure, publishProgress),
|
||||
attempt,
|
||||
generation,
|
||||
pendingRetry,
|
||||
);
|
||||
}
|
||||
return yield* establishConnection(attempt, generation, lastFailure).pipe(
|
||||
return yield* establishConnection(attempt, generation, lastFailure, publishProgress).pipe(
|
||||
Effect.map((lease) => ({
|
||||
attemptSpan: Option.none<Tracer.Span>(),
|
||||
lease,
|
||||
@@ -363,6 +385,37 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
const forkScopedTracedConnection = Effect.fnUntraced(function* (
|
||||
attempt: number,
|
||||
generation: number,
|
||||
lastFailure: ConnectionAttemptError | null,
|
||||
pendingRetry: Option.Option<PendingRetryTrace>,
|
||||
publishProgress: boolean,
|
||||
) {
|
||||
const parentScope = yield* Scope.Scope;
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
const connectionScope = yield* Scope.fork(parentScope, "sequential");
|
||||
const fiber = yield* restore(
|
||||
establishTracedConnection(
|
||||
attempt,
|
||||
generation,
|
||||
lastFailure,
|
||||
pendingRetry,
|
||||
publishProgress,
|
||||
).pipe(
|
||||
Scope.provide(connectionScope),
|
||||
Effect.map(
|
||||
(established) =>
|
||||
({ ...established, scope: connectionScope }) satisfies ScopedConnection,
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
return { fiber, scope: connectionScope };
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
|
||||
for (;;) {
|
||||
const next = yield* Queue.take(signals);
|
||||
@@ -484,32 +537,136 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
}
|
||||
});
|
||||
|
||||
const waitForAuthorizationRefresh = Effect.fnUntraced(function* (
|
||||
const waitForAuthorizationDeadline = Effect.fnUntraced(function* (
|
||||
preparedConnection: PreparedConnection,
|
||||
skewMs: number,
|
||||
) {
|
||||
const authorization = preparedConnection.httpAuthorization;
|
||||
if (authorization?._tag !== "Dpop") {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
yield* Effect.sleep(
|
||||
Math.max(0, authorization.expiresAtEpochMs - now - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS),
|
||||
yield* Effect.sleep(Math.max(0, authorization.expiresAtEpochMs - now - skewMs));
|
||||
});
|
||||
|
||||
const waitForActiveCompletion = Effect.fnUntraced(function* (active: ScopedConnection) {
|
||||
const exit = yield* exitUnlessInterrupted(
|
||||
Effect.raceAllFirst([
|
||||
active.lease.session.closed.pipe(
|
||||
Effect.mapError((error): TracedAttemptFailure => ({
|
||||
error,
|
||||
attemptSpan: active.attemptSpan,
|
||||
})),
|
||||
),
|
||||
monitorConnectedLease(active.lease).pipe(
|
||||
Effect.mapError((error): TracedAttemptFailure => ({
|
||||
error,
|
||||
attemptSpan: active.attemptSpan,
|
||||
})),
|
||||
),
|
||||
]),
|
||||
);
|
||||
yield* Effect.logDebug("Refreshing the environment connection before its DPoP token expires.");
|
||||
return true;
|
||||
return { _tag: "ActiveCompleted", exit } satisfies ConnectedLeaseEvent;
|
||||
});
|
||||
|
||||
const prepareReplacement = Effect.fnUntraced(function* (
|
||||
active: ScopedConnection,
|
||||
generation: number,
|
||||
) {
|
||||
yield* waitForAuthorizationDeadline(active.lease.prepared, DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS);
|
||||
yield* Effect.logDebug(
|
||||
"Preparing a replacement environment connection before its DPoP token expires.",
|
||||
);
|
||||
|
||||
let failureCount = 0;
|
||||
for (;;) {
|
||||
const candidate = yield* forkScopedTracedConnection(
|
||||
failureCount + 1,
|
||||
generation,
|
||||
null,
|
||||
Option.none(),
|
||||
false,
|
||||
);
|
||||
const replacement = yield* Effect.raceAllFirst([
|
||||
Fiber.await(candidate.fiber).pipe(
|
||||
Effect.map((exit): ReplacementPreparationEvent => ({ _tag: "Completed", exit })),
|
||||
),
|
||||
waitForAuthorizationDeadline(active.lease.prepared, 0).pipe(
|
||||
Effect.as<ReplacementPreparationEvent>({ _tag: "AuthorizationExpired" }),
|
||||
),
|
||||
Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
|
||||
Effect.as<ReplacementPreparationEvent>({ _tag: "TimedOut" }),
|
||||
),
|
||||
]);
|
||||
|
||||
if (replacement._tag !== "Completed") {
|
||||
yield* Fiber.interrupt(candidate.fiber);
|
||||
yield* Fiber.await(candidate.fiber);
|
||||
yield* Scope.close(candidate.scope, Exit.void).pipe(Effect.ignore);
|
||||
} else if (Exit.isFailure(replacement.exit)) {
|
||||
yield* Scope.close(candidate.scope, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
if (replacement._tag === "AuthorizationExpired") {
|
||||
return Option.none<ScopedConnection>();
|
||||
}
|
||||
if (replacement._tag === "Completed" && Exit.isSuccess(replacement.exit)) {
|
||||
return Option.some(replacement.exit.value);
|
||||
}
|
||||
|
||||
let replacementError: ConnectionTransientError;
|
||||
if (replacement._tag === "Completed") {
|
||||
if (Exit.isSuccess(replacement.exit)) {
|
||||
return yield* Effect.die("A successful replacement was not installed.");
|
||||
}
|
||||
const failure = Cause.findErrorOption(replacement.exit.cause);
|
||||
if (Option.isNone(failure) || failure.value.error._tag === "ConnectionBlockedError") {
|
||||
return yield* Effect.failCause(replacement.exit.cause);
|
||||
}
|
||||
replacementError = failure.value.error;
|
||||
} else {
|
||||
replacementError = new ConnectionTransientError({
|
||||
reason: "timeout",
|
||||
detail: `${target.label} did not respond during connection setup.`,
|
||||
});
|
||||
}
|
||||
|
||||
const retryDelay = retryDelayMs(failureCount);
|
||||
failureCount += 1;
|
||||
yield* Effect.logWarning(
|
||||
"Could not prepare a replacement environment connection; keeping the active connection.",
|
||||
).pipe(
|
||||
Effect.annotateLogs({
|
||||
"authorization.refresh.retry_delay_ms": retryDelay,
|
||||
...safeErrorLogAttributes(replacementError),
|
||||
}),
|
||||
);
|
||||
const retryBeforeExpiry = yield* Effect.raceFirst(
|
||||
Effect.sleep(retryDelay).pipe(Effect.as(true)),
|
||||
waitForAuthorizationDeadline(active.lease.prepared, 0).pipe(Effect.as(false)),
|
||||
);
|
||||
if (!retryBeforeExpiry) {
|
||||
return Option.none<ScopedConnection>();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const runAttempt = Effect.fnUntraced(function* (
|
||||
attempt: number,
|
||||
generation: number,
|
||||
previousGeneration: number,
|
||||
lastFailure: ConnectionAttemptError | null,
|
||||
pendingRetry: Option.Option<PendingRetryTrace>,
|
||||
) {
|
||||
const initialGeneration = previousGeneration + 1;
|
||||
yield* SubscriptionRef.set(prepared, Option.none());
|
||||
const initial = yield* forkScopedTracedConnection(
|
||||
attempt,
|
||||
initialGeneration,
|
||||
lastFailure,
|
||||
pendingRetry,
|
||||
true,
|
||||
);
|
||||
const establishment = yield* Effect.raceAllFirst([
|
||||
exitUnlessInterrupted(
|
||||
establishTracedConnection(attempt, generation, lastFailure, pendingRetry),
|
||||
).pipe(
|
||||
Fiber.await(initial.fiber).pipe(
|
||||
Effect.map((exit): EstablishmentEvent => ({
|
||||
_tag: "Completed",
|
||||
exit,
|
||||
@@ -526,10 +683,18 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
),
|
||||
]);
|
||||
|
||||
if (establishment._tag !== "Completed") {
|
||||
yield* Fiber.interrupt(initial.fiber);
|
||||
yield* Fiber.await(initial.fiber);
|
||||
yield* Scope.close(initial.scope, Exit.void).pipe(Effect.ignore);
|
||||
} else if (Exit.isFailure(establishment.exit)) {
|
||||
yield* Scope.close(initial.scope, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
if (establishment._tag === "Interrupted") {
|
||||
return {
|
||||
_tag: "Interrupted",
|
||||
established: false,
|
||||
generation: previousGeneration,
|
||||
stable: false,
|
||||
resetRetry: establishment.resetRetry,
|
||||
} satisfies AttemptOutcome;
|
||||
@@ -538,6 +703,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
return {
|
||||
_tag: "Failure",
|
||||
established: false,
|
||||
generation: previousGeneration,
|
||||
stable: false,
|
||||
failure: {
|
||||
error: new ConnectionTransientError({
|
||||
@@ -552,7 +718,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
const isUnexpectedDefect =
|
||||
!Cause.hasInterruptsOnly(establishment.exit.cause) &&
|
||||
!establishment.exit.cause.reasons.some(Cause.isFailReason);
|
||||
const outcome = failureFromExit(target, establishment.exit, false, false);
|
||||
const outcome = failureFromExit(target, establishment.exit, false, previousGeneration, false);
|
||||
if (isUnexpectedDefect) {
|
||||
const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
|
||||
yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
|
||||
@@ -567,18 +733,20 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
return outcome;
|
||||
}
|
||||
|
||||
const active = establishment.exit.value;
|
||||
const currentIntent = yield* Ref.get(intent);
|
||||
if (!currentIntent.desired || currentIntent.network === "offline") {
|
||||
return {
|
||||
_tag: "Interrupted",
|
||||
established: false,
|
||||
generation: previousGeneration,
|
||||
stable: false,
|
||||
resetRetry: false,
|
||||
} satisfies AttemptOutcome;
|
||||
}
|
||||
|
||||
const connectedAt = yield* Clock.currentTimeMillis;
|
||||
let active = establishment.exit.value;
|
||||
let activeGeneration = initialGeneration;
|
||||
yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
|
||||
yield* SubscriptionRef.set(session, Option.some(active.lease.session));
|
||||
yield* setState({
|
||||
@@ -587,36 +755,78 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
phase: "connected",
|
||||
stage: null,
|
||||
attempt,
|
||||
generation,
|
||||
generation: activeGeneration,
|
||||
lastFailure: null,
|
||||
retryAt: null,
|
||||
});
|
||||
|
||||
const connectedExit = yield* Effect.raceAllFirst([
|
||||
active.lease.session.closed.pipe(
|
||||
Effect.mapError((error): TracedAttemptFailure => ({
|
||||
error,
|
||||
attemptSpan: active.attemptSpan,
|
||||
})),
|
||||
),
|
||||
monitorConnectedLease(active.lease).pipe(
|
||||
Effect.mapError((error): TracedAttemptFailure => ({
|
||||
error,
|
||||
attemptSpan: active.attemptSpan,
|
||||
})),
|
||||
),
|
||||
waitForAuthorizationRefresh(active.lease.prepared),
|
||||
]).pipe(exitUnlessInterrupted);
|
||||
const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
|
||||
if (Exit.isSuccess(connectedExit)) {
|
||||
return {
|
||||
_tag: "Interrupted",
|
||||
established: true,
|
||||
stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
|
||||
resetRetry: connectedExit.value,
|
||||
} satisfies AttemptOutcome;
|
||||
for (;;) {
|
||||
const connectedEvent = yield* Effect.raceAllFirst([
|
||||
waitForActiveCompletion(active),
|
||||
exitUnlessInterrupted(prepareReplacement(active, activeGeneration + 1)).pipe(
|
||||
Effect.map((exit): ConnectedLeaseEvent => ({ _tag: "ReplacementCompleted", exit })),
|
||||
),
|
||||
]);
|
||||
const stable = (yield* Clock.currentTimeMillis) - connectedAt >= BACKOFF_RESET_AFTER_MS;
|
||||
if (connectedEvent._tag === "ActiveCompleted") {
|
||||
if (Exit.isSuccess(connectedEvent.exit)) {
|
||||
return {
|
||||
_tag: "Interrupted",
|
||||
established: true,
|
||||
generation: activeGeneration,
|
||||
stable,
|
||||
resetRetry: connectedEvent.exit.value,
|
||||
} satisfies AttemptOutcome;
|
||||
}
|
||||
return failureFromExit(target, connectedEvent.exit, true, activeGeneration, stable);
|
||||
}
|
||||
if (Exit.isFailure(connectedEvent.exit)) {
|
||||
return failureFromExit(target, connectedEvent.exit, true, activeGeneration, stable);
|
||||
}
|
||||
if (Option.isNone(connectedEvent.exit.value)) {
|
||||
return {
|
||||
_tag: "Interrupted",
|
||||
established: true,
|
||||
generation: activeGeneration,
|
||||
stable,
|
||||
resetRetry: true,
|
||||
} satisfies AttemptOutcome;
|
||||
}
|
||||
|
||||
const candidate = connectedEvent.exit.value.value;
|
||||
const replacementIntent = yield* Ref.get(intent);
|
||||
if (!replacementIntent.desired || replacementIntent.network === "offline") {
|
||||
yield* Scope.close(candidate.scope, Exit.void).pipe(Effect.ignore);
|
||||
return {
|
||||
_tag: "Interrupted",
|
||||
established: true,
|
||||
generation: activeGeneration,
|
||||
stable,
|
||||
resetRetry: false,
|
||||
} satisfies AttemptOutcome;
|
||||
}
|
||||
|
||||
const previous = active;
|
||||
yield* Effect.uninterruptible(
|
||||
Effect.gen(function* () {
|
||||
active = candidate;
|
||||
activeGeneration += 1;
|
||||
yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
|
||||
yield* SubscriptionRef.set(session, Option.some(active.lease.session));
|
||||
yield* setState({
|
||||
desired: true,
|
||||
network: replacementIntent.network,
|
||||
phase: "connected",
|
||||
stage: null,
|
||||
attempt: 1,
|
||||
generation: activeGeneration,
|
||||
lastFailure: null,
|
||||
retryAt: null,
|
||||
});
|
||||
yield* Scope.close(previous.scope, Exit.void).pipe(Effect.ignore);
|
||||
}),
|
||||
);
|
||||
}
|
||||
return failureFromExit(target, connectedExit, true, connectedForMs >= BACKOFF_RESET_AFTER_MS);
|
||||
}, Effect.ensuring(clearLease));
|
||||
|
||||
const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
|
||||
@@ -681,15 +891,14 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
}
|
||||
|
||||
const attempt = failureCount + 1;
|
||||
const nextGeneration = generation + 1;
|
||||
const outcome: AttemptOutcome = yield* Effect.scoped(
|
||||
runAttempt(attempt, nextGeneration, latestFailure, pendingRetry),
|
||||
runAttempt(attempt, generation, latestFailure, pendingRetry),
|
||||
);
|
||||
// Consumed on every iteration so a stale marker can never leak into a
|
||||
// later, unrelated failure.
|
||||
const failedWakeProbe = yield* Ref.getAndSet(wakeProbeFailed, false);
|
||||
generation = outcome.generation;
|
||||
if (outcome.established) {
|
||||
generation = nextGeneration;
|
||||
if (outcome.stable) {
|
||||
resetRetryLadder();
|
||||
latestFailure = null;
|
||||
|
||||
Reference in new issue
Block a user