Skip to content

Commit

Permalink
Merge pull request #1707 from balena-io/update-balena-lint
Browse files Browse the repository at this point in the history
Update @balena/lint and fix warnings
  • Loading branch information
Page- authored Jul 10, 2024
2 parents 706a535 + b8249a7 commit e1681d6
Show file tree
Hide file tree
Showing 43 changed files with 189 additions and 140 deletions.
4 changes: 2 additions & 2 deletions init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,14 +213,14 @@ app.set('trust proxy', TRUST_PROXY);

const init = async () => {
try {
const generateConfig = (process.env.GENERATE_CONFIG || '').trim();
const generateConfig = (process.env.GENERATE_CONFIG ?? '').trim();
if (generateConfig.length > 0) {
await fs.writeFile(generateConfig, JSON.stringify(config, null, '\t'));
process.exit();
}

const doRunTests =
(process.env.RUN_TESTS || '').trim() === '1'
(process.env.RUN_TESTS ?? '').trim() === '1'
? await import('./test/test-lib/init-tests.js')
: undefined;

Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
"validator": "^13.12.0"
},
"devDependencies": {
"@balena/lint": "^8.0.2",
"@balena/lint": "^8.2.2",
"@types/chai": "^4.3.16",
"@types/mocha": "^10.0.7",
"@types/mockery": "^1.4.33",
Expand Down
2 changes: 1 addition & 1 deletion src/commands/dummy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Application } from 'express';

export async function execute(_app: Application, args: string[]) {
export function execute(_app: Application, args: string[]) {
// grab your args as an array, like so...
const [arg1] = args;

Expand Down
4 changes: 3 additions & 1 deletion src/features/cascade-delete/setup-delete-cascade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ import { addDeleteHookForDependents } from '../../infra/cascade-delete/index.js'
export const setupDeleteCascade = (
resource: string,
dependents: Parameters<typeof addDeleteHookForDependents>[2],
) => addDeleteHookForDependents('resin', resource, dependents);
) => {
addDeleteHookForDependents('resin', resource, dependents);
};
4 changes: 3 additions & 1 deletion src/features/contracts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,9 @@ export const startContractSynchronization = _.once(() => {
scheduleJob(
'contractSync',
'*/5 * * * *',
async () => await synchronizeContracts(contractRepos),
async () => {
await synchronizeContracts(contractRepos);
},
{
// The maximum expected amount of time that the job needs to complete
// and it should hold the lock to prevent other jobs from starting.
Expand Down
17 changes: 9 additions & 8 deletions src/features/device-heartbeat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export class DeviceOnlineStateManager extends EventEmitter<{

private readonly featureIsEnabled: boolean;

private isConsuming: boolean = false;
private isConsuming = false;
private rsmq: RedisSMQ;

public constructor() {
Expand All @@ -215,11 +215,11 @@ export class DeviceOnlineStateManager extends EventEmitter<{
throw err;
}
})
.then(() =>
.then(() => {
this.setupQueueStatsEmitter(
DeviceOnlineStateManager.QUEUE_STATS_INTERVAL_MSEC,
),
);
);
});
}

private setupQueueStatsEmitter(interval: number) {
Expand Down Expand Up @@ -301,7 +301,8 @@ export class DeviceOnlineStateManager extends EventEmitter<{
.then(async (msg) => {
if (!('id' in msg)) {
// no messages to consume, wait a second...
return await setTimeout(1000);
await setTimeout(1000);
return;
}

const { id, message } = msg;
Expand Down Expand Up @@ -358,12 +359,12 @@ export class DeviceOnlineStateManager extends EventEmitter<{
);
}
})
.catch((err: Error) =>
.catch((err: Error) => {
captureException(
err,
'An error occurred while consuming API heartbeat state queue',
),
)
);
})
.then(() => this.consume());

return null;
Expand Down
20 changes: 13 additions & 7 deletions src/features/device-logs/lib/backends/loki.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ async function assertLokiLogContext(

// Mutate so that we don't have to repeatedly amend the same context and instead cache it
(ctx as Writable<typeof ctx>).belongs_to__application =
device?.belongs_to__application!.__id;
device?.belongs_to__application?.__id;

return ctx as types.RequiredField<typeof ctx, 'belongs_to__application'>;
}
Expand Down Expand Up @@ -139,9 +139,7 @@ export class LokiBackend implements DeviceLogsBackend {
);
}

public get available(): boolean {
return true;
}
public readonly available = true;

/**
*
Expand Down Expand Up @@ -232,9 +230,17 @@ export class LokiBackend implements DeviceLogsBackend {
{
deadline: startAt + PUSH_TIMEOUT,
},
(err, response) => (err ? reject(err) : resolve(response)),
(err, response) => {
if (err) {
reject(err);
} else {
resolve(response);
}
},
);
}).finally(() => updateLokiPushDurationHistogram(Date.now() - startAt));
}).finally(() => {
updateLokiPushDurationHistogram(Date.now() - startAt);
});
}

public async subscribe($ctx: LogContext, subscription: Subscription) {
Expand Down Expand Up @@ -327,7 +333,7 @@ export class LokiBackend implements DeviceLogsBackend {
try {
return stream.getEntriesList().map((entry: loki.EntryAdapter) => {
const log = JSON.parse(entry.getLine());
const timestamp = entry.getTimestamp() as loki.Timestamp;
const timestamp = entry.getTimestamp()!;
log.nanoTimestamp =
BigInt(timestamp.getSeconds()) * 1000000000n +
BigInt(timestamp.getNanos());
Expand Down
19 changes: 8 additions & 11 deletions src/features/device-logs/lib/backends/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,38 +70,35 @@ export function setCurrentSubscriptions(value: number) {
metrics.gauge(names.api_device_logs_current_subscriptions, value);
}

export function incrementSubscriptionTotal(value: number = 1) {
export function incrementSubscriptionTotal(value = 1) {
metrics.counter(names.api_device_logs_subscription_total, value);
}

export function incrementPublishLogMessagesTotal(value: number = 1) {
export function incrementPublishLogMessagesTotal(value = 1) {
metrics.counter(names.api_device_logs_publish_log_messages_total, value);
}

export function incrementPublishLogMessagesDropped(value: number = 1) {
export function incrementPublishLogMessagesDropped(value = 1) {
metrics.counter(names.api_device_logs_publish_log_messages_dropped, value);
}

export function incrementPublishCallTotal(value: number = 1) {
export function incrementPublishCallTotal(value = 1) {
metrics.counter(names.api_device_logs_publish_call_total, value);
}

export function incrementPublishCallSuccessTotal(value: number = 1) {
export function incrementPublishCallSuccessTotal(value = 1) {
metrics.counter(names.api_device_logs_publish_call_success_total, value);
}

export function incrementPublishCallFailedTotal(value: number = 1) {
export function incrementPublishCallFailedTotal(value = 1) {
metrics.counter(names.api_device_logs_publish_call_failed_total, value);
}

export function incrementLokiPushTotal(value: number = 1) {
export function incrementLokiPushTotal(value = 1) {
metrics.counter(names.api_device_logs_loki_push_total, value);
}

export function incrementLokiPushErrorTotal(
errorCode: string,
value: number = 1,
) {
export function incrementLokiPushErrorTotal(errorCode: string, value = 1) {
metrics.counter(names.api_device_logs_loki_push_error_total, value, {
errorCode,
});
Expand Down
16 changes: 6 additions & 10 deletions src/features/device-logs/lib/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,9 @@ export const store: RequestHandler = async (req: Request, res: Response) => {
await Promise.all([
getBackend().publish(ctx, logs),
shouldPublishToLoki()
? (await getLokiBackend())
.publish(ctx, logs)
.catch((err) =>
captureException(err, 'Failed to publish logs to Loki'),
)
? (await getLokiBackend()).publish(ctx, logs).catch((err) => {
captureException(err, 'Failed to publish logs to Loki');
})
: undefined,
]);
}
Expand Down Expand Up @@ -150,11 +148,9 @@ const publishBackend = LOKI_ENABLED
) => {
const publishingToRedis = backend.publish(ctx, buffer);
const publishingToLoki = shouldPublishToLoki()
? (await getLokiBackend())
.publish(ctx, buffer)
.catch((err) =>
captureException(err, 'Failed to publish logs to Loki'),
)
? (await getLokiBackend()).publish(ctx, buffer).catch((err) => {
captureException(err, 'Failed to publish logs to Loki');
})
: undefined;
await Promise.all([publishingToRedis, publishingToLoki]);
}
Expand Down
4 changes: 3 additions & 1 deletion src/features/device-logs/lib/supervisor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export class Supervisor {

private isOldLog(log: any): log is OldSupervisorLog {
const old: OldSupervisorLog = log;
return !!(old.is_stderr || old.is_system || old.image_id);
return (
old.is_stderr != null || old.is_system != null || old.image_id != null
);
}
}
18 changes: 10 additions & 8 deletions src/features/device-proxy/device-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ const validateSupervisorResponse = (
try {
jsonBody = JSON.parse(body);
} catch (e) {
return badSupervisorResponse(req, res, filter, 'Invalid JSON data');
badSupervisorResponse(req, res, filter, 'Invalid JSON data');
return;
}
}
res.status(statusCode).json(jsonBody);
Expand Down Expand Up @@ -125,7 +126,8 @@ export const proxy = async (req: Request, res: Response) => {

const responses = await requestDevices({ url, req, filter, data, method });
if (responses.length === 1) {
return validateSupervisorResponse(responses[0], req, res, filter);
validateSupervisorResponse(responses[0], req, res, filter);
return;
}
res.status(207).json(multiResponse(responses));
} catch (err) {
Expand Down Expand Up @@ -162,20 +164,20 @@ async function requestDevices(
opts: RequestDevicesOpts & {
wait: false;
},
): Promise<void>;
): Promise<undefined>;
// This override is identical to the main form in order for `postDevices` to be able
// to call it with the generic form
async function requestDevices(
opts: RequestDevicesOpts,
): Promise<void | RequestResponse[]>;
): Promise<undefined | RequestResponse[]>;
async function requestDevices({
url,
filter,
data,
req,
wait = true,
method = 'POST',
}: RequestDevicesOpts): Promise<void | RequestResponse[]> {
}: RequestDevicesOpts): Promise<undefined | RequestResponse[]> {
if (url == null) {
throw new BadRequestError('You must specify a url to request!');
}
Expand Down Expand Up @@ -263,7 +265,7 @@ async function requestDevices({
vpnIp = `[${vpnIp}]`;
}
const deviceUrl = `http://${device.uuid}.balena:${
device.api_port || 80
device.api_port ?? 80
}${url}?apikey=${device.api_secret}`;
try {
return await requestAsync({
Expand Down Expand Up @@ -300,9 +302,9 @@ export async function postDevices(
opts: FixedMethodRequestDevicesOpts & {
wait: false;
},
): Promise<void>;
): Promise<undefined>;
export async function postDevices(
opts: FixedMethodRequestDevicesOpts,
): Promise<void | RequestResponse[]> {
): Promise<undefined | RequestResponse[]> {
return await requestDevices({ ...opts, method: 'POST' });
}
2 changes: 1 addition & 1 deletion src/features/device-types/storage/s3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export async function listFolders(
const objects = _(res.CommonPrefixes)
.map(({ Prefix }) => Prefix)
// only keep the folder paths (which are ending with `/`)
.filter((p): p is NonNullable<typeof p> => p != null && p.endsWith('/'))
.filter((p): p is NonNullable<typeof p> => p?.endsWith('/') === true)
.map((p) =>
// get the name of the immediately contained folder
path.basename(p),
Expand Down
2 changes: 2 additions & 0 deletions src/features/devices/hooks/defaults-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ hooks.addPureHook('POST', 'resin', 'device', {
if (request.values.is_pinned_on__release !== undefined) {
// Add an async boundary so that value updates,
// and doesn't remove the properties that we add.
// eslint-disable-next-line @typescript-eslint/await-thenable
await null;
request.values.should_be_running__release =
request.values.is_pinned_on__release;
Expand Down Expand Up @@ -87,6 +88,7 @@ hooks.addPureHook('PATCH', 'resin', 'device', {
if (request.values.is_pinned_on__release !== undefined) {
// Add an async boundary so that value updates,
// and doesn't remove the properties that we add.
// eslint-disable-next-line @typescript-eslint/await-thenable
await null;
request.values.should_be_running__release =
request.values.is_pinned_on__release;
Expand Down
17 changes: 10 additions & 7 deletions src/features/registry/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ export const basicApiKeyAuthenticate: RequestHandler = async (
res,
next,
) => {
const creds = BasicAuth.parse(req.headers['authorization']!);
if (creds) {
req.params.subject = creds.name;
req.params.apikey = creds.pass;
const authHeader = req.headers['authorization'];
if (authHeader != null) {
const creds = BasicAuth.parse(authHeader);
if (creds) {
req.params.subject = creds.name;
req.params.apikey = creds.pass;
}
}
if (req.params.apikey === TOKEN_AUTH_BUILDER_TOKEN) {
next();
Expand All @@ -47,9 +50,9 @@ export const basicApiKeyAuthenticate: RequestHandler = async (
req.user == null
) {
if (
req.headers['authorization'] ||
req.params['apikey'] ||
req.body['apikey'] ||
req.headers['authorization'] ??
req.params['apikey'] ??
req.body['apikey'] ??
req.query['apikey']
) {
throw new InvalidAuthProvidedError();
Expand Down
4 changes: 2 additions & 2 deletions src/features/registry/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,7 @@ const authorizeRequest = async (
};

const generateToken = (
subject: string = '',
subject = '',
audience: string,
access: Access[],
): string => {
Expand Down Expand Up @@ -597,7 +597,7 @@ export const token: RequestHandler = async (req, res) => {
]),
);
res.json({
token: generateToken(sub, REGISTRY2_HOST, access!),
token: generateToken(sub, REGISTRY2_HOST, access),
});
} catch (err) {
if (handleHttpErrors(req, res, err)) {
Expand Down
Loading

0 comments on commit e1681d6

Please sign in to comment.