pub struct PeerTaskQueue<T: Topic, D: Data, TM: TaskMerger<T, D> = DefaultTaskMerger> { /* private fields */ }
Expand description

Prioritzed list of tasks to be executed on peers.

Tasks are added to the queue, then popped off alternately between peers (roughly) to execute the block with the highest priority, or otherwise the one added first if priorities are equal.

Implementations§

Examples found in repository?
src/peer_task_queue.rs (line 37)
36
37
38
    fn default() -> Self {
        Self::new(TM::default(), Config::default())
    }
More examples
Hide additional examples
src/server/decision.rs (lines 132-138)
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
    pub async fn new(store: S, _self_id: PeerId, config: Config) -> Self {
        // TODO: insert options for peertaskqueue

        // TODO: limit?
        let outbox = async_channel::bounded(1024);
        let work_signal = Arc::new(Notify::new());

        let task_merger = TaskMerger::default();
        let peer_task_queue = PeerTaskQueue::new(
            task_merger,
            PTQConfig {
                max_outstanding_work_per_peer: config.max_outstanding_bytes_per_peer,
                ignore_freezing: true,
            },
        );
        let peer_task_hook = peer_task_queue.add_hook(64).await;
        let blockstore_manager = Arc::new(RwLock::new(
            BlockstoreManager::new(store, config.engine_blockstore_worker_count).await,
        ));
        let score_ledger = DefaultScoreLedger::new(Box::new(|_peer, _score| {
            // if score == 0 {
            //     // untag peer("useful")
            // } else {
            //     // tag peer("useful", score)
            // }
        }))
        .await;
        let target_message_size = config.target_message_size;
        let task_worker_count = config.engine_task_worker_count;
        let mut workers = Vec::with_capacity(task_worker_count);

        let rt = tokio::runtime::Handle::current();
        for i in 0..task_worker_count {
            let outbox = outbox.0.clone();
            let (closer_s, mut closer_r) = oneshot::channel();

            let peer_task_queue = peer_task_queue.clone();
            let mut ticker = tokio::time::interval(Duration::from_millis(100));
            let work_signal = work_signal.clone();
            let blockstore_manager = blockstore_manager.clone();
            let peer_task_hook = peer_task_hook.clone();

            let handle = rt.spawn(async move {
                loop {
                    inc!(BitswapMetrics::EngineLoopTick);
                    tokio::select! {
                        biased;
                        _ = &mut closer_r => {
                            break;
                        }
                        event = peer_task_hook.recv() => {
                            debug!("peer queue event: {:?}", event);
                            // TODO: tag/untag peer
                        }
                        _ = work_signal.notified() => {
                            // not needed anymore?
                        }
                        _ = ticker.tick() => {
                            // TODO: remove thaw_round is not used atm
                            // When a task is cancelled, the qeue may be "frozen"
                            // for a period of time. We periodically "thaw" the queue
                            // to make sure it doesn't get suck in a frozen state.
                            // peer_task_queue.thaw_round().await;
                            if let Some((peer, next_tasks, pending_bytes)) = peer_task_queue.pop_tasks(target_message_size).await {
                                if next_tasks.is_empty() {
                                    continue;
                                }
                                debug!("engine:{} next envelope:tick tasks: {}", i, next_tasks.len());

                                // create a new message
                                let mut msg = BitswapMessage::new(false);
                                msg.set_pending_bytes(pending_bytes as _);

                                // split out want-blocks, want-have and DONT_HAVEs
                                let mut block_cids = Vec::new();
                                let mut block_tasks = AHashMap::new();

                                for task in &next_tasks {
                                    if task.data.have_block {
                                        if task.data.is_want_block {
                                            block_cids.push(task.topic);
                                            block_tasks.insert(task.topic, task);
                                        } else {
                                            // add HAVEs to the message
                                            msg.add_have(task.topic);
                                        }
                                    } else {
                                        // add DONT_HAVEs to the message
                                        msg.add_dont_have(task.topic);
                                    }
                                }

                                // Fetch blocks from the store
                                let mut blocks = match blockstore_manager
                                    .read()
                                    .await
                                    .get_blocks(&block_cids)
                                    .await {
                                        Ok(blocks) => blocks,
                                        Err(err) => {
                                            warn!("failed to load blocks: {:?}", err);
                                            continue;
                                        }
                                    };

                                for (cid, task) in block_tasks {
                                    if let Some(block) = blocks.remove(&cid) {
                                        msg.add_block(block);
                                    } else {
                                        // block was not found
                                        if task.data.send_dont_have {
                                            msg.add_dont_have(cid);
                                        }
                                    }
                                }

                                // nothing to see here
                                if msg.is_empty() {
                                    peer_task_queue.tasks_done(peer, &next_tasks).await;
                                    continue;
                                }

                                let envelope = Ok(Envelope {
                                    peer,
                                    message: msg,
                                    sent_tasks: next_tasks,
                                    queue: peer_task_queue.clone(),
                                    work_signal: work_signal.clone(),
                                });
                                if let Err(err) = outbox.send(envelope).await {
                                    error!("failed to deliver envelope: {:?}", err);
                                }
                            }
                        }
                    }
                }
            });
            workers.push((closer_s, handle));
        }

        Engine {
            peer_task_queue,
            outbox: outbox.1,
            blockstore_manager,
            ledger_map: Default::default(),
            peer_ledger: Mutex::new(PeerLedger::default()),
            score_ledger,
            max_block_size_replace_has_with_block: config.max_replace_size,
            send_dont_haves: config.send_dont_haves,
            metrics_update_counter: Default::default(),
            peer_block_request_filter: config.peer_block_request_filter,
            workers,
            work_signal,
        }
    }

