-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement cancel() and terminate() methods #4
Comments
|
Example implementation: const cancellableConnection = async (pool: DatabasePoolType, handler: (connection: DatabaseConnectionType, cancel: () => Promise<void>) => Promise<*>) => {
return pool.connect(async (connection0) => {
let done = false;
const backendProcessId = await connection0.oneFirst(sql`SELECT pg_backend_pid()`);
await pool.connect(async (connection1) => {
await handler(connection1, async () => {
if (done) {
return;
}
await connection1.query(sql`
SELECT pg_terminate_backend(${backendProcessId})
`);
});
done = true;
});
});
}; Used as: await cancellableConnection(target, (connection, cancel) => {
setTimeout(() => {
cancel();
}, 1000);
return connection.query(sql`SELECT pg_sleep(10)`);
}); |
A more correct implementation: const cancellableConnection = async (pool: DatabasePoolType, cancellableConnectionRoutine: CancellableConnectionRoutineType) => {
let done = false;
return pool.connect(async (connection0) => {
return pool.connect(async (connection1) => {
const backendProcessId = await connection1.oneFirst(sql`SELECT pg_backend_pid()`);
const cancel = () => {
if (done) {
return;
}
done = true;
connection0.query(sql`
SELECT pg_terminate_backend(${backendProcessId})
`)
.catch((error) => {
if (!(error instanceof BackendTerminatedError)) {
throw error;
}
});
};
let result;
try {
result = await cancellableConnectionRoutine(connection1, cancel);
done = true;
} catch (error) {
done = true;
throw error;
}
return result;
});
});
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
These methods would abstract the following patterns:
and
The design challenge:
pool.cancellableConnect((connection) => {})
.The text was updated successfully, but these errors were encountered: