Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

android-push-watch.ts

242 lines9.2 KB

1// @effect-diagnostics nodeBuiltinImport:off - Local developer verification reads private credential files.
2import * as NodeFSP from "node:fs/promises";
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeWS from "@effect/platform-node/NodeWS";
5import {
6 ORCHESTRATION_V2_WS_METHODS,
7 WS_METHODS,
8 WsRpcGroup,
9 type OrchestrationProjectShell,
10 type OrchestrationV2ThreadShell,
11} from "@t3tools/contracts";
12import type { RelayAgentActivityState } from "@t3tools/contracts/relay";
13import { projectThreadAwarenessV2 } from "@t3tools/shared/agentAwareness";
14import * as Cause from "effect/Cause";
15import * as Option from "effect/Option";
16import * as Clock from "effect/Clock";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Redacted from "effect/Redacted";
20import * as Schema from "effect/Schema";
21import * as Stream from "effect/Stream";
22import * as FetchHttpClient from "effect/http/FetchHttpClient";
23import * as RpcClient from "effect/rpc/RpcClient";
24import * as RpcSerialization from "effect/rpc/RpcSerialization";
25import * as Socket from "effect/socket/Socket";
26​
27import * as RelayConfiguration from "../src/Config.ts";
28import {
29 androidActivityData,
30 androidRecipientData,
31 fitFcmData,
32} from "../src/agentActivity/fcmPayloads.ts";
33import * as WebCrypto from "../src/WebCrypto.ts";
34import * as FcmAssertionSigner from "../src/agentActivity/FcmAssertionSigner.ts";
35import * as FcmClient from "../src/agentActivity/FcmClient.ts";
36import * as FcmDeliveries from "../src/agentActivity/FcmDeliveries.ts";
37import { makeAggregateState } from "../src/agentActivity/agentActivityAggregate.ts";
38​
39const Device = Schema.Struct({
40 token: Schema.NonEmptyString,
41 deviceId: Schema.NonEmptyString,
42 userId: Schema.NonEmptyString,
43 packageName: Schema.NonEmptyString,
44});
45const Connection = Schema.Struct({
46 wsUrl: Schema.NonEmptyString,
47 bearerToken: Schema.NonEmptyString,
48});
49class WatchReadFileError extends Schema.TaggedError<WatchReadFileError>()("WatchReadFileError", {
50 path: Schema.String,
51 cause: Schema.Defect(),
52}) {
53 override get message() {
54 return `Could not read ${this.path}`;
55 }
57const readFile = (path: string) =>
58 Effect.tryPromise({
59 try: () => NodeFSP.readFile(path, "utf8"),
60 catch: (cause) => new WatchReadFileError({ path, cause }),
61 });
62const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
63class WatchUnregisteredDeviceError extends Schema.TaggedError<WatchUnregisteredDeviceError>()(
64 "WatchUnregisteredDeviceError",
65 {},
66) {
67 override get message() {
68 return "Device token is no longer registered";
69 }
71​
72class WatchStoppedError extends Schema.TaggedError<WatchStoppedError>()("WatchStoppedError", {
73 cause: Schema.Defect(),
74}) {
75 override get message() {
76 return "Android push watcher stopped. Check the private connection and Firebase configuration.";
77 }
79​
80const isWatchUnregisteredDeviceError = Schema.is(WatchUnregisteredDeviceError);
81​
82const preferences = {
83 notificationsEnabled: true,
84 liveActivitiesEnabled: true,
85 notifyOnApproval: true,
86 notifyOnInput: true,
87 notifyOnCompletion: true,
88 notifyOnFailure: true,
89};
90​
91const main = Effect.gen(function* () {
92 const [credentialsPath, devicePath, connectionPath] = process.argv.slice(2);
93 if (!credentialsPath || !devicePath || !connectionPath) {
94 return yield* Effect.logError(
95 "Usage: node scripts/android-push-watch.ts <service-account.json> <device.json> <connection.json>",
96 );
97 }
98 const credentials = yield* readFile(credentialsPath);
99 const device = yield* readFile(devicePath).pipe(
100 Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Device))),
101 );
102 const connection = yield* readFile(connectionPath).pipe(
103 Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Connection))),
104 );
105 const layerSocketConstructor = Layer.succeed(
106 Socket.WebSocketConstructor,
107 (url, protocols) =>
108 new NodeWS.WebSocket(url, protocols as string | string[] | undefined, {
109 headers: { authorization: `Bearer ${connection.bearerToken}` },
110 }) as unknown as globalThis.WebSocket,
111 );
112 const layerProtocol = RpcClient.layerProtocolSocket().pipe(
113 Layer.provide(
114 Socket.layerWebSocket(connection.wsUrl).pipe(Layer.provide(layerSocketConstructor)),
115 ),
116 Layer.provide(RpcSerialization.layerJson),
117 );
118 const layerFcm = FcmClient.layer.pipe(
119 Layer.provide(
120 FcmAssertionSigner.layer.pipe(
121 Layer.provide(Layer.succeed(WebCrypto.WebCrypto, { subtle: globalThis.crypto.subtle })),
122 ),
123 ),
124 Layer.provide(
125 Layer.mergeAll(
126 FetchHttpClient.layer,
127 Layer.succeed(RelayConfiguration.RelayConfiguration, {
128 relayIssuer: "http://localhost",
129 apns: null,
130 fcmServiceAccount: Redacted.make(credentials),
131 clerkSecretKey: Redacted.make(""),
132 clerkPublishableKey: "",
133 clerkJwtAudience: "",
134 apnsDeliveryJobSigningSecret: Redacted.make(""),
135 cloudMintPrivateKey: Redacted.make(""),
136 cloudMintPublicKey: "",
137 managedEndpointBaseDomain: undefined,
138 managedEndpointNamespace: undefined,
139 }),
140 ),
141 ),
142 );
143 yield* Effect.gen(function* () {
144 const rpc = yield* RpcClient.make(WsRpcGroup);
145 const sender = yield* FcmClient.FcmClient;
146 const config = yield* rpc[WS_METHODS.serverGetConfig]({});
147 const projects = new Map<string, OrchestrationProjectShell>();
148 const threads = new Map<string, OrchestrationV2ThreadShell>();
149 let states = new Map<string, RelayAgentActivityState>();
150 let previouslyActive = false;
151 yield* Effect.logInfo("Watching this paired environment for Android push verification.");
152 yield* rpc[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({}).pipe(
153 Stream.runForEach(
154 Effect.fnUntraced(function* (item) {
155 switch (item.kind) {
156 case "synchronized":
157 return;
158 case "snapshot":
159 projects.clear();
160 threads.clear();
161 for (const project of item.snapshot.projects) projects.set(project.id, project);
162 for (const thread of item.snapshot.threads) threads.set(thread.id, thread);
163 break;
164 case "project.updated":
165 projects.set(item.project.id, item.project);
166 break;
167 case "project.removed":
168 projects.delete(item.projectId);
169 break;
170 case "thread.updated":
171 threads.set(item.thread.id, item.thread);
172 break;
173 case "thread.removed":
174 threads.delete(item.threadId);
175 break;
176 }
177 const next = new Map<string, RelayAgentActivityState>();
178 for (const thread of threads.values()) {
179 const project = projects.get(thread.projectId);
180 if (!project || thread.archivedAt) continue;
181 const state = projectThreadAwarenessV2({
182 environmentId: config.environment.environmentId,
183 project,
184 thread,
185 });
186 if (state) next.set(thread.id, state);
187 }
188 const state = item.kind === "thread.updated" ? next.get(item.thread.id) : undefined;
189 const previous = state ? states.get(state.threadId) : undefined;
190 const now = yield* Clock.currentTimeMillis;
191 const alert =
192 state && state.phase !== previous?.phase && item.kind !== "snapshot"
193 ? FcmDeliveries.androidAlertForState(state, preferences, now)
194 : null;
195 const aggregate = makeAggregateState({
196 activeStates: [...next.values()],
197 terminalState: null,
198 nowMs: now,
199 });
200 const active = (aggregate?.activeCount ?? 0) > 0;
201 const same = encodeJson([...next.values()]) === encodeJson([...states.values()]);
202 states = next;
203 if ((!active && !previouslyActive && !alert) || (same && !alert)) return;
204 const result = yield* sender.send({
205 token: device.token,
206 packageName: device.packageName,
207 alert: alert !== null,
208 data: fitFcmData({
209 t3_kind: "agent_activity",
210 ...androidRecipientData(device.userId, device.deviceId, null),
211 updated_at: String(now),
212 ...androidActivityData(aggregate),
213 ...alert,
214 }),
215 });
216 if (result.unregistered) return yield* new WatchUnregisteredDeviceError({});
217 previouslyActive = active;
218 yield* Effect.logInfo(
219 `Android push accepted: ${state?.phase ?? (active ? "active" : "ended")}`,
220 );
221 }),
222 ),
223 );
224 }).pipe(Effect.provide(Layer.mergeAll(layerProtocol, layerFcm)));
225});
226​
227NodeRuntime.runMain(
228 main.pipe(
229 Effect.scoped,
230 Effect.catchCause((cause) => {
231 const failure = Cause.findErrorOption(cause);
232 return Effect.fail(
233 Option.isSome(failure) && isWatchUnregisteredDeviceError(failure.value)
234 ? failure.value
235 : new WatchStoppedError({ cause }),
236 );
237 }),
238 // Socket errors can expose credential headers; retain the cause but print only the fixed message.
239 Effect.tapError((error) => Effect.logError(error.message)),
240 ),
241 { disableErrorReporting: true },
242);