Skip to content

Commit 4e5692c

Browse files
committed
feat(backend-platform): clean code
1 parent f532219 commit 4e5692c

File tree

2 files changed

+156
-90
lines changed

2 files changed

+156
-90
lines changed

packages/backend-platform/src/AccountActivityService.ts

Lines changed: 77 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ import type {
1515
} from './types';
1616
import type { AccountActivityServiceMethodActions } from './AccountActivityService-method-action-types';
1717
import type {
18-
WebSocketService,
1918
WebSocketConnectionInfo,
2019
WebSocketServiceConnectionStateChangedEvent,
20+
SubscriptionInfo,
2121
} from './WebsocketService';
2222
import { WebSocketState } from './WebsocketService';
2323

@@ -72,6 +72,14 @@ export const ACCOUNT_ACTIVITY_SERVICE_ALLOWED_ACTIONS = [
7272
'AccountsController:getAccountByAddress',
7373
'AccountsController:getSelectedAccount',
7474
'TokenBalancesController:updateBalances',
75+
'BackendWebSocketService:connect',
76+
'BackendWebSocketService:disconnect',
77+
'BackendWebSocketService:isChannelSubscribed',
78+
'BackendWebSocketService:getSubscriptionByChannel',
79+
'BackendWebSocketService:findSubscriptionsByChannelPrefix',
80+
'BackendWebSocketService:addChannelCallback',
81+
'BackendWebSocketService:removeChannelCallback',
82+
'BackendWebSocketService:sendRequest',
7583
] as const;
7684

7785
// Allowed events that AccountActivityService can listen to
@@ -92,6 +100,38 @@ export type AccountActivityServiceAllowedActions =
92100
| {
93101
type: 'TokenBalancesController:updateBalances';
94102
handler: (options?: { chainIds?: string[]; queryAllAccounts?: boolean }) => Promise<void>;
103+
}
104+
| {
105+
type: 'BackendWebSocketService:connect';
106+
handler: () => Promise<void>;
107+
}
108+
| {
109+
type: 'BackendWebSocketService:disconnect';
110+
handler: () => Promise<void>;
111+
}
112+
| {
113+
type: 'BackendWebSocketService:isChannelSubscribed';
114+
handler: (channel: string) => boolean;
115+
}
116+
| {
117+
type: 'BackendWebSocketService:getSubscriptionByChannel';
118+
handler: (channel: string) => SubscriptionInfo | undefined;
119+
}
120+
| {
121+
type: 'BackendWebSocketService:findSubscriptionsByChannelPrefix';
122+
handler: (channelPrefix: string) => SubscriptionInfo[];
123+
}
124+
| {
125+
type: 'BackendWebSocketService:addChannelCallback';
126+
handler: (options: { channelName: string; callback: (notification: any) => void }) => void;
127+
}
128+
| {
129+
type: 'BackendWebSocketService:removeChannelCallback';
130+
handler: (channelName: string) => boolean;
131+
}
132+
| {
133+
type: 'BackendWebSocketService:sendRequest';
134+
handler: (message: any) => Promise<any>;
95135
};
96136

