pi-async-task-queue 0.1.5

任务队列接口及默认实现
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! 单线程本地侵入式双端队列(intrusive deque),不承担执行器(executor)职责。
use crate::external::TaskBatch;
use crate::management::QueueCleanupProgress;
use intrusive_collections::linked_list::LinkOps;
use intrusive_collections::{Adapter, DefaultPointerOps, LinkedList, LinkedListLink, UnsafeRef};
use pi_async_task::definitions::TaskOwnerId;
use pi_async_task::{QueueEntry, Runnable, TaskThread};
use pi_result::RawResult as Result;
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::rc::Rc;

// TaskQueue只在其创建线程使用,&mut串行维护链接及usize计数,无额外互斥锁。
// QueueEntry内嵌于原任务,UnsafeRef仅承载结构指针;真正强持有在node.ticket,
// 入链前store唯一Runnable,安全摘链后take,队列Drop必须逐个归还,不能只drop UnsafeRef。
// 这是有界的结构往返:Adapter.get_link -> QueueEntry.link_from_node;
// Adapter.get_value -> QueueEntry.node_from_link;只处理本队列已保活节点,不恢复F/Header。
// 同一组链接同一时刻只属一个队列。成功出队且链接操作完整结束后才可复用。
// push_front是下一个选择优先,不切断当前poll,不承诺高优先级无限插入时仍公平。
// 外部批次只能append到尾部,保持其获取顺序;不将加权池称为全局FIFO。
// closed仅控制三个压入入口,不控制摘链或Drop。所有访问均在所属线程(owner thread)
// 的独占借用中完成,无新增原子(atomic)或锁(lock)。close先停收再调用clear,
// clear内部处理当前固定范围,不交出待清理原值、不轮询(poll)。普通drain仍明确交付原批次。
// 内部释放(drop)只经原Runnable路径,不直接访问原Future;本队列(queue)结束不证明原Future已析构。

/// 内部任务队列(internal task queue),在所属线程(owner thread)排他访问。
///
/// 一个实例只能绑定一个执行器(executor)。实现可自行保管原可执行句柄(Runnable),
/// 使用者须分别给每个执行器提供自己的内部队列。该要求也适用于可复制句柄(handle)的实现。
///
/// 交接按值移动同一原可执行句柄(Runnable)。合法拒绝返还原值和原因;成功后不由调用方继续持有。
/// 实现接管原值后须正常返回 `Ok(())`;可能展开(unwind)的处理须在接管前完成。
/// 开放后须接收所有符合所属域、状态及本实现布局的任务,特别是已经接纳的合法返回;
/// 已接纳任务能继续回到本队列,无需等待空位。单项存取和查询不轮询(poll)或调用应用代码。
// @trace 107
pub trait InternalTaskQueue {
    /// 成功把原值放在下次取得的位置;拒绝时原值和顺序保持。
    fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError>;
    /// 成功把同一原值放在现有任务后;拒绝返还原值和实际原因。
    fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError>;
    /// 取回队首原值一次;空时为 None,无额外接纳(admission)。
    fn pop_internal_front(&mut self) -> Option<Runnable>;
    /// 本次查询时队列实际持有的原值数量。
    fn internal_len(&self) -> usize;
    /// 已预绑定的所属域;None 表示本实现没有预绑定。
    fn internal_owner_id(&self) -> Option<TaskOwnerId>;
    /// 是否已永久停止接收;不据此推断清理已完成。
    fn is_internal_closed(&self) -> bool;
    /// 清理当前范围并返回真实进度,保留原开放或关闭状态。原值析构(drop)的恐慌(panic)沿原责任传播。
    /// 完成只确认本队列的持有已清理或合法移交。
    fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress>;
    /// 先永久停收再清理。处理失败仍维持停收,未结清持有继续由队列负责。
    /// 返回的进度只描述本队列的责任。
    fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress>;
}

