Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
106 changes: 106 additions & 0 deletions app/lib/task/cloudcompute/zone_tracker.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:clock/clock.dart';
import 'package:logging/logging.dart';
import 'package:pub_dev/task/cloudcompute/cloudcompute.dart';

final _log = Logger('pub.task.zone_tracker');

/// Tracks compute zones and custom ban periods.
final class ComputeZoneTracker {
final List<String> _zones;
final _bannedUntil = <String, DateTime>{};

int _nextZoneIndex = 0;

ComputeZoneTracker(this._zones);

/// Creates or extends zone ban period.
void banZone(String zone, {int minutes = 0}) {
final until = clock.fromNow(minutes: minutes);
final currentBan = _bannedUntil[zone];
if (currentBan == null || currentBan.isBefore(until)) {
_bannedUntil[zone] = until;
}
}

void _pruneBans() {
final now = clock.now();
_bannedUntil.removeWhere((k, v) => v.isBefore(now));
}

/// Whether there is any available zone that is not banned.
bool hasAvailableZone() {
_pruneBans();
return _zones.any((zone) => !_bannedUntil.containsKey(zone));
}

/// Tries to pick an available zone.
///
/// Zone selection follows a round-robin algorithm, skipping the banned zones.
///
/// Returns `null` if there is no zone available.
String? tryPickZone() {
_pruneBans();
// cursor may be moved at most the number of zones times
for (var i = 0; i < _zones.length; i++) {
final zone = _zones[_nextZoneIndex];
_nextZoneIndex = (_nextZoneIndex + 1) % _zones.length;
if (!_bannedUntil.containsKey(zone)) {
return zone;
}
}
return null;
}

/// Executes [fn] in compute [zone] and handles zone-related exceptions
/// with the appropriate bans.
Future<void> withZoneAndInstance(
Copy link
Member

Choose a reason for hiding this comment

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

let's not move this logic. Do we need to?

The interactions here are subtle, this is not reusable, and shouldn't attempt to be.

Whether to ban or not ban a zone is a scheduling decision.

I'm not keen on ComputeZoneTracker being mutable, nor am I keen on it containing much logic. Isn't it mostly just a container for state between iterations.

Keeping state immutable, means runSchedulerIteration (I assume we are working towards) will have to return a new state object, that it can mutate with timers after returning it.

I think spreading logic across files will make it harder to track.


wouldn't it be better for runSchedulerIteration to return a ZoneTrackerState object? that is effectively immutable.

String zone,
String instanceName,
Future<void> Function() fn,
) async {
try {
await fn();
} on ZoneExhaustedException catch (e, st) {
// A zone being exhausted is normal operations, we just use another
// zone for 15 minutes.
_log.info(
'zone resources exhausted, banning ${e.zone} for 30 minutes',
e,
st,
);
// Ban usage of zone for 30 minutes
banZone(e.zone, minutes: 30);
} on QuotaExhaustedException catch (e, st) {
// Quota exhausted, this can happen, but it shouldn't. We'll just stop
// doing anything for 10 minutes. Hopefully that'll resolve the issue.
// We log severe, because this is a reason to adjust the quota or
// instance limits.
_log.severe(
'Quota exhausted trying to create $instanceName, banning all zones '
'for 10 minutes',
e,
st,
);

// Ban all zones for 10 minutes
for (final zone in _zones) {
banZone(zone, minutes: 10);
}
} on Exception catch (e, st) {
// No idea what happened, but for robustness we'll stop using the zone
// and shout into the logs
_log.shout(
'Failed to create instance $instanceName, banning zone "$zone" for '
'15 minutes',
e,
st,
);
// Ban usage of zone for 15 minutes
banZone(zone, minutes: 15);
}
}
}
100 changes: 19 additions & 81 deletions app/lib/task/scheduler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import 'package:pub_dev/shared/utils.dart';
import 'package:pub_dev/task/backend.dart';
import 'package:pub_dev/task/clock_control.dart';
import 'package:pub_dev/task/cloudcompute/cloudcompute.dart';
import 'package:pub_dev/task/cloudcompute/zone_tracker.dart';
import 'package:pub_dev/task/global_lock.dart';
import 'package:pub_dev/task/models.dart';

