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

android-push-watch.ts

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