/// 与所属域(owner domain)绑定的内部任务队列(internal task queue),仅在所属线程访问。
/// 队列不可跨线程移动或共享。
///
/// 默认构造只接收同所属域的任务(Task)。选择 `true` 时尾插可接收未绑定任务,
/// 头插和整批追加仍要求同所属域。持有任务不建立接纳(admission)或改变其所属域。
// @trace 100
pub struct TaskQueue<const ALLOW_UNBOUND: bool = false> {
    owner: TaskOwnerId,
    entries: LinkedList<QueueAdapter>,
    count: usize,
    closed: bool,
    local: PhantomData<Rc<()>>,
}

/// 入队失败时返还原持有,队列不改变原任务(Task)的绑定。
// @trace 101
pub struct QueuePushError {
    /// 未接纳到本队列的原Runnable。
    pub task: Runnable,
    /// 明确拒绝原因。
    pub cause: QueuePushErrorKind,
}

/// 整批预检查失败,原批次完整返回,没有已插入前缀。
// @trace 102
pub struct BatchPushError {
    /// 原顺序保持,调用者继续承担交付或退出责任。
    pub batch: TaskBatch,
    /// 首个明确拒绝原因。
    pub cause: QueuePushErrorKind,
}

// @trace 103
struct QueueAdapter {
    links: LinkOps,
    pointers: DefaultPointerOps<UnsafeRef<QueueEntry>>,
}

// SAFETY: 两个换算严格互逆且仅用于保活QueueEntry;指针持有槽由TaskQueue维护。
unsafe impl Adapter for QueueAdapter {
    type LinkOps = LinkOps;
    type PointerOps = DefaultPointerOps<UnsafeRef<QueueEntry>>;
    unsafe fn get_value(&self, link: NonNull<LinkedListLink>) -> *const QueueEntry {
        // SAFETY: Adapter调用者保证这是本适配器先前返回的有效链接。
        unsafe { adapter_value_inner(self, link) }
    }
    unsafe fn get_link(&self, value: *const QueueEntry) -> NonNull<LinkedListLink> {
        // SAFETY: Adapter调用者保证value有效且仍由本队列保活。
        unsafe { adapter_link_inner(self, value) }
    }
    fn link_ops(&self) -> &Self::LinkOps {
        adapter_ops_inner(self)
    }
    fn link_ops_mut(&mut self) -> &mut Self::LinkOps {
        adapter_ops_mut_inner(self)
    }
    fn pointer_ops(&self) -> &Self::PointerOps {
        adapter_pointer_ops_inner(self)
    }
}

/// 本地队列的有限拒绝分类;拒绝不隐式取消原任务(Task)。
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
// @trace 104
pub enum QueuePushErrorKind {
    /// 本队列(queue)已关闭;优先拒绝压入,原值或完整原批次(batch)返还。
    Closed,
    /// 入口要求同域而任务(Task)尚未绑定,或原任务已属于其它域。
    WrongOwner,
    /// 创建时未选择包含本地链接(link)的IntrusiveLocal或IntrusiveLocalAndMpsc布局(layout)。
    LinkMissing,
    /// 对应链接仍被另一次成员关系占用。
    AlreadyLinked,
    /// 本地精确计数将溢出;不允许回绕。
    CountOverflow,
}

// @trace 1
impl TaskQueue<false> {
    /// 建立与当前所属域绑定的空队列(queue);不接纳或执行任务(Task)。
    pub fn new(owner: &TaskThread) -> Self {
        queue_new_inner(owner)
    }
}

// @trace 2
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 取得不可更换的所属域身份,O(1)。
    pub fn owner_id(&self) -> TaskOwnerId {
        queue_owner_inner(self)
    }
}

// @trace 3
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 查询本队列当前精确数量,O(1),不含外部队列及执行中任务。
    pub fn len(&self) -> usize {
        queue_len_inner(self)
    }
}

// @trace 4
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 只判断本地是否无节点,不证明运行时(runtime)可以结束。
    pub fn is_empty(&self) -> bool {
        queue_is_empty_inner(self)
    }
}

