Skip to content

Commit c2ec1b5

Browse files
committed
fix: optimize reg and dereg
1 parent f97007b commit c2ec1b5

File tree

3 files changed

+54
-34
lines changed

3 files changed

+54
-34
lines changed

components/client/typescript/README.md

+2-3
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ server helpers to handle all node interactions transparently.
4040
1. Create configuration objects for the local server and the Chainhook node you'll be interacting
4141
with
4242
```typescript
43-
import { ServerOptions, ChainhookNodeOptions } from "@hirosystems/chainhook-client/dist/server";
43+
import { ServerOptions, ChainhookNodeOptions } from "@hirosystems/chainhook-client";
4444
4545
// Local server options
4646
const opts: ServerOptions = {
@@ -54,8 +54,7 @@ server helpers to handle all node interactions transparently.
5454
5555
// Chainhook node options
5656
const chainhook: ChainhookNodeOptions = {
57-
hostname: "<node_hostname>",
58-
port: 20456
57+
base_url: "<node_base_url>"
5958
};
6059
```
6160

components/client/typescript/src/index.ts

+3
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,6 @@ export class ChainhookEventObserver {
4747
this.fastify = undefined;
4848
}
4949
}
50+
51+
export * from './server';
52+
export * from './schemas/payload';

components/client/typescript/src/server.ts

+49-31
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@ const ServerOptionsSchema = Type.Object({
2727
export type ServerOptions = Static<typeof ServerOptionsSchema>;
2828

2929
const ChainhookNodeOptionsSchema = Type.Object({
30-
hostname: Type.String(),
31-
port: Type.Integer(),
30+
base_url: Type.String(),
3231
});
3332
/** Chainhook node connection options */
3433
export type ChainhookNodeOptions = Static<typeof ChainhookNodeOptionsSchema>;
@@ -77,13 +76,13 @@ export async function buildServer(
7776
predicates: [ServerPredicate],
7877
callback: OnEventCallback
7978
) {
80-
const base_path = `http://${chainhookOpts.hostname}:${chainhookOpts.port}`;
81-
8279
async function waitForNode(this: FastifyInstance) {
83-
logger.info(`EventServer connecting to chainhook node at ${base_path}...`);
80+
logger.info(
81+
`ChainhookEventObserver connecting to chainhook node at ${chainhookOpts.base_url}...`
82+
);
8483
while (true) {
8584
try {
86-
await request(`${base_path}/ping`, { method: 'GET', throwOnError: true });
85+
await request(`${chainhookOpts.base_url}/ping`, { method: 'GET', throwOnError: true });
8786
break;
8887
} catch (error) {
8988
logger.error(error, 'Chainhook node not available, retrying...');
@@ -93,45 +92,64 @@ export async function buildServer(
9392
}
9493

9594
async function registerPredicates(this: FastifyInstance) {
96-
logger.info(predicates, `EventServer registering predicates at ${base_path}...`);
95+
logger.info(
96+
predicates,
97+
`ChainhookEventObserver registering predicates at ${chainhookOpts.base_url}`
98+
);
9799
for (const predicate of predicates) {
98100
const thenThat: ThenThatHttpPost = {
99101
http_post: {
100-
url: `${serverOpts.external_base_url}/chainhook/${predicate.uuid}`,
102+
url: `${serverOpts.external_base_url}/chainhook/${encodeURIComponent(predicate.uuid)}`,
101103
authorization_header: `Bearer ${serverOpts.auth_token}`,
102104
},
103105
};
104106
try {
105107
const body = predicate as Predicate;
106108
if ('mainnet' in body.networks) body.networks.mainnet.then_that = thenThat;
107109
if ('testnet' in body.networks) body.networks.testnet.then_that = thenThat;
108-
await request(`${base_path}/v1/chainhooks`, {
110+
await request(`${chainhookOpts.base_url}/v1/chainhooks`, {
109111
method: 'POST',
110112
body: JSON.stringify(body),
111113
headers: { 'content-type': 'application/json' },
112114
throwOnError: true,
113115
});
114-
logger.info(`EventServer registered '${predicate.name}' predicate (${predicate.uuid})`);
116+
logger.info(
117+
`ChainhookEventObserver registered '${predicate.name}' predicate (${predicate.uuid})`
118+
);
115119
} catch (error) {
116-
logger.error(error, `EventServer unable to register predicate`);
120+
logger.error(error, `ChainhookEventObserver unable to register predicate`);
117121
}
118122
}
119123
}
120124

121125
async function removePredicates(this: FastifyInstance) {
122-
logger.info(`EventServer closing predicates at ${base_path}...`);
123-
for (const predicate of predicates) {
124-
try {
125-
await request(`${base_path}/v1/chainhooks/${predicate.chain}/${predicate.uuid}`, {
126-
method: 'DELETE',
127-
headers: { 'content-type': 'application/json' },
128-
throwOnError: true,
129-
});
130-
logger.info(`EventServer removed '${predicate.name}' predicate (${predicate.uuid})`);
131-
} catch (error) {
132-
logger.error(error, `EventServer unable to deregister predicate`);
133-
}
134-
}
126+
logger.info(`ChainhookEventObserver closing predicates at ${chainhookOpts.base_url}`);
127+
const removals = predicates.map(
128+
predicate =>
129+
new Promise<void>((resolve, reject) => {
130+
request(
131+
`${chainhookOpts.base_url}/v1/chainhooks/${predicate.chain}/${encodeURIComponent(
132+
predicate.uuid
133+
)}`,
134+
{
135+
method: 'DELETE',
136+
headers: { 'content-type': 'application/json' },
137+
throwOnError: true,
138+
}
139+
)
140+
.then(() => {
141+
logger.info(
142+
`ChainhookEventObserver removed '${predicate.name}' predicate (${predicate.uuid})`
143+
);
144+
resolve();
145+
})
146+
.catch(error => {
147+
logger.error(error, `ChainhookEventObserver unable to deregister predicate`);
148+
reject(error);
149+
});
150+
})
151+
);
152+
await Promise.allSettled(removals);
135153
}
136154

137155
async function isEventAuthorized(request: FastifyRequest, reply: FastifyReply) {
@@ -142,11 +160,11 @@ export async function buildServer(
142160
await reply.code(403).send();
143161
}
144162

145-
const EventServer: FastifyPluginCallback<Record<never, never>, Server, TypeBoxTypeProvider> = (
146-
fastify,
147-
options,
148-
done
149-
) => {
163+
const ChainhookEventObserver: FastifyPluginCallback<
164+
Record<never, never>,
165+
Server,
166+
TypeBoxTypeProvider
167+
> = (fastify, options, done) => {
150168
fastify.addHook('preHandler', isEventAuthorized);
151169
fastify.post(
152170
'/chainhook/:uuid',
@@ -162,7 +180,7 @@ export async function buildServer(
162180
try {
163181
await callback(request.params.uuid, request.body);
164182
} catch (error) {
165-
logger.error(error, `EventServer error processing payload`);
183+
logger.error(error, `ChainhookEventObserver error processing payload`);
166184
await reply.code(422).send();
167185
}
168186
await reply.code(200).send();
@@ -182,6 +200,6 @@ export async function buildServer(
182200
fastify.addHook('onReady', registerPredicates);
183201
fastify.addHook('onClose', removePredicates);
184202

185-
await fastify.register(EventServer);
203+
await fastify.register(ChainhookEventObserver);
186204
return fastify;
187205
}

0 commit comments

Comments
 (0)