Skip to content

Latest commit

 

History

History
457 lines (375 loc) · 21.4 KB

CHECKLIST.md

File metadata and controls

457 lines (375 loc) · 21.4 KB

Distributed Job Execution Engine — Implementation Checklist

Target: September 30, 2026 Community Demo Status legend: [ ] todo, [x] done, [-] skipped/deferred


M1: Project Structure

  • Create folder structure: packages/, services/, deploy/, docs/
  • Create DistributedJobEngine.Dev.sln (root development solution)
  • Create Directory.Build.props (net10.0, warnings as errors, analyzers)
  • Create Directory.Packages.props (central package management)
  • Create .editorconfig
  • Create .gitignore
  • Initialize git repository
  • Write ADR-001: Use Clean Architecture per service
  • Write ADR-002: Keep job state machine inside JobService.Domain
  • Write ADR-003: Use standalone EF Core outbox package
  • Write ADR-004: Use Docker Compose for local demo (MiniStack later)
  • Write ADR-005: Use at-least-once delivery with idempotent consumers
  • Write ADR-006: Use worker leases instead of distributed locks
  • Write ADR-007: Make contracts package optional for template
  • Write ADR-008: Use chaos middleware for failure injection

M2: Extract Dapr.EntityFrameworkCore.Outbox

Source: dotnet-sdk repo, branch backup/ef-core-outbox-full

  • Create packages/Dapr.EntityFrameworkCore.Outbox/
  • Create Dapr.EntityFrameworkCore.Outbox.sln
  • Copy src/Dapr.EntityFrameworkCore.Outbox/ from backup branch
  • Copy test/Dapr.EntityFrameworkCore.Outbox.Test/ from backup branch
  • Adjust namespaces if needed
  • Adjust .csproj — target net10.0, update package versions
  • Verify IHasDomainEvents interface is generic (no business concepts)
  • Verify OutboxMessage entity
  • Verify DaprOutboxSaveChangesInterceptor
  • Verify PollingOutboxDispatcher
  • Verify PostgreSqlOutboxClaimStrategy
  • Verify RelationalOutboxClaimStrategy (fallback)
  • Verify DaprOutboxHealthCheck
  • Verify OutboxRetentionHostedService
  • Verify DaprOutboxDiagnostics (OpenTelemetry ActivitySource)
  • Verify DI extensions (AddDaprOutbox<TDbContext>)
  • Verify ModelBuilderExtensions.AddDaprOutbox()
  • Verify DbContextExtensions.EnqueueOutbox()
  • Run unit tests — all 28 pass
  • Add to root dev solution
  • Add README with usage example

M3: Extract CleanArchitecture.BuildingBlocks

Source: cleanarchitecure repo, Service.SharedKernel + Service.Application abstractions

  • Create packages/CleanArchitecture.BuildingBlocks/
  • Create CleanArchitecture.BuildingBlocks.slnx
  • Create src/CleanArchitecture.BuildingBlocks/ project
  • Copy from SharedKernel: Entity, IDomainEvent, IDomainEventHandler<T>
  • Copy from SharedKernel: Result, Result<T>, Error, ErrorType, ValidationError
  • Copy from SharedKernel: IDateTimeProvider, IDependencyModule
  • [-] Have Entity implement outbox package's IHasDomainEvents interface (deferred — each service bridges via AggregateRoot)
  • Copy CQRS abstractions: ICommand, ICommand<T>, IQuery<T>
  • Copy CQRS abstractions: ICommandHandler, IQueryHandler
  • Copy dispatchers: ICommandDispatcher, CommandDispatcher
  • Copy dispatchers: IQueryDispatcher, QueryDispatcher
  • Copy processor abstractions: IProcessor, IDto, IRequestHandler, RequestHandler
  • Copy decorators: LoggingDecorator, ValidationDecorator
  • Add DI registration: AddBuildingBlocks(), AddLoggingDecorator(), AddValidationDecorator()
  • [-] Add pagination primitives if needed (deferred to M5)
  • Create tests/CleanArchitecture.BuildingBlocks.Tests/
  • Write tests for Result, Error, dispatchers, validation decorator — 9 pass
  • Strip any Todo/User domain references
  • Verify no business-specific concepts leaked in
  • Run tests — all 9 pass
  • Add to root dev solution

