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

android-push-watch.ts

228 lines9.1 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_WS_METHODS,
7 WS_METHODS,
8 WsRpcGroup,
9 type OrchestrationProjectShell,
10 type OrchestrationThreadShell,
11} from "@t3tools/contracts";
12import type { RelayAgentActivityState } from "@t3tools/contracts/relay";
13import { projectThreadAwareness } 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 // Socket.makeWebSocket only ever passes its `protocols` option here.
92 (url, protocols) =>
93 new NodeSocket.NodeWS.WebSocket(url, protocols as string | string[] | undefined, {
94 headers: { authorization: `Bearer ${connection.bearerToken}` },
95 }) as unknown as globalThis.WebSocket,
96 );
97 const protocol = RpcClient.layerProtocolSocket().pipe(
98 Layer.provide(Socket.layerWebSocket(connection.wsUrl).pipe(Layer.provide(socketConstructor))),
99 Layer.provide(RpcSerialization.layerJson),
100 );
101 const fcm = FcmClient.layer.pipe(
102 Layer.provide(
103 FcmAssertionSigner.layer.pipe(
104 Layer.provide(Layer.succeed(WebCrypto.WebCrypto, { subtle: globalThis.crypto.subtle })),
105 ),
106 ),
107 Layer.provide(
108 Layer.mergeAll(
109 FetchHttpClient.layer,
110 Layer.succeed(RelayConfiguration.RelayConfiguration, {
111 relayIssuer: "http://localhost",
112 apns: null,
113 fcmServiceAccount: Redacted.make(credentials),
114 clerkSecretKey: Redacted.make(""),
115 clerkPublishableKey: "",
116 clerkJwtAudience: "",
117 apnsDeliveryJobSigningSecret: Redacted.make(""),
118 cloudMintPrivateKey: Redacted.make(""),
119 cloudMintPublicKey: "",
120 managedEndpointBaseDomain: undefined,
121 managedEndpointNamespace: undefined,
122 }),
123 ),
124 ),
125 );
126 yield* Effect.gen(function* () {
127 const rpc = yield* RpcClient.make(WsRpcGroup);
128 const sender = yield* FcmClient.FcmClient;
129 const config = yield* rpc[WS_METHODS.serverGetConfig]({});
130 const projects = new Map<string, OrchestrationProjectShell>();
131 const threads = new Map<string, OrchestrationThreadShell>();
132 let states = new Map<string, RelayAgentActivityState>();
133 let previouslyActive = false;
134 yield* Effect.logInfo("Watching this paired environment for Android push verification.");
135 yield* rpc[ORCHESTRATION_WS_METHODS.subscribeShell]({}).pipe(
136 Stream.runForEach(
137 Effect.fnUntraced(function* (item) {
138 switch (item.kind) {
139 case "synchronized":
140 return;
141 case "snapshot":
142 projects.clear();
143 threads.clear();
144 for (const project of item.snapshot.projects) projects.set(project.id, project);
145 for (const thread of item.snapshot.threads) threads.set(thread.id, thread);
146 break;
147 case "project-upserted":
148 projects.set(item.project.id, item.project);
149 break;
150 case "project-removed":
151 projects.delete(item.projectId);
152 break;
153 case "thread-upserted":
154 threads.set(item.thread.id, item.thread);
155 break;
156 case "thread-removed":
157 threads.delete(item.threadId);
158 break;
159 }
160 const next = new Map<string, RelayAgentActivityState>();
161 for (const thread of threads.values()) {
162 const project = projects.get(thread.projectId);
163 if (!project || thread.archivedAt) continue;
164 const state = projectThreadAwareness({
165 environmentId: config.environment.environmentId,
166 project,
167 thread,
168 });
169 if (state) next.set(thread.id, state);
170 }
171 const state = item.kind === "thread-upserted" ? next.get(item.thread.id) : undefined;
172 const previous = state ? states.get(state.threadId) : undefined;
173 // A fresh subscription restores ongoing work without announcing old completions.
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(protocol, fcm)));
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 failures may contain credential-bearing request headers. Keep the
224 // cause on the error, but print only the fixed message at the CLI boundary.
225 Effect.tapError((error) => Effect.logError(error.message)),
226 ),
227 { disableErrorReporting: true },
228);