작업 미들웨어
미들웨어는 작업의 각 시도 전후에 실행됩니다. 작업은 fn middleware()에서 미들웨어를 나열하며, 이는 작업의 필드로 계산되므로 키에 필드를 포함할 수 있습니다:
<import package="KScript.Queue" />
<job name="ImportContacts">
<field name="user_id" type="int" />
<fn name="middleware" value="[@without_overlapping("contacts-{.user_id}"), @rate_limited('crm', limit: 10, per: 1m)]" />
<fn name="handle">
<echo>Importing contacts for {.user_id}</echo>
</fn>
</job>import KScript.Queue
job ImportContacts {
user_id: int
fn middleware() => [@without_overlapping("contacts-{.user_id}"), @rate_limited('crm', limit: 10, per: 1m)]
fn handle() {
echo "Importing contacts for {.user_id}"
}
}@without_overlapping(key)은 같은 키를 가진 이 유형의 작업을 한 번에 하나씩 실행합니다. 다른 작업은 시도 횟수를 소모하지 않고 release_after(기본 10초) 동안 큐로 돌아갑니다. 워커가 키를 쥔 채 멈추면 키는 expires(기본은 작업의 제한 시간) 후에 해제됩니다.
@rate_limited(key, limit:, per:)은 같은 키를 가진 작업이 연결의 모든 워커에 걸쳐 각 기간마다 최대 limit개까지 시작되도록 합니다. 한도를 넘는 작업은 시도 횟수를 소모하지 않고 다음 기간까지 큐로 돌아갑니다.
미들웨어는 함수일 수도 있습니다. 함수는 나머지 미들웨어를 실행한 뒤 handle를 호출할지 결정하는 next를 받습니다:
<import package="KScript.Queue" />
<job name="Sync">
<fn name="middleware" value="[fn(next) => @env('SYNC_PAUSED', 'no') == 'yes' ? null : $next()]" />
<fn name="handle">
<echo>Syncing</echo>
</fn>
</job>import KScript.Queue
job Sync {
fn middleware() => [fn(next) => @env('SYNC_PAUSED', 'no') == 'yes' ? null : $next()]
fn handle() {
echo 'Syncing'
}
}