// @trace 5
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 将本地任务放到队首,影响下一次选择,不打断当前轮询(poll)。
    /// 失败返还原值;不隐式接纳到执行器(executor)。
    /// 关闭后优先返回Closed,O(1)且不访问节点(node)或执行原值。
    pub fn push_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        self.try_push::<true>(task)
    }
}

// @trace 6
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 从队首取出唯一可执行持有;空时None,不轮询(poll)。
    pub fn pop_front(&mut self) -> Option<Runnable> {
        let node = queue_unlink_inner::<ALLOW_UNBOUND, true>(self)?;
        // SAFETY: 链接已完整摘除,节点仍由同一次存入的原值保活。
        Some(unsafe { take_for_queue::<ALLOW_UNBOUND>(node, self.owner) })
    }
}

// @trace 7
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 将任务(Task)放到队尾。挂起(Pending)后重新唤醒可使用此入口。
    /// `TaskQueue<true>` 还允许未绑定原值。失败返还原值,保持原接纳(admission)状态。
    /// 关闭后优先返回Closed,O(1)且不访问节点(node)或执行原值。
    pub fn push_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        self.try_push::<false>(task)
    }
}

// @trace 8
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 从队尾取出唯一可执行持有;空时None,不轮询(poll)。
    pub fn pop_back(&mut self) -> Option<Runnable> {
        let node = queue_unlink_inner::<ALLOW_UNBOUND, false>(self)?;
        // SAFETY: 链接已完整摘除,节点仍由同一次存入的原值保活。
        Some(unsafe { take_for_queue::<ALLOW_UNBOUND>(node, self.owner) })
    }
}

// @trace 9
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 把外部单次获取的有序批次完整追加到队尾,返回追加数量。
    /// 先完整预检查;失败返回原批次,不留下部分成功前缀。O(n),不等待新增任务。
    /// 关闭后优先返回Closed,保留完整原批次(TaskBatch)及顺序;此路径O(1)。
    pub fn append_batch(&mut self, mut batch: TaskBatch) -> Result<usize, BatchPushError> {
        if self.closed {
            return Err(BatchPushError { batch, cause: QueuePushErrorKind::Closed });
        }
        let count = match queue_append_count_inner(self, &batch) {
            Ok(value) => value,
            Err(cause) => return Err(BatchPushError { batch, cause }),
        };
        let length = batch.tasks.len();
        for checked in 0..length {
            let task = batch.tasks.pop_front().unwrap_or_else(|| std::process::abort());
            // SAFETY: 全批通过同域预检查,每份唯一原值保活节点。预查存入后立即配对取回,尚未入链。
            match unsafe { store_for_queue::<ALLOW_UNBOUND>(task, self.owner) } {
                Ok(node) => {
                    // SAFETY: 本次存入尚未入链,节点由原值保活,仍持有唯一取回权。
                    let task = unsafe { take_for_queue::<ALLOW_UNBOUND>(node, self.owner) };
                    batch.tasks.push_back(task);
                }
                Err(task) => {
                    batch.tasks.push_front(task);
                    batch.tasks.rotate_right(checked);
                    return Err(BatchPushError { batch, cause: QueuePushErrorKind::LinkMissing });
                }
            }
        }
        for task in batch.tasks {
            // SAFETY: 预查和提交之间保持队列及原值的独占访问,没有执行用户代码。
            let node = unsafe { store_for_queue::<ALLOW_UNBOUND>(task, self.owner) }
                .unwrap_or_else(|_| std::process::abort());
            // SAFETY: 保管槽内的原值保活节点,链接仍空闲。
            unsafe { self.link_stored::<false>(node) };
        }
        self.count = count;
        Ok(length)
    }
}

// @trace 10
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 按队首顺序取回全部当前持有,返回批次;不执行或自动取消它们。
    pub fn drain(&mut self) -> TaskBatch {
        let mut tasks = std::collections::VecDeque::with_capacity(self.count);
        while let Some(task) = self.pop_front() {
            tasks.push_back(task);
        }
        TaskBatch::from_tasks(tasks)
    }
}

