-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.ts
More file actions
221 lines (194 loc) · 7.23 KB
/
router.ts
File metadata and controls
221 lines (194 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { initTRPC } from '@trpc/server';
import { observable } from '@trpc/server/observable';
import { TRPCClientError, type TRPCLink } from '@trpc/client';
import { io as ioClient } from 'socket.io-client';
import {
attachTrpcResponseHandler,
createSocketLink,
type BackendConfig,
} from '@arken/node/trpc/socketLink';
import ApplicationService from './modules/application/application.service';
import { createRouter as createApplicationRouter } from './modules/application/application.router';
import ConfigService from './modules/config/config.service';
import { createRouter as createConfigRouter } from './modules/config/config.router';
import MathService from './modules/math/math.service';
import { createRouter as createMathRouter } from './modules/math/math.router';
import HelpService from './modules/help/help.service';
import { createRouter as createHelpRouter } from './modules/help/help.router';
import TestService from './modules/test/test.service';
import { createRouter as createTestRouter } from './modules/test/test.router';
import { createRouter as createCerebroRouter } from '@arken/cerebro-protocol';
import dotEnv from 'dotenv';
dotEnv.config();
const isLocal = process.env.ARKEN_ENV === 'local';
type RouteDef = {
local?: () => any;
remoteUrl?: () => string | undefined;
create?: () => any;
};
const ROUTES = {
application: { local: () => createApplicationRouter(new ApplicationService()) },
config: { local: () => createConfigRouter(new ConfigService()) },
math: { local: () => createMathRouter(new MathService()) },
help: { local: () => createHelpRouter(new HelpService()) },
test: { local: () => createTestRouter(new TestService()) },
cerebro: {
remoteUrl: () => process.env.CEREBRO_SERVICE_URI,
create: () => createCerebroRouter(),
},
seer: {
remoteUrl: () => process.env['SEER_SERVICE_URI' + (isLocal ? '_LOCAL' : '')],
create: () => require('@arken/seer-protocol').createRouter({} as any),
},
'seer-prd': {
remoteUrl: () => process.env.SEER_SERVICE_URI,
create: () => require('@arken/seer-protocol').createRouter({} as any),
},
evolution: {
remoteUrl: () => process.env['EVOLUTION_SERVICE_URI' + (isLocal ? '_LOCAL' : '')],
create: () => require('@arken/evolution-protocol/realm/realm.router').createRouter({} as any),
},
'evolution-prd': {
remoteUrl: () => process.env.EVOLUTION_SERVICE_URI,
create: () => require('@arken/evolution-protocol/realm/realm.router').createRouter({} as any),
},
'evolution-dev': {
remoteUrl: () => process.env.EVOLUTION_SERVICE_URI_DEV,
create: () => require('@arken/evolution-protocol/realm/realm.router').createRouter({} as any),
},
} satisfies Record<string, RouteDef>;
type RouteKey = keyof typeof ROUTES;
const ROUTE_KEYS = Object.keys(ROUTES) as RouteKey[];
const resolveRequestedRoute = (): RouteKey | undefined => {
const command = process.argv[2];
if (!command) return undefined;
const [namespace] = command.split('.');
if (!namespace) return undefined;
if (!ROUTE_KEYS.includes(namespace as RouteKey)) return undefined;
return namespace as RouteKey;
};
const requestedRoute = resolveRequestedRoute();
const shouldInstantiateRoute = (routeKey: RouteKey) => {
if (!requestedRoute) return true;
if (routeKey === requestedRoute) return true;
return Boolean(ROUTES[routeKey].local);
};
export const t = initTRPC.context<{ app: any; router?: any }>().create();
const localRouters = Object.fromEntries(
ROUTE_KEYS.flatMap((k) => (ROUTES[k].local && shouldInstantiateRoute(k) ? [[k, ROUTES[k].local!()]] : []))
) as Partial<Record<RouteKey, any>>;
export const router = t.router({
...(localRouters as any),
...Object.fromEntries(
ROUTE_KEYS.flatMap((k) => {
if (!ROUTES[k].create || !shouldInstantiateRoute(k)) return [];
try {
return [[k, ROUTES[k].create!()]];
} catch {
return [];
}
})
),
});
export type AppRouter = typeof router;
const backends: BackendConfig[] = ROUTE_KEYS.flatMap((name) => {
if (!shouldInstantiateRoute(name)) return [];
const url = ROUTES[name].remoteUrl?.();
return url ? [{ name, url }] : [];
});
type Client = {
ioCallbacks: Record<string, any>;
socket: ReturnType<typeof ioClient>;
};
const clients: Record<string, Client> = {};
for (const backend of backends) {
const client: Client = {
ioCallbacks: {},
socket: ioClient(backend.url, {
transports: ['websocket'],
upgrade: false,
autoConnect: true,
autoUnref: true,
}),
};
attachTrpcResponseHandler({
client,
backendName: backend.name,
logging: false,
preferOnAny: true,
});
clients[backend.name] = client;
}
function waitUntil(predicate: () => boolean, timeoutMs: number, intervalMs = 100): Promise<void> {
const start = Date.now();
if (predicate()) return Promise.resolve();
return new Promise((resolve, reject) => {
const check = () => {
if (predicate()) return resolve();
if (Date.now() - start >= timeoutMs) return reject(new Error('Timeout waiting for condition'));
setTimeout(check, intervalMs);
};
setTimeout(check, intervalMs);
});
}
function getNestedMethod(obj: any, path: string) {
const fn = path.split('.').reduce((curr, key) => {
if (curr?.[key] === undefined) throw new Error(`Method "${key}" not found in "${path}"`);
return curr[key];
}, obj);
if (typeof fn !== 'function') throw new Error(`"${path}" is not a function`);
return fn;
}
const remoteLink = createSocketLink({
backends,
clients,
waitUntil: (predicate) => waitUntil(predicate, 15_000),
notifyTRPCError: () => undefined,
requestTimeoutMs: 15_000,
});
export const link: TRPCLink<any> =
(ctx) =>
() =>
({ op }) => {
const [routerNameRaw, ...restPath] = op.path.split('.');
if (routerNameRaw && clients[routerNameRaw]) {
return (remoteLink(ctx) as any)({ op });
}
return observable((observer) => {
const execute = async () => {
try {
let localRouter: any;
let methodPath: string;
if (
routerNameRaw &&
ROUTE_KEYS.includes(routerNameRaw as RouteKey) &&
localRouters[routerNameRaw as RouteKey] &&
restPath.length > 0
) {
localRouter = localRouters[routerNameRaw as RouteKey];
methodPath = restPath.join('.');
} else if ((ctx as any)?.router) {
localRouter = (ctx as any).router;
methodPath = op.path;
} else if (
routerNameRaw &&
ROUTE_KEYS.includes(routerNameRaw as RouteKey) &&
localRouters[routerNameRaw as RouteKey]
) {
localRouter = localRouters[routerNameRaw as RouteKey];
methodPath = routerNameRaw;
} else {
throw new TRPCClientError(`Unknown router: ${routerNameRaw}`);
}
const caller = t.createCallerFactory(localRouter)(ctx as any);
const method = getNestedMethod(caller, methodPath);
const result = await method(op.input);
observer.next({ result: { data: result } });
observer.complete();
} catch (error: any) {
observer.error(error instanceof TRPCClientError ? error : new TRPCClientError(error?.message ?? String(error)));
}
};
void execute();
});
};