Adds a hook to be notified on Events.

Examples found in repository?
src/server/decision.rs (line 139)
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
    pub async fn new(store: S, _self_id: PeerId, config: Config) -> Self {
        // TODO: insert options for peertaskqueue

        // TODO: limit?
        let outbox = async_channel::bounded(1024);
        let work_signal = Arc::new(Notify::new());

        let task_merger = TaskMerger::default();
        let peer_task_queue = PeerTaskQueue::new(
            task_merger,
            PTQConfig {
                max_outstanding_work_per_peer: config.max_outstanding_bytes_per_peer,
                ignore_freezing: true,
            },
        );
        let peer_task_hook = peer_task_queue.add_hook(64).await;
        let blockstore_manager = Arc::new(RwLock::new(
            BlockstoreManager::new(store, config.engine_blockstore_worker_count).await,
        ));
        let score_ledger = DefaultScoreLedger::new(Box::new(|_peer, _score| {
            // if score == 0 {
            //     // untag peer("useful")
            // } else {
            //     // tag peer("useful", score)
            // }
        }))
        .await;
        let target_message_size = config.target_message_size;
        let task_worker_count = config.engine_task_worker_count;
        let mut workers = Vec::with_capacity(task_worker_count);

        let rt = tokio::runtime::Handle::current();
        for i in 0..task_worker_count {
            let outbox = outbox.0.clone();
            let (closer_s, mut closer_r) = oneshot::channel();

            let peer_task_queue = peer_task_queue.clone();
            let mut ticker = tokio::time::interval(Duration::from_millis(100));
            let work_signal = work_signal.clone();
            let blockstore_manager = blockstore_manager.clone();
            let peer_task_hook = peer_task_hook.clone();

            let handle = rt.spawn(async move {
                loop {
                    inc!(BitswapMetrics::EngineLoopTick);
                    tokio::select! {
                        biased;
                        _ = &mut closer_r => {
                            break;
                        }
                        event = peer_task_hook.recv() => {
                            debug!("peer queue event: {:?}", event);
                            // TODO: tag/untag peer
                        }
                        _ = work_signal.notified() => {
                            // not needed anymore?
                        }
                        _ = ticker.tick() => {
                            // TODO: remove thaw_round is not used atm
                            // When a task is cancelled, the qeue may be "frozen"
                            // for a period of time. We periodically "thaw" the queue
                            // to make sure it doesn't get suck in a frozen state.
                            // peer_task_queue.thaw_round().await;
                            if let Some((peer, next_tasks, pending_bytes)) = peer_task_queue.pop_tasks(target_message_size).await {
                                if next_tasks.is_empty() {
                                    continue;
                                }
                                debug!("engine:{} next envelope:tick tasks: {}", i, next_tasks.len());

                                // create a new message
                                let mut msg = BitswapMessage::new(false);
                                msg.set_pending_bytes(pending_bytes as _);

                                // split out want-blocks, want-have and DONT_HAVEs
                                let mut block_cids = Vec::new();
                                let mut block_tasks = AHashMap::new();

                                for task in &next_tasks {
                                    if task.data.have_block {
                                        if task.data.is_want_block {
                                            block_cids.push(task.topic);
                                            block_tasks.insert(task.topic, task);
                                        } else {
                                            // add HAVEs to the message
                                            msg.add_have(task.topic);
                                        }
                                    } else {
                                        // add DONT_HAVEs to the message
                                        msg.add_dont_have(task.topic);
                                    }
                                }

                                // Fetch blocks from the store
                                let mut blocks = match blockstore_manager
                                    .read()
                                    .await
                                    .get_blocks(&block_cids)
                                    .await {
                                        Ok(blocks) => blocks,
                                        Err(err) => {
                                            warn!("failed to load blocks: {:?}", err);
                                            continue;
                                        }
                                    };

                                for (cid, task) in block_tasks {
                                    if let Some(block) = blocks.remove(&cid) {
                                        msg.add_block(block);
                                    } else {
                                        // block was not found
                                        if task.data.send_dont_have {
                                            msg.add_dont_have(cid);
                                        }
                                    }
                                }

                                // nothing to see here
                                if msg.is_empty() {
                                    peer_task_queue.tasks_done(peer, &next_tasks).await;
                                    continue;
                                }

                                let envelope = Ok(Envelope {
                                    peer,
                                    message: msg,
                                    sent_tasks: next_tasks,
                                    queue: peer_task_queue.clone(),
                                    work_signal: work_signal.clone(),
                                });
                                if let Err(err) = outbox.send(envelope).await {
                                    error!("failed to deliver envelope: {:?}", err);
                                }
                            }
                        }
                    }
                }
            });
            workers.push((closer_s, handle));
        }

        Engine {
            peer_task_queue,
            outbox: outbox.1,
            blockstore_manager,
            ledger_map: Default::default(),
            peer_ledger: Mutex::new(PeerLedger::default()),
            score_ledger,
            max_block_size_replace_has_with_block: config.max_replace_size,
            send_dont_haves: config.send_dont_haves,
            metrics_update_counter: Default::default(),
            peer_block_request_filter: config.peer_block_request_filter,
            workers,
            work_signal,
        }
    }