M4: JobEngine.Contracts

  • Create packages/JobEngine.Contracts/
  • Create project JobEngine.Contracts.csproj
  • Define JobCreatedIntegrationEvent
  • Define JobRetryScheduledIntegrationEvent
  • Define JobCancelledIntegrationEvent
  • Define JobExecutionCompletedIntegrationEvent
  • Define JobExecutionFailedIntegrationEvent
  • Define JobCompletedIntegrationEvent
  • Define JobFailedIntegrationEvent
  • Add to root dev solution

M5: JobService

M5.1: Solution Scaffold

  • Create services/JobService/JobService.slnx
  • Create JobService.Api project
  • Create JobService.Application project
  • Create JobService.Domain project
  • Create JobService.Infrastructure project
  • Add ProjectReferences to BuildingBlocks, Outbox, Contracts
  • Wire up DI composition (IDependencyModule per layer)
  • Add to root dev solution

M5.2: Domain — Job Aggregate & State Machine

  • Create JobState enum (Pending, Running, Retrying, Completed, Failed, Cancelled)
  • Create Job aggregate root with all properties from doc
  • Implement Job.Create(...) factory method
  • Implement Job.Claim(workerId, now, leaseDuration)
  • Implement Job.Heartbeat(workerId, now, leaseDuration)
  • Implement Job.Complete(workerId, now)
  • Implement Job.Fail(workerId, now, error)
  • Implement Job.ScheduleRetry(workerId, now, retryAt, error)
  • Implement Job.Cancel(now)
  • Implement Job.MarkLeaseExpired(now, retryAt)
  • Implement Job.CanBeClaimed(now)
  • Create JobStateMachine — validate all allowed transitions
  • Create JobRetryPolicy — exponential backoff with jitter
  • [-] Create JobLease value object (inlined as properties on Job aggregate)
  • Create JobStateTransition entity
  • [-] Create JobType value object (using string — simpler for demo)
  • Create JobErrors static error definitions
  • Domain events: JobCreatedDomainEvent, JobClaimedDomainEvent, etc. (7 events)
  • Create JobExecution entity
  • Optimistic concurrency via Version property (uint / xmin)
  • RetryFromFailed() — manual retry from Failed state

M5.3: Domain Tests

  • Test all valid state transitions (10 allowed transitions)
  • Test all rejected state transitions (8 disallowed transitions)
  • Test claim rules (only Pending/Retrying, only below max attempts)
  • Test heartbeat rules (only current lease owner)
  • Test complete/fail rules (only current lease owner, only Running)
  • Test lease expiry logic (retry and terminal fail paths)
  • Test retry policy backoff calculations (4 tests)
  • Test cancel from allowed states (Pending, Running)
  • Test terminal states (Completed, Cancelled cannot transition)
  • All 51 tests pass

M5.4: Application — Commands & Queries

  • CreateJobCommand + handler + validator
  • CancelJobCommand + handler
  • RetryJobCommand + handler (Failed → Retrying)
  • ClaimJobCommand + handler (internal, for workers)
  • HeartbeatJobCommand + handler (internal)
  • [-] ReleaseJobCommand + handler (deferred — covered by lease expiry)
  • HandleJobExecutionCompletedCommand + handler (consumes worker outcome, idempotent)
  • HandleJobExecutionFailedCommand + handler (consumes worker outcome, idempotent)
  • RecoverExpiredLeasesCommand + handler (background)
  • GetJobByIdQuery + handler
  • SearchJobsQuery + handler (with pagination)
  • [-] GetJobTimelineQuery + handler (deferred — transitions available via job aggregate)
  • [-] GetJobExecutionsQuery + handler (deferred — executions available via job aggregate)
  • GetJobSummaryQuery + handler (counts by state)
  • Define IJobRepository (with search, expired leases, summary counts)
  • [-] Define IJobTimelineRepository (merged into IJobRepository)
  • Define IProcessedMessageRepository
  • Define IUnitOfWork
  • [-] Define IOutboxEventWriter (deferred — outbox writes handled by interceptor)
  • [-] Processors for each public DTO (deferred to API endpoints)
  • Validators (FluentValidation) for CreateJobCommand