// @trace 11
impl<const ALLOW_UNBOUND: bool> Drop for TaskQueue<ALLOW_UNBOUND> {
    /// 归还所有队列持有并正常释放;不遗留节点内自持有环,不直接推进业务原值。
    fn drop(&mut self) {
        let mut remaining = Remaining { queue: self };
        // 首个析构(drop)展开时,守卫的析构继续处理余项。
        remaining.release();
    }
}

// @trace 105
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 在队列(queue)内部清理当前全部持有,保持接收的开放/关闭标记,不轮询(poll)。
    ///
    /// 在所属线程(owner thread)通过排他借用同步完成;无并发提交扩展本次范围。
    /// 不返回待清理批次(TaskBatch),按原Runnable的合法释放(drop)路径处理;
    /// `Complete`不保证原异步计算(Future)已确认析构(drop)。
    /// 无新增内容时重复调用不重复释放;O(n)处理当前数量,不等待其它线程(thread)。
    /// 本地实现当前无可恢复错误;分配或原有操作的恐慌(panic)不转换为伪成功。
    pub fn clear(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        drop(self.drain());
        Ok(QueueCleanupProgress::Complete)
    }
}

// @trace 106
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    /// 永久停止压入,再按`clear`内部处理全部当前持有;幂等(idempotent),不重新开放。
    ///
    /// `push_front`、`push_back`、`append_batch`从停收后返还原值和Closed分类。
    /// 已有弹出、`drain`及析构(Drop)仍处理余项,不因停收跳过清理。
    /// 返回语义、所属线程(owner thread)及成本同`clear`;若清理异常,停收标记仍保持。
    /// 完成只确认本队列(queue)的责任结束/合法移交,不确认任务(Task)取消成功或全部退出。
    pub fn close(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.closed = true;
        self.clear()
    }
}

// 内部设计。单项存入先检查停收、所属域与数量,再保管原值、实际入链并记数。
// 存入与链接之间由 UnlinkedTicket 保有撤销权。全部取出先完成摘链并结清数量,
// 再由同组取回交还原持有。clear 经 drain 移出独立 TaskBatch,余项由独立批次管理。
// close 先停收。Drop 经 Remaining 逐项摘除并释放,可在首次原值析构展开时接续。
// 前后入链、拒绝、批次预查或成功提交的中间状态均在线程排他访问内,数量在调用边界精确。
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
    fn try_push<const FRONT: bool>(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        if self.closed {
            return Err(QueuePushError { task, cause: QueuePushErrorKind::Closed });
        }
        let count = match queue_push_count_inner::<ALLOW_UNBOUND, FRONT>(self, &task) {
            Ok(count) => count,
            Err(cause) => return Err(QueuePushError { task, cause }),
        };
        // SAFETY: 原 Runnable 是本次唯一的可执行持有,保活独占访问的未入链节点。
        let node = unsafe { store_for_queue::<ALLOW_UNBOUND>(task, self.owner) }
            .map_err(|task| QueuePushError { task, cause: QueuePushErrorKind::LinkMissing })?;
        let mut rollback = UnlinkedTicket::<ALLOW_UNBOUND> {
            node,
            owner: self.owner,
            armed: true,
        };
        // SAFETY: 存入成功,节点由保管槽持有,链接仍空闲。
        unsafe { self.link_stored::<FRONT>(node) };
        self.count = count;
        rollback.armed = false;
        Ok(())
    }

    /// 调用者持有保管槽中的唯一原值,节点仍未入链,且当前队列由所属线程独占。
    unsafe fn link_stored<const FRONT: bool>(&mut self, node: NonNull<QueueEntry>) {
        unsafe { queue_link_inner::<ALLOW_UNBOUND, FRONT>(self, node) };
    }
}

