From bbf91840a52a1521cc7123187ac4b0ee7519afd9 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Sat, 18 Mar 2023 16:21:20 -0500 Subject: [PATCH 01/14] Added backend tests Signed-off-by: Andre Wanlin --- .changeset/shaggy-gorillas-occur.md | 5 + plugins/linguist-backend/api-report.md | 12 + .../20230216_remove_processed_date_default.js | 39 +++ .../src/api/LinguistBackendApi.test.ts | 309 +++++++++++++++++- .../src/api/LinguistBackendApi.ts | 17 +- .../src/db/LinguistBackendDatabase.test.ts | 169 ++++++++++ .../src/db/LinguistBackendDatabase.ts | 22 +- 7 files changed, 562 insertions(+), 11 deletions(-) create mode 100644 .changeset/shaggy-gorillas-occur.md create mode 100644 plugins/linguist-backend/migrations/20230216_remove_processed_date_default.js create mode 100644 plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts diff --git a/.changeset/shaggy-gorillas-occur.md b/.changeset/shaggy-gorillas-occur.md new file mode 100644 index 0000000000..c122032e7f --- /dev/null +++ b/.changeset/shaggy-gorillas-occur.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-linguist-backend': patch +--- + +Added tests for the `LinguistBackendDatabase` and `LinguistBackendApi` which included refactoring to better support using SQLite and removed the default from the `processes_date` column diff --git a/plugins/linguist-backend/api-report.md b/plugins/linguist-backend/api-report.md index a47f123ac4..ca36a1f816 100644 --- a/plugins/linguist-backend/api-report.md +++ b/plugins/linguist-backend/api-report.md @@ -3,6 +3,7 @@ > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts +import { EntitiesOverview } from '@backstage/plugin-linguist-common'; import { EntityResults } from '@backstage/plugin-linguist-common'; import express from 'express'; import { HumanDuration } from '@backstage/types'; @@ -13,6 +14,7 @@ import { PluginDatabaseManager } from '@backstage/backend-common'; import { PluginEndpointDiscovery } from '@backstage/backend-common'; import { PluginTaskScheduler } from '@backstage/backend-tasks'; import { ProcessedEntity } from '@backstage/plugin-linguist-common'; +import { Results } from 'linguist-js/dist/types'; import { TaskScheduleDefinition } from '@backstage/backend-tasks'; import { TokenManager } from '@backstage/backend-common'; import { UrlReader } from '@backstage/backend-common'; @@ -38,8 +40,18 @@ export class LinguistBackendApi { linguistJsOptions?: Record, ); // (undocumented) + addNewEntities(): Promise; + // (undocumented) + generateEntitiesLanguages(): Promise; + // (undocumented) + generateEntityLanguages(entityRef: string, url: string): Promise; + // (undocumented) + getEntitiesOverview(): Promise; + // (undocumented) getEntityLanguages(entityRef: string): Promise; // (undocumented) + getLinguistResults(dir: string): Promise; + // (undocumented) processEntities(): Promise; } diff --git a/plugins/linguist-backend/migrations/20230216_remove_processed_date_default.js b/plugins/linguist-backend/migrations/20230216_remove_processed_date_default.js new file mode 100644 index 0000000000..5aaf02216e --- /dev/null +++ b/plugins/linguist-backend/migrations/20230216_remove_processed_date_default.js @@ -0,0 +1,39 @@ +/* + * Copyright 2023 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @param {import('knex').Knex} knex + */ +exports.up = async function up(knex) { + // Sqlite does not support this raw SQL + if (!knex.client.config.client.includes('sqlite3')) { + await knex.raw( + 'ALTER TABLE entity_result ALTER COLUMN processed_date DROP DEFAULT;', + ); + } +}; + +/** + * @param {import('knex').Knex} knex + */ +exports.down = async function down(knex) { + // Sqlite does not support this raw SQL + if (!knex.client.config.client.includes('sqlite3')) { + await knex.raw( + 'ALTER TABLE entity_result ALTER COLUMN processed_date SET DEFAULT now();', + ); + } +}; diff --git a/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts b/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts index 741d52e734..baf7d27ad7 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts @@ -13,7 +13,49 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { kindOrDefault } from './LinguistBackendApi'; +import { + getVoidLogger, + PluginEndpointDiscovery, + ReadTreeResponse, + ServerTokenManager, + UrlReader, +} from '@backstage/backend-common'; +import { GetEntitiesResponse } from '@backstage/catalog-client'; +import { Results } from 'linguist-js/dist/types'; +import { DateTime } from 'luxon'; +import { LinguistBackendStore } from '../db'; +import { kindOrDefault, LinguistBackendApi } from './LinguistBackendApi'; +import fs from 'fs-extra'; + +const linguistResultMock = Promise.resolve({ + files: { + count: 4, + bytes: 6010, + results: { + '/src/index.ts': 'TypeScript', + '/src/cli.js': 'JavaScript', + '/readme.md': 'Markdown', + '/no-lang': null, + }, + }, + languages: { + count: 3, + bytes: 6000, + results: { + JavaScript: { type: 'programming', bytes: 1000, color: '#f1e05a' }, + TypeScript: { type: 'programming', bytes: 2000, color: '#2b7489' }, + Markdown: { type: 'prose', bytes: 3000, color: '#083fa1' }, + }, + }, + unknown: { + count: 1, + bytes: 10, + filenames: { + 'no-lang': 10, + }, + extensions: {}, + }, +} as Results); describe('kindOrDefault', () => { it('should return default kind when undefined', () => { @@ -26,3 +68,268 @@ describe('kindOrDefault', () => { expect(kindOrDefault(['API'])).toEqual(['API']); }); }); + +describe('Linguist backend API', () => { + const getEntitiesMock = jest.fn(); + jest.mock('@backstage/catalog-client', () => { + return { + CatalogClient: jest + .fn() + .mockImplementation(() => ({ getEntities: getEntitiesMock })), + }; + }); + + const logger = getVoidLogger(); + + const store: jest.Mocked = { + insertEntityResults: jest.fn(), + insertNewEntity: jest.fn(), + getEntityResults: jest.fn(), + getProcessedEntities: jest.fn(), + getUnprocessedEntities: jest.fn(), + }; + + const urlReader: jest.Mocked = { + readTree: jest.fn(), + search: jest.fn(), + readUrl: jest.fn(), + }; + + const discovery: jest.Mocked = { + getBaseUrl: jest.fn(), + getExternalBaseUrl: jest.fn(), + }; + + const tokenManager = ServerTokenManager.noop(); + + const api = new LinguistBackendApi( + logger, + store, + urlReader, + discovery, + tokenManager, + ); + + beforeEach(() => { + jest.resetAllMocks(); + }); + + it('should get languages for an entity', async () => { + store.getEntityResults.mockResolvedValue({ + languageCount: 1, + totalBytes: 2205, + processedDate: '2023-02-15T20:10:21.378Z', + breakdown: [ + { + name: 'YAML', + percentage: 100, + bytes: 2205, + type: 'data', + color: '#cb171e', + }, + ], + }); + + const entityRef = 'template:default/create-react-app-template'; + const languages = await api.getEntityLanguages(entityRef); + expect(languages).toEqual({ + languageCount: 1, + totalBytes: 2205, + processedDate: '2023-02-15T20:10:21.378Z', + breakdown: [ + { + name: 'YAML', + percentage: 100, + bytes: 2205, + type: 'data', + color: '#cb171e', + }, + ], + }); + }); + + it('should add new entities', async () => { + const testEntityListResponse: GetEntitiesResponse = { + items: [ + { + apiVersion: 'backstage.io/v1beta1', + metadata: { + name: 'service-one', + }, + kind: 'Component', + }, + { + apiVersion: 'backstage.io/v1beta1', + metadata: { + name: 'service-two', + }, + kind: 'Component', + }, + { + apiVersion: 'backstage.io/v1beta1', + metadata: { + name: 'service-three', + }, + kind: 'Component', + }, + ], + }; + getEntitiesMock.mockResolvedValue(testEntityListResponse); + + await api.addNewEntities(); + expect(store.insertNewEntity).toHaveBeenCalledTimes(3); + }); + + it('should get default entity overview', async () => { + store.getProcessedEntities.mockResolvedValue([ + { + entityRef: 'component:default/service-one', + processedDate: DateTime.now().toJSDate(), + }, + { + entityRef: 'component:default/stale-service-two', + processedDate: DateTime.now().minus({ days: 45 }).toJSDate(), + }, + ]); + + store.getUnprocessedEntities.mockResolvedValue([ + 'component:default/service-three', + 'component:default/service-four', + 'component:default/service-five', + ]); + + const overview = await api.getEntitiesOverview(); + expect(overview.entityCount).toEqual(5); + expect(overview.processedCount).toEqual(2); + expect(overview.staleCount).toEqual(0); + expect(overview.pendingCount).toEqual(3); + expect(overview.filteredEntities).toEqual([ + 'component:default/service-three', + 'component:default/service-four', + 'component:default/service-five', + ]); + }); + + it('should get entity overview with stale items', async () => { + const staleApi = new LinguistBackendApi( + logger, + store, + urlReader, + discovery, + tokenManager, + { days: 5 }, + ); + store.getProcessedEntities.mockResolvedValue([ + { + entityRef: 'component:default/service-one', + processedDate: DateTime.now().toJSDate(), + }, + { + entityRef: 'component:default/stale-service-two', + processedDate: DateTime.now().minus({ days: 45 }).toJSDate(), + }, + ]); + + store.getUnprocessedEntities.mockResolvedValue([ + 'component:default/service-three', + 'component:default/service-four', + 'component:default/service-five', + ]); + + const overview = await staleApi.getEntitiesOverview(); + expect(overview.entityCount).toEqual(5); + expect(overview.processedCount).toEqual(2); + expect(overview.staleCount).toEqual(1); + expect(overview.pendingCount).toEqual(4); + expect(overview.filteredEntities).toEqual([ + 'component:default/stale-service-two', + 'component:default/service-three', + 'component:default/service-four', + 'component:default/service-five', + ]); + }); + + it('should generate and save languages for an entity', async () => { + const spy = jest + .spyOn(api, 'getLinguistResults') + .mockImplementation(() => linguistResultMock); + + urlReader.readTree.mockResolvedValueOnce({ + files: async () => [ + { + content: async () => Buffer.from('-- XXX: code-data', 'utf8'), + path: 'my-file.js', + }, + ], + dir: async () => '/temp/my-code', + } as ReadTreeResponse); + + const fsSpy = jest.spyOn(fs, 'remove'); + + await api.generateEntityLanguages( + 'component:default/fake-service', + 'https://some.fake/service/', + ); + expect(api.getLinguistResults).toHaveBeenCalled(); + expect(store.insertEntityResults).toHaveBeenCalled(); + expect(fs.remove).toHaveBeenCalled(); + spy.mockClear(); + fsSpy.mockClear(); + }); + + it('should generate languages for multiple entities using default', async () => { + store.getProcessedEntities.mockResolvedValue([ + { + entityRef: 'component:default/service-one', + processedDate: DateTime.now().toJSDate(), + }, + { + entityRef: 'component:default/stale-service-two', + processedDate: DateTime.now().minus({ days: 45 }).toJSDate(), + }, + ]); + + store.getUnprocessedEntities.mockResolvedValue([ + 'component:default/service-three', + 'component:default/service-four', + 'component:default/service-five', + ]); + const generateEntityLanguages = jest.spyOn(api, 'generateEntityLanguages'); + await api.generateEntitiesLanguages(); + expect(generateEntityLanguages).toHaveBeenCalledTimes(3); + }); + + it('should generate languages for multiple entities using defined batch size', async () => { + const batchApi = new LinguistBackendApi( + logger, + store, + urlReader, + discovery, + tokenManager, + undefined, + 1, + ); + store.getProcessedEntities.mockResolvedValue([ + { + entityRef: 'component:default/service-one', + processedDate: DateTime.now().toJSDate(), + }, + { + entityRef: 'component:default/stale-service-two', + processedDate: DateTime.now().minus({ days: 45 }).toJSDate(), + }, + ]); + + store.getUnprocessedEntities.mockResolvedValue([ + 'component:default/service-three', + 'component:default/service-four', + 'component:default/service-five', + ]); + const generateEntityLanguages = jest.spyOn( + batchApi, + 'generateEntityLanguages', + ); + await batchApi.generateEntitiesLanguages(); + expect(generateEntityLanguages).toHaveBeenCalledTimes(1); + }); +}); diff --git a/plugins/linguist-backend/src/api/LinguistBackendApi.ts b/plugins/linguist-backend/src/api/LinguistBackendApi.ts index df7e30a7b0..766012018f 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendApi.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendApi.ts @@ -99,7 +99,7 @@ export class LinguistBackendApi { await this.generateEntitiesLanguages(); } - private async addNewEntities() { + public async addNewEntities() { const annotationKey = this.useSourceLocation ? ANNOTATION_SOURCE_LOCATION : LINGUIST_ANNOTATION; @@ -121,7 +121,7 @@ export class LinguistBackendApi { }); } - private async generateEntitiesLanguages() { + public async generateEntitiesLanguages() { const entitiesOverview = await this.getEntitiesOverview(); this.logger?.info( `Entities overview: Entity: ${entitiesOverview.entityCount}, Processed: ${entitiesOverview.processedCount}, Pending: ${entitiesOverview.pendingCount}, Stale ${entitiesOverview.staleCount}`, @@ -156,7 +156,7 @@ export class LinguistBackendApi { }); } - private async getEntitiesOverview(): Promise { + public async getEntitiesOverview(): Promise { this.logger?.debug('Getting pending entities'); const processedEntities = await this.store.getProcessedEntities(); @@ -172,7 +172,7 @@ export class LinguistBackendApi { const filteredEntities = staleEntities.concat(unprocessedEntities); const entitiesOverview: EntitiesOverview = { - entityCount: unprocessedEntities.length, + entityCount: unprocessedEntities.length + processedEntities.length, processedCount: processedEntities.length, staleCount: staleEntities.length, pendingCount: filteredEntities.length, @@ -182,7 +182,7 @@ export class LinguistBackendApi { return entitiesOverview; } - private async generateEntityLanguages( + public async generateEntityLanguages( entityRef: string, url: string, ): Promise { @@ -193,7 +193,7 @@ export class LinguistBackendApi { const readTreeResponse = await this.urlReader.readTree(url); const dir = await readTreeResponse.dir(); - const results = await linguist(dir, this.linguistJsOptions); + const results = await this.getLinguistResults(dir); try { const totalBytes = results.languages.bytes; @@ -233,6 +233,11 @@ export class LinguistBackendApi { await fs.remove(dir); } } + + public async getLinguistResults(dir: string) { + const results = await linguist(dir, this.linguistJsOptions); + return results; + } } export function kindOrDefault(kind?: string[]) { diff --git a/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts b/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts new file mode 100644 index 0000000000..f4e0bba627 --- /dev/null +++ b/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts @@ -0,0 +1,169 @@ +/* + * Copyright 2021 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Knex as KnexType, Knex } from 'knex'; +import { TestDatabases } from '@backstage/backend-test-utils'; +import { + LinguistBackendDatabase, + LinguistBackendStore, +} from './LinguistBackendDatabase'; +import { Languages, ProcessedEntity } from '@backstage/plugin-linguist-common'; + +function createDatabaseManager( + client: KnexType, + skipMigrations: boolean = false, +) { + return { + getClient: async () => client, + migrations: { + skip: skipMigrations, + }, + }; +} + +const rawDbEntityResultRows = [ + { + id: '14b32439-848a-49b2-92a4-98753f932606', + entity_ref: 'template:default/create-react-app-template', + languages: undefined, + processed_date: undefined, + }, + { + id: '8c85d3ec-ccea-4b29-9de9-ccdd7e5ba452', + entity_ref: 'template:default/docs-template', + languages: undefined, + processed_date: undefined, + }, + { + id: 'b922c87b-37bc-4505-b4af-70a1438decda', + entity_ref: 'template:default/pull-request', + languages: + '{"languageCount":1,"totalBytes":2205,"processedDate":"2023-02-15T20:10:21.378Z","breakdown":[{"name":"YAML","percentage":100,"bytes":2205,"type":"data","color":"#cb171e"}]}', + processed_date: new Date('2023-02-15 20:10:21.378Z'), + }, + { + id: 'bd555e6d-a3d0-4b48-a930-194db8f80db7', + entity_ref: 'template:default/react-ssr-template', + languages: + '{"languageCount":8,"totalBytes":8988,"processedDate":"2023-02-15T20:10:21.388Z","breakdown":[{"name":"INI","percentage":2.26,"bytes":203,"type":"data","color":"#d1dbe0"},{"name":"JavaScript","percentage":5.94,"bytes":534,"type":"programming","color":"#f1e05a"},{"name":"YAML","percentage":31.09,"bytes":2794,"type":"data","color":"#cb171e"},{"name":"Markdown","percentage":11.79,"bytes":1060,"type":"prose","color":"#083fa1"},{"name":"JSON","percentage":21.09,"bytes":1896,"type":"data","color":"#292929"},{"name":"CSS","percentage":0,"bytes":0,"type":"markup","color":"#563d7c"},{"name":"TSX","percentage":26.01,"bytes":2338,"type":"programming","color":"#3178c6"},{"name":"TypeScript","percentage":1.81,"bytes":163,"type":"programming","color":"#3178c6"}]}', + processed_date: new Date('2023-02-15 20:10:21.388Z'), + }, + { + id: '4145c0cf-44e9-4e95-9d57-781af4685b28', + entity_ref: 'template:default/springboot-template', + languages: + '{"languageCount":9,"totalBytes":80986,"processedDate":"2023-02-15T20:10:21.419Z","breakdown":[{"name":"Shell","percentage":0.16,"bytes":130,"type":"programming","color":"#89e051"},{"name":"INI","percentage":0.35,"bytes":286,"type":"data","color":"#d1dbe0"},{"name":"Dockerfile","percentage":0.3,"bytes":246,"type":"programming","color":"#384d54"},{"name":"YAML","percentage":3.92,"bytes":3171,"type":"data","color":"#cb171e"},{"name":"Markdown","percentage":1.31,"bytes":1059,"type":"prose","color":"#083fa1"},{"name":"XML","percentage":10.48,"bytes":8491,"type":"data","color":"#0060ac"},{"name":"Java","percentage":1.8,"bytes":1455,"type":"programming","color":"#b07219"},{"name":"Text","percentage":81.22,"bytes":65780,"type":"prose"},{"name":"Protocol Buffer","percentage":0.45,"bytes":368,"type":"data"}]}', + processed_date: new Date('2023-02-15 20:10:21.419Z'), + }, +]; + +describe('Linguist database', () => { + const databases = TestDatabases.create(); + let store: LinguistBackendStore; + let testDbClient: Knex; + beforeAll(async () => { + testDbClient = await databases.init('SQLITE_3'); + const database = createDatabaseManager(testDbClient); + + store = await LinguistBackendDatabase.create(await database.getClient()); + }); + beforeEach(async () => { + await testDbClient.batchInsert('entity_result', rawDbEntityResultRows); + }); + afterEach(async () => { + await testDbClient('entity_result').delete(); + }); + + it('should be able to return entity results', async () => { + const validLanguagesResult: Languages = { + languageCount: 1, + totalBytes: 2205, + processedDate: '2023-02-15T20:10:21.378Z', + breakdown: [ + { + name: 'YAML', + percentage: 100, + bytes: 2205, + type: 'data', + color: '#cb171e', + }, + ], + }; + + const entityResult = await store.getEntityResults( + 'template:default/pull-request', + ); + expect(entityResult).toMatchObject(validLanguagesResult); + }); + + it('should return empty entity results when not found', async () => { + const validEmptyLanguagesResult: Languages = { + languageCount: 0, + totalBytes: 0, + processedDate: 'undefined', + breakdown: [], + }; + + const entityResult = await store.getEntityResults( + 'template:default/create-react-app-template', + ); + expect(entityResult).toMatchObject(validEmptyLanguagesResult); + }); + + it('should be able to return unprocessed entities', async () => { + const validUnprocessedEntities: string[] = [ + 'template:default/create-react-app-template', + 'template:default/docs-template', + ]; + + const unprocessedEntities = await store.getUnprocessedEntities(); + + expect(unprocessedEntities).toMatchObject(validUnprocessedEntities); + }); + + it('should be able to return processed entities', async () => { + const validProcessedEntities: ProcessedEntity[] = [ + { + entityRef: 'template:default/pull-request', + processedDate: new Date('2023-02-15 20:10:21.378Z'), + }, + { + entityRef: 'template:default/react-ssr-template', + processedDate: new Date('2023-02-15 20:10:21.388Z'), + }, + { + entityRef: 'template:default/springboot-template', + processedDate: new Date('2023-02-15 20:10:21.419Z'), + }, + ]; + + const processedEntities = await store.getProcessedEntities(); + + expect(processedEntities).toMatchObject(validProcessedEntities); + }); + + it('should insert new entities and ignore duplicates', async () => { + const before = testDbClient.count('entity_result'); + + await store.insertNewEntity('component:/default/new-entity-one'); + await store.insertNewEntity('component:/default/new-entity-two'); + await store.insertNewEntity('template:default/pull-request'); + + const after = testDbClient.count('entity_result'); + + expect(before).toEqual(after); + }); +}); diff --git a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts index cf93374800..c045d0a4a9 100644 --- a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts +++ b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts @@ -26,8 +26,8 @@ import { export type RawDbEntityResultRow = { id: string; entity_ref: string; - languages: string; - processed_date: Date; + languages?: string; + processed_date?: Date; }; /** @public */ @@ -102,7 +102,7 @@ export class LinguistBackendDatabase implements LinguistBackendStore { } try { - return JSON.parse(entityResults.languages); + return JSON.parse(entityResults.languages as string); } catch (error) { throw new Error(`Failed to parse languages for '${entityRef}', ${error}`); } @@ -118,9 +118,20 @@ export class LinguistBackendDatabase implements LinguistBackendStore { } const processedEntities = rawEntities.map(rawEntity => { + // Note: processed_date should never be null, this is handled by the DB query above + let processedDate = new Date(); + if (rawEntity.processed_date) { + // SQLite will return a Timestamp whereas Postgres will return a proper Date + // This tests to see if we are getting a timestamp and convert if needed + processedDate = new Date(+rawEntity.processed_date.toString()); + if (isNaN(+rawEntity.processed_date.toString())) { + processedDate = rawEntity.processed_date; + } + } + const processEntity = { entityRef: rawEntity.entity_ref, - processedDate: rawEntity.processed_date, + processedDate: processedDate, }; return processEntity; @@ -131,6 +142,9 @@ export class LinguistBackendDatabase implements LinguistBackendStore { async getUnprocessedEntities(): Promise { const rawEntities = await this.db('entity_result') + // TODO(ahhhndre) processed_date should always be null as well but it had a default to the current date + // once the default has been removed and released, we can then come back an enable this check + // .whereNull('processed_date') .whereNull('languages') .orderBy('created_at', 'asc'); From 72b27b1bf6fb37023b86fe31815f4459660e9902 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Sat, 18 Mar 2023 17:09:04 -0500 Subject: [PATCH 02/14] Added backend-test-utils Signed-off-by: Andre Wanlin --- plugins/linguist-backend/package.json | 1 + yarn.lock | 1 + 2 files changed, 2 insertions(+) diff --git a/plugins/linguist-backend/package.json b/plugins/linguist-backend/package.json index f3feacb740..a559ec5222 100644 --- a/plugins/linguist-backend/package.json +++ b/plugins/linguist-backend/package.json @@ -44,6 +44,7 @@ "yn": "^4.0.0" }, "devDependencies": { + "@backstage/backend-test-utils": "workspace:^", "@backstage/cli": "workspace:^", "@types/supertest": "^2.0.8", "msw": "^1.0.0", diff --git a/yarn.lock b/yarn.lock index 977fcbf506..d12796c4e5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7573,6 +7573,7 @@ __metadata: dependencies: "@backstage/backend-common": "workspace:^" "@backstage/backend-tasks": "workspace:^" + "@backstage/backend-test-utils": "workspace:^" "@backstage/catalog-client": "workspace:^" "@backstage/catalog-model": "workspace:^" "@backstage/cli": "workspace:^" From 23fade04fd460d72470b3cc7f4482f8bf73dc198 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Sun, 26 Mar 2023 13:25:07 -0500 Subject: [PATCH 03/14] Completed tests Signed-off-by: Andre Wanlin --- plugins/linguist-backend/api-report.md | 3 +- .../src/api/LinguistBackendApi.test.ts | 117 +++++++++++++----- .../src/api/LinguistBackendApi.ts | 26 ++-- .../linguist-backend/src/service/router.ts | 5 +- 4 files changed, 106 insertions(+), 45 deletions(-) diff --git a/plugins/linguist-backend/api-report.md b/plugins/linguist-backend/api-report.md index ca36a1f816..907a48c50f 100644 --- a/plugins/linguist-backend/api-report.md +++ b/plugins/linguist-backend/api-report.md @@ -3,6 +3,7 @@ > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts +import { CatalogApi } from '@backstage/catalog-client'; import { EntitiesOverview } from '@backstage/plugin-linguist-common'; import { EntityResults } from '@backstage/plugin-linguist-common'; import express from 'express'; @@ -31,8 +32,8 @@ export class LinguistBackendApi { logger: Logger, store: LinguistBackendStore, urlReader: UrlReader, - discovery: PluginEndpointDiscovery, tokenManager: TokenManager, + catalogApi: CatalogApi, age?: HumanDuration, batchSize?: number, useSourceLocation?: boolean, diff --git a/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts b/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts index baf7d27ad7..b0f20f0207 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts @@ -13,19 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import { getVoidLogger, - PluginEndpointDiscovery, ReadTreeResponse, ServerTokenManager, UrlReader, } from '@backstage/backend-common'; -import { GetEntitiesResponse } from '@backstage/catalog-client'; +import { CatalogApi, GetEntitiesResponse } from '@backstage/catalog-client'; import { Results } from 'linguist-js/dist/types'; import { DateTime } from 'luxon'; import { LinguistBackendStore } from '../db'; import { kindOrDefault, LinguistBackendApi } from './LinguistBackendApi'; import fs from 'fs-extra'; +import { LINGUIST_ANNOTATION } from '@backstage/plugin-linguist-common'; const linguistResultMock = Promise.resolve({ files: { @@ -70,15 +71,6 @@ describe('kindOrDefault', () => { }); describe('Linguist backend API', () => { - const getEntitiesMock = jest.fn(); - jest.mock('@backstage/catalog-client', () => { - return { - CatalogClient: jest - .fn() - .mockImplementation(() => ({ getEntities: getEntitiesMock })), - }; - }); - const logger = getVoidLogger(); const store: jest.Mocked = { @@ -95,10 +87,10 @@ describe('Linguist backend API', () => { readUrl: jest.fn(), }; - const discovery: jest.Mocked = { - getBaseUrl: jest.fn(), - getExternalBaseUrl: jest.fn(), - }; + const catalogApi: jest.Mocked = { + getEntities: jest.fn(), + getEntityByRef: jest.fn(), + } as any; const tokenManager = ServerTokenManager.noop(); @@ -106,8 +98,8 @@ describe('Linguist backend API', () => { logger, store, urlReader, - discovery, tokenManager, + catalogApi, ); beforeEach(() => { @@ -174,7 +166,7 @@ describe('Linguist backend API', () => { }, ], }; - getEntitiesMock.mockResolvedValue(testEntityListResponse); + catalogApi.getEntities.mockResolvedValue(testEntityListResponse); await api.addNewEntities(); expect(store.insertNewEntity).toHaveBeenCalledTimes(3); @@ -211,12 +203,12 @@ describe('Linguist backend API', () => { }); it('should get entity overview with stale items', async () => { - const staleApi = new LinguistBackendApi( + const apiWithAge = new LinguistBackendApi( logger, store, urlReader, - discovery, tokenManager, + catalogApi, { days: 5 }, ); store.getProcessedEntities.mockResolvedValue([ @@ -236,7 +228,7 @@ describe('Linguist backend API', () => { 'component:default/service-five', ]); - const overview = await staleApi.getEntitiesOverview(); + const overview = await apiWithAge.getEntitiesOverview(); expect(overview.entityCount).toEqual(5); expect(overview.processedCount).toEqual(2); expect(overview.staleCount).toEqual(1); @@ -277,7 +269,7 @@ describe('Linguist backend API', () => { fsSpy.mockClear(); }); - it('should generate languages for multiple entities using default', async () => { + it('should generate languages for entities using default', async () => { store.getProcessedEntities.mockResolvedValue([ { entityRef: 'component:default/service-one', @@ -294,21 +286,56 @@ describe('Linguist backend API', () => { 'component:default/service-four', 'component:default/service-five', ]); + + const entity = { + apiVersion: 'backstage.io/v1beta1', + metadata: { + name: 'service-one', + annotations: { + [LINGUIST_ANNOTATION]: 'https://some.fake/service/', + }, + }, + kind: 'Component', + }; + + catalogApi.getEntityByRef.mockResolvedValue(entity); + + const resultsSpy = jest + .spyOn(api, 'getLinguistResults') + .mockImplementation(() => linguistResultMock); + + urlReader.readTree.mockResolvedValue({ + files: async () => [ + { + content: async () => Buffer.from('-- XXX: code-data', 'utf8'), + path: 'my-file.js', + }, + ], + dir: async () => '/temp/my-code', + } as ReadTreeResponse); + + const fsSpy = jest.spyOn(fs, 'remove'); + const generateEntityLanguages = jest.spyOn(api, 'generateEntityLanguages'); await api.generateEntitiesLanguages(); expect(generateEntityLanguages).toHaveBeenCalledTimes(3); + + generateEntityLanguages.mockClear(); + resultsSpy.mockClear(); + fsSpy.mockClear(); }); - it('should generate languages for multiple entities using defined batch size', async () => { - const batchApi = new LinguistBackendApi( + it('should generate languages for entities using defined batch size', async () => { + const apiWithBatchSize = new LinguistBackendApi( logger, store, urlReader, - discovery, tokenManager, + catalogApi, undefined, - 1, + 2, ); + store.getProcessedEntities.mockResolvedValue([ { entityRef: 'component:default/service-one', @@ -325,11 +352,45 @@ describe('Linguist backend API', () => { 'component:default/service-four', 'component:default/service-five', ]); + + const entity = { + apiVersion: 'backstage.io/v1beta1', + metadata: { + name: 'service-one', + annotations: { + [LINGUIST_ANNOTATION]: 'https://some.fake/service/', + }, + }, + kind: 'Component', + }; + + catalogApi.getEntityByRef.mockResolvedValue(entity); + + const resultsSpy = jest + .spyOn(apiWithBatchSize, 'getLinguistResults') + .mockImplementation(() => linguistResultMock); + + urlReader.readTree.mockResolvedValue({ + files: async () => [ + { + content: async () => Buffer.from('-- XXX: code-data', 'utf8'), + path: 'my-file.js', + }, + ], + dir: async () => '/temp/my-code', + } as ReadTreeResponse); + + const fsSpy = jest.spyOn(fs, 'remove'); + const generateEntityLanguages = jest.spyOn( - batchApi, + apiWithBatchSize, 'generateEntityLanguages', ); - await batchApi.generateEntitiesLanguages(); - expect(generateEntityLanguages).toHaveBeenCalledTimes(1); + await apiWithBatchSize.generateEntitiesLanguages(); + expect(generateEntityLanguages).toHaveBeenCalledTimes(2); + + generateEntityLanguages.mockClear(); + resultsSpy.mockClear(); + fsSpy.mockClear(); }); }); diff --git a/plugins/linguist-backend/src/api/LinguistBackendApi.ts b/plugins/linguist-backend/src/api/LinguistBackendApi.ts index 766012018f..f00aebcee1 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendApi.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendApi.ts @@ -22,14 +22,10 @@ import { } from '@backstage/plugin-linguist-common'; import { CATALOG_FILTER_EXISTS, - CatalogClient, GetEntitiesRequest, + CatalogApi, } from '@backstage/catalog-client'; -import { - PluginEndpointDiscovery, - TokenManager, - UrlReader, -} from '@backstage/backend-common'; +import { TokenManager, UrlReader } from '@backstage/backend-common'; import { DateTime } from 'luxon'; import { LINGUIST_ANNOTATION } from '@backstage/plugin-linguist-common'; @@ -49,10 +45,9 @@ export class LinguistBackendApi { private readonly logger: Logger; private readonly store: LinguistBackendStore; private readonly urlReader: UrlReader; - private readonly discovery: PluginEndpointDiscovery; private readonly tokenManager: TokenManager; - private readonly catalogClient: CatalogClient; + private readonly catalogApi: CatalogApi; private readonly age?: HumanDuration; private readonly batchSize?: number; private readonly useSourceLocation?: boolean; @@ -62,8 +57,8 @@ export class LinguistBackendApi { logger: Logger, store: LinguistBackendStore, urlReader: UrlReader, - discovery: PluginEndpointDiscovery, tokenManager: TokenManager, + catalogApi: CatalogApi, age?: HumanDuration, batchSize?: number, useSourceLocation?: boolean, @@ -73,9 +68,8 @@ export class LinguistBackendApi { this.logger = logger; this.store = store; this.urlReader = urlReader; - this.discovery = discovery; this.tokenManager = tokenManager; - this.catalogClient = new CatalogClient({ discoveryApi: this.discovery }); + this.catalogApi = catalogApi; this.batchSize = batchSize; this.age = age; this.useSourceLocation = useSourceLocation; @@ -112,7 +106,7 @@ export class LinguistBackendApi { }; const { token } = await this.tokenManager.getToken(); - const response = await this.catalogClient.getEntities(request, { token }); + const response = await this.catalogApi.getEntities(request, { token }); const entities = response.items; entities.forEach(entity => { @@ -131,9 +125,10 @@ export class LinguistBackendApi { 0, this.batchSize ?? 20, ); - entities.forEach(async entityRef => { + + for (const entityRef of entities) { const { token } = await this.tokenManager.getToken(); - const entity = await this.catalogClient.getEntityByRef(entityRef, { + const entity = await this.catalogApi.getEntityByRef(entityRef, { token, }); const annotationKey = this.useSourceLocation @@ -148,12 +143,13 @@ export class LinguistBackendApi { try { await this.generateEntityLanguages(entityRef, url); } catch (error) { + console.log(error); assertError(error); this.logger.error( `Unable to process "${entityRef}" using "${url}", message: ${error.message}, stack: ${error.stack}`, ); } - }); + } } public async getEntitiesOverview(): Promise { diff --git a/plugins/linguist-backend/src/service/router.ts b/plugins/linguist-backend/src/service/router.ts index 8d52a2e01d..4c636aa854 100644 --- a/plugins/linguist-backend/src/service/router.ts +++ b/plugins/linguist-backend/src/service/router.ts @@ -31,6 +31,7 @@ import { TaskScheduleDefinition, } from '@backstage/backend-tasks'; import { HumanDuration } from '@backstage/types'; +import { CatalogClient } from '@backstage/catalog-client'; /** @public */ export interface PluginOptions { @@ -74,14 +75,16 @@ export async function createRouter( await database.getClient(), ); + const catalogClient = new CatalogClient({ discoveryApi: discovery }); + const linguistBackendApi = routerOptions.linguistBackendApi || new LinguistBackendApi( logger, linguistBackendStore, reader, - discovery, tokenManager, + catalogClient, age, batchSize, useSourceLocation, From 4e08dda90960a5618c1ef7965497694fe8a03391 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Fri, 7 Apr 2023 08:07:39 -0500 Subject: [PATCH 04/14] Implemented interface for API Signed-off-by: Andre Wanlin --- plugins/linguist-backend/api-report.md | 22 ++++++-------- ....test.ts => LinguistBackendClient.test.ts} | 8 ++--- ...BackendApi.ts => LinguistBackendClient.ts} | 30 +++++++++++++------ plugins/linguist-backend/src/api/index.ts | 3 +- plugins/linguist-backend/src/index.ts | 3 +- .../src/service/router.test.ts | 2 +- .../linguist-backend/src/service/router.ts | 10 +++---- 7 files changed, 44 insertions(+), 34 deletions(-) rename plugins/linguist-backend/src/api/{LinguistBackendApi.test.ts => LinguistBackendClient.test.ts} (97%) rename plugins/linguist-backend/src/api/{LinguistBackendApi.ts => LinguistBackendClient.ts} (90%) diff --git a/plugins/linguist-backend/api-report.md b/plugins/linguist-backend/api-report.md index 907a48c50f..795271f46c 100644 --- a/plugins/linguist-backend/api-report.md +++ b/plugins/linguist-backend/api-report.md @@ -4,7 +4,6 @@ ```ts import { CatalogApi } from '@backstage/catalog-client'; -import { EntitiesOverview } from '@backstage/plugin-linguist-common'; import { EntityResults } from '@backstage/plugin-linguist-common'; import express from 'express'; import { HumanDuration } from '@backstage/types'; @@ -15,7 +14,6 @@ import { PluginDatabaseManager } from '@backstage/backend-common'; import { PluginEndpointDiscovery } from '@backstage/backend-common'; import { PluginTaskScheduler } from '@backstage/backend-tasks'; import { ProcessedEntity } from '@backstage/plugin-linguist-common'; -import { Results } from 'linguist-js/dist/types'; import { TaskScheduleDefinition } from '@backstage/backend-tasks'; import { TokenManager } from '@backstage/backend-common'; import { UrlReader } from '@backstage/backend-common'; @@ -27,7 +25,15 @@ export function createRouter( ): Promise; // @public (undocumented) -export class LinguistBackendApi { +export interface LinguistBackendApi { + // (undocumented) + getEntityLanguages(entityRef: string): Promise; + // (undocumented) + processEntities(): Promise; +} + +// @public (undocumented) +export class LinguistBackendClient implements LinguistBackendApi { constructor( logger: Logger, store: LinguistBackendStore, @@ -41,18 +47,8 @@ export class LinguistBackendApi { linguistJsOptions?: Record, ); // (undocumented) - addNewEntities(): Promise; - // (undocumented) - generateEntitiesLanguages(): Promise; - // (undocumented) - generateEntityLanguages(entityRef: string, url: string): Promise; - // (undocumented) - getEntitiesOverview(): Promise; - // (undocumented) getEntityLanguages(entityRef: string): Promise; // (undocumented) - getLinguistResults(dir: string): Promise; - // (undocumented) processEntities(): Promise; } diff --git a/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts b/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts similarity index 97% rename from plugins/linguist-backend/src/api/LinguistBackendApi.test.ts rename to plugins/linguist-backend/src/api/LinguistBackendClient.test.ts index b0f20f0207..58aae70106 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendApi.test.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts @@ -24,7 +24,7 @@ import { CatalogApi, GetEntitiesResponse } from '@backstage/catalog-client'; import { Results } from 'linguist-js/dist/types'; import { DateTime } from 'luxon'; import { LinguistBackendStore } from '../db'; -import { kindOrDefault, LinguistBackendApi } from './LinguistBackendApi'; +import { kindOrDefault, LinguistBackendClient } from './LinguistBackendClient'; import fs from 'fs-extra'; import { LINGUIST_ANNOTATION } from '@backstage/plugin-linguist-common'; @@ -94,7 +94,7 @@ describe('Linguist backend API', () => { const tokenManager = ServerTokenManager.noop(); - const api = new LinguistBackendApi( + const api = new LinguistBackendClient( logger, store, urlReader, @@ -203,7 +203,7 @@ describe('Linguist backend API', () => { }); it('should get entity overview with stale items', async () => { - const apiWithAge = new LinguistBackendApi( + const apiWithAge = new LinguistBackendClient( logger, store, urlReader, @@ -326,7 +326,7 @@ describe('Linguist backend API', () => { }); it('should generate languages for entities using defined batch size', async () => { - const apiWithBatchSize = new LinguistBackendApi( + const apiWithBatchSize = new LinguistBackendClient( logger, store, urlReader, diff --git a/plugins/linguist-backend/src/api/LinguistBackendApi.ts b/plugins/linguist-backend/src/api/LinguistBackendClient.ts similarity index 90% rename from plugins/linguist-backend/src/api/LinguistBackendApi.ts rename to plugins/linguist-backend/src/api/LinguistBackendClient.ts index f00aebcee1..890e6438b2 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendApi.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendClient.ts @@ -39,9 +39,16 @@ import { } from '@backstage/catalog-model'; import { assertError } from '@backstage/errors'; import { HumanDuration } from '@backstage/types'; +import { Results } from 'linguist-js/dist/types'; /** @public */ -export class LinguistBackendApi { +export interface LinguistBackendApi { + getEntityLanguages(entityRef: string): Promise; + processEntities(): Promise; +} + +/** @public */ +export class LinguistBackendClient implements LinguistBackendApi { private readonly logger: Logger; private readonly store: LinguistBackendStore; private readonly urlReader: UrlReader; @@ -77,13 +84,13 @@ export class LinguistBackendApi { this.linguistJsOptions = linguistJsOptions; } - public async getEntityLanguages(entityRef: string): Promise { + async getEntityLanguages(entityRef: string): Promise { this.logger?.debug(`Getting languages for entity "${entityRef}"`); return this.store.getEntityResults(entityRef); } - public async processEntities() { + async processEntities(): Promise { this.logger?.info('Updating list of entities'); await this.addNewEntities(); @@ -93,7 +100,8 @@ export class LinguistBackendApi { await this.generateEntitiesLanguages(); } - public async addNewEntities() { + /** @internal */ + async addNewEntities(): Promise { const annotationKey = this.useSourceLocation ? ANNOTATION_SOURCE_LOCATION : LINGUIST_ANNOTATION; @@ -115,7 +123,8 @@ export class LinguistBackendApi { }); } - public async generateEntitiesLanguages() { + /** @internal */ + async generateEntitiesLanguages(): Promise { const entitiesOverview = await this.getEntitiesOverview(); this.logger?.info( `Entities overview: Entity: ${entitiesOverview.entityCount}, Processed: ${entitiesOverview.processedCount}, Pending: ${entitiesOverview.pendingCount}, Stale ${entitiesOverview.staleCount}`, @@ -152,7 +161,8 @@ export class LinguistBackendApi { } } - public async getEntitiesOverview(): Promise { + /** @internal */ + async getEntitiesOverview(): Promise { this.logger?.debug('Getting pending entities'); const processedEntities = await this.store.getProcessedEntities(); @@ -178,7 +188,8 @@ export class LinguistBackendApi { return entitiesOverview; } - public async generateEntityLanguages( + /** @internal */ + async generateEntityLanguages( entityRef: string, url: string, ): Promise { @@ -230,13 +241,14 @@ export class LinguistBackendApi { } } - public async getLinguistResults(dir: string) { + /** @internal */ + async getLinguistResults(dir: string): Promise { const results = await linguist(dir, this.linguistJsOptions); return results; } } -export function kindOrDefault(kind?: string[]) { +export function kindOrDefault(kind?: string[]): string[] { if (!kind || kind.length === 0) { return ['API', 'Component', 'Template']; } diff --git a/plugins/linguist-backend/src/api/index.ts b/plugins/linguist-backend/src/api/index.ts index a88fa051d4..53b427b3a7 100644 --- a/plugins/linguist-backend/src/api/index.ts +++ b/plugins/linguist-backend/src/api/index.ts @@ -14,4 +14,5 @@ * limitations under the License. */ -export { LinguistBackendApi } from './LinguistBackendApi'; +export { LinguistBackendClient } from './LinguistBackendClient'; +export type { LinguistBackendApi } from './LinguistBackendClient'; diff --git a/plugins/linguist-backend/src/index.ts b/plugins/linguist-backend/src/index.ts index da1e0ffb00..8969880618 100644 --- a/plugins/linguist-backend/src/index.ts +++ b/plugins/linguist-backend/src/index.ts @@ -15,6 +15,7 @@ */ export * from './service/router'; -export { LinguistBackendApi } from './api'; +export { LinguistBackendClient } from './api'; +export type { LinguistBackendApi } from './api'; export { LinguistBackendDatabase } from './db'; export type { LinguistBackendStore } from './db'; diff --git a/plugins/linguist-backend/src/service/router.test.ts b/plugins/linguist-backend/src/service/router.test.ts index b8bde9d35d..7ab8f1c238 100644 --- a/plugins/linguist-backend/src/service/router.test.ts +++ b/plugins/linguist-backend/src/service/router.test.ts @@ -73,7 +73,7 @@ describe('createRouter', () => { const router = await createRouter( { schedule: schedule, age: { days: 30 }, useSourceLocation: false }, { - linguistBackendApi, + linguistBackendApi: linguistBackendApi, discovery: testDiscovery, database: createDatabase(), reader: mockUrlReader, diff --git a/plugins/linguist-backend/src/service/router.ts b/plugins/linguist-backend/src/service/router.ts index 4c636aa854..21f03e08a3 100644 --- a/plugins/linguist-backend/src/service/router.ts +++ b/plugins/linguist-backend/src/service/router.ts @@ -24,7 +24,7 @@ import { import express from 'express'; import Router from 'express-promise-router'; import { Logger } from 'winston'; -import { LinguistBackendApi } from '../api'; +import { LinguistBackendApi, LinguistBackendClient } from '../api'; import { LinguistBackendDatabase } from '../db'; import { PluginTaskScheduler, @@ -77,9 +77,9 @@ export async function createRouter( const catalogClient = new CatalogClient({ discoveryApi: discovery }); - const linguistBackendApi = + const linguistBackendClient = routerOptions.linguistBackendApi || - new LinguistBackendApi( + new LinguistBackendClient( logger, linguistBackendStore, reader, @@ -103,7 +103,7 @@ export async function createRouter( initialDelay: schedule.initialDelay, scope: schedule.scope, fn: async () => { - await linguistBackendApi.processEntities(); + await linguistBackendClient.processEntities(); }, }); } @@ -125,7 +125,7 @@ export async function createRouter( throw new Error('No entityRef was provided'); } - const entityLanguages = await linguistBackendApi.getEntityLanguages( + const entityLanguages = await linguistBackendClient.getEntityLanguages( entityRef as string, ); res.status(200).json(entityLanguages); From 763bf4c8f29de23d9ccef692981f7ec1ffb60d3e Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Fri, 7 Apr 2023 08:07:51 -0500 Subject: [PATCH 05/14] Refactored README Signed-off-by: Andre Wanlin --- plugins/linguist-backend/README.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/plugins/linguist-backend/README.md b/plugins/linguist-backend/README.md index 46c067fb5a..c1201fc70a 100644 --- a/plugins/linguist-backend/README.md +++ b/plugins/linguist-backend/README.md @@ -57,7 +57,11 @@ Here's how to get the backend up and running: 4. Now run `yarn start-backend` from the repo root 5. Finally open `http://localhost:7007/api/linguist/health` in a browser and it should return `{"status":"ok"}` -## Batch Size +## Plugin Option + +The Linguist backend has various plugin options that you can provide to the `createRouter` function in your `packages/backend/src/plugins/linguist.ts` file that will allow you to configure various aspects of how it works. The following sections go into the details of these options + +### Batch Size The Linguist backend is setup to process entities by acting as a queue where it will pull down all the applicable entities from the Catalog and add them to it's database (saving just the `entityRef`). Then it will grab the `n` oldest entities that have not been processed to determine their languages and process them. To control the batch size simply provide that to the `createRouter` function in your `packages/backend/src/plugins/linguist.ts` like this: @@ -67,7 +71,7 @@ return createRouter({ schedule: schedule, batchSize: 40 }, { ...env }); **Note:** The default batch size is 20 -## Kind +### Kind The default setup only processes entities of kind `['API', 'Component', 'Template']`. To control the `kind` that are processed provide that to the `createRouter` function in your `packages/backend/src/plugins/linguist.ts` like this: @@ -75,7 +79,7 @@ The default setup only processes entities of kind `['API', 'Component', 'Templat return createRouter({ schedule: schedule, kind: ['Component'] }, { ...env }); ``` -## Refresh +### Refresh The default setup will only generate the language breakdown for entities with the linguist annotation that have not been generated yet. If you want this process to also refresh the data you can do so by adding the `age` (as a `HumanDuration`) in your `packages/backend/src/plugins/linguist.ts` when you call `createRouter`: @@ -85,7 +89,7 @@ return createRouter({ schedule: schedule, age: { days: 30 } }, { ...env }); With the `age` setup like this if the language breakdown is older than 15 days it will get regenerated. It's recommended that if you choose to use this configuration to set it to a large value - 30, 90, or 180 - as this data generally does not change drastically. -## Linguist JS options +### Linguist JS options The default setup will use the default [linguist-js](https://www.npmjs.com/package/linguist-js) options, a full list of the available options can be found [here](https://www.npmjs.com/package/linguist-js#API). @@ -96,7 +100,7 @@ return createRouter( ); ``` -## Use Source Location +### Use Source Location You may wish to use the `backstage.io/source-location` annotation over using the `backstage.io/linguist` as you may not be able to quickly add that annotation to your Entities. To do this you'll just need to set the `useSourceLocation` boolean to `true` in your `packages/backend/src/plugins/linguist.ts` when you call `createRouter`: From 9febc291d62339a5e61827f5a2a591f1baa4a175 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Fri, 7 Apr 2023 11:14:04 -0500 Subject: [PATCH 06/14] Unprocessed should be processed before stale Signed-off-by: Andre Wanlin --- plugins/linguist-backend/api-report.md | 8 ++++---- .../src/api/LinguistBackendClient.test.ts | 2 +- .../src/api/LinguistBackendClient.ts | 2 +- .../src/db/LinguistBackendDatabase.test.ts | 14 ++++++++++++++ .../src/db/LinguistBackendDatabase.ts | 8 ++++---- 5 files changed, 24 insertions(+), 10 deletions(-) diff --git a/plugins/linguist-backend/api-report.md b/plugins/linguist-backend/api-report.md index 795271f46c..8b17b997dd 100644 --- a/plugins/linguist-backend/api-report.md +++ b/plugins/linguist-backend/api-report.md @@ -60,9 +60,9 @@ export class LinguistBackendDatabase implements LinguistBackendStore { // (undocumented) getEntityResults(entityRef: string): Promise; // (undocumented) - getProcessedEntities(): Promise; + getProcessedEntities(): Promise; // (undocumented) - getUnprocessedEntities(): Promise; + getUnprocessedEntities(): Promise; // (undocumented) insertEntityResults(entityLanguages: EntityResults): Promise; // (undocumented) @@ -74,9 +74,9 @@ export interface LinguistBackendStore { // (undocumented) getEntityResults(entityRef: string): Promise; // (undocumented) - getProcessedEntities(): Promise; + getProcessedEntities(): Promise; // (undocumented) - getUnprocessedEntities(): Promise; + getUnprocessedEntities(): Promise; // (undocumented) insertEntityResults(entityLanguages: EntityResults): Promise; // (undocumented) diff --git a/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts b/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts index 58aae70106..35336bb5e9 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts @@ -234,10 +234,10 @@ describe('Linguist backend API', () => { expect(overview.staleCount).toEqual(1); expect(overview.pendingCount).toEqual(4); expect(overview.filteredEntities).toEqual([ - 'component:default/stale-service-two', 'component:default/service-three', 'component:default/service-four', 'component:default/service-five', + 'component:default/stale-service-two', ]); }); diff --git a/plugins/linguist-backend/src/api/LinguistBackendClient.ts b/plugins/linguist-backend/src/api/LinguistBackendClient.ts index 890e6438b2..a2f6e1ef67 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendClient.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendClient.ts @@ -175,7 +175,7 @@ export class LinguistBackendClient implements LinguistBackendApi { .map(pe => pe.entityRef); const unprocessedEntities = await this.store.getUnprocessedEntities(); - const filteredEntities = staleEntities.concat(unprocessedEntities); + const filteredEntities = unprocessedEntities.concat(staleEntities); const entitiesOverview: EntitiesOverview = { entityCount: unprocessedEntities.length + processedEntities.length, diff --git a/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts b/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts index f4e0bba627..1ab092b953 100644 --- a/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts +++ b/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts @@ -134,6 +134,13 @@ describe('Linguist database', () => { expect(unprocessedEntities).toMatchObject(validUnprocessedEntities); }); + it('should return string[] when there is no unprocessed entities', async () => { + await testDbClient('entity_result').delete(); + const unprocessedEntities = await store.getUnprocessedEntities(); + + expect(unprocessedEntities).toMatchObject([]); + }); + it('should be able to return processed entities', async () => { const validProcessedEntities: ProcessedEntity[] = [ { @@ -155,6 +162,13 @@ describe('Linguist database', () => { expect(processedEntities).toMatchObject(validProcessedEntities); }); + it('should return string[] when there is no processed entities', async () => { + await testDbClient('entity_result').delete(); + const unprocessedEntities = await store.getProcessedEntities(); + + expect(unprocessedEntities).toMatchObject([]); + }); + it('should insert new entities and ignore duplicates', async () => { const before = testDbClient.count('entity_result'); diff --git a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts index c045d0a4a9..5a165695da 100644 --- a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts +++ b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts @@ -35,8 +35,8 @@ export interface LinguistBackendStore { insertEntityResults(entityLanguages: EntityResults): Promise; insertNewEntity(entityRef: string): Promise; getEntityResults(entityRef: string): Promise; - getProcessedEntities(): Promise; - getUnprocessedEntities(): Promise; + getProcessedEntities(): Promise; + getUnprocessedEntities(): Promise; } const migrationsDir = resolvePackagePath( @@ -108,7 +108,7 @@ export class LinguistBackendDatabase implements LinguistBackendStore { } } - async getProcessedEntities(): Promise { + async getProcessedEntities(): Promise { const rawEntities = await this.db('entity_result') .whereNotNull('processed_date') .whereNotNull('languages'); @@ -140,7 +140,7 @@ export class LinguistBackendDatabase implements LinguistBackendStore { return processedEntities; } - async getUnprocessedEntities(): Promise { + async getUnprocessedEntities(): Promise { const rawEntities = await this.db('entity_result') // TODO(ahhhndre) processed_date should always be null as well but it had a default to the current date // once the default has been removed and released, we can then come back an enable this check From 25659d38d6486019a167eb4c57f454c03d711e3d Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Fri, 7 Apr 2023 11:27:20 -0500 Subject: [PATCH 07/14] Clean up orphan entities Signed-off-by: Andre Wanlin --- plugins/linguist-backend/api-report.md | 8 +++++++ .../src/api/LinguistBackendClient.test.ts | 22 ++++++++++++++++++- .../src/api/LinguistBackendClient.ts | 22 +++++++++++++++++-- .../src/db/LinguistBackendDatabase.test.ts | 21 ++++++++++++++++-- .../src/db/LinguistBackendDatabase.ts | 22 +++++++++++++++++++ 5 files changed, 90 insertions(+), 5 deletions(-) diff --git a/plugins/linguist-backend/api-report.md b/plugins/linguist-backend/api-report.md index 8b17b997dd..1b2c4af832 100644 --- a/plugins/linguist-backend/api-report.md +++ b/plugins/linguist-backend/api-report.md @@ -58,6 +58,10 @@ export class LinguistBackendDatabase implements LinguistBackendStore { // (undocumented) static create(knex: Knex): Promise; // (undocumented) + deleteEntity(entityRef: string): Promise; + // (undocumented) + getAllEntities(): Promise; + // (undocumented) getEntityResults(entityRef: string): Promise; // (undocumented) getProcessedEntities(): Promise; @@ -71,6 +75,10 @@ export class LinguistBackendDatabase implements LinguistBackendStore { // @public (undocumented) export interface LinguistBackendStore { + // (undocumented) + deleteEntity(entityRef: string): Promise; + // (undocumented) + getAllEntities(): Promise; // (undocumented) getEntityResults(entityRef: string): Promise; // (undocumented) diff --git a/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts b/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts index 35336bb5e9..1b0a4f4673 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendClient.test.ts @@ -79,6 +79,8 @@ describe('Linguist backend API', () => { getEntityResults: jest.fn(), getProcessedEntities: jest.fn(), getUnprocessedEntities: jest.fn(), + getAllEntities: jest.fn(), + deleteEntity: jest.fn(), }; const urlReader: jest.Mocked = { @@ -140,7 +142,7 @@ describe('Linguist backend API', () => { }); }); - it('should add new entities', async () => { + it('should insert new entities', async () => { const testEntityListResponse: GetEntitiesResponse = { items: [ { @@ -172,6 +174,24 @@ describe('Linguist backend API', () => { expect(store.insertNewEntity).toHaveBeenCalledTimes(3); }); + it('should delete entities not in Catalog', async () => { + store.getAllEntities.mockResolvedValue([ + 'component:default/service-one', + 'component:default/stale-service-two', + ]); + + catalogApi.getEntityByRef.mockResolvedValueOnce({ + apiVersion: 'backstage.io/v1beta1', + metadata: { + name: 'service-one', + }, + kind: 'Component', + }); + + await api.cleanEntities(); + expect(store.deleteEntity).toHaveBeenCalledTimes(1); + }); + it('should get default entity overview', async () => { store.getProcessedEntities.mockResolvedValue([ { diff --git a/plugins/linguist-backend/src/api/LinguistBackendClient.ts b/plugins/linguist-backend/src/api/LinguistBackendClient.ts index a2f6e1ef67..0bd6370ac3 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendClient.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendClient.ts @@ -92,11 +92,12 @@ export class LinguistBackendClient implements LinguistBackendApi { async processEntities(): Promise { this.logger?.info('Updating list of entities'); - await this.addNewEntities(); - this.logger?.info('Processing applicable entities through Linguist'); + this.logger?.info('Cleaning list of entities'); + await this.cleanEntities(); + this.logger?.info('Processing applicable entities through Linguist'); await this.generateEntitiesLanguages(); } @@ -123,6 +124,23 @@ export class LinguistBackendClient implements LinguistBackendApi { }); } + /** @internal */ + async cleanEntities(): Promise { + this.logger?.info('Cleaning entities in Linguist queue'); + const allEntities = await this.store.getAllEntities(); + + for (const entityRef of allEntities) { + const result = await this.catalogApi.getEntityByRef(entityRef); + + if (!result) { + this.logger?.info( + `Entity ${entityRef} was not found in the Catalog, it will be deleted`, + ); + await this.store.deleteEntity(entityRef); + } + } + } + /** @internal */ async generateEntitiesLanguages(): Promise { const entitiesOverview = await this.getEntitiesOverview(); diff --git a/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts b/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts index 1ab092b953..5998ddfc1e 100644 --- a/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts +++ b/plugins/linguist-backend/src/db/LinguistBackendDatabase.test.ts @@ -170,14 +170,31 @@ describe('Linguist database', () => { }); it('should insert new entities and ignore duplicates', async () => { - const before = testDbClient.count('entity_result'); + const before = testDbClient.from('entity_result').count(); await store.insertNewEntity('component:/default/new-entity-one'); await store.insertNewEntity('component:/default/new-entity-two'); await store.insertNewEntity('template:default/pull-request'); - const after = testDbClient.count('entity_result'); + const after = testDbClient.from('entity_result').count(); expect(before).toEqual(after); }); + + it('should get all entities', async () => { + const allEntities = await store.getAllEntities(); + + expect(allEntities.length).toEqual(5); + }); + + it('should delete entity by its entityRef', async () => { + const before = await testDbClient.from('entity_result').count(); + + await store.deleteEntity('template:default/create-react-app-template'); + + const after = await testDbClient.from('entity_result').count(); + + expect(before).toEqual([{ 'count(*)': 5 }]); + expect(after).toEqual([{ 'count(*)': 4 }]); + }); }); diff --git a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts index 5a165695da..2a15b2d823 100644 --- a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts +++ b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts @@ -37,6 +37,8 @@ export interface LinguistBackendStore { getEntityResults(entityRef: string): Promise; getProcessedEntities(): Promise; getUnprocessedEntities(): Promise; + getAllEntities(): Promise; + deleteEntity(entityRef: string): Promise; } const migrationsDir = resolvePackagePath( @@ -158,4 +160,24 @@ export class LinguistBackendDatabase implements LinguistBackendStore { return unprocessedEntities; } + + async getAllEntities(): Promise { + const rawEntities = await this.db('entity_result'); + + if (!rawEntities) { + return []; + } + + const allEntities = rawEntities.map(rawEntity => { + return rawEntity.entity_ref; + }); + + return allEntities; + } + + async deleteEntity(entityRef: string): Promise { + await this.db('entity_result') + .where('entity_ref', entityRef) + .delete(); + } } From 75fe31e5a4f3e05130e7c14f72640d1ac4467bb1 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Fri, 7 Apr 2023 11:38:52 -0500 Subject: [PATCH 08/14] Updated changeset to match changes Signed-off-by: Andre Wanlin --- .changeset/shaggy-gorillas-occur.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.changeset/shaggy-gorillas-occur.md b/.changeset/shaggy-gorillas-occur.md index c122032e7f..94b0f6c21d 100644 --- a/.changeset/shaggy-gorillas-occur.md +++ b/.changeset/shaggy-gorillas-occur.md @@ -2,4 +2,13 @@ '@backstage/plugin-linguist-backend': patch --- -Added tests for the `LinguistBackendDatabase` and `LinguistBackendApi` which included refactoring to better support using SQLite and removed the default from the `processes_date` column +Several improvements to the Linguist backend have been made: + +- Added tests for the `LinguistBackendDatabase` and `LinguistBackendApi` +- Added support for using SQLite as a database, helpful for local development +- Removed the default from the `processes_date` column +- Converted the `LinguistBackendApi` into an Interface +- Added the `LinguistBackendClient` which implements the `LinguistBackendApi` Interface +- Unprocessed entities will get processed before stale entities +- Entities in the Linguist database but not in the Catalog anymore will be deleted +- Improved the README's headings From 62631dbbd7182b72e8bffae2b0fcd142bf4b9188 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Fri, 14 Apr 2023 20:14:52 -0500 Subject: [PATCH 09/14] Removed export Signed-off-by: Andre Wanlin --- plugins/linguist-backend/api-report.md | 21 ------------------- plugins/linguist-backend/src/api/index.ts | 1 - plugins/linguist-backend/src/index.ts | 1 - .../linguist-backend/src/service/router.ts | 3 ++- 4 files changed, 2 insertions(+), 24 deletions(-) diff --git a/plugins/linguist-backend/api-report.md b/plugins/linguist-backend/api-report.md index 1b2c4af832..0c70f936c6 100644 --- a/plugins/linguist-backend/api-report.md +++ b/plugins/linguist-backend/api-report.md @@ -3,7 +3,6 @@ > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts -import { CatalogApi } from '@backstage/catalog-client'; import { EntityResults } from '@backstage/plugin-linguist-common'; import express from 'express'; import { HumanDuration } from '@backstage/types'; @@ -32,26 +31,6 @@ export interface LinguistBackendApi { processEntities(): Promise; } -// @public (undocumented) -export class LinguistBackendClient implements LinguistBackendApi { - constructor( - logger: Logger, - store: LinguistBackendStore, - urlReader: UrlReader, - tokenManager: TokenManager, - catalogApi: CatalogApi, - age?: HumanDuration, - batchSize?: number, - useSourceLocation?: boolean, - kind?: string[], - linguistJsOptions?: Record, - ); - // (undocumented) - getEntityLanguages(entityRef: string): Promise; - // (undocumented) - processEntities(): Promise; -} - // @public (undocumented) export class LinguistBackendDatabase implements LinguistBackendStore { constructor(db: Knex); diff --git a/plugins/linguist-backend/src/api/index.ts b/plugins/linguist-backend/src/api/index.ts index 53b427b3a7..b3f73587e7 100644 --- a/plugins/linguist-backend/src/api/index.ts +++ b/plugins/linguist-backend/src/api/index.ts @@ -14,5 +14,4 @@ * limitations under the License. */ -export { LinguistBackendClient } from './LinguistBackendClient'; export type { LinguistBackendApi } from './LinguistBackendClient'; diff --git a/plugins/linguist-backend/src/index.ts b/plugins/linguist-backend/src/index.ts index 8969880618..6d3c86a8f2 100644 --- a/plugins/linguist-backend/src/index.ts +++ b/plugins/linguist-backend/src/index.ts @@ -15,7 +15,6 @@ */ export * from './service/router'; -export { LinguistBackendClient } from './api'; export type { LinguistBackendApi } from './api'; export { LinguistBackendDatabase } from './db'; export type { LinguistBackendStore } from './db'; diff --git a/plugins/linguist-backend/src/service/router.ts b/plugins/linguist-backend/src/service/router.ts index 21f03e08a3..9e45438ec8 100644 --- a/plugins/linguist-backend/src/service/router.ts +++ b/plugins/linguist-backend/src/service/router.ts @@ -24,7 +24,7 @@ import { import express from 'express'; import Router from 'express-promise-router'; import { Logger } from 'winston'; -import { LinguistBackendApi, LinguistBackendClient } from '../api'; +import { LinguistBackendApi } from '../api'; import { LinguistBackendDatabase } from '../db'; import { PluginTaskScheduler, @@ -32,6 +32,7 @@ import { } from '@backstage/backend-tasks'; import { HumanDuration } from '@backstage/types'; import { CatalogClient } from '@backstage/catalog-client'; +import { LinguistBackendClient } from '../api/LinguistBackendClient'; /** @public */ export interface PluginOptions { From 0f439d6508789da9d5e301d46f62d240e9f10d41 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Sat, 22 Apr 2023 10:12:28 -0500 Subject: [PATCH 10/14] Removed database export Signed-off-by: Andre Wanlin --- plugins/linguist-backend/api-report.md | 42 -------------------------- plugins/linguist-backend/src/index.ts | 2 -- 2 files changed, 44 deletions(-) diff --git a/plugins/linguist-backend/api-report.md b/plugins/linguist-backend/api-report.md index 0c70f936c6..294d569ff7 100644 --- a/plugins/linguist-backend/api-report.md +++ b/plugins/linguist-backend/api-report.md @@ -3,16 +3,13 @@ > Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts -import { EntityResults } from '@backstage/plugin-linguist-common'; import express from 'express'; import { HumanDuration } from '@backstage/types'; -import { Knex } from 'knex'; import { Languages } from '@backstage/plugin-linguist-common'; import { Logger } from 'winston'; import { PluginDatabaseManager } from '@backstage/backend-common'; import { PluginEndpointDiscovery } from '@backstage/backend-common'; import { PluginTaskScheduler } from '@backstage/backend-tasks'; -import { ProcessedEntity } from '@backstage/plugin-linguist-common'; import { TaskScheduleDefinition } from '@backstage/backend-tasks'; import { TokenManager } from '@backstage/backend-common'; import { UrlReader } from '@backstage/backend-common'; @@ -31,45 +28,6 @@ export interface LinguistBackendApi { processEntities(): Promise; } -// @public (undocumented) -export class LinguistBackendDatabase implements LinguistBackendStore { - constructor(db: Knex); - // (undocumented) - static create(knex: Knex): Promise; - // (undocumented) - deleteEntity(entityRef: string): Promise; - // (undocumented) - getAllEntities(): Promise; - // (undocumented) - getEntityResults(entityRef: string): Promise; - // (undocumented) - getProcessedEntities(): Promise; - // (undocumented) - getUnprocessedEntities(): Promise; - // (undocumented) - insertEntityResults(entityLanguages: EntityResults): Promise; - // (undocumented) - insertNewEntity(entityRef: string): Promise; -} - -// @public (undocumented) -export interface LinguistBackendStore { - // (undocumented) - deleteEntity(entityRef: string): Promise; - // (undocumented) - getAllEntities(): Promise; - // (undocumented) - getEntityResults(entityRef: string): Promise; - // (undocumented) - getProcessedEntities(): Promise; - // (undocumented) - getUnprocessedEntities(): Promise; - // (undocumented) - insertEntityResults(entityLanguages: EntityResults): Promise; - // (undocumented) - insertNewEntity(entityRef: string): Promise; -} - // @public (undocumented) export interface PluginOptions { // (undocumented) diff --git a/plugins/linguist-backend/src/index.ts b/plugins/linguist-backend/src/index.ts index 6d3c86a8f2..37ecf2d47f 100644 --- a/plugins/linguist-backend/src/index.ts +++ b/plugins/linguist-backend/src/index.ts @@ -16,5 +16,3 @@ export * from './service/router'; export type { LinguistBackendApi } from './api'; -export { LinguistBackendDatabase } from './db'; -export type { LinguistBackendStore } from './db'; From b66092c1349c386b8efc8546e6faed8aa29b7e0d Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Tue, 2 May 2023 15:35:25 -0500 Subject: [PATCH 11/14] Latest changes based on feedback Signed-off-by: Andre Wanlin --- .changeset/shaggy-gorillas-occur.md | 2 ++ plugins/linguist-backend/src/api/LinguistBackendClient.ts | 1 - plugins/linguist-backend/src/db/LinguistBackendDatabase.ts | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.changeset/shaggy-gorillas-occur.md b/.changeset/shaggy-gorillas-occur.md index 94b0f6c21d..149ff6f424 100644 --- a/.changeset/shaggy-gorillas-occur.md +++ b/.changeset/shaggy-gorillas-occur.md @@ -2,6 +2,8 @@ '@backstage/plugin-linguist-backend': patch --- +**BREAKING**: Removed public constructor from `LinguistBackendApi`. Removed export of `LinguistBackendDatabase` and `LinguistBackendDatabase` + Several improvements to the Linguist backend have been made: - Added tests for the `LinguistBackendDatabase` and `LinguistBackendApi` diff --git a/plugins/linguist-backend/src/api/LinguistBackendClient.ts b/plugins/linguist-backend/src/api/LinguistBackendClient.ts index 0bd6370ac3..5a84201bcb 100644 --- a/plugins/linguist-backend/src/api/LinguistBackendClient.ts +++ b/plugins/linguist-backend/src/api/LinguistBackendClient.ts @@ -170,7 +170,6 @@ export class LinguistBackendClient implements LinguistBackendApi { try { await this.generateEntityLanguages(entityRef, url); } catch (error) { - console.log(error); assertError(error); this.logger.error( `Unable to process "${entityRef}" using "${url}", message: ${error.message}, stack: ${error.stack}`, diff --git a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts index 2a15b2d823..12f44a5dca 100644 --- a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts +++ b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts @@ -93,7 +93,7 @@ export class LinguistBackendDatabase implements LinguistBackendStore { .where({ entity_ref: entityRef }) .first(); - if (!entityResults) { + if (!entityResults || !entityResults.languages) { const emptyResults: Languages = { languageCount: 0, totalBytes: 0, @@ -104,7 +104,7 @@ export class LinguistBackendDatabase implements LinguistBackendStore { } try { - return JSON.parse(entityResults.languages as string); + return JSON.parse(entityResults.languages); } catch (error) { throw new Error(`Failed to parse languages for '${entityRef}', ${error}`); } From 7a0010adee499756177e0f2e1c82039f55feb9c6 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Tue, 2 May 2023 15:36:47 -0500 Subject: [PATCH 12/14] Fixed changeset typo Signed-off-by: Andre Wanlin --- .changeset/shaggy-gorillas-occur.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/shaggy-gorillas-occur.md b/.changeset/shaggy-gorillas-occur.md index 149ff6f424..d36b8aef01 100644 --- a/.changeset/shaggy-gorillas-occur.md +++ b/.changeset/shaggy-gorillas-occur.md @@ -2,7 +2,7 @@ '@backstage/plugin-linguist-backend': patch --- -**BREAKING**: Removed public constructor from `LinguistBackendApi`. Removed export of `LinguistBackendDatabase` and `LinguistBackendDatabase` +**BREAKING**: Removed public constructor from `LinguistBackendApi`. Removed export of `LinguistBackendDatabase` and `LinguistBackendStore` Several improvements to the Linguist backend have been made: From 8676ebfd42d8c270fb4b400a6108b3e42c2f9442 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Tue, 2 May 2023 15:38:31 -0500 Subject: [PATCH 13/14] Syntax improvement Signed-off-by: Andre Wanlin --- plugins/linguist-backend/src/db/LinguistBackendDatabase.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts index 12f44a5dca..5a59d18e90 100644 --- a/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts +++ b/plugins/linguist-backend/src/db/LinguistBackendDatabase.ts @@ -133,7 +133,7 @@ export class LinguistBackendDatabase implements LinguistBackendStore { const processEntity = { entityRef: rawEntity.entity_ref, - processedDate: processedDate, + processedDate, }; return processEntity; From d787cc504a4bc92669c413266fbe46dff5f1d282 Mon Sep 17 00:00:00 2001 From: Andre Wanlin Date: Tue, 2 May 2023 15:40:14 -0500 Subject: [PATCH 14/14] Changed to minor Signed-off-by: Andre Wanlin --- .changeset/shaggy-gorillas-occur.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/shaggy-gorillas-occur.md b/.changeset/shaggy-gorillas-occur.md index d36b8aef01..ce7c2aba3b 100644 --- a/.changeset/shaggy-gorillas-occur.md +++ b/.changeset/shaggy-gorillas-occur.md @@ -1,5 +1,5 @@ --- -'@backstage/plugin-linguist-backend': patch +'@backstage/plugin-linguist-backend': minor --- **BREAKING**: Removed public constructor from `LinguistBackendApi`. Removed export of `LinguistBackendDatabase` and `LinguistBackendStore`