Skip to content

Commit

Permalink
Add @typescript-eslint/no-floating-promises (#181456)
Browse files Browse the repository at this point in the history
Co-authored-by: kibanamachine <[email protected]>
Co-authored-by: Aleh Zasypkin <[email protected]>
Co-authored-by: Patrick Mueller <[email protected]>
  • Loading branch information
4 people authored May 1, 2024
1 parent 0288bb4 commit 593d391
Show file tree
Hide file tree
Showing 345 changed files with 1,664 additions and 1,430 deletions.
2 changes: 1 addition & 1 deletion examples/response_stream/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class ResponseStreamPlugin implements Plugin {
public setup(core: CoreSetup, plugins: ResponseStreamSetupPlugins) {
const router = core.http.createRouter<DataRequestHandlerContext>();

core.getStartServices().then(([_, depsStart]) => {
void core.getStartServices().then(([_, depsStart]) => {
defineReducerStreamRoute(router, this.logger);
defineSimpleStringStreamRoute(router, this.logger);
});
Expand Down
69 changes: 35 additions & 34 deletions examples/response_stream/server/routes/reducer_stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,44 +85,45 @@ export const defineReducerStreamRoute = (router: IRouter, logger: Logger) => {
let progress = 0;

async function pushStreamUpdate() {
setTimeout(() => {
try {
progress++;

if (progress > 100 || shouldStop) {
end();
return;
}

push(updateProgressAction(progress));

const randomEntity = entities[Math.floor(Math.random() * entities.length)];
const randomAction = actions[Math.floor(Math.random() * actions.length)];

if (randomAction === 'add') {
const randomCommits = Math.floor(Math.random() * 100);
push(addToEntityAction(randomEntity, randomCommits));
} else if (randomAction === 'delete') {
push(deleteEntityAction(randomEntity));
} else if (randomAction === 'throw-error') {
// Throw an error. It should not crash Kibana!
// It should be caught and logged to the Kibana server console.
throw new Error('There was a (simulated) server side error!');
} else if (randomAction === 'emit-error') {
// Emit an error as a stream action.
push(errorAction('(Simulated) error pushed to the stream'));
return;
}

pushStreamUpdate();
} catch (e) {
logger.error(e);
await new Promise((resolve) =>
setTimeout(resolve, Math.floor(Math.random() * maxTimeoutMs))
);
try {
progress++;

if (progress > 100 || shouldStop) {
end();
return;
}
}, Math.floor(Math.random() * maxTimeoutMs));

push(updateProgressAction(progress));

const randomEntity = entities[Math.floor(Math.random() * entities.length)];
const randomAction = actions[Math.floor(Math.random() * actions.length)];

if (randomAction === 'add') {
const randomCommits = Math.floor(Math.random() * 100);
push(addToEntityAction(randomEntity, randomCommits));
} else if (randomAction === 'delete') {
push(deleteEntityAction(randomEntity));
} else if (randomAction === 'throw-error') {
// Throw an error. It should not crash Kibana!
// It should be caught and logged to the Kibana server console.
throw new Error('There was a (simulated) server side error!');
} else if (randomAction === 'emit-error') {
// Emit an error as a stream action.
push(errorAction('(Simulated) error pushed to the stream'));
return;
}

void pushStreamUpdate();
} catch (e) {
logger.error(e);
}
}

// do not call this using `await` so it will run asynchronously while we return the stream already.
pushStreamUpdate();
void pushStreamUpdate();

return response.ok(responseWithHeaders);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const defineSimpleStringStreamRoute = (router: IRouter, logger: Logger) =
await timeout(Math.floor(Math.random() * maxTimeoutMs));

if (!shouldStop) {
pushStreamUpdate();
void pushStreamUpdate();
}
} else {
end();
Expand All @@ -78,7 +78,7 @@ export const defineSimpleStringStreamRoute = (router: IRouter, logger: Logger) =
}

// do not call this using `await` so it will run asynchronously while we return the stream already.
pushStreamUpdate();
void pushStreamUpdate();

return response.ok(responseWithHeaders);
}
Expand Down
2 changes: 1 addition & 1 deletion examples/search_examples/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class SearchExamplesPlugin
this.logger.debug('search_examples: Setup');
const router = core.http.createRouter<DataRequestHandlerContext>();

core.getStartServices().then(([_, depsStart]) => {
void core.getStartServices().then(([_, depsStart]) => {
const myStrategy = mySearchStrategyProvider(depsStart.data);
const fibonacciStrategy = fibonacciStrategyProvider();
deps.data.search.registerSearchStrategy('myStrategy', myStrategy);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ describe('Cookie based SessionStorage', () => {
await server.preboot(prebootDeps);
const { server: innerServer } = await server.setup(setupDeps);

expect(
await expect(
createCookieSessionStorageFactory(logger.get(), innerServer, {
...cookieOptions,
sameSite: 'None',
Expand Down
2 changes: 1 addition & 1 deletion src/core/server/integration_tests/http/oas.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ afterEach(async () => {

it('is disabled by default', async () => {
const server = await startService();
supertest(server.listener).get('/api/oas').expect(404);
await supertest(server.listener).get('/api/oas').expect(404);
});

it('handles requests when enabled', async () => {
Expand Down
6 changes: 3 additions & 3 deletions src/core/server/integration_tests/http/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,15 +333,15 @@ describe('Options', () => {
let i = 0;
const intervalId = setInterval(() => {
if (i < body.length) {
request.write(body[i++]);
void request.write(body[i++]);
} else {
clearInterval(intervalId);
request.end((err, res) => {
void request.end((err, res) => {
resolve(res);
});
}
}, interval);
request.on('error', (err) => {
void request.on('error', (err) => {
clearInterval(intervalId);
reject(err);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,13 @@ const setupBaseline = async () => {

// inject corrupt saved objects directly using esClient
await Promise.all(
savedObjects.map((savedObject) => {
savedObjects.map((savedObject) =>
client.create({
index: defaultKibanaIndex,
refresh: 'wait_for',
...savedObject,
});
})
})
)
);

return client;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ describe('migration actions', () => {
const redStatusResponse = await client.cluster.health({ index: 'red_then_yellow_index' });
expect(redStatusResponse.status).toBe('red');

client.indices.putSettings({
void client.indices.putSettings({
index: 'red_then_yellow_index',
body: {
// Enable all shard allocation so that the index status turns yellow
Expand Down Expand Up @@ -574,7 +574,7 @@ describe('migration actions', () => {

let indexGreen = false;
setTimeout(() => {
client.indices.putSettings({
void client.indices.putSettings({
index: 'clone_red_then_green_index',
body: {
// Enable all shard allocation so that the index status goes green
Expand Down Expand Up @@ -1844,7 +1844,7 @@ describe('migration actions', () => {
let indexYellow = false;

setTimeout(() => {
client.indices.putSettings({
void client.indices.putSettings({
index: 'red_then_yellow_index',
body: {
// Renable allocation so that the status becomes yellow
Expand Down Expand Up @@ -1897,7 +1897,7 @@ describe('migration actions', () => {
let indexGreen = false;

setTimeout(() => {
client.indices.putSettings({
void client.indices.putSettings({
index: 'yellow_then_green_index',
body: {
// Set 0 replican so that this index becomes green
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ export const runActionTestSuite = ({
const redStatusResponse = await client.cluster.health({ index: 'red_then_yellow_index' });
expect(redStatusResponse.status).toBe('red');

client.indices.putSettings({
void client.indices.putSettings({
index: 'red_then_yellow_index',
body: {
// Enable all shard allocation so that the index status turns yellow
Expand Down Expand Up @@ -619,7 +619,7 @@ export const runActionTestSuite = ({

let indexGreen = false;
setTimeout(() => {
client.indices.putSettings({
void client.indices.putSettings({
index: 'clone_red_then_green_index',
body: {
// Enable all shard allocation so that the index status goes green
Expand Down Expand Up @@ -1898,7 +1898,7 @@ export const runActionTestSuite = ({
let indexYellow = false;

setTimeout(() => {
client.indices.putSettings({
void client.indices.putSettings({
index: 'red_then_yellow_index',
body: {
// Renable allocation so that the status becomes yellow
Expand Down Expand Up @@ -1951,7 +1951,7 @@ export const runActionTestSuite = ({
let indexGreen = false;

setTimeout(() => {
client.indices.putSettings({
void client.indices.putSettings({
index: 'yellow_then_green_index',
body: {
// Set 0 replican so that this index becomes green
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import { createRoot } from '@kbn/core-test-helpers-kbn-server';
describe('SO default search fields', () => {
let root: ReturnType<typeof createRoot>;

afterEach(() => {
afterEach(async () => {
try {
root?.shutdown();
await root?.shutdown();
} catch (e) {
/* trap */
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,14 @@ describe.skip('when splitting .kibana into multiple indices and one clone fails'
});

// cause a failure when cloning .kibana_slow_clone_* indices
client.cluster.putSettings({ persistent: { 'cluster.max_shards_per_node': 15 } });
void client.cluster.putSettings({ persistent: { 'cluster.max_shards_per_node': 15 } });

await expect(runMigrationsWhichFailsWhenCloning()).rejects.toThrowError(
/cluster_shard_limit_exceeded/
);

// remove the failure
client.cluster.putSettings({ persistent: { 'cluster.max_shards_per_node': 20 } });
void client.cluster.putSettings({ persistent: { 'cluster.max_shards_per_node': 20 } });

const { runMigrations: runMigrations2ndTime } = await migratorTestKitFactory();
await runMigrations2ndTime();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,9 @@ const previouslyRegisteredTypes = [
describe('SO type registrations', () => {
let root: ReturnType<typeof createRoot>;

afterEach(() => {
afterEach(async () => {
try {
root?.shutdown();
await root?.shutdown();
} catch (e) {
/* trap */
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ describe('migration with waitForCompletion=true', () => {
await root.preboot();
await root.setup();

root.start();
void root.start();
const esClient = esServer.es.getClient();

await retryAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export const getEsClient = async ({

// configure logging system
const loggingConf = await firstValueFrom(configService.atPath<LoggingConfigType>('logging'));
loggingSystem.upgrade(loggingConf);
await loggingSystem.upgrade(loggingConf);

return await getElasticsearchClient(configService, loggerFactory, kibanaVersion);
};
Expand All @@ -148,7 +148,7 @@ export const getKibanaMigratorTestKit = async ({

// configure logging system
const loggingConf = await firstValueFrom(configService.atPath<LoggingConfigType>('logging'));
loggingSystem.upgrade(loggingConf);
await loggingSystem.upgrade(loggingConf);

const rawClient = await getElasticsearchClient(configService, loggerFactory, kibanaVersion);
const client = clientWrapperFactory ? clientWrapperFactory(rawClient) : rawClient;
Expand Down Expand Up @@ -568,7 +568,7 @@ export const getCurrentVersionTypeRegistry = async ({
await root.preboot();
const coreSetup = await root.setup();
const typeRegistry = coreSetup.savedObjects.getTypeRegistry();
root.shutdown(); // do not await for it, or we might block the tests
void root.shutdown(); // do not await for it, or we might block the tests
return typeRegistry;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ describe.skip('validates saved object types when a schema is provided', () => {
});

it('is superseded by migration errors and does not run if a migration fails', async () => {
expect(async () => {
await expect(async () => {
await savedObjectsClient.create(
'migration-error',
{
Expand Down Expand Up @@ -233,7 +233,7 @@ describe.skip('validates saved object types when a schema is provided', () => {

describe('when validating with a config schema', () => {
it('throws when an invalid attribute is provided', async () => {
expect(async () => {
await expect(async () => {
await savedObjectsClient.create(
'schema-using-kbn-config',
{
Expand Down
10 changes: 10 additions & 0 deletions src/dev/eslint/types.eslint.config.template.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,14 @@ module.exports = {
rules: {
'@typescript-eslint/consistent-type-exports': 'error',
},
overrides: [
{
files: ['server/**/*'],
rules: {
// Let's focus on server-side errors first to avoid server crashes.
// We'll tackle /public eventually.
'@typescript-eslint/no-floating-promises': 'error',
},
},
],
};
10 changes: 5 additions & 5 deletions src/plugins/content_management/server/core/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ describe('Content Core', () => {
{ title: 'Hello' },
{ id: '1234' } // We send this "id" option to specify the id of the content created
);
expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
contentTypeId: FOO_CONTENT_ID,
result: {
item: {
Expand All @@ -327,7 +327,7 @@ describe('Content Core', () => {

await fooContentCrud!.create(ctx, { title: 'Hello' }, { id: '1234' });
await fooContentCrud!.update(ctx, '1234', { title: 'changed' });
expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
contentTypeId: FOO_CONTENT_ID,
result: {
item: {
Expand Down Expand Up @@ -363,7 +363,7 @@ describe('Content Core', () => {
},
});

expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
contentTypeId: FOO_CONTENT_ID,
result: {
item: {
Expand All @@ -380,14 +380,14 @@ describe('Content Core', () => {
const { fooContentCrud, ctx, cleanUp } = setup({ registerFooType: true });

await fooContentCrud!.create(ctx, { title: 'Hello' }, { id: '1234' });
expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
contentTypeId: FOO_CONTENT_ID,
result: {
item: expect.any(Object),
},
});
await fooContentCrud!.delete(ctx, '1234');
expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
await expect(fooContentCrud!.get(ctx, '1234')).resolves.toEqual({
contentTypeId: FOO_CONTENT_ID,
result: {
item: undefined,
Expand Down
Loading

0 comments on commit 593d391

Please sign in to comment.