Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,64 @@ describe("makeRelayDeviceRegistrationRequest", () => {
);
});

it.effect("registers the device again when the relay no longer has it", () => {
const calls: Array<string> = [];
let rejectLiveActivity = true;
vi.stubGlobal("fetch", (request: RequestInfo | URL) => {
const url = request instanceof Request ? request.url : String(request);
if (url.endsWith("/v1/client/dpop-token")) {
return Promise.resolve(
Response.json({
access_token: "relay-dpop-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "DPoP",
expires_in: 300,
scope: "mobile:registration",
}),
);
}
const path = new URL(url).pathname;
if (path === "/v1/mobile/devices" || path === "/v1/mobile/live-activities") calls.push(path);
if (url.endsWith("/v1/mobile/live-activities") && rejectLiveActivity) {
rejectLiveActivity = false;
return Promise.resolve(
Response.json(
{
_tag: "RelayMobileDeviceNotRegisteredError",
code: "mobile_device_not_registered",
traceId: "trace-1",
},
{ status: 404 },
),
);
}
return Promise.resolve(Response.json({ ok: true }));
});
Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
const activity = {
getId: () => "activity-1",
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
};

return Effect.gen(function* () {
yield* runBackgroundOperations();
expect(registrationRecordStore.current).not.toBeNull();

expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(true);
expect(calls).toEqual([
"/v1/mobile/devices",
"/v1/mobile/live-activities",
"/v1/mobile/devices",
"/v1/mobile/live-activities",
]);
}).pipe(
Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
Effect.provide(layerRelayTest),
);
});

it.effect("registers a rotated Live Activity token only after an older registration", () => {
const arrivals: Array<string> = [];
let openOldRequest: (() => void) | undefined;
Expand Down
30 changes: 29 additions & 1 deletion apps/mobile/src/features/agent-awareness/remoteRegistration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
type RelayDeviceRegistrationRequest,
type RelayAgentActivitySnapshotResponse,
type RelayLiveActivityRegistrationRequest,
RelayMobileDeviceNotRegisteredError,
} from "@t3tools/contracts/relay";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
Expand Down Expand Up @@ -161,6 +162,8 @@ interface DeviceRegistrationInput {

interface RegisterDeviceInput extends DeviceRegistrationInput {
readonly preferencesOverride?: Partial<Preferences>;
/** Send even when the saved record matches, because the relay reported the device missing. */
readonly force?: boolean;
}

function mergeAgentAwarenessRegistrationPreferences(
Expand Down Expand Up @@ -389,6 +392,7 @@ function registrationSignature(body: RelayDeviceRegistrationRequest): string {
const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWithRelay")(function* (
body: RelayDeviceRegistrationRequest,
expectedGeneration: number,
force = false,
): Effect.fn.Return<void, AgentAwarenessRegistrationError, AgentAwarenessRegistrationServices> {
if (expectedGeneration !== deviceRegistrationGeneration) {
return;
Expand Down Expand Up @@ -431,6 +435,7 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
(androidDeviceReplayedAt === null ||
now - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS);
if (
!force &&
persisted &&
persisted.identity === identity &&
persisted.signature === signature &&
Expand Down Expand Up @@ -764,6 +769,7 @@ const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function*
preferences,
}),
expectedGeneration,
input.force,
);
});

Expand Down Expand Up @@ -988,6 +994,7 @@ const registerLiveActivityPushTokenValue = Effect.fn(
) {
return true;
}
const generation = deviceRegistrationGeneration;
const storage = yield* MobileStorage.MobileStorage;
const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
Effect.mapError(
Expand All @@ -998,16 +1005,37 @@ const registerLiveActivityPushTokenValue = Effect.fn(
}),
),
);
const registered = yield* registerLiveActivityWithRelay({
const register = registerLiveActivityWithRelay({
deviceId,
activityPushToken: input.activityPushToken,
});
const registered = yield* register.pipe(
// The relay pruned this device, so the saved record no longer proves it is registered.
// A sign-out or account switch meanwhile must not re-send this token under the new account.
Effect.catchIf(isDeviceNotRegisteredError, (error) =>
generation !== deviceRegistrationGeneration
? Effect.fail(error)
: registerDevice({ force: true }, generation).pipe(
Effect.andThen(
Effect.suspend(() =>
generation === deviceRegistrationGeneration ? register : Effect.fail(error),
),
),
),
),
);
if (registered) {
registeredActivityPushTokens.set(input.activityPushToken, yield* Clock.currentTimeMillis);
}
return registered;
});

const isRelayDeviceNotRegistered = Schema.is(RelayMobileDeviceNotRegisteredError);

function isDeviceNotRegisteredError(error: AgentAwarenessRegistrationError): boolean {
return error._tag === "ManagedRelayRequestFailedError" && isRelayDeviceNotRegistered(error.cause);
}

function scheduleActiveLiveActivityRegistrationRetry(): void {
if (activeLiveActivityRegistrationRetry || !relayTokenProvider) {
return;
Expand Down
4 changes: 3 additions & 1 deletion infra/relay/src/agentActivity/AgentActivityPublisher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ function makeLiveActivities(
markDelivery: () => Effect.void,

invalidateDeliveryToken: () => Effect.void,
clearEndedAggregates: Effect.void,
...overrides,
};
}
Expand All @@ -83,7 +84,7 @@ function makeAgentActivityRows(
return {
upsert: () => Effect.void,
remove: () => Effect.void,
pruneTerminal: () => Effect.void,
prune: Effect.void,
listForUser: () => Effect.succeed([state]),
getForUserThread: () => Effect.succeed(state),
...overrides,
Expand All @@ -109,6 +110,7 @@ function makeEnvironmentLinks(
updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"),
setHoldWebhooksWhileOffline: () => Effect.void,
revokeForUser: () => Effect.succeed(false),
pruneRevoked: Effect.succeed(0),
...overrides,
};
}
Expand Down
54 changes: 54 additions & 0 deletions infra/relay/src/agentActivity/AgentActivityRows.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { RelayAgentActivityState } from "@t3tools/contracts/relay";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";

import { makePgliteRelayDb } from "../persistence/pgliteTestDb.ts";
import { relayAgentActivityRows } from "../persistence/schema.ts";
import * as AgentActivityRows from "./AgentActivityRows.ts";

describe("AgentActivityRows", () => {
it.effect("prunes finished rows after 30 minutes and any row the read side has expired", () =>
Effect.gen(function* () {
const now = Date.parse("2026-06-01T00:00:00.000Z");
yield* TestClock.setTime(now);
const minutesAgo = (minutes: number) =>
DateTime.formatIso(DateTime.makeUnsafe(now - minutes * 60_000));
const { db, layer } = yield* makePgliteRelayDb;
const row = (
threadId: string,
phase: RelayAgentActivityState["phase"],
updatedAt: string,
) => ({
environmentId: "env-1",
environmentPublicKey: "key-1",
threadId,
stateJson: { phase, updatedAt } as RelayAgentActivityState,
updatedAt,
createdAt: updatedAt,
});
yield* Effect.promise(() =>
db
.insert(relayAgentActivityRows)
.values([
row("old-completed", "completed", minutesAgo(31)),
row("recent-completed", "completed", minutesAgo(29)),
row("abandoned-running", "running", minutesAgo(24 * 60 + 1)),
row("waiting", "waiting_for_input", minutesAgo(24 * 60 - 1)),
]),
);
const rows = yield* Effect.service(AgentActivityRows.AgentActivityRows).pipe(
Effect.provide(AgentActivityRows.layer.pipe(Layer.provide(layer))),
);

yield* rows.prune;
const remaining = yield* Effect.promise(() => db.select().from(relayAgentActivityRows));
expect(remaining.map((remainingRow) => remainingRow.threadId).toSorted()).toEqual([
"recent-completed",
"waiting",
]);
}),
);
});
52 changes: 29 additions & 23 deletions infra/relay/src/agentActivity/AgentActivityRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import * as Function from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { and, desc, eq, isNull, lt, sql } from "drizzle-orm";
import { and, desc, eq, isNull, lt, or, sql } from "drizzle-orm";

import * as RelayDb from "../db.ts";
import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts";
import { MAX_AGENT_ACTIVITY_ROW_TTL_MS } from "./agentActivityPayloads.ts";

export class AgentActivityRowUpsertPersistenceError extends Schema.TaggedError<AgentActivityRowUpsertPersistenceError>()(
"AgentActivityRowUpsertPersistenceError",
Expand Down Expand Up @@ -38,18 +39,19 @@ export class AgentActivityRowDeletePersistenceError extends Schema.TaggedError<A
}
}

export class AgentActivityRowPruneTerminalPersistenceError extends Schema.TaggedError<AgentActivityRowPruneTerminalPersistenceError>()(
"AgentActivityRowPruneTerminalPersistenceError",
export class AgentActivityRowPrunePersistenceError extends Schema.TaggedError<AgentActivityRowPrunePersistenceError>()(
"AgentActivityRowPrunePersistenceError",
{
updatedBefore: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to prune terminal agent activity rows updated before ${this.updatedBefore}.`;
return "Failed to prune finished and expired agent activity rows.";
}
}

const TERMINAL_AGENT_ACTIVITY_ROW_RETENTION_MINUTES = 30;

export class AgentActivityRowListPersistenceError extends Schema.TaggedError<AgentActivityRowListPersistenceError>()(
"AgentActivityRowListPersistenceError",
{
Expand All @@ -69,9 +71,8 @@ export class AgentActivityRows extends Context.Service<
readonly environmentPublicKey: string;
readonly state: RelayAgentActivityState;
}) => Effect.Effect<void, AgentActivityRowUpsertPersistenceError>;
readonly pruneTerminal: (input: {
readonly updatedBefore: string;
}) => Effect.Effect<void, AgentActivityRowPruneTerminalPersistenceError>;
/** Deletes finished rows after a short grace and any row the read side already treats as expired. */
readonly prune: Effect.Effect<void, AgentActivityRowPrunePersistenceError>;
readonly remove: (input: {
readonly environmentId: string;
readonly environmentPublicKey: string;
Expand Down Expand Up @@ -180,28 +181,33 @@ const make = Effect.gen(function* () {
);
}),

pruneTerminal: Effect.fn("relay.agent_activity_rows.prune_terminal")(function* (input) {
prune: Effect.gen(function* () {
const now = yield* DateTime.now;
const terminalBefore = DateTime.formatIso(
DateTime.subtract(now, { minutes: TERMINAL_AGENT_ACTIVITY_ROW_RETENTION_MINUTES }),
);
const expiredBefore = DateTime.formatIso(
DateTime.subtract(now, { milliseconds: MAX_AGENT_ACTIVITY_ROW_TTL_MS }),
);
yield* Effect.annotateCurrentSpan({
"relay.agent_activity_prune.before": input.updatedBefore,
"relay.agent_activity_prune.terminal_before": terminalBefore,
"relay.agent_activity_prune.expired_before": expiredBefore,
});
yield* db
.delete(relayAgentActivityRows)
.where(
and(
sql`${relayAgentActivityRows.stateJson} ->> 'phase' IN ('completed', 'failed')`,
lt(relayAgentActivityRows.updatedAt, input.updatedBefore),
),
)
.pipe(
Effect.mapError(
(cause) =>
new AgentActivityRowPruneTerminalPersistenceError({
updatedBefore: input.updatedBefore,
cause,
}),
or(
and(
sql`${relayAgentActivityRows.stateJson} ->> 'phase' IN ('completed', 'failed')`,
lt(relayAgentActivityRows.updatedAt, terminalBefore),
),
lt(relayAgentActivityRows.updatedAt, expiredBefore),
),
);
}),
}).pipe(
Effect.mapError((cause) => new AgentActivityRowPrunePersistenceError({ cause })),
Effect.withSpan("relay.agent_activity_rows.prune"),
),

listForUser: Effect.fn("relay.agent_activity_rows.list_for_user")(function* (input) {
return yield* db
Expand Down
3 changes: 2 additions & 1 deletion infra/relay/src/agentActivity/ApnsDeliveries.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ function layerFor(input: {
Layer.succeed(AgentActivityRows.AgentActivityRows, {
upsert: () => Effect.void,
remove: () => Effect.void,
pruneTerminal: () => Effect.void,
prune: Effect.void,
listForUser: () =>
input.activityStates !== undefined
? Effect.succeed([...input.activityStates])
Expand Down Expand Up @@ -230,6 +230,7 @@ function layerFor(input: {
Effect.sync(() => {
input.invalidatedTokens?.push(invalidated);
}),
clearEndedAggregates: Effect.void,
}),
RelayConfiguration.layer(input.config ?? config),
input.execute
Expand Down
Loading
Loading