Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Bảo Vệ Dữ Liệu: Optimistic Locking Trong Rails REST APIs

Hãy tưởng tượng scenario: hệ thống quản lý bất động sản cho thuê. Nhân viên A chỉnh contact info Rental X, thêm số điện thoại. Cùng lúc, nhân viên B thấy typo contact info Rental X và update. Vài phút sau, nhân viên A update contact info với số điện thoại mới → update fix typo bị mất!

Không tốt! Scenario trival. Tưởng tượng conflict tương tự trong hệ thống tài chính!

Có tránh được không? May mắn thay: CÓ! Cần concurrency protection và locking - cụ thể optimistic locking - để prevent vấn đề này.

'Lost Updates' Và Optimistic Locking vs Pessimistic Locking

Scenario trên là kiểu 'Lost Update'. 2 concurrent transactions update cùng column cùng row → transaction 2 override changes transaction 1 → như thể transaction 1 không bao giờ xảy ra.

Thường address bằng:

  • Set Transaction Isolation level phù hợp (database level)
  • Pessimistic locking - prevent concurrent transactions update cùng row. Transaction 2 chờ transaction 1 xong mới đọc data. Ưu: impossible operate on stale data. Nhược: block cả đọc data từ row.
  • Optimistic locking - stop modification nếu state tại thời điểm modify khác lúc read.

Vấn đề không về concurrent DB transactions (hơn là business transactions) → solution 1 không áp dụng. Còn pessimistic vs optimistic.

Pessimistic locking prevent lost update nhưng khiến user khó khăn nếu block data lâu (đọc/sửa 30+ phút).

Optimistic locking ít restrictive hơn: cho multiple users access data. Nhưng nếu several users edit concurrently → chỉ 1 thành công, rest thấy error: operated on stale data, cần retry. Không ideal nhưng với proper UX có thể chấp nhận được.

Xem implement optimistic locking trong Rails REST API giả định.

Optimistic Locking Trong REST APIs

Trước khi implement Rails, nghĩ optimistic locking trong REST APIs context.

Cần track object's original state khi read để compare với state lúc update. Nếu state không đổi → allow. Nếu đổi → fail.

Cần giải quyết trong REST APIs:

  • Khi read resource, express current state object như thế nào và return trong response cho consumer?
  • Consumer propagate original state như thế nào khi update?
  • API return gì cho consumer nếu state changed và update không possible?

Tin tốt: tất cả answered bằng HTTP semantics.

Track resource state: dùng Entity Tags (ETags). Return resource fingerprint/checksum/version trong header ETag để consumer gửi sau với PATCH request. Dùng If-Match header → server dễ dàng check resource changed hay không (compare checksums/version/ETag).

Request succeed nếu current ETag và If-Match giống nhau. Nếu khác → respond 412 Precondition Failed (status phù hợp nhất).

Scenario khác: consumer không provide If-Match. Có thể ignore concurrency protection, nhưng không ideal. Solution: require If-Match header, respond 428 Precondition Required nếu thiếu.

Solid overview done. Implement Rails!

Optimistic Locking Trong Rails

Tin tốt: Rails hỗ trợ optimistic locking out-of-the-box qua ActiveRecord::Locking::Optimistic. Thêm column lock_version (hoặc custom column, cần declare thêm trên model), ActiveRecord sẽ increment sau mỗi change và check version hiện tại có expected không. Nếu stale → raise ActiveRecord::StaleObjectError trên update/destroy.

Cách dễ nhất handle trong API: dùng giá trị lock_version làm ETag. Implement trong RentalsController:

class RentalsController
  after_action :assign_etag, only: [:show]
  def show
    @rental = Rental.find(params[:id])
    respond_with @rental
  end
  private
  def assign_etag
    response.headers["ETag"] = @rental.lock_version
  end
end

Controller simplified (chỉ quan tâm optimistic locking, không auth/authorization). Expose ETag cho consumer. Xử lý If-Match header consumer cung cấp:

class RentalsController
  after_action :assign_etag, only: [:show, :update]
  def show
    @rental = Rental.find(params[:id])
    respond_with @rental
  end
  def update
    @rental = Rental.find(params[:id])
    @rental.update(rental_params)
    respond_with @rental
  end
  private
  def assign_etag
    response.headers["ETag"] = @rental.lock_version
  end
  def rental_params
    params
      .require(:rental)
      .permit(:some, :permitted, :attributes)
      .merge(lock_version: lock_version_from_if_match_header)
  end
  def lock_version_from_if_match_header
    request.headers["If-Match"].to_i
  end
end

Đã đủ minimal optimistic locking! Nhưng không muốn return 500 nếu conflict. Make If-Match required cho update:

class RentalsController
  before_action :ensure_if_match_header_provided, only: [:update]
  after_action :assign_etag, only: [:show, :update]
  rescue_from ActiveRecord::StaleObjectError do
    head 412
  end
  def show
    @rental = Rental.find(params[:id])
    respond_with @rental
  end
  def update
    @rental = Rental.find(params[:id])
    @rental.update(rental_params)
    respond_with @rental
  end
  private
  def ensure_if_match_header_provided
    request.headers["If-Match"].present? or head 428 and return
  end
  def assign_etag
    response.headers["ETag"] = @rental.lock_version
  end
  def rental_params
    params
      .require(:rental)
      .permit(:some, :permitted, :attributes)
      .merge(lock_version: lock_version_from_if_match_header)
  end
  def lock_version_from_if_match_header
    request.headers["If-Match"].to_i
  end
end

Đã implement đầy đủ functionality. Có thể improve thêm (error messages chi tiết hơn) nhưng ngoài scope bài viết.

Tóm Tắt: Tầm Quan Trọng Của Optimistic Locking Trong Rails APIs

Concurrency protection thường bị overlooked khi design REST APIs → severe consequences.

Tuy nhiên, implement optimistic locking trong Rails APIs straightforward - như bài demo - giúp avoid critical issues.

Happy coding!

P.S. Đăng ký Ruby Magic newsletter để đọc sớm nhất!