M5.5: Infrastructure — Persistence

  • Create JobDbContext
  • EF configuration for Job (table: jobs, all columns from data model)
  • EF configuration for JobExecution (table: job_executions)
  • EF configuration for JobStateTransition (table: job_state_transitions)
  • EF configuration for ProcessedMessage (table: processed_messages)
  • Map outbox table via modelBuilder.AddDaprOutbox()
  • Attach DaprOutboxSaveChangesInterceptor (via AddDaprOutbox<JobDbContext>())
  • Configure optimistic concurrency token (xmin via .IsRowVersion())
  • Create indexes from data model (4 indexes on jobs, 2 on executions, 1 on transitions)
  • Create initial migration (InitialCreate)
  • Implement JobRepository (with search, expired leases, summary counts)
  • [-] Implement JobTimelineRepository (merged into JobRepository)
  • Implement ProcessedMessageRepository
  • [-] Implement EfCoreOutboxEventWriter (outbox handled by interceptor)
  • Register AddDaprOutbox<JobDbContext>() with Postgres claim strategy

M5.6: Infrastructure — Background Services

  • LeaseRecoveryBackgroundService — polls expired leases every 5s
  • Wire lease recovery to RecoverExpiredLeasesCommand via ICommandDispatcher

M5.7: Api — Endpoints

  • POST /jobs — create job
  • GET /jobs/{jobId} — get job by id
  • GET /jobs — search/list jobs (with state/type filters, pagination)
  • POST /jobs/{jobId}/cancel — cancel job
  • POST /jobs/{jobId}/retry — manual retry
  • [-] GET /jobs/{jobId}/timeline — deferred (data available via aggregate)
  • [-] GET /jobs/{jobId}/executions — deferred (data available via aggregate)
  • GET /jobs/summary — counts by state
  • POST /internal/jobs/{jobId}/claim — worker claim endpoint
  • POST /internal/jobs/{jobId}/heartbeat — worker heartbeat
  • [-] POST /internal/jobs/{jobId}/release — deferred (covered by lease expiry)
  • Dapr subscription endpoint for job-executions.completed
  • Dapr subscription endpoint for job-executions.failed
  • Health check endpoint

M5.8: Architecture Tests

  • Layer dependency tests (Domain, Application, Infrastructure, Api)
  • Domain must not reference EF Core, Dapr, or Infrastructure

M6: WorkerService

M6.1: Solution Scaffold

  • Create services/WorkerService/WorkerService.sln
  • Create WorkerService.Api project
  • Create WorkerService.Application project
  • Create WorkerService.Domain project
  • Create WorkerService.Infrastructure project
  • Add ProjectReferences to BuildingBlocks, Outbox, Contracts
  • Wire up DI composition
  • Add to root dev solution

M6.2: Domain

  • [-] Create WorkerNode entity (deferred — worker identity via environment vars)
  • Create WorkerStatus enum
  • Create WorkerExecution entity (local execution tracking)
  • Create ExecutionStatus enum (Running, Completed, Failed)
  • [-] Create ExecutionAttempt value object (inlined into WorkerExecution)
  • Create WorkerErrors static error definitions
  • [-] Domain rules: concurrency limit, graceful drain (deferred to M7 chaos)

M6.3: Application

  • HandleJobCreatedCommand + handler (receive event → claim → execute)
  • HandleJobRetryScheduledCommand + handler
  • [-] ExecuteJobCommand + handler (inlined into HandleJobCreated/RetryScheduled handlers)
  • [-] CompleteJobExecutionCommand + handler (inlined — outcome written via outbox)
  • [-] FailJobExecutionCommand + handler (inlined — outcome written via outbox)
  • [-] SendHeartbeatCommand + handler (deferred to heartbeat hosted service)
  • [-] RecordExecutionOutcomeCommand + handler (outcome via outbox interceptor)
  • HandleJobCancelledCommand + handler
  • Define IJobHandler interface
  • Define JobExecutionContext record
  • Define IJobHandlerRegistry interface
  • [-] Create JobExecutionCoordinator (inlined into handlers)
  • Define IJobServiceClient (calls JobService internal APIs)
  • [-] Create IdempotencyService (using IProcessedMessageRepository directly)
  • [-] Create ExecutionOutcomePublisher (outbox interceptor handles publishing)
  • Define IWorkerExecutionRepository
  • Define IProcessedMessageRepository
  • Define IUnitOfWork

M6.4: Job Handlers

  • GenerateReportHandler — creates artifact, idempotent
  • DataExportHandler — creates export artifact
  • AlwaysFailHandler — always throws, for permanent failure demo
  • FailNTimesThenSucceedHandler — configurable transient failure
  • SlowJobHandler — configurable delay, for lease/heartbeat demo