struct UnlinkedTicket<const ALLOW_UNBOUND: bool> {
    node: NonNull<QueueEntry>,
    owner: TaskOwnerId,
    armed: bool,
}

impl<const ALLOW_UNBOUND: bool> Drop for UnlinkedTicket<ALLOW_UNBOUND> {
    fn drop(&mut self) {
        if self.armed {
            // SAFETY: 保管槽仍持有原值,本次守卫覆盖对未提交节点的排他访问。
            let link = unsafe { QueueEntry::link_from_node(self.node) };
            // SAFETY: 投影来自同一个仍保活的节点,只有此线程可以改变链接。
            if !unsafe { link.as_ref() }.is_linked() {
                // SAFETY: 本次原存入尚未入链,此守卫持有唯一撤销权。
                drop(unsafe { take_for_queue::<ALLOW_UNBOUND>(self.node, self.owner) });
            }
        }
    }
}

struct Remaining<'queue, const ALLOW_UNBOUND: bool> {
    queue: &'queue mut TaskQueue<ALLOW_UNBOUND>,
}

impl<const ALLOW_UNBOUND: bool> Remaining<'_, ALLOW_UNBOUND> {
    fn release(&mut self) {
        while let Some(task) = self.queue.pop_front() {
            drop(task);
        }
    }
}

impl<const ALLOW_UNBOUND: bool> Drop for Remaining<'_, ALLOW_UNBOUND> {
    fn drop(&mut self) {
        self.release();
    }
}

// 成对存取由类型(type)决定。拒绝返还原持有,无需读额外模式字段。
// 调用者独占实际节点及配对责任,取回时已完整摘链或从未入链。
#[inline(always)]
unsafe fn store_for_queue<const ALLOW_UNBOUND: bool>(
    task: Runnable,
    owner: TaskOwnerId,
) -> Result<NonNull<QueueEntry>, Runnable> {
    if ALLOW_UNBOUND {
        // SAFETY: 调用者持有原可执行句柄及排他节点访问权。
        unsafe { QueueEntry::store_with_unbound(task, owner) }
    } else {
        // SAFETY: 原持有已核本域,调用者独占该节点。
        unsafe { QueueEntry::store(task, owner) }
    }
}

#[inline(always)]
unsafe fn take_for_queue<const ALLOW_UNBOUND: bool>(
    node: NonNull<QueueEntry>,
    owner: TaskOwnerId,
) -> Runnable {
    if ALLOW_UNBOUND {
        // SAFETY: 节点仍由本次同组存入的原值保活,且从未入链或完整摘链。
        unsafe { QueueEntry::take_with_unbound(node, owner) }
    } else {
        // SAFETY: 本次同组存入的同域节点仍保活,链接已解除或尚未建立。
        unsafe { QueueEntry::take(node, owner) }
    }
}

// @trace 108
impl TaskQueue<true> {
    /// 建立开放的空队列,允许从队尾接收未绑定或属于 `owner` 的原任务(Task)。
    ///
    /// 头插和整批追加仍要求同所属域。队列由 `owner` 的所属线程(owner thread)独占使用。
    pub fn new_with_unbound(owner: &TaskThread) -> Self {
        queue_new_with_unbound_inner(owner)
    }
}

impl<const ALLOW_UNBOUND: bool> InternalTaskQueue for TaskQueue<ALLOW_UNBOUND> {
    fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        self.push_front(task)
    }
    /// 沿 [`TaskQueue::push_back`] 的接收和拒绝条件。
    fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
        self.push_back(task)
    }
    fn pop_internal_front(&mut self) -> Option<Runnable> {
        self.pop_front()
    }
    fn internal_len(&self) -> usize {
        self.len()
    }
    fn internal_owner_id(&self) -> Option<TaskOwnerId> {
        Some(self.owner_id())
    }
    fn is_internal_closed(&self) -> bool {
        self.closed
    }
    fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.clear()
    }
    fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
        self.close()
    }
}

include!("local_inner.rs");