Update query to be more efficient

This commit is contained in:
Owen
2026-06-09 11:54:46 -07:00
parent 1907a3c93b
commit 1089cfbacc
+41 -11
View File
@@ -152,10 +152,21 @@ export async function buildClientConfigurationForNewtClient(
const targetsToSend: SubnetProxyTargetV2[] = []; const targetsToSend: SubnetProxyTargetV2[] = [];
for (const resource of allSiteResources) { if (allSiteResources.length === 0) {
// Get clients associated with this specific resource return {
const resourceClients = await db peers: validPeers,
targets: targetsToSend
};
}
// Batch fetch all client associations for every site resource in one query
// to avoid an N+1 lookup that would issue thousands of queries when a site
// has many resources.
const siteResourceIds = allSiteResources.map((r) => r.siteResourceId);
const resourceClientRows = await db
.select({ .select({
siteResourceId: clientSiteResourcesAssociationsCache.siteResourceId,
clientId: clients.clientId, clientId: clients.clientId,
pubKey: clients.pubKey, pubKey: clients.pubKey,
subnet: clients.subnet subnet: clients.subnet
@@ -163,23 +174,42 @@ export async function buildClientConfigurationForNewtClient(
.from(clients) .from(clients)
.innerJoin( .innerJoin(
clientSiteResourcesAssociationsCache, clientSiteResourcesAssociationsCache,
eq( eq(clients.clientId, clientSiteResourcesAssociationsCache.clientId)
clients.clientId,
clientSiteResourcesAssociationsCache.clientId
)
) )
.where( .where(
eq( inArray(
clientSiteResourcesAssociationsCache.siteResourceId, clientSiteResourcesAssociationsCache.siteResourceId,
resource.siteResourceId siteResourceIds
) )
); );
const resourceTargets = await generateSubnetProxyTargetV2( const clientsByResourceId = new Map<
number,
{ clientId: number; pubKey: string | null; subnet: string | null }[]
>();
for (const row of resourceClientRows) {
let list = clientsByResourceId.get(row.siteResourceId);
if (!list) {
list = [];
clientsByResourceId.set(row.siteResourceId, list);
}
list.push({
clientId: row.clientId,
pubKey: row.pubKey,
subnet: row.subnet
});
}
const resourceTargetsArr = await Promise.all(
allSiteResources.map((resource) =>
generateSubnetProxyTargetV2(
resource, resource,
resourceClients clientsByResourceId.get(resource.siteResourceId) ?? []
)
)
); );
for (const resourceTargets of resourceTargetsArr) {
if (resourceTargets) { if (resourceTargets) {
targetsToSend.push(...resourceTargets); targetsToSend.push(...resourceTargets);
} }