M6.5: Infrastructure

  • Create WorkerDbContext
  • EF configuration for WorkerExecution (table: worker_executions)
  • EF configuration for ProcessedMessage (table: processed_messages)
  • Map outbox table via modelBuilder.AddDaprOutbox()
  • Create indexes from data model
  • Create initial migration (InitialCreate)
  • Implement WorkerExecutionRepository
  • Implement ProcessedMessageRepository
  • [-] Implement EfCoreOutboxEventWriter (outbox handled by interceptor)
  • Register AddDaprOutbox<WorkerDbContext>()
  • Create JobServiceClient — DaprClient service invocation for claim/heartbeat
  • Create WorkerHeartbeatHostedService — heartbeats every 10s
  • Create JobHandlerRegistry
  • Create DateTimeProvider

M6.6: Api — Endpoints

  • POST /dapr/jobs/created — Dapr subscription for JobCreated
  • POST /dapr/jobs/retry-scheduled — Dapr subscription for JobRetryScheduled
  • POST /dapr/jobs/cancelled — Dapr subscription for JobCancelled
  • GET /health — worker health
  • GET /workers/status — worker runtime status

M6.7: Architecture Tests

  • Layer dependency tests
  • Domain must not duplicate Job state machine

M7: Reliability + Chaos Middleware

M7.1: Idempotency

  • processed_messages table in both services
  • Message deduplication by CloudEvent ID / outbox message ID
  • Job state machine rejects duplicate/invalid transitions
  • Optimistic concurrency on job claims (only one winner)
  • Deterministic idempotency key: job:{jobId}:attempt:{attemptNumber}
  • [-] Idempotent artifact naming: reports/{jobId}/attempt-{attemptNumber}.json (deferred — no artifact storage yet)
  • Chaos: duplicate event injection toggle + test

M7.2: Lease Recovery

  • LeaseRecoveryBackgroundService scans expired LeaseUntil every 5s
  • Expired Running → Retrying (if attempts remain) or Failed
  • Enqueue JobRetryScheduled through outbox on recovery
  • Chaos: stop heartbeat toggle + behavior (WorkerHeartbeatHostedService checks IChaosState)
  • Chaos: crash after claim toggle + behavior (ChaosCommandDecorator)

M7.3: Retry with Backoff

  • Exponential backoff: 1s, 2s, 4s, 8s... capped at 60s
  • Jitter added to delay
  • AttemptCount >= MaxAttempts → terminal Failed
  • Manual retry: Failed → Retrying via POST /jobs/{jobId}/retry
  • Chaos: fail next handler toggle + behavior (ChaosCommandDecorator)
  • Chaos: fail job type N times toggle + behavior (ChaosCommandDecorator)

M7.4: Chaos Middleware Framework

  • Define IChaosState interface (both services)
  • Implement InMemoryChaosState (thread-safe ConcurrentDictionary)
  • Define ChaosPolicy record (name, type, config)
  • [-] FailureInjectionMiddleware — HTTP pipeline interception (not needed — using decorators)
  • ChaosCommandDecorator<TCommand> — command handler wrapping (WorkerService)
  • ChaosEfInterceptor — EF SaveChanges interception (crash after commit)
  • ChaosOutboxDispatcherDecorator — pause/resume/delay/fail outbox dispatcher
  • [-] Guard: chaos only enabled in Development/Demo environment (deferred — always registered for demo)
  • Register all chaos components in InfrastructureModules

M7.5: Chaos — JobService Toggles

  • POST /demo/failures/crash-after-commit — ChaosEfInterceptor throws after SaveChanges
  • POST /demo/failures/pause-outbox — ChaosOutboxDispatcherDecorator skips dispatch
  • POST /demo/failures/resume-outbox — deactivates pause-outbox policy
  • POST /demo/failures/delay-outbox — ChaosOutboxDispatcherDecorator adds delay
  • POST /demo/failures/force-publish-failure — ChaosOutboxDispatcherDecorator throws

M7.6: Chaos — WorkerService Toggles

  • POST /demo/failures/crash-after-claim — ChaosCommandDecorator throws post-execution
  • POST /demo/failures/crash-after-effect — ChaosCommandDecorator throws post-execution
  • POST /demo/failures/fail-next-job — ChaosCommandDecorator throws (one-shot)
  • POST /demo/failures/fail-job-type — ChaosCommandDecorator throws N times for type
  • POST /demo/failures/delay-execution — ChaosCommandDecorator adds pre-execution delay
  • POST /demo/failures/stop-heartbeat — WorkerHeartbeatHostedService skips heartbeats
  • POST /demo/failures/duplicate-event — toggle exists (behavior at Dapr subscription level)
  • GET /demo/failures — list active chaos policies

