Skip to content

Commit d3ba3e6

Browse files
committed
Allow manually awaiting heartbeat events
In addition to the easy-to-use `heartbeat` function, the `Heartbeat` class is also exposed, allowing finer control to customers who might want to send the `start` and `finish` events independently from each other. Since the events are sent asynchronously, it makes sense to return the corresponding promise so that it can be awaited by the caller. However, since awaiting a rejected promise raises an error, and we strongly avoid causing AppSignal-related errors to be raised in customers' applications, the promise is overriden on rejection with an empty resolved promise, making it safe to await it.
1 parent b2cb8b1 commit d3ba3e6

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

src/heartbeat.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,12 @@ export class Heartbeat {
3838
await Heartbeat.heartbeatPromises.allSettled()
3939
}
4040

41-
public start() {
42-
this.transmit(this.event("start"))
41+
public start(): Promise<void> {
42+
return this.transmit(this.event("start"))
4343
}
4444

45-
public finish() {
46-
this.transmit(this.event("finish"))
45+
public finish(): Promise<void> {
46+
return this.transmit(this.event("finish"))
4747
}
4848

4949
private event(kind: EventKind): Event {
@@ -55,12 +55,12 @@ export class Heartbeat {
5555
}
5656
}
5757

58-
private transmit(event: Event) {
58+
private transmit(event: Event): Promise<void> {
5959
if (Client.client === undefined || !Client.client.isActive) {
6060
Client.internalLogger.debug(
61-
"AppSignal not started; not sending heartbeat"
61+
"AppSignal not active, not transmitting heartbeat event"
6262
)
63-
return
63+
return Promise.resolve()
6464
}
6565

6666
const promise = new Transmitter(
@@ -70,19 +70,27 @@ export class Heartbeat {
7070

7171
const handledPromise = promise
7272
.then(({ status }: { status: number }) => {
73-
if (status !== 200) {
73+
if (status >= 200 && status <= 299) {
74+
Client.internalLogger.trace(
75+
`Transmitted heartbeat \`${event.name}\` (${event.id}) ${event.kind} event`
76+
)
77+
} else {
7478
Client.internalLogger.warn(
75-
`Failed to transmit heartbeat: status code ${status}`
79+
`Failed to transmit heartbeat event: status code was ${status}`
7680
)
7781
}
7882
})
7983
.catch(({ error }: { error: Error }) => {
8084
Client.internalLogger.warn(
81-
`Failed to transmit heartbeat: ${error.message}`
85+
`Failed to transmit heartbeat event: ${error.message}`
8286
)
87+
88+
return Promise.resolve()
8389
})
8490

8591
Heartbeat.heartbeatPromises.add(handledPromise)
92+
93+
return handledPromise
8694
}
8795
}
8896

0 commit comments

Comments
 (0)