Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
75 changes: 75 additions & 0 deletions api/src/ever-connect/ever-connect-managed.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,4 +366,79 @@ describeOnSqlite('EverConnectManagedService', () => {
expect(platform.managedResults[op.operation_id]).toMatchObject({ status: 'succeeded' });
expect(platform.names()).toContain('ack');
});

it('keeps the lease renewed while one long step of a round runs, and releases it after the round', async () => {
const { connect, managed, scheduler } = await connected();
await consent(connect);
const connections = dataSource.getRepository(EverConnectConnection);
await connections.update({ id: 'self' }, { nextHeartbeatAt: Date.now() + 3600000, nextEntitlementAt: Date.now() + 3600000 });
scheduler.keepAliveMs = 20;
const seen: number[] = [];
// One step much longer than the renewal interval (as a backup that outlives the lease would be)
const runDue = jest.spyOn(managed, 'runDue').mockImplementation(async () => {
for (let i = 0; i < 4; i++) {
await new Promise(resolve => setTimeout(resolve, 40));
Comment thread
evereq marked this conversation as resolved.
Resolved
const row = await connections.findOne({ where: { id: 'self' } });
expect(row.leasedBy).toBe(scheduler.holderId);
seen.push(row.leaseUntil);
}
return 0;
});
await scheduler.tick();
expect(runDue).toHaveBeenCalledTimes(1);
expect(seen).toHaveLength(4);
// Renewed while the step ran: each reading is later than the one before
expect(seen.every((until, i) => i === 0 || until > seen[i - 1])).toBe(true);
// Released after the round
expect(await connections.findOne({ where: { id: 'self' } })).toMatchObject({ leasedBy: null, leaseUntil: null });
});

it('renews one lease at a time, and releases the lease only after the renewal in flight settled', async () => {
const { connect, managed, scheduler } = await connected();
await consent(connect);
const connections = dataSource.getRepository(EverConnectConnection);
await connections.update({ id: 'self' }, { nextHeartbeatAt: Date.now() + 3600000, nextEntitlementAt: Date.now() + 3600000 });
scheduler.keepAliveMs = 5;
const lease = scheduler as unknown as { renew: () => Promise<boolean> };
const realRenew = lease.renew.bind(scheduler);
let stepRunning = false;
let timerRenewals = 0;
let releaseHeld: () => void = () => undefined;
const held = new Promise<void>(resolve => (releaseHeld = resolve));
let renewalStarted: () => void = () => undefined;
const started = new Promise<void>(resolve => (renewalStarted = resolve));
jest.spyOn(lease, 'renew').mockImplementation(async () => {
if (stepRunning) {
// A renewal of the timer that stays pending until the test lets it finish (a slow database)
timerRenewals += 1;
renewalStarted();
await held;
}
return realRenew();
});
let stepDone: () => void = () => undefined;
const stepFinished = new Promise<void>(resolve => (stepDone = resolve));
jest.spyOn(managed, 'runDue').mockImplementation(async () => {
stepRunning = true;
await started;
// Many timer periods pass while that renewal is still pending
await new Promise(resolve => setTimeout(resolve, 50));
stepRunning = false;
stepDone();
return 0;
});
let finished = false;
const round = scheduler.tick().then(() => (finished = true));
await stepFinished;
await new Promise(resolve => setTimeout(resolve, 20));
// No second renewal started, and the round waits for the pending one: the lease is still this process's
expect(timerRenewals).toBe(1);
expect(finished).toBe(false);
expect((await connections.findOne({ where: { id: 'self' } })).leasedBy).toBe(scheduler.holderId);
releaseHeld();
await round;
// Released once that renewal settled, and nothing takes it again
await new Promise(resolve => setTimeout(resolve, 20));
expect(await connections.findOne({ where: { id: 'self' } })).toMatchObject({ leasedBy: null, leaseUntil: null });
});
});
16 changes: 16 additions & 0 deletions api/src/ever-connect/ever-connect-scheduler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
private feedFailed = false;
/** This process, as the lease names it (random, nothing else). */
readonly holderId = randomUUID();
/** How often a running round renews its lease: a third of it, so two renewals in a row may fail before it ends. */
keepAliveMs = Math.floor(LEASE_MS / 3);

constructor(
@InjectRepository(EverConnectConnection) private readonly connections: Repository<EverConnectConnection>,
Expand Down Expand Up @@ -153,6 +155,18 @@
if (!(await this.acquire(now))) {
return;
}
// While the round runs, a timer renews the lease too: one long step (a backup, a restore check, a slow call) never
// outlives it, so another process cannot take over in the middle of it. One renewal at a time (a slow one is never
// overtaken by the next), and the one in flight is awaited before the release, so none takes the lease again after
let renewing: Promise<unknown> | null = null;
const keepAlive = setInterval(() => {
renewing ??= this.renew()
Comment thread
evereq marked this conversation as resolved.
Resolved
.catch(error => this.logger.warn(`ever_connect.lease_renew error=${(error && error.name) || 'error'}`))

Check warning on line 164 in api/src/ever-connect/ever-connect-scheduler.service.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer using an optional chain expression instead, as it's more concise and easier to read.

See more on https://sonarcloud.io/project/issues?id=ever-co_ever-traduora&issues=AaH9QrSh5VJpughOFXJL&open=AaH9QrSh5VJpughOFXJL&pullRequest=646
.finally(() => {
renewing = null;
});
}, this.keepAliveMs);
keepAlive.unref();
try {
// Read again under the lease: another process may have made the due calls meanwhile
const connection = await this.connect.read();
Expand Down Expand Up @@ -210,6 +224,8 @@
}
}
} finally {
clearInterval(keepAlive);
await renewing;

Check failure on line 228 in api/src/ever-connect/ever-connect-scheduler.service.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

This "await" does not apply to a "Promise". Remove it or fix the expression.

See more on https://sonarcloud.io/project/issues?id=ever-co_ever-traduora&issues=AaH9QrSh5VJpughOFXJM&open=AaH9QrSh5VJpughOFXJM&pullRequest=646
await this.release();
}
}
Expand Down
3 changes: 3 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ To download the source code for each release, check out [GitHub](https://github.
the calls listed in [Outbound calls](ever-platform/outbound-calls.md).
- A path under `/api` that no route answers is now a 404 (JSON), never the web app's page: a client asking for a route
that does not exist, or of a module that is not loaded, gets a clear answer.
- Ever Platform connection with several API processes: a running background round also renews its lease on a timer, so
one long step (a backup or a restore check longer than the 2-minute lease) never lets another process start its own
maintenance work alongside it

## 0.24.1

Expand Down