Returns stats about the queue.

Examples found in repository?
src/server/decision.rs (line 285)
280
281
282
283
284
285
286
287
288
289
    async fn update_metrics(&self) {
        let mut counter = self.metrics_update_counter.lock().await;
        *counter += 1;

        if *counter % 100 == 0 {
            let stats = self.peer_task_queue.stats().await;
            record!(BitswapMetrics::EnginePendingTasks, stats.num_pending as u64);
            record!(BitswapMetrics::EngineActiveTasks, stats.num_active as u64);
        }
    }

List all topics for a specific peer

Adds a new group of tasks for the given peer to the queue.

Examples found in repository?
src/peer_task_queue.rs (line 140)
139
140
141
    pub async fn push_task(&self, peer: PeerId, task: Task<T, D>) {
        self.push_tasks(peer, vec![task]).await;
    }
More examples
Hide additional examples
src/server/decision.rs (line 447)
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
    pub async fn message_received(&self, peer: &PeerId, message: &BitswapMessage) {
        if message.is_empty() {
            info!("received empty message from {}", peer);
        }

        let mut new_work_exists = false;
        let (wants, cancels, denials) = self.split_wants(peer, message.wantlist());

        // get block sizes
        let mut want_ks = AHashSet::new();
        for entry in &wants {
            want_ks.insert(entry.cid);
        }
        let want_ks: Vec<_> = want_ks.into_iter().collect();
        let block_sizes = match self
            .blockstore_manager
            .read()
            .await
            .get_block_sizes(&want_ks)
            .await
        {
            Ok(s) => s,
            Err(err) => {
                warn!("failed to fetch block sizes: {:?}", err);
                return;
            }
        };

        {
            let mut peer_ledger = self.peer_ledger.lock().await;
            for want in &wants {
                peer_ledger.wants(*peer, want.cid);
            }
            for canel in &cancels {
                peer_ledger.cancel_want(peer, &canel.cid);
            }
        }

        // get the ledger for the peer
        let l = self.find_or_create(peer).await;
        let mut ledger = l.lock().await;

        // if the peer sent a full wantlist, clear the existing wantlist.
        if message.full() {
            ledger.clear_wantlist();
        }
        let mut active_entries = Vec::new();
        for entry in &cancels {
            if ledger.cancel_want(&entry.cid).is_some() {
                self.peer_task_queue.remove(&entry.cid, *peer).await;
            }
        }

        let send_dont_have = |entries: &mut Vec<_>, new_work_exists: &mut bool, entry: &Entry| {
            // only add the task to the queue if the requester wants DONT_HAVE
            if self.send_dont_haves && entry.send_dont_have {
                let cid = entry.cid;
                *new_work_exists = true;
                let is_want_block = entry.want_type == WantType::Block;
                entries.push(Task {
                    topic: cid,
                    priority: entry.priority as isize,
                    work: BlockPresence::encoded_len_for_cid(cid),
                    data: TaskData {
                        block_size: 0,
                        have_block: false,
                        is_want_block,
                        send_dont_have: entry.send_dont_have,
                    },
                });
            }
        };

        // deny access to blocks
        for entry in &denials {
            send_dont_have(&mut active_entries, &mut new_work_exists, entry);
        }

        // for each want-have/want-block
        for entry in &wants {
            let cid = entry.cid;

            // add each want-have/want-block to the ledger
            ledger.wants(cid, entry.priority, entry.want_type);

            if let Some(block_size) = block_sizes.get(&cid) {
                // the block was found
                new_work_exists = true;
                let is_want_block = self.send_as_block(entry.want_type, *block_size);
                let entry_size = if is_want_block {
                    *block_size
                } else {
                    BlockPresence::encoded_len_for_cid(cid)
                };

                active_entries.push(Task {
                    topic: cid,
                    priority: entry.priority as isize,
                    work: entry_size,
                    data: TaskData {
                        is_want_block,
                        send_dont_have: entry.send_dont_have,
                        block_size: *block_size,
                        have_block: true,
                    },
                });
            } else {
                // if the block was not found
                send_dont_have(&mut active_entries, &mut new_work_exists, entry);
            }
        }

        if !active_entries.is_empty() {
            self.peer_task_queue.push_tasks(*peer, active_entries).await;
            self.update_metrics().await;
        }

        if new_work_exists {
            self.signal_new_work();
        }
    }
