Skip to content

Extract cron schedule registration out of runServeCmd#47562

Open
raju249 wants to merge 1 commit into
fleetdm:mainfrom
raju249:33370-cron-registration-extraction
Open

Extract cron schedule registration out of runServeCmd#47562
raju249 wants to merge 1 commit into
fleetdm:mainfrom
raju249:33370-cron-registration-extraction

Conversation

@raju249

@raju249 raju249 commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

Extracts the cron schedule registration out of runServeCmd and into a new cmd/fleet/cron_registration.go. Same pattern as the prior extractions on this issue (#44929, #45343, #45583, #46166, #46421, #46517, #46742, #46830, #46893, #47151). This is the largest slice so far — runServeCmd drops from ~1300 to ~1000 lines, and serve.go from 1776 to 1472.

The 33 StartCronSchedule registrations move into one startCronSchedules entry point backed by a cronSchedulesDeps struct (the dependencies the closures previously captured from runServeCmd). Registration is grouped by domain:

  • registerCleanupAndMaintenanceCrons — chart data collection, the cron_stats cleanup goroutine, software migrations, frequent cleanups, cleanups-then-aggregation, query results cleanup, upcoming activities, usage statistics, batch activities.
  • registerVulnerabilityCrons — the vulnerabilities schedule, or the remote-trigger proxy when processing is disabled on this instance.
  • registerWorkerCrons — automations and worker integrations.
  • registerMDMCrons — Apple MDM worker, DEP profile assigner, service discovery, the Apple/Windows/Android profile managers, the Android device reconciler, the Android policy migrations, and the APNs pusher.
  • registerPremiumCrons — iPhone/iPad refetcher and reviver, maintained apps, VPP app version refresh (and the one-shot VPP country backfill), recovery lock passwords, managed local account rotation, activities streaming, and the calendar schedule.
  • registerMiscCrons — host vitals label membership and the batch activity completion checker.

Behavior is preserved — the schedules register in the same order with the same arguments, the same conditionals gate them (premium, audit log, env vars, software store presence), and the config is threaded as a pointer so the &config and config.Calendar mutations inside the calendar closure keep their original semantics. cmd/fleet/cron.go (the schedule definitions) is intentionally untouched; only the wiring moved.

One unit test added: TestVulnerabilityProcessingDisabled covers the vuln enable/disable predicate extracted into vulnerabilityProcessingDisabled, including the legacy current_instance_checks "0" value. The rest of the file is dependency-wiring relocation with no further decision logic to unit-test — those paths construct real schedules, so they stay covered by the existing suite and integration tests. The full cmd/fleet suite passes against MySQL + Redis, and a local server boot confirms the same 30 cron schedules start as before (verified against the "started cron schedules" log line).

Related issue: Refs #33370

Checklist for submitter

  • Added/updated automated tests
  • QA'd all new/changed functionality manually (verified via local server boot — same 30 cron schedules start)
  • Changes file: not applicable — internal refactor with no user-visible behavior change

Summary by CodeRabbit

  • Refactor

    • Cron schedule registration centralized and reordered for clearer startup sequencing; no user-facing API changes.
  • New Features / Behavior

    • Background schedules for maintenance, vulnerabilities, MDM (Apple/Windows/Android), device/reconciler tasks, APNs delivery, and premium-only jobs now run according to config and license settings.
    • Several schedules honor config/env flags (e.g., chart data collection, audit/event streaming) and fallback timing defaults.
  • Tests

    • Added tests covering vulnerability-schedule enable/disable behavior.

@raju249 raju249 requested a review from a team as a code owner June 13, 2026 06:13
@coderabbitai

coderabbitai Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9a1876af-463a-476c-993d-cdee526bfd79

📥 Commits

Reviewing files that changed from the base of the PR and between 17fb140 and 4216ea1.

📒 Files selected for processing (3)
  • cmd/fleet/cron_registration.go
  • cmd/fleet/cron_registration_test.go
  • cmd/fleet/serve.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • cmd/fleet/serve.go
  • cmd/fleet/cron_registration.go

Walkthrough

Refactors cron schedule registration by moving inline registration from cmd/fleet/serve.go into a new cmd/fleet/cron_registration.go. Introduces cronSchedulesDeps and startCronSchedules which call domain-scoped registration helpers (cleanup/maintenance, vulnerabilities, worker, MDM, premium, miscellaneous). serve.go now calls startCronSchedules with the consolidated deps, unused imports were removed, and tracing.StartSettingsPoller is started earlier.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main refactoring change: extracting cron schedule registration code from runServeCmd into a separate file.
Description check ✅ Passed The description is comprehensive and follows the template structure, covering testing approach, behavior preservation, and related issue references. However, the checklist is incomplete with some items unchecked or deleted.
Docstring Coverage ✅ Passed Docstring coverage is 90.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
cmd/fleet/cron_registration.go (1)

62-68: 🏗️ Heavy lift

Add a regression test around the orchestrator order and gates.

startCronSchedules is now the single entry point for 30+ conditional registrations, but this refactor still relies on manual verification that helper order and gating match the old inline flow. A small recorder around CronSchedules.StartCronSchedule would make future edits here much safer.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/fleet/cron_registration.go` around lines 62 - 68, Add a regression test
that verifies the orchestrator order and gating in startCronSchedules by
creating a test double for CronSchedules whose StartCronSchedule method records
each registration call (name/identifier and any gate-relevant params), then call
startCronSchedules with controlled deps toggling the various gates and assert
that the recorded sequence matches the expected order of helper registrations
(registerCleanupAndMaintenanceCrons, registerVulnerabilityCrons,
registerWorkerCrons, registerMDMCrons, registerPremiumCrons, registerMiscCrons)
and that gated registrations only occur when their deps permit; implement
assertions for both full-enabled and selectively-disabled gate permutations to
catch regressions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@cmd/fleet/cron_registration.go`:
- Around line 62-68: Add a regression test that verifies the orchestrator order
and gating in startCronSchedules by creating a test double for CronSchedules
whose StartCronSchedule method records each registration call (name/identifier
and any gate-relevant params), then call startCronSchedules with controlled deps
toggling the various gates and assert that the recorded sequence matches the
expected order of helper registrations (registerCleanupAndMaintenanceCrons,
registerVulnerabilityCrons, registerWorkerCrons, registerMDMCrons,
registerPremiumCrons, registerMiscCrons) and that gated registrations only occur
when their deps permit; implement assertions for both full-enabled and
selectively-disabled gate permutations to catch regressions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d923fb08-f6dd-4200-975e-8eaceec6dea3

📥 Commits

Reviewing files that changed from the base of the PR and between 268c918 and fa0e5a0.

📒 Files selected for processing (2)
  • cmd/fleet/cron_registration.go
  • cmd/fleet/serve.go

@raju249 raju249 force-pushed the 33370-cron-registration-extraction branch from fa0e5a0 to 17fb140 Compare June 13, 2026 06:21
Move the 33 StartCronSchedule registrations into a new
cmd/fleet/cron_registration.go, grouped by domain (cleanup/maintenance,
vulnerabilities, workers, MDM, premium, misc) and driven by a
cronSchedulesDeps struct. runServeCmd builds the struct once and makes a
single startCronSchedules call; registration order and arguments are
preserved exactly.

Extract the vuln enable/disable decision into vulnerabilityProcessingDisabled
and unit-test it (covers the legacy current_instance_checks "0" value).

Refs fleetdm#33370
@raju249 raju249 force-pushed the 33370-cron-registration-extraction branch from 17fb140 to 4216ea1 Compare June 13, 2026 06:32
@raju249

raju249 commented Jun 13, 2026

Copy link
Copy Markdown
Contributor Author

Hello @MagnusHJensen - I am slicing the cron related code out of serve.go -

For context on the structure: the domain-grouped register*Crons functions and the cronSchedulesDeps struct are meant to be the template for the rest of this effort, not a one-off. As I keep slicing runServeCmd on #33370, further cron-adjacent extraction (and the remaining init blocks) will follow the same shape — one deps struct, domain-grouped registration, registration order preserved exactly — so the files stay consistent and easy to review against each other.

Would you be able to take a review, please? And let me know wdyt of the approach forward for other cron extractions.

@codecov

codecov Bot commented Jun 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 1.48148% with 266 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.17%. Comparing base (268c918) to head (4216ea1).

Files with missing lines Patch % Lines
cmd/fleet/cron_registration.go 1.64% 239 Missing ⚠️
cmd/fleet/serve.go 0.00% 27 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #47562      +/-   ##
==========================================
- Coverage   67.19%   67.17%   -0.03%     
==========================================
  Files        3616     3617       +1     
  Lines      229016   229057      +41     
  Branches    11785    11785              
==========================================
- Hits       153885   153858      -27     
- Misses      61303    61360      +57     
- Partials    13828    13839      +11     
Flag Coverage Δ
backend 68.81% <1.48%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant