Skip to content

Commit

Permalink
feat: add logic to return services with no tasks too
Browse files Browse the repository at this point in the history
  • Loading branch information
juanmahidalgo committed Nov 27, 2024
1 parent df6c7d0 commit ff0561b
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 42 deletions.
6 changes: 1 addition & 5 deletions src/components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,10 @@ export async function initComponents(): Promise<AppComponents> {
})
const corsString = await config.requireString('CORS_METHODS')
const validCORSJsonString = corsString.replace(/'/g, '"')
console.log('corsString: ', corsString)
console.log('validCORSJsonString: ', validCORSJsonString)
console.log('JSON.parse(validCORSJsonString): ', JSON.parse(validCORSJsonString))
console.log('hardcoding cors')

const cors = {
origin: (await config.requireString('CORS_ORIGIN')).split(';').map(origin => new RegExp(origin)),
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
methods: JSON.parse(validCORSJsonString),
credentials: true
}

Expand Down
6 changes: 4 additions & 2 deletions src/controllers/handlers/squid-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ export async function stopSquidHandler(context: Pick<HandlerContextWithPath<'squ
status: StatusCode.OK
}
} catch (e) {
console.error('error: ', e)
return {
status: StatusCode.BAD_REQUEST,
body: {
message: isErrorWithMessage(e) ? e.message : 'Could not stop squid'
message: isErrorWithMessage(e) ? e.message : 'Could not stop the squid'
}
}
}
Expand All @@ -48,10 +49,11 @@ export async function promoteSquidHandler(context: Pick<HandlerContextWithPath<'
status: StatusCode.OK
}
} catch (e) {
console.error('error: ', e)
return {
status: StatusCode.BAD_REQUEST,
body: {
message: isErrorWithMessage(e) ? e.message : 'Could not promote squid'
message: isErrorWithMessage(e) ? e.message : 'Could not promote the squid'
}
}
}
Expand Down
46 changes: 22 additions & 24 deletions src/ports/squids/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,6 @@ export async function createSubsquidComponent({
const taskResponse = await client.send(listTasksCommand)
const taskArns = taskResponse.taskArns || []

if (taskArns.length === 0) return null

const describeTasksCommand = new DescribeTasksCommand({
cluster,
tasks: taskArns
})
const describeResponse = await client.send(describeTasksCommand)
const tasks = describeResponse.tasks || []

const squidName = squidService.serviceName || ''
const schemaName = (await dappsDatabase.query(getSchemaByServiceNameQuery(squidName))).rows[0]?.schema
const projectActiveSchema = (await dappsDatabase.query(getActiveSchemaQuery(squidName))).rows[0]?.schema
Expand All @@ -78,9 +69,21 @@ export async function createSubsquidComponent({
name: squidName,
service_name: squidService.serviceName || '',
schema_name: schemaName,
project_active_schema: projectActiveSchema
project_active_schema: projectActiveSchema,
metrics: {} as Record<Network.ETHEREUM | Network.MATIC, SquidMetric>
}

if (taskArns.length === 0) {
return squid
}

const describeTasksCommand = new DescribeTasksCommand({
cluster,
tasks: taskArns
})
const describeResponse = await client.send(describeTasksCommand)
const tasks = describeResponse.tasks || []

// there should be just one task per service
for (const task of tasks) {
squid.version = task.version || 0
Expand Down Expand Up @@ -151,26 +154,21 @@ export async function createSubsquidComponent({
service: serviceName,
desiredCount: 0
})
const updateServiceResponse = await client.send(updateServiceCommand)
console.log('updateServiceResponse: ', updateServiceResponse) // @TODO: refactor this, for now just print it to the console
await client.send(updateServiceCommand)
console.log(`Service ${serviceName} stopped!`)
} catch (error) {
console.log('error: ', error)
}
}

async function promote(serviceName: string): Promise<void> {
try {
const projectName = getProjectNameFromService(serviceName) // e.g: service name is marketplace-squid-server-a-blue-92e812a, project is marketplace
const schemaName = `squid_${projectName}` // e.g: squid_marketplace
const promoteQuery = getPromoteQuery(serviceName, schemaName, projectName)

// NOTE: in the future, depending on the project we might want to run the promote query in a different db
const result = await dappsDatabase.query(promoteQuery)
console.log('result: ', result) // @TODO implement a proper response
console.log('result.rows: ', result.rows) // @TODO implement a proper response
} catch (error) {
console.log('error: ', error)
}
const projectName = getProjectNameFromService(serviceName) // e.g: service name is marketplace-squid-server-a-blue-92e812a, project is marketplace
const schemaName = `squid_${projectName}` // e.g: squid_marketplace
const promoteQuery = getPromoteQuery(serviceName, schemaName, projectName)

// NOTE: in the future, depending on the project we might want to run the promote query in a different db
await dappsDatabase.query(promoteQuery)
console.log(`The ${serviceName} was promoted and the active schema is ${schemaName}`) // @TODO implement a proper response
}

return {
Expand Down
61 changes: 50 additions & 11 deletions src/ports/squids/queries.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,95 @@
import { Client } from 'pg'
import { SQL, SQLStatement } from 'sql-template-strings'
import { getProjectNameFromService } from './utils'

const client = new Client()

export function escapeLiteral(value: string): string {
return client.escapeLiteral(value) // Escapes a string safely for use in PostgreSQL
}

export function escapeIdentifier(value: string): string {
return client.escapeIdentifier(value) // Escapes an identifier (e.g., schema, table names)
}

export const getPromoteQuery = (serviceName: string, schemaName: string, project: string): SQLStatement => {
const safeServiceName = escapeLiteral(serviceName)
const safeSchemaName = escapeIdentifier(schemaName)
const safeProjectName = escapeLiteral(project)

return SQL`
DO $$
DECLARE
old_schema_name TEXT;
new_schema_name TEXT;
db_user TEXT;
writer_user TEXT;
BEGIN
-- Fetch the new schema name and database user from the indexers table
SELECT schema, db_user INTO new_schema_name, db_user
SELECT schema, db_user INTO new_schema_name, writer_user
FROM public.indexers
WHERE service = ${serviceName};
WHERE service = `
.append(safeServiceName)
.append(
SQL` ORDER BY created_at DESC LIMIT 1;
-- Fetch the old schema name from the squids table
SELECT schema INTO old_schema_name
FROM squids
WHERE name = '${project}';
WHERE name = '`
.append(safeProjectName)
.append(
SQL`';
-- Rename the old schema
EXECUTE format('ALTER SCHEMA ${schemaName} RENAME TO %I', old_schema_name);
EXECUTE format('ALTER SCHEMA `
.append(safeSchemaName)
.append(
SQL` RENAME TO %I', old_schema_name);
-- Rename the new schema to the desired name
EXECUTE format('ALTER SCHEMA %I RENAME TO ${schemaName}', new_schema_name);
EXECUTE format('ALTER SCHEMA %I RENAME TO `
.append(safeSchemaName)
.append(
SQL`', new_schema_name);
-- Update the search path for the user
EXECUTE format('ALTER USER %I SET search_path TO ${schemaName}', db_user);
EXECUTE format('ALTER USER %I SET search_path TO `
.append(safeSchemaName)
.append(
SQL`', writer_user);
-- Update the schema in the squids table
UPDATE squids SET schema = new_schema_name WHERE name = '${project}';
UPDATE squids SET schema = new_schema_name WHERE name = '`.append(project).append(SQL`';
-- Commit the transaction
COMMIT;
END $$;
`
`)
)
)
)
)
)
}

export const getSchemaByServiceNameQuery = (serviceName: string): SQLStatement => {
const safeServiceName = escapeLiteral(serviceName)
return SQL`
SELECT schema
FROM public.indexers
WHERE service = ${serviceName};
WHERE service = ${safeServiceName}
ORDER BY created_at DESC
LIMIT 1;
`
}

export const getActiveSchemaQuery = (serviceName: string): SQLStatement => {
const projectName = getProjectNameFromService(serviceName)
const safeProjectName = escapeLiteral(projectName)

return SQL`
SELECT schema
FROM public.squids
WHERE name = ${projectName};
WHERE name = ${safeProjectName};
`
}

0 comments on commit ff0561b

Please sign in to comment.