Examples found in repository?
src/server/decision.rs (lines 564-577)
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
    pub async fn notify_new_blocks(&self, blocks: &[Block]) {
        if blocks.is_empty() {
            return;
        }

        // get the sizes of each block
        let block_sizes: AHashMap<_, _> = blocks
            .iter()
            .map(|block| (block.cid(), block.data().len()))
            .collect();

        let mut work = false;
        let mut missing_wants: AHashMap<PeerId, Vec<Cid>> = AHashMap::new();
        for block in blocks {
            let cid = block.cid();
            let peer_ledger = self.peer_ledger.lock().await;
            let peers = peer_ledger.peers(cid);
            if peers.is_none() {
                continue;
            }
            for peer in peers.unwrap() {
                let l = self.ledger_map.read().await.get(peer).cloned();
                if l.is_none() {
                    missing_wants.entry(*peer).or_default().push(*cid);
                    continue;
                }
                let l = l.unwrap();
                let ledger = l.lock().await;
                let entry = ledger.wantlist_get(cid);
                if entry.is_none() {
                    missing_wants.entry(*peer).or_default().push(*cid);
                    continue;
                }
                let entry = entry.unwrap();

                work = true;
                let block_size = block_sizes.get(cid).copied().unwrap_or_default();
                let is_want_block = self.send_as_block(entry.want_type, block_size);
                let entry_size = if is_want_block {
                    block_size
                } else {
                    BlockPresence::encoded_len_for_cid(*cid)
                };

                self.peer_task_queue
                    .push_task(
                        *peer,
                        Task {
                            topic: entry.cid,
                            priority: entry.priority as isize,
                            work: entry_size,
                            data: TaskData {
                                block_size,
                                have_block: true,
                                is_want_block,
                                send_dont_have: false,
                            },
                        },
                    )
                    .await;
                self.update_metrics().await;
            }
        }

        // If we found missing wants remove them from the list
        if !missing_wants.is_empty() {
            let ledger_map = self.ledger_map.read().await;
            let mut peer_ledger = self.peer_ledger.lock().await;
            for (peer, wants) in missing_wants.into_iter() {
                if let Some(l) = ledger_map.get(&peer) {
                    let ledger = l.lock().await;
                    for cid in wants {
                        if ledger.wantlist_get(&cid).is_some() {
                            continue;
                        }
                        peer_ledger.cancel_want(&peer, &cid);
                    }
                } else {
                    for cid in wants {
                        peer_ledger.cancel_want(&peer, &cid);
                    }
                }
            }
        }

        if work {
            self.signal_new_work();
        }
    }

