Skip to content

Commit

Permalink
Add autosleep
Browse files Browse the repository at this point in the history
  • Loading branch information
nzws committed May 13, 2024
1 parent d25eaa3 commit 5f9f046
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 6 deletions.
11 changes: 11 additions & 0 deletions apps/push-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { apiInternalOnUnPublish } from './controllers/internal/on_unpublish';
import { Streaming } from './streaming';
import * as Sentry from '@sentry/node';
import { CaptureConsole } from '@sentry/integrations';
import { isServerIdling } from './utils/sessions';

const dsn = process.env.SENTRY_DSN;

Expand Down Expand Up @@ -55,7 +56,17 @@ console.log(`Listening on port ${port}`);

new Streaming(server);

const autoSleep = setInterval(() => {
if (isServerIdling()) {
console.log('all lives ended, stopping server');
clearInterval(autoSleep);
server.close();
process.exit(0);
}
}, 1000 * 60);

process.on('SIGTERM', () => {
clearInterval(autoSleep);
server.close();
process.exit(0);
});
5 changes: 0 additions & 5 deletions apps/push-serverless/src/services/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,6 @@ export class Action {
} finally {
sessions.delete(liveId);
lives.delete(liveId);

if (lives.size === 0) {
console.log('all lives ended, stopping server');
process.exit(0);
}
}
})();
}
Expand Down
4 changes: 4 additions & 0 deletions apps/push-serverless/src/utils/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ export const lives = new Map<
}
>();

export const isServerIdling = () => {
return sessions.size === 0 && lives.size === 0;
};

export const rejectSession = async (liveId: number) => {
const session = sessions.get(liveId);
if (!session) {
Expand Down
4 changes: 3 additions & 1 deletion infra/push-serverless/fly.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ app = 'knzklive2-push-prd'
primary_region = 'nrt'

[build]
image = "ghcr.io/nzws/knzklive2-push-serverless:production-amd64"
image = "ghcr.io/nzws/knzklive2-push-serverless:latest-amd64"

[processes]
app = "/knzk/entry.sh"
Expand All @@ -27,6 +27,7 @@ protocol = "tcp"
auto_stop_machines = true
auto_start_machines = true
min_machines_running = 0
processes = ['app']
[[services.ports]]
handlers = ["tls"]
port = 1936
Expand All @@ -38,6 +39,7 @@ protocol = "tcp"
auto_stop_machines = true
auto_start_machines = true
min_machines_running = 0
processes = ['app']
[[services.ports]]
port = 1935

Expand Down

0 comments on commit 5f9f046

Please sign in to comment.