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

android-push-watch.ts

227 lines9.0 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 NodeSocket from "@effect/platform-node/NodeSocket";
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/unstable/http/FetchHttpClient";
23import * as RpcClient from "effect/unstable/rpc/RpcClient";
24import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
25import * as Socket from "effect/unstable/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 socketConstructor = Layer.succeed(
90 Socket.WebSocketConstructor,
91 (url, protocols) =>
92 new NodeSocket.NodeWS.WebSocket(url, protocols, {
93 headers: { authorization: `Bearer ${connection.bearerToken}` },
94 }) as unknown as globalThis.WebSocket,
95 );
96 const protocol = RpcClient.layerProtocolSocket().pipe(
97 Layer.provide(Socket.layerWebSocket(connection.wsUrl).pipe(Layer.provide(socketConstructor))),
98 Layer.provide(RpcSerialization.layerJson),
99 );
100 const fcm = FcmClient.layer.pipe(
101 Layer.provide(
102 FcmAssertionSigner.layer.pipe(
103 Layer.provide(Layer.succeed(WebCrypto.WebCrypto, { subtle: globalThis.crypto.subtle })),
104 ),
105 ),
106 Layer.provide(
107 Layer.mergeAll(
108 FetchHttpClient.layer,
109 Layer.succeed(RelayConfiguration.RelayConfiguration, {
110 relayIssuer: "http://localhost",
111 apns: null,
112 fcmServiceAccount: Redacted.make(credentials),
113 clerkSecretKey: Redacted.make(""),
114 clerkPublishableKey: "",
115 clerkJwtAudience: "",
116 apnsDeliveryJobSigningSecret: Redacted.make(""),
117 cloudMintPrivateKey: Redacted.make(""),
118 cloudMintPublicKey: "",
119 managedEndpointBaseDomain: undefined,
120 managedEndpointNamespace: undefined,
121 }),
122 ),
123 ),
124 );
125 yield* Effect.gen(function* () {
126 const rpc = yield* RpcClient.make(WsRpcGroup);
127 const sender = yield* FcmClient.FcmClient;
128 const config = yield* rpc[WS_METHODS.serverGetConfig]({});
129 const projects = new Map<string, OrchestrationProjectShell>();
130 const threads = new Map<string, OrchestrationV2ThreadShell>();
131 let states = new Map<string, RelayAgentActivityState>();
132 let previouslyActive = false;
133 yield* Effect.logInfo("Watching this paired environment for Android push verification.");
134 yield* rpc[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({}).pipe(
135 Stream.runForEach(
136 Effect.fnUntraced(function* (item) {
137 switch (item.kind) {
138 case "synchronized":
139 return;
140 case "snapshot":
141 projects.clear();
142 threads.clear();
143 for (const project of item.snapshot.projects) projects.set(project.id, project);
144 for (const thread of item.snapshot.threads) threads.set(thread.id, thread);
145 break;
146 case "project.updated":
147 projects.set(item.project.id, item.project);
148 break;
149 case "project.removed":
150 projects.delete(item.projectId);
151 break;
152 case "thread.updated":
153 threads.set(item.thread.id, item.thread);
154 break;
155 case "thread.removed":
156 threads.delete(item.threadId);
157 break;
158 }
159 const next = new Map<string, RelayAgentActivityState>();
160 for (const thread of threads.values()) {
161 const project = projects.get(thread.projectId);
162 if (!project || thread.archivedAt) continue;
163 const state = projectThreadAwarenessV2({
164 environmentId: config.environment.environmentId,
165 project,
166 thread,
167 });
168 if (state) next.set(thread.id, state);
169 }
170 const state = item.kind === "thread.updated" ? next.get(item.thread.id) : undefined;
171 const previous = state ? states.get(state.threadId) : undefined;
172 // A fresh subscription restores ongoing work without announcing old completions.
173 const now = yield* Clock.currentTimeMillis;
174 const alert =
175 state && state.phase !== previous?.phase && item.kind !== "snapshot"
176 ? FcmDeliveries.androidAlertForState(state, preferences, now)
177 : null;
178 const aggregate = makeAggregateState({
179 activeStates: [...next.values()],
180 terminalState: null,
181 nowMs: now,
182 });
183 const active = (aggregate?.activeCount ?? 0) > 0;
184 const same = encodeJson([...next.values()]) === encodeJson([...states.values()]);
185 states = next;
186 if ((!active && !previouslyActive && !alert) || (same && !alert)) return;
187 const result = yield* sender.send({
188 token: device.token,
189 packageName: device.packageName,
190 alert: alert !== null,
191 data: fitFcmData({
192 t3_kind: "agent_activity",
193 device_id: device.deviceId,
194 user_id: device.userId,
195 updated_at: String(now),
196 ...androidActivityData(aggregate),
197 ...alert,
198 }),
199 });
200 if (result.unregistered) return yield* new WatchUnregisteredDeviceError({});
201 previouslyActive = active;
202 yield* Effect.logInfo(
203 `Android push accepted: ${state?.phase ?? (active ? "active" : "ended")}`,
204 );
205 }),
206 ),
207 );
208 }).pipe(Effect.provide(Layer.mergeAll(protocol, fcm)));
209});
210​
211NodeRuntime.runMain(
212 main.pipe(
213 Effect.scoped,
214 Effect.catchCause((cause) => {
215 const failure = Cause.findErrorOption(cause);
216 return Effect.fail(
217 Option.isSome(failure) && isWatchUnregisteredDeviceError(failure.value)
218 ? failure.value
219 : new WatchStoppedError({ cause }),
220 );
221 }),
222 // Socket failures may contain credential-bearing request headers. Keep the
223 // cause on the error, but print only the fixed message at the CLI boundary.
224 Effect.tapError((error) => Effect.logError(error.message)),
225 ),
226 { disableErrorReporting: true },
227);