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

android-push-smoke.ts

152 lines5.3 KB

1// @effect-diagnostics nodeBuiltinImport:off - This developer command reads local credential files.
2import * as NodeFSP from "node:fs/promises";
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as Effect from "effect/Effect";
5import * as Clock from "effect/Clock";
6import * as Layer from "effect/Layer";
7import * as Redacted from "effect/Redacted";
8import * as Schema from "effect/Schema";
9import * as FetchHttpClient from "effect/http/FetchHttpClient";
10​
11import * as RelayConfiguration from "../src/Config.ts";
12import * as WebCrypto from "../src/WebCrypto.ts";
13import * as FcmAssertionSigner from "../src/agentActivity/FcmAssertionSigner.ts";
14import * as FcmClient from "../src/agentActivity/FcmClient.ts";
15import { androidRecipientData } from "../src/agentActivity/fcmPayloads.ts";
16​
17const Device = Schema.Struct({
18 token: Schema.NonEmptyString,
19 deviceId: Schema.NonEmptyString,
20 userId: Schema.NonEmptyString,
21 packageName: Schema.NonEmptyString,
22 deepLink: Schema.optional(Schema.NonEmptyString),
23});
24const decodeDevice = Schema.decodeUnknownEffect(Schema.fromJsonString(Device));
25const Phase = Schema.Literals(["running", "approval", "input", "completed", "failed", "end"]);
26const decodePhase = Schema.decodeUnknownEffect(Phase);
27​
28class SmokeUsageError extends Schema.TaggedError<SmokeUsageError>()("SmokeUsageError", {}) {
29 override get message() {
30 return "Usage: node scripts/android-push-smoke.ts <service-account.json> <device.json> <running|approval|input|completed|failed|end>";
31 }
33​
34class SmokeCredentialReadError extends Schema.TaggedError<SmokeCredentialReadError>()(
35 "SmokeCredentialReadError",
36 { cause: Schema.Defect() },
37) {
38 override get message() {
39 return "Could not read service-account file.";
40 }
42​
43class SmokeDeviceReadError extends Schema.TaggedError<SmokeDeviceReadError>()(
44 "SmokeDeviceReadError",
45 { cause: Schema.Defect() },
46) {
47 override get message() {
48 return "Could not read device file.";
49 }
51​
52class SmokeUnregisteredDeviceError extends Schema.TaggedError<SmokeUnregisteredDeviceError>()(
53 "SmokeUnregisteredDeviceError",
54 {},
55) {
56 override get message() {
57 return "This device token is no longer registered with Firebase.";
58 }
60​
61const main = Effect.gen(function* () {
62 const [credentialPath, devicePath, phaseArg] = process.argv.slice(2);
63 if (!credentialPath || !devicePath || !phaseArg) return yield* new SmokeUsageError({});
64 const phase = yield* decodePhase(phaseArg);
65 const credentials = yield* Effect.tryPromise({
66 try: () => NodeFSP.readFile(credentialPath, "utf8"),
67 catch: (cause) => new SmokeCredentialReadError({ cause }),
68 });
69 const device = yield* Effect.tryPromise({
70 try: () => NodeFSP.readFile(devicePath, "utf8"),
71 catch: (cause) => new SmokeDeviceReadError({ cause }),
72 }).pipe(Effect.flatMap(decodeDevice));
73 const title =
74 phase === "completed"
75 ? "Agent finished"
76 : phase === "failed"
77 ? "Agent failed"
78 : phase === "approval"
79 ? "Approval needed"
80 : phase === "input"
81 ? "Input needed"
82 : null;
83 const active = phase === "running" || phase === "approval" || phase === "input";
84 const now = yield* Clock.currentTimeMillis;
85 const config: RelayConfiguration.RelayConfiguration["Service"] = {
86 relayIssuer: "http://localhost",
87 fcmServiceAccount: Redacted.make(credentials),
88 apns: null,
89 clerkSecretKey: Redacted.make(""),
90 clerkPublishableKey: "",
91 clerkJwtAudience: "",
92 apnsDeliveryJobSigningSecret: Redacted.make(""),
93 cloudMintPrivateKey: Redacted.make(""),
94 cloudMintPublicKey: "",
95 managedEndpointBaseDomain: undefined,
96 managedEndpointNamespace: undefined,
97 };
98 const result = yield* FcmClient.FcmClient.pipe(
99 Effect.flatMap((client) =>
100 client.send({
101 token: device.token,
102 packageName: device.packageName,
103 alert: title !== null,
104 data: {
105 t3_kind: "agent_activity",
106 ...androidRecipientData(device.userId, device.deviceId, null),
107 updated_at: String(now),
108 active: String(active),
109 activity_title: active
110 ? "1 active agent"
111 : phase === "failed"
112 ? "Agent work failed"
113 : "Agent work completed",
114 activity_expires_at: String(
115 phase === "end" ? 0 : now + (active ? 2 * 60 * 60 * 1000 : 15 * 60 * 1000),
116 ),
117 activity_body: "Android notification test",
118 activity_path: device.deepLink ?? "/",
119 ...(title
120 ? {
121 alert_id: `smoke-${now}`,
122 alert_title: title,
123 alert_body: "T3 Code Android push test",
124 alert_path: device.deepLink ?? "/",
125 }
126 : {}),
127 },
128 }),
129 ),
130 Effect.provide(
131 FcmClient.layer.pipe(
132 Layer.provide(
133 FcmAssertionSigner.layer.pipe(
134 Layer.provide(Layer.succeed(WebCrypto.WebCrypto, { subtle: globalThis.crypto.subtle })),
135 ),
136 ),
137 Layer.provide(
138 Layer.mergeAll(
139 Layer.succeed(RelayConfiguration.RelayConfiguration, config),
140 FetchHttpClient.layer,
141 ),
142 ),
143 ),
144 ),
145 );
146 if (result.unregistered) return yield* new SmokeUnregisteredDeviceError({});
147 yield* Effect.logInfo(
148 `Firebase accepted the ${phase} notification. Verify delivery on the device.`,
149 );
150});
151​
152NodeRuntime.runMain(main);