Expand Down Expand Up @@ -43,31 +44,13 @@ Future<void> schedule(
}
}

// Map from zone to DateTime when zone is allowed again
final zoneBannedUntil = <String, DateTime>{
for (final zone in compute.zones) zone: DateTime(0),
};
void banZone(String zone, {int minutes = 0, int hours = 0, int days = 0}) {
if (!zoneBannedUntil.containsKey(zone)) {
throw ArgumentError.value(zone, 'zone');
}

final until = clock.now().add(
Duration(minutes: minutes, hours: hours, days: days),
);
if (zoneBannedUntil[zone]!.isBefore(until)) {
zoneBannedUntil[zone] = until;
}
}
final zoneTracker = ComputeZoneTracker(compute.zones);

// Set of `CloudInstance.instanceName`s currently being deleted.
// This to avoid deleting instances where the deletion process is still
// running.
final deletionInProgress = <String>{};

// Create a fast RNG with random seed for picking zones.
final rng = Random(Random.secure().nextInt(2 << 31));

// Run scheduling iterations, so long as we have a valid claim
while (claim.valid && !abort.isCompleted) {
final iterationStart = clock.now();
Expand Down Expand Up @@ -124,18 +107,8 @@ Future<void> schedule(
continue; // skip the rest of the iteration
}

// Determine which zones are not banned
final allowedZones =
zoneBannedUntil.entries
.where((e) => e.value.isBefore(clock.now()))
.map((e) => e.key)
.toList()
..shuffle(rng);
var nextZoneIndex = 0;
String pickZone() => allowedZones[nextZoneIndex++ % allowedZones.length];

// If no zones are available, we sleep and try again later.
if (allowedZones.isEmpty) {
if (!zoneTracker.hasAvailableZone()) {
_log.info('All compute-engine zones are banned, trying again in 30s');
await sleepOrAborted(Duration(seconds: 30), since: iterationStart);
continue;
Expand All @@ -152,7 +125,10 @@ Future<void> schedule(
pendingPackagesReviewed += 1;

final instanceName = compute.generateInstanceName();
final zone = pickZone();
final zone = zoneTracker.tryPickZone();
if (zone == null) {
return;
}

final updated = await updatePackageStateWithPendingVersions(
db,
Expand All @@ -171,7 +147,7 @@ Future<void> schedule(

await Future.microtask(() async {
var rollbackPackageState = true;
try {
await zoneTracker.withZoneAndInstance(zone, instanceName, () async {
// Purging cache is important for the edge case, where the new upload happens
// on a different runtime version, and the current one's cache is still stale
// and does not have the version yet.
Expand All @@ -189,56 +165,18 @@ Future<void> schedule(
description: description,
);
rollbackPackageState = false;
} on ZoneExhaustedException catch (e, st) {
// A zone being exhausted is normal operations, we just use another
// zone for 15 minutes.
_log.info(
'zone resources exhausted, banning ${e.zone} for 30 minutes',
e,
st,
);
// Ban usage of zone for 30 minutes
banZone(e.zone, minutes: 30);
} on QuotaExhaustedException catch (e, st) {
// Quota exhausted, this can happen, but it shouldn't. We'll just stop
// doing anything for 10 minutes. Hopefully that'll resolve the issue.
// We log severe, because this is a reason to adjust the quota or
// instance limits.
_log.severe(
'Quota exhausted trying to create $instanceName, banning all zones '
'for 10 minutes',
e,
st,
);

// Ban all zones for 10 minutes
for (final zone in compute.zones) {
banZone(zone, minutes: 10);
}
} on Exception catch (e, st) {
// No idea what happened, but for robustness we'll stop using the zone
// and shout into the logs
_log.shout(
'Failed to create instance $instanceName, banning zone "$zone" for '
'15 minutes',
e,
st,
});
if (rollbackPackageState) {
final oldVersionsMap = updated?.$2 ?? const {};
// Restore the state of the PackageState for versions that were
// suppose to run on the instance we just failed to create.
// If this doesn't work, we'll eventually retry. Hence, correctness
// does not hinge on this transaction being successful.
await db.tasks.restorePreviousVersionsState(
selected.package,
instanceName,
oldVersionsMap,
);
// Ban usage of zone for 15 minutes
banZone(zone, minutes: 15);
} finally {
if (rollbackPackageState) {
final oldVersionsMap = updated?.$2 ?? const {};
// Restore the state of the PackageState for versions that were
// suppose to run on the instance we just failed to create.
// If this doesn't work, we'll eventually retry. Hence, correctness
// does not hinge on this transaction being successful.
await db.tasks.restorePreviousVersionsState(
selected.package,
instanceName,
oldVersionsMap,
);
}
}
});
}
Expand Down
104 changes: 104 additions & 0 deletions app/test/task/cloudcompute/zone_tracker_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:clock/clock.dart';
import 'package:pub_dev/task/cloudcompute/cloudcompute.dart';
import 'package:pub_dev/task/cloudcompute/zone_tracker.dart';
import 'package:test/test.dart';

void main() {
group('ComputeZoneTracker', () {
test('no zones provided', () {
final tracker = ComputeZoneTracker([]);
expect(tracker.hasAvailableZone(), false);
expect(tracker.tryPickZone(), null);
});

test('unrelated zone gets banned', () {
final tracker = ComputeZoneTracker(['a']);
expect(tracker.hasAvailableZone(), true);
expect(tracker.tryPickZone(), 'a');
expect(tracker.tryPickZone(), 'a');

tracker.banZone('b', minutes: 2);
expect(tracker.tryPickZone(), 'a');
});

test('single zone gets banned and ban expires', () {
final tracker = ComputeZoneTracker(['a']);
expect(tracker.hasAvailableZone(), true);
expect(tracker.tryPickZone(), 'a');
expect(tracker.tryPickZone(), 'a');

tracker.banZone('a', minutes: 2);
expect(tracker.tryPickZone(), null);

withClock(Clock.fixed(clock.fromNow(minutes: 3)), () {
expect(tracker.tryPickZone(), 'a');
});
});

test('round robin with one zone banned', () {
final tracker = ComputeZoneTracker(['a', 'b', 'c']);
expect(tracker.hasAvailableZone(), true);
expect(tracker.tryPickZones(7), ['a', 'b', 'c', 'a', 'b', 'c', 'a']);

tracker.banZone('b', minutes: 2);
expect(tracker.tryPickZones(5), ['c', 'a', 'c', 'a', 'c']);

withClock(Clock.fixed(clock.fromNow(minutes: 30)), () {
expect(tracker.tryPickZones(5), ['a', 'b', 'c', 'a', 'b']);
});
});

test('ZoneExhaustedException bans single zone', () async {
final tracker = ComputeZoneTracker(['a', 'b', 'c']);
await tracker.withZoneAndInstance(
'a',
'instance-a',
() => throw ZoneExhaustedException('a', 'exhausted'),
);
expect(tracker.tryPickZones(6), ['b', 'c', 'b', 'c', 'b', 'c']);

withClock(Clock.fixed(clock.fromNow(minutes: 30)), () {
expect(tracker.tryPickZones(5), ['a', 'b', 'c', 'a', 'b']);
});
});

test('QuotaExhaustedException bans all zones', () async {
final tracker = ComputeZoneTracker(['a', 'b', 'c']);
await tracker.withZoneAndInstance(
'a',
'instance-a',
() => throw QuotaExhaustedException('exhausted'),
);
expect(tracker.hasAvailableZone(), isFalse);
expect(tracker.tryPickZones(2), [null, null]);

withClock(Clock.fixed(clock.fromNow(minutes: 30)), () {
expect(tracker.tryPickZones(5), ['a', 'b', 'c', 'a', 'b']);
});
});

test('generic Exception bans single zone', () async {
final tracker = ComputeZoneTracker(['a', 'b', 'c']);
await tracker.withZoneAndInstance(
'a',
'instance-a',
() => throw Exception('unrelated'),
);
expect(tracker.tryPickZones(6), ['b', 'c', 'b', 'c', 'b', 'c']);

withClock(Clock.fixed(clock.fromNow(minutes: 30)), () {
expect(tracker.tryPickZones(5), ['a', 'b', 'c', 'a', 'b']);
});
});
});
}

extension on ComputeZoneTracker {
List<String?> tryPickZones(int n) {
return List.generate(n, (_) => tryPickZone());
}
}