Latihan 1: Resilience Patterns — System Design

Latihan 1 dari materi Resilience Patterns di System Design — praktek dengan editor kode interaktif, test case otomatis, dan hint terpandu. Langsung jalan di browser.

Lengkapi class CircuitBreaker di kode awal. Constructor-nya sudah ada, biarkan apa adanya: dia menyimpan failureThreshold, memulai state di 'closed', dan failures di 0.

  1. recordSuccess(): set this.failures ke 0. Kalau this.state sedang 'half-open', ubah jadi 'closed'.
  2. recordFailure(): tambah this.failures satu. Kalau this.state sedang 'half-open', langsung jadi 'open'. Kalau this.state 'closed' dan this.failures sudah minimal this.failureThreshold, jadi 'open'.
  3. tryReset(): dipanggil setelah waktu open berlalu. Kalau this.state 'open', ubah jadi 'half-open'.

Baris console.log di kode awal biarkan, dan jangan tambah console.log lain: output dicek per baris sesuai urutannya. Dengan new CircuitBreaker(3), output-nya harus persis enam baris ini:

  1. closed (awal)
  2. closed (2 kegagalan, masih di bawah threshold 3)
  3. open (kegagalan ke-3)
  4. half-open (setelah tryReset())
  5. open (gagal saat half-open)
  6. closed (tryReset() lalu recordSuccess())

Class-nya juga diuji langsung dengan new CircuitBreaker(2): gagal, gagal, tryReset(), sukses harus memberi state berurutan closed, closed, open, half-open, closed; dan gagal, gagal, tryReset(), gagal harus berakhir di open. Nama class-nya tetap CircuitBreaker.

Hint