Finds the peer with the highest priority and pops as many tasks off the peer’s queue as necessary to cover targetMinWork, in priority order.

If there are not enough tasks to cover targetMinWork it just returns whatever is in the peer’s queue.

  • Peers with the most “active” work are deprioritized. This heuristic is for fairness, we try to keep all peers “busy”.
  • Peers with the most “pending” work are prioritized. This heuristic is so that peers with a lot to do get asked for work first.

The third response argument is pending work: the amount of work in the queue for this peer.

Examples found in repository?
src/server/decision.rs (line 187)
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
    pub async fn new(store: S, _self_id: PeerId, config: Config) -> Self {
        // TODO: insert options for peertaskqueue

        // TODO: limit?
        let outbox = async_channel::bounded(1024);
        let work_signal = Arc::new(Notify::new());

        let task_merger = TaskMerger::default();
        let peer_task_queue = PeerTaskQueue::new(
            task_merger,
            PTQConfig {
                max_outstanding_work_per_peer: config.max_outstanding_bytes_per_peer,
                ignore_freezing: true,
            },
        );
        let peer_task_hook = peer_task_queue.add_hook(64).await;
        let blockstore_manager = Arc::new(RwLock::new(
            BlockstoreManager::new(store, config.engine_blockstore_worker_count).await,
        ));
        let score_ledger = DefaultScoreLedger::new(Box::new(|_peer, _score| {
            // if score == 0 {
            //     // untag peer("useful")
            // } else {
            //     // tag peer("useful", score)
            // }
        }))
        .await;
        let target_message_size = config.target_message_size;
        let task_worker_count = config.engine_task_worker_count;
        let mut workers = Vec::with_capacity(task_worker_count);

        let rt = tokio::runtime::Handle::current();
        for i in 0..task_worker_count {
            let outbox = outbox.0.clone();
            let (closer_s, mut closer_r) = oneshot::channel();

            let peer_task_queue = peer_task_queue.clone();
            let mut ticker = tokio::time::interval(Duration::from_millis(100));
            let work_signal = work_signal.clone();
            let blockstore_manager = blockstore_manager.clone();
            let peer_task_hook = peer_task_hook.clone();

            let handle = rt.spawn(async move {
                loop {
                    inc!(BitswapMetrics::EngineLoopTick);
                    tokio::select! {
                        biased;
                        _ = &mut closer_r => {
                            break;
                        }
                        event = peer_task_hook.recv() => {
                            debug!("peer queue event: {:?}", event);
                            // TODO: tag/untag peer
                        }
                        _ = work_signal.notified() => {
                            // not needed anymore?
                        }
                        _ = ticker.tick() => {
                            // TODO: remove thaw_round is not used atm
                            // When a task is cancelled, the qeue may be "frozen"
                            // for a period of time. We periodically "thaw" the queue
                            // to make sure it doesn't get suck in a frozen state.
                            // peer_task_queue.thaw_round().await;
                            if let Some((peer, next_tasks, pending_bytes)) = peer_task_queue.pop_tasks(target_message_size).await {
                                if next_tasks.is_empty() {
                                    continue;
                                }
                                debug!("engine:{} next envelope:tick tasks: {}", i, next_tasks.len());

                                // create a new message
                                let mut msg = BitswapMessage::new(false);
                                msg.set_pending_bytes(pending_bytes as _);

                                // split out want-blocks, want-have and DONT_HAVEs
                                let mut block_cids = Vec::new();
                                let mut block_tasks = AHashMap::new();

                                for task in &next_tasks {
                                    if task.data.have_block {
                                        if task.data.is_want_block {
                                            block_cids.push(task.topic);
                                            block_tasks.insert(task.topic, task);
                                        } else {
                                            // add HAVEs to the message
                                            msg.add_have(task.topic);
                                        }
                                    } else {
                                        // add DONT_HAVEs to the message
                                        msg.add_dont_have(task.topic);
                                    }
                                }

                                // Fetch blocks from the store
                                let mut blocks = match blockstore_manager
                                    .read()
                                    .await
                                    .get_blocks(&block_cids)
                                    .await {
                                        Ok(blocks) => blocks,
                                        Err(err) => {
                                            warn!("failed to load blocks: {:?}", err);
                                            continue;
                                        }
                                    };

                                for (cid, task) in block_tasks {
                                    if let Some(block) = blocks.remove(&cid) {
                                        msg.add_block(block);
                                    } else {
                                        // block was not found
                                        if task.data.send_dont_have {
                                            msg.add_dont_have(cid);
                                        }
                                    }
                                }

                                // nothing to see here
                                if msg.is_empty() {
                                    peer_task_queue.tasks_done(peer, &next_tasks).await;
                                    continue;
                                }

                                let envelope = Ok(Envelope {
                                    peer,
                                    message: msg,
                                    sent_tasks: next_tasks,
                                    queue: peer_task_queue.clone(),
                                    work_signal: work_signal.clone(),
                                });
                                if let Err(err) = outbox.send(envelope).await {
                                    error!("failed to deliver envelope: {:?}", err);
                                }
                            }
                        }
                    }
                }
            });
            workers.push((closer_s, handle));
        }

        Engine {
            peer_task_queue,
            outbox: outbox.1,
            blockstore_manager,
            ledger_map: Default::default(),
            peer_ledger: Mutex::new(PeerLedger::default()),
            score_ledger,
            max_block_size_replace_has_with_block: config.max_replace_size,
            send_dont_haves: config.send_dont_haves,
            metrics_update_counter: Default::default(),
            peer_block_request_filter: config.peer_block_request_filter,
            workers,
            work_signal,
        }
    }

