Skip to content

Commit

Permalink
Optimize finding which devices to publish & unpublish
Browse files Browse the repository at this point in the history
Change-type: patch
  • Loading branch information
thgreasi committed Sep 16, 2024
1 parent a6034ec commit cd3ae9e
Showing 1 changed file with 12 additions and 28 deletions.
40 changes: 12 additions & 28 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,40 +143,24 @@ const reapDevices = async (addresses: string[], deviceTld?: string) => {
for (const address of addresses) {
// Query the SDK using the Proxy service key for *all* current devices
try {
const devices = await balena.pine.get({
const newAccessible = await balena.pine.get({
resource: 'device',
options: {$orderby: 'device_name asc'}
}) as BalenaSdk.Device[];

// Get list of all accessible devices
const newAccessible = _.filter(
devices,
(device) => device.is_web_accessible,
);

// Get all devices that are not in both lists
const xorList = _.xorBy(accessibleDevices, newAccessible, 'uuid');

// Get all new devices to be published and old to be unpublished
const toUnpublish: BalenaSdk.Device[] = [];
const toPublish = _.filter(xorList, (device) => {
const filter = _.find(newAccessible, { uuid: device.uuid })
? true
: false;
if (!filter) {
toUnpublish.push(device);
// Publish everything new
const oldAccessibleUuids = new Set(accessibleDevices.map(d => d.uuid));
for (const device of newAccessible) {
if (!oldAccessibleUuids.has(device.uuid)) {
await addHostAddress(`${device.uuid}.devices.${deviceTld}`, [address]);
}
return filter;
});

// Publish everything required
for (const device of toPublish) {
await addHostAddress(`${device.uuid}.devices.${deviceTld}`, [address]);
}

// Unpublish the rest
for (const device of toUnpublish) {
await removeHostAddress(`${device.uuid}.devices.${deviceTld}`);
// Unpublish everything no longer accessible
const newAccessibleUuids = new Set(newAccessible.map(d => d.uuid));
for (const device of accessibleDevices) {
if (!newAccessibleUuids.has(device.uuid)) {
await removeHostAddress(`${device.uuid}.devices.${deviceTld}`);
}
}

accessibleDevices = newAccessible;
Expand Down

0 comments on commit cd3ae9e

Please sign in to comment.