Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add _queue-status endpoint to realm server #2070

Merged
merged 3 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions packages/realm-server/handlers/handle-queue-status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import Koa from 'koa';
import { query, SupportedMimeType } from '@cardstack/runtime-common';
import { setContextResponse } from '../middleware';
import { CreateRoutesArgs } from '../routes';

export default function handleQueueStatusRequest({
dbAdapter,
}: CreateRoutesArgs): (ctxt: Koa.Context, next: Koa.Next) => Promise<void> {
return async function (ctxt: Koa.Context, _next: Koa.Next) {
let [{ pending_job_count }] = (await query(dbAdapter, [
`SELECT COUNT(*) as pending_job_count FROM jobs WHERE status='unfulfilled'`,
])) as {
pending_job_count: string;
}[];
return setContextResponse(
ctxt,
new Response(
JSON.stringify({
data: {
type: 'queue-status',
id: 'queue-status',
attributes: {
pending: parseInt(pending_job_count, 10),
},
},
}),
{
headers: { 'content-type': SupportedMimeType.JSONAPI },
},
),
);
};
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it ok that this is an unprotected route? perhaps we should have a shared secret to access this? otherwise a malicious client might try to DDoS our DB impacting the system overall.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In our previous projects we had a x-data-integrity-checks-authorization header was used to authorize requests of this type. Perhaps we could have something similar here, depending on the service that will consume this

2 changes: 2 additions & 0 deletions packages/realm-server/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { healthCheck, jwtMiddleware, livenessCheck } from './middleware';
import Koa from 'koa';
import handleStripeLinksRequest from './handlers/handle-stripe-links';
import handleCreateUserRequest from './handlers/handle-create-user';
import handleQueueStatusRequest from './handlers/handle-queue-status';

export type CreateRoutesArgs = {
dbAdapter: DBAdapter;
Expand Down Expand Up @@ -46,6 +47,7 @@ export function createRoutes(args: CreateRoutesArgs) {
handleCreateRealmRequest(args),
);
router.get('/_catalog-realms', handleFetchCatalogRealmsRequest(args));
router.get('/_queue-status', handleQueueStatusRequest(args));
router.post('/_stripe-webhook', handleStripeWebhookRequest(args));
router.get(
'/_user',
Expand Down
40 changes: 40 additions & 0 deletions packages/realm-server/tests/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -522,3 +522,43 @@ export function mtimes(
traverseDir(path);
return mtimes;
}

export async function insertJob(
dbAdapter: PgAdapter,
params: {
job_type: string;
args?: Record<string, any>;
concurrency_group?: string | null;
timeout?: number;
status?: string;
finished_at?: string | null;
result?: Record<string, any> | null;
priority?: number;
},
): Promise<Record<string, any>> {
let { valueExpressions, nameExpressions: nameExpressions } = asExpressions({
job_type: params.job_type,
args: params.args ?? {},
concurrency_group: params.concurrency_group ?? null,
timeout: params.timeout ?? 240,
status: params.status ?? 'unfulfilled',
finished_at: params.finished_at ?? null,
result: params.result ?? null,
priority: params.priority ?? 0,
});
let result = await query(
dbAdapter,
insert('jobs', nameExpressions, valueExpressions),
);
return {
id: result[0].id,
job_type: result[0].job_type,
args: result[0].args,
concurrency_group: result[0].concurrency_group,
timeout: result[0].timeout,
status: result[0].status,
finished_at: result[0].finished_at,
result: result[0].result,
priority: result[0].priority,
};
}
34 changes: 34 additions & 0 deletions packages/realm-server/tests/server-endpoints-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
insertUser,
insertPlan,
fetchSubscriptionsByUserId,
insertJob,
} from './helpers';
import '@cardstack/runtime-common/helpers/code-equality-assertion';
import { shimExternals } from '../lib/externals';
Expand Down Expand Up @@ -1544,6 +1545,39 @@ module(basename(__filename), function () {
waitForBillingNotification(assert, assert.async());
});
});

module('_queue-status', function (hooks) {
setupPermissionedRealm(hooks, {
'*': ['read', 'write'],
});

hooks.beforeEach(async function () {
shimExternals(virtualNetwork);
});

test('returns 200 with JSON-API doc', async function (assert) {
await insertJob(dbAdapter, {
job_type: 'test-job',
});
await insertJob(dbAdapter, {
job_type: 'test-job',
status: 'resolved',
finished_at: new Date().toISOString(),
});
let response = await request.get('/_queue-status');
assert.strictEqual(response.status, 200, 'HTTP 200 status');
let json = response.body;
assert.deepEqual(json, {
data: {
type: 'queue-status',
id: 'queue-status',
attributes: {
pending: 1,
},
},
});
});
});
},
);
module('Realm server authentication', function (hooks) {
Expand Down
Loading