Called to indicate that the given tasks have completed.

Examples found in repository?
src/server.rs (line 342)
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
async fn send_blocks(network: &Network, envelope: Envelope) {
    let Envelope {
        peer,
        message,
        sent_tasks,
        queue,
        work_signal,
    } = envelope;

    if let Err(err) = network.send_message(peer, message).await {
        debug!("failed to send message {}: {:?}", peer, err);
    }

    // trigger sent updates
    queue.tasks_done(peer, &sent_tasks).await;
    work_signal.notify_one();
}
More examples
Hide additional examples
src/server/decision.rs (line 242)
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
    pub async fn new(store: S, _self_id: PeerId, config: Config) -> Self {
        // TODO: insert options for peertaskqueue

        // TODO: limit?
        let outbox = async_channel::bounded(1024);
        let work_signal = Arc::new(Notify::new());

        let task_merger = TaskMerger::default();
        let peer_task_queue = PeerTaskQueue::new(
            task_merger,
            PTQConfig {
                max_outstanding_work_per_peer: config.max_outstanding_bytes_per_peer,
                ignore_freezing: true,
            },
        );
        let peer_task_hook = peer_task_queue.add_hook(64).await;
        let blockstore_manager = Arc::new(RwLock::new(
            BlockstoreManager::new(store, config.engine_blockstore_worker_count).await,
        ));
        let score_ledger = DefaultScoreLedger::new(Box::new(|_peer, _score| {
            // if score == 0 {
            //     // untag peer("useful")
            // } else {
            //     // tag peer("useful", score)
            // }
        }))
        .await;
        let target_message_size = config.target_message_size;
        let task_worker_count = config.engine_task_worker_count;
        let mut workers = Vec::with_capacity(task_worker_count);

        let rt = tokio::runtime::Handle::current();
        for i in 0..task_worker_count {
            let outbox = outbox.0.clone();
            let (closer_s, mut closer_r) = oneshot::channel();

            let peer_task_queue = peer_task_queue.clone();
            let mut ticker = tokio::time::interval(Duration::from_millis(100));
            let work_signal = work_signal.clone();
            let blockstore_manager = blockstore_manager.clone();
            let peer_task_hook = peer_task_hook.clone();

            let handle = rt.spawn(async move {
                loop {
                    inc!(BitswapMetrics::EngineLoopTick);
                    tokio::select! {
                        biased;
                        _ = &mut closer_r => {
                            break;
                        }
                        event = peer_task_hook.recv() => {
                            debug!("peer queue event: {:?}", event);
                            // TODO: tag/untag peer
                        }
                        _ = work_signal.notified() => {
                            // not needed anymore?
                        }
                        _ = ticker.tick() => {
                            // TODO: remove thaw_round is not used atm
                            // When a task is cancelled, the qeue may be "frozen"
                            // for a period of time. We periodically "thaw" the queue
                            // to make sure it doesn't get suck in a frozen state.
                            // peer_task_queue.thaw_round().await;
                            if let Some((peer, next_tasks, pending_bytes)) = peer_task_queue.pop_tasks(target_message_size).await {
                                if next_tasks.is_empty() {
                                    continue;
                                }
                                debug!("engine:{} next envelope:tick tasks: {}", i, next_tasks.len());

                                // create a new message
                                let mut msg = BitswapMessage::new(false);
                                msg.set_pending_bytes(pending_bytes as _);

                                // split out want-blocks, want-have and DONT_HAVEs
                                let mut block_cids = Vec::new();
                                let mut block_tasks = AHashMap::new();

                                for task in &next_tasks {
                                    if task.data.have_block {
                                        if task.data.is_want_block {
                                            block_cids.push(task.topic);
                                            block_tasks.insert(task.topic, task);
                                        } else {
                                            // add HAVEs to the message
                                            msg.add_have(task.topic);
                                        }
                                    } else {
                                        // add DONT_HAVEs to the message
                                        msg.add_dont_have(task.topic);
                                    }
                                }

                                // Fetch blocks from the store
                                let mut blocks = match blockstore_manager
                                    .read()
                                    .await
                                    .get_blocks(&block_cids)
                                    .await {
                                        Ok(blocks) => blocks,
                                        Err(err) => {
                                            warn!("failed to load blocks: {:?}", err);
                                            continue;
                                        }
                                    };

                                for (cid, task) in block_tasks {
                                    if let Some(block) = blocks.remove(&cid) {
                                        msg.add_block(block);
                                    } else {
                                        // block was not found
                                        if task.data.send_dont_have {
                                            msg.add_dont_have(cid);
                                        }
                                    }
                                }

                                // nothing to see here
                                if msg.is_empty() {
                                    peer_task_queue.tasks_done(peer, &next_tasks).await;
                                    continue;
                                }

                                let envelope = Ok(Envelope {
                                    peer,
                                    message: msg,
                                    sent_tasks: next_tasks,
                                    queue: peer_task_queue.clone(),
                                    work_signal: work_signal.clone(),
                                });
                                if let Err(err) = outbox.send(envelope).await {
                                    error!("failed to deliver envelope: {:?}", err);
                                }
                            }
                        }
                    }
                }
            });
            workers.push((closer_s, handle));
        }

        Engine {
            peer_task_queue,
            outbox: outbox.1,
            blockstore_manager,
            ledger_map: Default::default(),
            peer_ledger: Mutex::new(PeerLedger::default()),
            score_ledger,
            max_block_size_replace_has_with_block: config.max_replace_size,
            send_dont_haves: config.send_dont_haves,
            metrics_update_counter: Default::default(),
            peer_block_request_filter: config.peer_block_request_filter,
            workers,
            work_signal,
        }
    }