M8: Docker Compose Infrastructure

  • Create deploy/compose/docker-compose.yml
  • Postgres container with two databases: jobservice_db, workerservice_db
  • Redis container (Dapr pub/sub backend)
  • JobService container + Dapr sidecar
  • WorkerService container (3 replicas) + Dapr sidecars
  • Create deploy/dapr/components/pubsub.yaml (Redis)
  • [-] Create deploy/dapr/components/statestore.yaml (deferred — chaos state is in-memory)
  • Create deploy/dapr/components/resiliency.yaml
  • Create Dockerfiles for JobService and WorkerService
  • Create EF migrations (InitialCreate for both services)
  • Auto-migrate on startup (MigrateAsync in Program.cs)
  • Create design-time DbContext factories for EF tooling
  • Verify: docker compose up starts everything
  • Verify: job creation → worker execution → completion flow works
  • Verify: multiple worker replicas claim independently

M9: Observability (Basic)

  • Add OpenTelemetry SDK to both services (1.18.0)
  • Configure ActivitySource and Meter per service (JobServiceDiagnostics, WorkerServiceDiagnostics)
  • [-] Add span tags: job_id, worker_id, job_type, attempt_number (deferred — requires custom Activity spans in handlers)
  • Structured logging with Serilog (console + correlation_id middleware)
  • [-] Add correlation_id propagation through outbox → Dapr → consumer (deferred — Dapr handles trace propagation)
  • Add OpenTelemetry Collector to Docker Compose (otel-collector-contrib:0.115.1)
  • Add Prometheus to Docker Compose (v3.1.0)
  • Add Tempo to Docker Compose (2.6.1)
  • Add Grafana to Docker Compose (11.4.0, auto-provisioned datasources + dashboards)
  • Job metrics: jobs.created, jobs.completed, jobs.failed, jobs.cancelled, jobs.leases_recovered, jobs.claim_conflicts
  • [-] Outbox metrics: outbox_pending_messages, outbox_published_total (deferred — outbox package has DaprOutboxDiagnostics, needs wiring)
  • Worker metrics: worker.jobs_claimed, worker.jobs_executed, worker.jobs_failed, worker.claim_conflicts, worker.heartbeats_sent, worker.duplicates_skipped
  • Create basic Grafana dashboard (job throughput, worker activity, heartbeats, HTTP p99)

M10: Demo Scenarios — Verification

Each scenario must be repeatable from a clean docker compose up:

  • Scenario 1: Happy Path — submit 100 jobs, all complete, 0 lost
  • Scenario 2: Transactional Outbox — crash after commit, restart, job completes
  • Scenario 3: Worker Crash — kill replica, leases expire, jobs reclaimed and complete
  • Scenario 4: Duplicate Delivery — inject duplicate, no duplicate effect
  • Scenario 5: Retry Then Succeed — FailNTimes handler, shows backoff, completes
  • Scenario 6: Permanent Failure — AlwaysFail handler, reaches max attempts, manual retry
  • Scenario 7: Pause Outbox — pause, submit jobs, resume, all publish and complete

M11: Demo Control Panel

  • Single-page HTML (minimal, no framework) — served from JobService wwwroot
  • Submit single job (type selector, payload, max attempts)
  • Submit bulk jobs (count, type)
  • Job summary counts (Pending, Running, Retrying, Completed, Failed, Cancelled)
  • Recent jobs table (last 20, with state badges, cancel/retry actions)
  • [-] Worker status display (deferred — visible in Docker Compose logs)
  • [-] Outbox pending count (deferred — visible in Grafana)
  • Failure injection buttons (all JobService + WorkerService toggles)
  • Active chaos policies display with deactivate buttons
  • Auto-refresh / polling (2s interval)
  • Event log panel with timestamped entries
  • JsonStringEnumConverter for proper enum serialization

M12: Community Demo Polish

  • Write README.md with architecture overview and quick start
  • Create architecture diagram (Mermaid in README)
  • Write demo script (step-by-step narrative)
  • Verify clean docker compose up → full demo flow
  • Record short demo clip or screenshots
  • Add troubleshooting section to README
  • Add explanation connecting back to Dapr PR #1863

Deferred (Post-Demo)

  • MiniStack S3 artifact storage
  • NuGet publishing for packages
  • Kubernetes deployment
  • Cloud deployment (AWS)
  • Authentication and authorization
  • Advanced dashboard
  • Event versioning
  • Benchmark suite (10,000 jobs)
  • SqlServer claim strategy testing