feat: rpc client

This commit is contained in:
Max Koon
2025-11-29 00:57:32 -05:00
parent 3ebb7ee796
commit 74f4da1d3d
9 changed files with 214 additions and 105 deletions

View File

@@ -11,11 +11,14 @@ import { WebhookReceiverRoute } from "./webhook";
import { ZeroMutateRoute, ZeroQueryRoute } from "./zero/handler"; import { ZeroMutateRoute, ZeroQueryRoute } from "./zero/handler";
import { RpcRoute } from "./rpc/handler"; import { RpcRoute } from "./rpc/handler";
import { BASE_URL } from "@money/shared"; import { BASE_URL } from "@money/shared";
import { CurrentSession, SessionMiddleware } from "./middleware/session";
const RootRoute = HttpLayerRouter.add( const RootRoute = HttpLayerRouter.add(
"GET", "GET",
"/", "/",
Effect.gen(function* () { Effect.gen(function* () {
const d = yield* CurrentSession;
return HttpServerResponse.text("OK"); return HttpServerResponse.text("OK");
}), }),
); );
@@ -28,11 +31,11 @@ const AllRoutes = Layer.mergeAll(
RpcRoute, RpcRoute,
WebhookReceiverRoute, WebhookReceiverRoute,
).pipe( ).pipe(
Layer.provide(SessionMiddleware.layer),
Layer.provide( Layer.provide(
HttpLayerRouter.cors({ HttpLayerRouter.cors({
allowedOrigins: ["https://money.koon.us", `${BASE_URL}:8081`], allowedOrigins: ["https://money.koon.us", `${BASE_URL}:8081`],
allowedMethods: ["POST", "GET", "OPTIONS"], allowedMethods: ["POST", "GET", "OPTIONS"],
// allowedHeaders: ["Content-Type", "Authorization", ""],
credentials: true, credentials: true,
}), }),
), ),

View File

@@ -1,13 +1,76 @@
import { RpcSerialization, RpcServer } from "@effect/rpc"; import { RpcSerialization, RpcServer } from "@effect/rpc";
import { Effect, Layer, Schema } from "effect"; import { Console, Effect, Layer, Schema } from "effect";
import { LinkRpcs, Link } from "@money/shared/rpc"; import { LinkRpcs, Link, AuthMiddleware } from "@money/shared/rpc";
import { CurrentSession } from "../middleware/session";
import { Authorization } from "../auth/context";
import { HttpServerRequest } from "@effect/platform";
import { AuthSchema } from "@money/shared/auth";
const parseAuthorization = (input: string) =>
Effect.gen(function* () {
const m = /^Bearer\s+(.+)$/.exec(input);
if (!m) {
return yield* Effect.fail(new Error("Invalid token"));
}
return m[1];
});
export const AuthLive = Layer.scoped(
AuthMiddleware,
Effect.gen(function* () {
const auth = yield* Authorization;
return AuthMiddleware.of(({ headers, payload, rpc }) =>
Effect.gen(function* () {
const newHeaders = { ...headers };
const token = yield* Schema.decodeUnknown(
Schema.Struct({
authorization: Schema.optional(Schema.String),
}),
)(headers).pipe(
// Effect.tap(Console.debug),
Effect.flatMap(({ authorization }) =>
authorization != undefined
? parseAuthorization(authorization)
: Effect.succeed(undefined),
),
);
if (token) {
newHeaders["cookie"] = token;
}
const session = yield* auth
.use((auth) => auth.api.getSession({ headers: newHeaders }))
.pipe(
Effect.flatMap((s) =>
s == null ? Effect.succeed(null) : Schema.decode(AuthSchema)(s),
),
Effect.tap((s) => Console.debug("Auth result", s)),
);
return { auth: session };
}).pipe(Effect.orDie),
);
}),
);
const LinkHandlers = LinkRpcs.toLayer({ const LinkHandlers = LinkRpcs.toLayer({
CreateLink: () => Effect.succeed(new Link({ href: "hi" })), CreateLink: () =>
Effect.gen(function* () {
const session = yield* CurrentSession;
return new Link({ href: session.auth?.user.name || "anon" });
}),
}); });
export const RpcRoute = RpcServer.layerHttpRouter({ export const RpcRoute = RpcServer.layerHttpRouter({
group: LinkRpcs, group: LinkRpcs,
path: "/rpc", path: "/rpc",
protocol: "http", protocol: "http",
}).pipe(Layer.provide(LinkHandlers), Layer.provide(RpcSerialization.layerJson)); }).pipe(
Layer.provide(LinkHandlers),
Layer.provide(RpcSerialization.layerJson),
Layer.provide(AuthLive),
);

View File

@@ -4,7 +4,7 @@ import "react-native-reanimated";
import { authClient } from "@/lib/auth-client"; import { authClient } from "@/lib/auth-client";
import { ZeroProvider } from "@rocicorp/zero/react"; import { ZeroProvider } from "@rocicorp/zero/react";
import { useMemo } from "react"; import { useMemo } from "react";
import { authDataSchema } from "@money/shared/auth"; import { AuthSchema } from "@money/shared/auth";
import { Platform } from "react-native"; import { Platform } from "react-native";
import type { ZeroOptions } from "@rocicorp/zero"; import type { ZeroOptions } from "@rocicorp/zero";
import { import {
@@ -15,6 +15,7 @@ import {
BASE_URL, BASE_URL,
} from "@money/shared"; } from "@money/shared";
import { expoSQLiteStoreProvider } from "@rocicorp/zero/react-native"; import { expoSQLiteStoreProvider } from "@rocicorp/zero/react-native";
import { Schema as S } from "effect";
export const unstable_settings = { export const unstable_settings = {
anchor: "index", anchor: "index",
@@ -26,8 +27,8 @@ export default function RootLayout() {
const { data: session, isPending } = authClient.useSession(); const { data: session, isPending } = authClient.useSession();
const authData = useMemo(() => { const authData = useMemo(() => {
const result = authDataSchema.safeParse(session); const result = session ? S.decodeSync(AuthSchema)(session) : null;
return result.success ? result.data : null; return result ? result : null;
}, [session]); }, [session]);
const cookie = useMemo(() => { const cookie = useMemo(() => {

View File

@@ -1,30 +0,0 @@
import { Button, Text, View } from "react-native";
import { AtomRpc, useAtomSet } from "@effect-atom/atom-react";
import { Layer } from "effect";
import { LinkRpcs } from "@money/shared/rpc";
import { FetchHttpClient } from "@effect/platform";
import { RpcClient, RpcSerialization } from "@effect/rpc";
class Client extends AtomRpc.Tag<Client>()("RpcClient", {
group: LinkRpcs,
protocol: RpcClient.layerProtocolHttp({
url: "http://laptop:3000/rpc",
}).pipe(Layer.provide([RpcSerialization.layerJson, FetchHttpClient.layer])),
}) {}
export default function Page() {
const create = useAtomSet(Client.mutation("CreateLink"));
const onPress = () => {
create({
payload: void 0,
});
};
return (
<View>
<Text>RPC Test</Text>
<Button onPress={onPress} title="Create link" />
</View>
);
}

View File

@@ -1,26 +1,6 @@
import { z } from "zod"; import { z } from "zod";
import { Schema } from "effect"; import { Schema } from "effect";
export const sessionSchema = z.object({
id: z.string(),
userId: z.string(),
expiresAt: z.date(),
});
export const userSchema = z.object({
id: z.string(),
email: z.string(),
emailVerified: z.boolean(),
name: z.string(),
createdAt: z.date(),
updatedAt: z.date(),
});
export const authDataSchema = z.object({
session: sessionSchema,
user: userSchema,
});
const DateFromDateOrString = Schema.Union( const DateFromDateOrString = Schema.Union(
Schema.DateFromString, Schema.DateFromString,
Schema.DateFromSelf, Schema.DateFromSelf,
@@ -53,7 +33,3 @@ export const AuthSchema = Schema.Struct({
}); });
export type AuthSchemaType = Schema.Schema.Type<typeof AuthSchema>; export type AuthSchemaType = Schema.Schema.Type<typeof AuthSchema>;
export type Session = z.infer<typeof sessionSchema>;
export type User = z.infer<typeof userSchema>;
export type AuthData = z.infer<typeof authDataSchema>;

View File

@@ -1,13 +1,29 @@
import { Schema } from "effect"; import { Context, Schema } from "effect";
import { Rpc, RpcGroup } from "@effect/rpc"; import { Rpc, RpcGroup, RpcMiddleware } from "@effect/rpc";
import type { AuthSchema } from "./auth";
export class Link extends Schema.Class<Link>("Link")({ export class Link extends Schema.Class<Link>("Link")({
href: Schema.String, href: Schema.String,
}) {} }) {}
export class CurrentSession extends Context.Tag("CurrentSession")<
CurrentSession,
{ readonly auth: Schema.Schema.Type<typeof AuthSchema> | null }
>() {}
export class AuthMiddleware extends RpcMiddleware.Tag<AuthMiddleware>()(
"AuthMiddleware",
{
// This middleware will provide the current user context
provides: CurrentSession,
// This middleware requires a client implementation too
requiredForClient: true,
},
) {}
export class LinkRpcs extends RpcGroup.make( export class LinkRpcs extends RpcGroup.make(
Rpc.make("CreateLink", { Rpc.make("CreateLink", {
success: Link, success: Link,
error: Schema.String, error: Schema.String,
}), }),
) {} ).middleware(AuthMiddleware) {}

View File

@@ -3,7 +3,7 @@ import { Transactions } from "./transactions";
import { View, Text } from "react-native"; import { View, Text } from "react-native";
import { Settings } from "./settings"; import { Settings } from "./settings";
import { useKeyboard } from "./useKeyboard"; import { useKeyboard } from "./useKeyboard";
import type { AuthData } from "@money/shared/auth"; import type { AuthSchemaType } from "@money/shared/auth";
const PAGES = { const PAGES = {
"/": { "/": {
@@ -39,7 +39,7 @@ type Routes<T> = {
export type Route = Routes<typeof PAGES>; export type Route = Routes<typeof PAGES>;
interface RouterContextType { interface RouterContextType {
auth: AuthData | null; auth: AuthSchemaType | null;
route: Route; route: Route;
setRoute: (route: Route) => void; setRoute: (route: Route) => void;
} }
@@ -51,7 +51,7 @@ export const RouterContext = createContext<RouterContextType>({
}); });
type AppProps = { type AppProps = {
auth: AuthData | null; auth: AuthSchemaType | null;
route: Route; route: Route;
setRoute: (page: Route) => void; setRoute: (page: Route) => void;
}; };

50
packages/ui/src/rpc.ts Normal file
View File

@@ -0,0 +1,50 @@
import { AtomRpc } from "@effect-atom/atom-react";
import { AuthMiddleware, LinkRpcs } from "@money/shared/rpc";
import { FetchHttpClient, Headers } from "@effect/platform";
import { Rpc, RpcClient, RpcMiddleware, RpcSerialization } from "@effect/rpc";
import * as Layer from "effect/Layer";
import { Effect } from "effect";
import { use } from "react";
import { RouterContext } from "./index";
import * as Redacted from "effect/Redacted";
import { Platform } from "react-native";
const protocol = RpcClient.layerProtocolHttp({
url: "http://laptop:3000/rpc",
}).pipe(
Layer.provide([
RpcSerialization.layerJson,
FetchHttpClient.layer.pipe(
Layer.provide(
Layer.succeed(FetchHttpClient.RequestInit, {
credentials: "include",
}),
),
),
]),
);
export const useRpc = () => {
const { auth } = use(RouterContext);
return class Client extends AtomRpc.Tag<Client>()("RpcClient", {
group: LinkRpcs,
protocol: Layer.merge(
protocol,
RpcMiddleware.layerClient(AuthMiddleware, ({ request }) =>
Effect.succeed({
...request,
...(auth && Platform.OS == ("TUI" as any)
? {
headers: Headers.set(
request.headers,
"authorization",
"Bearer " + Redacted.value(auth.session.token),
),
}
: {}),
}),
),
),
}) {};
};

View File

@@ -7,6 +7,9 @@ import { useKeyboard } from "../useKeyboard";
import { Button } from "../../components/Button"; import { Button } from "../../components/Button";
import * as Table from "../../components/Table"; import * as Table from "../../components/Table";
import * as Dialog from "../../components/Dialog"; import * as Dialog from "../../components/Dialog";
import { useAtomSet } from "@effect-atom/atom-react";
import { useRpc } from "../rpc";
import * as Exit from "effect/Exit";
const COLUMNS: Table.Column[] = [ const COLUMNS: Table.Column[] = [
{ name: "name", label: "Name" }, { name: "name", label: "Name" },
@@ -116,52 +119,79 @@ export function Accounts() {
} }
function AddAccount() { function AddAccount() {
const { auth } = use(RouterContext); const rpc = useRpc();
const [link, details] = useQuery(queries.getPlaidLink(auth)); const createLink = useAtomSet(rpc.mutation("CreateLink"), {
mode: "promiseExit",
});
const [href, setHref] = useState("");
// const [link, details] = useQuery(queries.getPlaidLink(auth));
const { close } = use(Dialog.Context); const { close } = use(Dialog.Context);
const openLink = () => { const init = () => {
if (!link) return; console.log("INIT");
Linking.openURL(link.link); const p = createLink({ payload: void 0 })
.then((link) => {
console.log("my link", link);
if (Exit.isSuccess(link)) {
setHref(link.value.href);
}
})
.finally(() => {
console.log("WHAT");
});
console.log(p);
}; };
const z = useZero<Schema, Mutators>();
useEffect(() => { useEffect(() => {
console.log(link, details); console.log("useEffect");
if (details.type != "complete") return; init();
if (link != undefined) { }, []);
if (!link.completeAt) {
const timer = setInterval(() => { // const openLink = () => {
console.log("Checking for link"); // if (!link) return;
z.mutate.link.get({ link_token: link.token }); // Linking.openURL(link.link);
}, 1000 * 5); // };
return () => clearInterval(timer);
} else { // const z = useZero<Schema, Mutators>();
if (close) close();
return; // useEffect(() => {
} // console.log(link, details);
} // if (details.type != "complete") return;
console.log("Creating new link"); // if (link != undefined) {
z.mutate.link.create(); // if (!link.completeAt) {
}, [link, details]); // const timer = setInterval(() => {
// console.log("Checking for link");
// z.mutate.link.get({ link_token: link.token });
// }, 1000 * 5);
// return () => clearInterval(timer);
// } else {
// if (close) close();
// return;
// }
// }
// console.log("Creating new link");
// z.mutate.link.create();
// }, [link, details]);
return ( return (
<> <>
<Text>Href: {href}</Text>
<Button onPress={() => close && close()}>close</Button> <Button onPress={() => close && close()}>close</Button>
{link ? ( {/* {link ? ( */}
<> {/* <> */}
<Text style={{ fontFamily: "mono" }}> {/* <Text style={{ fontFamily: "mono" }}> */}
Please click the button to complete setup. {/* Please click the button to complete setup. */}
</Text> {/* </Text> */}
{/**/}
<Button shortcut="return" onPress={openLink}> {/* <Button shortcut="return" onPress={openLink}> */}
Open Plaid {/* Open Plaid */}
</Button> {/* </Button> */}
</> {/* </> */}
) : ( {/* ) : ( */}
<Text style={{ fontFamily: "mono" }}>Loading Plaid Link</Text> {/* <Text style={{ fontFamily: "mono" }}>Loading Plaid Link</Text> */}
)} {/* )} */}
</> </>
); );
} }