97137
// Event types for the messaging system
@@ -154,17 +194,16 @@ export type AccountActivityServiceMessenger = RestrictedMessenger<
154194
* - Comprehensive balance updates with transfer tracking
155195
*
156196
* Architecture:
157-
* - WebSocketService manages the actual WebSocket subscriptions and callbacks
158-
* - AccountActivityService only tracks channel-to-subscriptionId mappings
197+
* - Uses messenger pattern to communicate with BackendWebSocketService
198+
* - AccountActivityService tracks channel-to-subscriptionId mappings via messenger calls
159199
* - Automatically subscribes to selected account on initialization
160200
* - Switches subscriptions when selected account changes
161-
* - No duplication of subscription state between services
201+
* - No direct dependency on WebSocketService (uses messenger instead)
162202
*
163203
* @example
164204
* ```typescript
165205
* const service = new AccountActivityService({
166206
* messenger: activityMessenger,
167-
* webSocketService: wsService,
168207
* });
169208
*
170209
* // Service automatically subscribes to the currently selected account
@@ -183,26 +222,22 @@ export class AccountActivityService {
183222

184223
readonly #messenger: AccountActivityServiceMessenger;
185224

186-
readonly #webSocketService: WebSocketService;
187-
188225
readonly #options: Required<AccountActivityServiceOptions>;
189226

190-
// WebSocketService is the source of truth for subscription state
191-
// Using WebSocketService.findSubscriptionsByChannelPrefix() for cleanup
227+
// BackendWebSocketService is the source of truth for subscription state
228+
// Using BackendWebSocketService:findSubscriptionsByChannelPrefix() for cleanup
192229

193230
/**
194231
* Creates a new Account Activity service instance
195232
*
196-
* @param options - Configuration options including messenger and WebSocket service
233+
* @param options - Configuration options including messenger
197234
*/
198235
constructor(
199236
options: AccountActivityServiceOptions & {
200237
messenger: AccountActivityServiceMessenger;
201-
webSocketService: WebSocketService;
202238
},
203239
) {
204240
this.#messenger = options.messenger;
205-
this.#webSocketService = options.webSocketService;
206241

207242
// Set configuration with defaults
208243
this.#options = {
@@ -228,21 +263,21 @@ export class AccountActivityService {
228263
*/
229264
async subscribeAccounts(subscription: AccountSubscription): Promise<void> {
230265
try {
231-
await this.#webSocketService.connect();
266+
await this.#messenger.call('BackendWebSocketService:connect');
232267

233268
// Create channel name from address
234269
const channel = `${this.#options.subscriptionNamespace}.${subscription.address}`;
235270

236271
// Check if already subscribed
237-
if (this.#webSocketService.isChannelSubscribed(channel)) {
272+
if (this.#messenger.call('BackendWebSocketService:isChannelSubscribed', channel)) {
238273
console.log(`[${SERVICE_NAME}] Already subscribed to channel: ${channel}`);
239274
return;
240275
}
241276

242277
// Set up system notifications callback for chain status updates
243278
const systemChannelName = `system-notifications.v1.${this.#options.subscriptionNamespace}`;
244279
console.log(`[${SERVICE_NAME}] Adding channel callback for '${systemChannelName}'`);
245-
this.#webSocketService.addChannelCallback({
280+
this.#messenger.call('BackendWebSocketService:addChannelCallback', {
246281
channelName: systemChannelName,
247282
callback: (notification) => {
248283
try {
@@ -255,9 +290,26 @@ export class AccountActivityService {
255290
}
256291
});
257292

258-
// Create subscription with optimized callback routing
259-
await this.#webSocketService.subscribe({
260-
channels: [channel],
293+
// Create subscription using sendRequest since subscribe isn't exposed as messenger action
294+
const subscriptionResponse = await this.#messenger.call('BackendWebSocketService:sendRequest', {
295+
event: 'subscribe',
296+
data: { channels: [channel] },
297+
});
298+
299+
if (!subscriptionResponse?.subscriptionId) {
300+
throw new Error('Invalid subscription response: missing subscription ID');
301+
}
302+
303+
// Check for failures
304+
if (subscriptionResponse.failed && subscriptionResponse.failed.length > 0) {
305+
throw new Error(
306+
`Subscription failed for channels: ${subscriptionResponse.failed.join(', ')}`,
307+
);
308+
}
309+
310+
// Set up channel callback for direct processing of account activity updates
311+
this.#messenger.call('BackendWebSocketService:addChannelCallback', {
312+
channelName: channel,
261313
callback: (notification) => {
262314
// Fast path: Direct processing of account activity updates
263315
this.#handleAccountActivityUpdate(
@@ -283,7 +335,7 @@ export class AccountActivityService {
283335
// Find channel for the specified address
284336
const channel = `${this.#options.subscriptionNamespace}.${address}`;
285337
const subscriptionInfo =
286-
this.#webSocketService.getSubscriptionByChannel(channel);
338+
this.#messenger.call('BackendWebSocketService:getSubscriptionByChannel', channel);
287339

288340
if (!subscriptionInfo) {
289341
console.log(`[${SERVICE_NAME}] No subscription found for address: ${address}`);
@@ -429,7 +481,7 @@ export class AccountActivityService {
429481
const newChannel = `${this.#options.subscriptionNamespace}.${newAddress}`;
430482

431483
// If already subscribed to this account, no need to change
432-
if (this.#webSocketService.isChannelSubscribed(newChannel)) {
484+
if (this.#messenger.call('BackendWebSocketService:isChannelSubscribed', newChannel)) {
433485
console.log(`[${SERVICE_NAME}] Already subscribed to account: ${newAddress}`);
434486
return;
435487
}
@@ -467,8 +519,8 @@ export class AccountActivityService {
467519

468520
// All subscriptions will be cleaned up automatically on WebSocket disconnect
469521

470-
await this.#webSocketService.disconnect();
471-
await this.#webSocketService.connect();
522+
await this.#messenger.call('BackendWebSocketService:disconnect');
523+
await this.#messenger.call('BackendWebSocketService:connect');
472524
} catch (error) {
473525
console.error(`[${SERVICE_NAME}] Failed to force WebSocket reconnection:`, error);
474526
}
@@ -537,7 +589,7 @@ export class AccountActivityService {
537589
const channel = `${this.#options.subscriptionNamespace}.${address}`;
538590

539591
// Only subscribe if we're not already subscribed to this account
540-
if (!this.#webSocketService.isChannelSubscribed(channel)) {
592+
if (!this.#messenger.call('BackendWebSocketService:isChannelSubscribed', channel)) {
541593
await this.subscribeAccounts({ address });
542594
console.log(`[${SERVICE_NAME}] Successfully subscribed to selected account: ${address}`);
543595
} else {
@@ -558,7 +610,7 @@ export class AccountActivityService {
558610
console.log(`[${SERVICE_NAME}] Unsubscribing from all account activity subscriptions...`);
559611

560612
// Use WebSocketService to find all subscriptions with our namespace prefix
561-
const accountActivitySubscriptions = this.#webSocketService.findSubscriptionsByChannelPrefix(
613+
const accountActivitySubscriptions = this.#messenger.call('BackendWebSocketService:findSubscriptionsByChannelPrefix',
562614
this.#options.subscriptionNamespace
563615
);
564616

@@ -617,7 +669,7 @@ export class AccountActivityService {
617669
// We don't need to manually unsubscribe here for fast cleanup
618670

619671
// Clean up system notification callback
620-
this.#webSocketService.removeChannelCallback(`system-notifications.v1.${this.#options.subscriptionNamespace}`);
672+
this.#messenger.call('BackendWebSocketService:removeChannelCallback', `system-notifications.v1.${this.#options.subscriptionNamespace}`);
621673

622674
// Unregister action handlers to prevent stale references
623675
this.#messenger.unregisterActionHandler(

0 commit comments

Comments
 (0)