Removes a task from the queue

Examples found in repository?
src/server/decision.rs (line 383)
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
    pub async fn message_received(&self, peer: &PeerId, message: &BitswapMessage) {
        if message.is_empty() {
            info!("received empty message from {}", peer);
        }

        let mut new_work_exists = false;
        let (wants, cancels, denials) = self.split_wants(peer, message.wantlist());

        // get block sizes
        let mut want_ks = AHashSet::new();
        for entry in &wants {
            want_ks.insert(entry.cid);
        }
        let want_ks: Vec<_> = want_ks.into_iter().collect();
        let block_sizes = match self
            .blockstore_manager
            .read()
            .await
            .get_block_sizes(&want_ks)
            .await
        {
            Ok(s) => s,
            Err(err) => {
                warn!("failed to fetch block sizes: {:?}", err);
                return;
            }
        };

        {
            let mut peer_ledger = self.peer_ledger.lock().await;
            for want in &wants {
                peer_ledger.wants(*peer, want.cid);
            }
            for canel in &cancels {
                peer_ledger.cancel_want(peer, &canel.cid);
            }
        }

        // get the ledger for the peer
        let l = self.find_or_create(peer).await;
        let mut ledger = l.lock().await;

        // if the peer sent a full wantlist, clear the existing wantlist.
        if message.full() {
            ledger.clear_wantlist();
        }
        let mut active_entries = Vec::new();
        for entry in &cancels {
            if ledger.cancel_want(&entry.cid).is_some() {
                self.peer_task_queue.remove(&entry.cid, *peer).await;
            }
        }

        let send_dont_have = |entries: &mut Vec<_>, new_work_exists: &mut bool, entry: &Entry| {
            // only add the task to the queue if the requester wants DONT_HAVE
            if self.send_dont_haves && entry.send_dont_have {
                let cid = entry.cid;
                *new_work_exists = true;
                let is_want_block = entry.want_type == WantType::Block;
                entries.push(Task {
                    topic: cid,
                    priority: entry.priority as isize,
                    work: BlockPresence::encoded_len_for_cid(cid),
                    data: TaskData {
                        block_size: 0,
                        have_block: false,
                        is_want_block,
                        send_dont_have: entry.send_dont_have,
                    },
                });
            }
        };

        // deny access to blocks
        for entry in &denials {
            send_dont_have(&mut active_entries, &mut new_work_exists, entry);
        }

        // for each want-have/want-block
        for entry in &wants {
            let cid = entry.cid;

            // add each want-have/want-block to the ledger
            ledger.wants(cid, entry.priority, entry.want_type);

            if let Some(block_size) = block_sizes.get(&cid) {
                // the block was found
                new_work_exists = true;
                let is_want_block = self.send_as_block(entry.want_type, *block_size);
                let entry_size = if is_want_block {
                    *block_size
                } else {
                    BlockPresence::encoded_len_for_cid(cid)
                };

                active_entries.push(Task {
                    topic: cid,
                    priority: entry.priority as isize,
                    work: entry_size,
                    data: TaskData {
                        is_want_block,
                        send_dont_have: entry.send_dont_have,
                        block_size: *block_size,
                        have_block: true,
                    },
                });
            } else {
                // if the block was not found
                send_dont_have(&mut active_entries, &mut new_work_exists, entry);
            }
        }

        if !active_entries.is_empty() {
            self.peer_task_queue.push_tasks(*peer, active_entries).await;
            self.update_metrics().await;
        }

        if new_work_exists {
            self.signal_new_work();
        }
    }

Completely thaws all peers in the queue so they can execute tasks.

Unthaws peers incrementally, so that those have been frozen the least become unfrozen and able to execute tasks first.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Converts to this type from a reference to the input type.
Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Attaches the current Context to this type, returning a WithContext wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Wrap the input message T in a tonic::Request
The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more