state.rs 19.2 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

Ryan Olson's avatar
Ryan Olson committed
4
5
6
7
mod local;
mod logical;
mod resources;

Ryan Olson's avatar
Ryan Olson committed
8
9
use super::*;

10
// use super::offload::{OffloadManager, OffloadManagerConfig};
11
use super::{
Ryan Olson's avatar
Ryan Olson committed
12
    block::{
13
14
        Block, GlobalRegistry, ImmutableBlock, MutableBlock, factory::IntoBlocks,
        factory::LocalBlockDataFactory, locality::LocalityProvider,
Ryan Olson's avatar
Ryan Olson committed
15
    },
16
    config::NixlOptions,
17
    events::{EventManager, NullEventManager},
18
    locality::LogicalResources,
Ryan Olson's avatar
Ryan Olson committed
19
    metrics::BlockManagerMetrics,
20
21
22
23
    offload::{
        OffloadFilters, OffloadManager, OffloadManagerConfig, filter::OffloadFilter,
        request::BlockResult,
    },
24
};
Ryan Olson's avatar
Ryan Olson committed
25
use derive_getters::Dissolve;
Ryan Olson's avatar
Ryan Olson committed
26
use std::sync::Arc;
27
use tokio::runtime::Handle;
Ryan Olson's avatar
Ryan Olson committed
28
use tokio::sync::oneshot;
Ryan Olson's avatar
Ryan Olson committed
29

Ryan Olson's avatar
Ryan Olson committed
30
31
32
33
pub(crate) struct Resources {
    pub worker_id: WorkerID,
    pub cancellation_token: CancellationToken,
    pub async_rt_handle: Handle,
Ryan Olson's avatar
Ryan Olson committed
34

Ryan Olson's avatar
Ryan Olson committed
35
36
37
38
    // nixl agent/backends for the block manager
    pub nixl_agent: Arc<Option<NixlAgent>>,
    #[expect(dead_code)]
    pub nixl_backends: HashMap<String, Arc<nixl_sys::Backend>>,
Ryan Olson's avatar
Ryan Olson committed
39

Ryan Olson's avatar
Ryan Olson committed
40
41
    // registry for blocks across all storage types
    pub global_registry: GlobalRegistry,
Ryan Olson's avatar
Ryan Olson committed
42

Ryan Olson's avatar
Ryan Olson committed
43
44
    // event manager for block manager events
    pub event_manager: Arc<dyn EventManager>,
45

Ryan Olson's avatar
Ryan Olson committed
46
47
48
49
50
    // metrics for the block manager
    pub metrics: Arc<BlockManagerMetrics>,

    // config for the block manager
    pub config: KvBlockManagerConfig,
Ryan Olson's avatar
Ryan Olson committed
51
52
}

Ryan Olson's avatar
Ryan Olson committed
53
54
55
#[allow(dead_code)]
pub struct KvBlockManagerState<Locality: LocalityProvider, Metadata: BlockMetadata> {
    resources: Arc<Resources>,
Ryan Olson's avatar
Ryan Olson committed
56

Ryan Olson's avatar
Ryan Olson committed
57
58
59
    disk_pool: Option<Arc<dyn BlockPool<DiskStorage, Locality, Metadata>>>,
    host_pool: Option<Arc<dyn BlockPool<PinnedStorage, Locality, Metadata>>>,
    device_pool: Option<Arc<dyn BlockPool<DeviceStorage, Locality, Metadata>>>,
Ryan Olson's avatar
Ryan Olson committed
60

Ryan Olson's avatar
Ryan Olson committed
61
62
63
64
    local_block_set: NixlBlockSet,
    remote_block_sets: RwLock<HashMap<WorkerID, HashMap<usize, RemoteBlocks>>>,
    offload_manager: Arc<OffloadManager<Locality, Metadata>>,
}
Ryan Olson's avatar
Ryan Olson committed
65

Ryan Olson's avatar
Ryan Olson committed
66
67
68
69
impl<Locality: LocalityProvider, Metadata: BlockMetadata> KvBlockManagerState<Locality, Metadata> {
    pub fn disk(&self) -> Option<&dyn BlockPool<DiskStorage, Locality, Metadata>> {
        self.disk_pool.as_ref().map(|pool| pool.as_ref())
    }
Ryan Olson's avatar
Ryan Olson committed
70

Ryan Olson's avatar
Ryan Olson committed
71
72
73
    pub fn host(&self) -> Option<&dyn BlockPool<PinnedStorage, Locality, Metadata>> {
        self.host_pool.as_ref().map(|pool| pool.as_ref())
    }
74

Ryan Olson's avatar
Ryan Olson committed
75
76
77
    pub fn device(&self) -> Option<&dyn BlockPool<DeviceStorage, Locality, Metadata>> {
        self.device_pool.as_ref().map(|pool| pool.as_ref())
    }
78

Ryan Olson's avatar
Ryan Olson committed
79
80
81
    pub fn worker_id(&self) -> WorkerID {
        self.resources.worker_id
    }
82

Ryan Olson's avatar
Ryan Olson committed
83
84
85
86
87
88
    pub(crate) async fn enqueue_offload_block<S: Storage + 'static>(
        &self,
        block: &ImmutableBlock<S, Locality, Metadata>,
        priority: u64,
    ) -> Result<()> {
        self.offload_manager.offload(block, priority).await?;
Ryan Olson's avatar
Ryan Olson committed
89

Ryan Olson's avatar
Ryan Olson committed
90
91
        Ok(())
    }
92

Ryan Olson's avatar
Ryan Olson committed
93
94
95
96
97
98
99
100
    pub fn onboard_blocks<S: Storage + 'static>(
        &self,
        blocks: Vec<ImmutableBlock<S, Locality, Metadata>>,
        targets: Option<Vec<MutableBlock<DeviceStorage, Locality, Metadata>>>,
    ) -> oneshot::Receiver<BlockResult<DeviceStorage, Locality, Metadata>> {
        self.offload_manager.onboard(blocks, targets)
    }
}
101

Ryan Olson's avatar
Ryan Olson committed
102
103
104
105
impl<R: LogicalResources, Metadata: BlockMetadata>
    KvBlockManagerState<locality::Logical<R>, Metadata>
{
    pub async fn new(config: KvBlockManagerConfig, logical_resources: R) -> Result<Arc<Self>> {
106
        let model_config = config.model.clone();
Ryan Olson's avatar
Ryan Olson committed
107
108
109
110
111
112
        let mut resources = Resources::new(config)?;
        let block_data_factories =
            logical::LogicalBlockFactories::new(&mut resources, logical_resources)?;

        let (disk_factory, host_factory, device_factory) = block_data_factories.dissolve();

113
        let (disk_pool, disk_blocks, disk_offload_filter) = match disk_factory {
Ryan Olson's avatar
Ryan Olson committed
114
            Some(factory) => {
115
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
116
                    create_block_pool::<_, _, Metadata>(factory, &resources, "disk")?;
117
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
118
119
120
            }
            None => {
                tracing::debug!("No disk layout provided; will not allocate disk blocks.");
121
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
122
123
            }
        };
Ryan Olson's avatar
Ryan Olson committed
124

125
        let (host_pool, host_blocks, host_offload_filter) = match host_factory {
Ryan Olson's avatar
Ryan Olson committed
126
            Some(factory) => {
127
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
128
                    create_block_pool::<_, _, Metadata>(factory, &resources, "host")?;
129
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
130
            }
Ryan Olson's avatar
Ryan Olson committed
131
132
            None => {
                tracing::debug!("No host layout provided; will not allocate host blocks.");
133
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
134
135
            }
        };
Ryan Olson's avatar
Ryan Olson committed
136

137
        let (device_pool, device_blocks, device_offload_filter) = match device_factory {
Ryan Olson's avatar
Ryan Olson committed
138
            Some(factory) => {
139
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
140
                    create_block_pool::<_, _, Metadata>(factory, &resources, "device")?;
141
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
142
143
144
            }
            None => {
                tracing::debug!("No device layout provided; will not allocate device blocks.");
145
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
146
            }
147
148
        };

149
150
151
152
153
154
        let offload_filters = OffloadFilters::builder()
            .device(device_offload_filter)
            .host(host_offload_filter)
            .disk(disk_offload_filter)
            .build()?;

155
156
157
158
159
160
161
162
        let offload_config = OffloadManagerConfig {
            nixl_agent: resources.nixl_agent.clone(),
            async_rt_handle: resources.async_rt_handle.clone(),
            metrics: resources.metrics.clone(),
            cancellation_token: resources.cancellation_token.clone(),
            model_config,
        };

Ryan Olson's avatar
Ryan Olson committed
163
164
165
166
        let offload_manager = OffloadManager::new(
            disk_pool.clone(),
            host_pool.clone(),
            device_pool.clone(),
167
            offload_filters,
168
            offload_config,
Ryan Olson's avatar
Ryan Olson committed
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
        )?;

        let resources = Arc::new(resources);

        let state = Arc::new(Self {
            resources: resources.clone(),
            disk_pool,
            host_pool,
            device_pool,
            local_block_set: NixlBlockSet::new(resources.worker_id),
            remote_block_sets: RwLock::new(HashMap::new()),
            offload_manager,
        });

        if let Some(mut blocks) = disk_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state.disk_pool.as_ref().unwrap().add_blocks(blocks).await?;
        }

        if let Some(mut blocks) = host_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state.host_pool.as_ref().unwrap().add_blocks(blocks).await?;
        }

        if let Some(mut blocks) = device_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state
                .device_pool
                .as_ref()
                .unwrap()
                .add_blocks(blocks)
                .await?;
        }

        Ok(state)
    }
}

// move into mod local
// move local block data factory into mod super::block
// create a method on locality to construct a block data factory from a layout builder and resources
// - this will allow us to use the locality abstraction to build our factories and block pools
impl<Metadata: BlockMetadata> KvBlockManagerState<locality::Local, Metadata> {
    pub async fn new(config: KvBlockManagerConfig) -> Result<Arc<Self>> {
222
        let model_config = config.model.clone();
Ryan Olson's avatar
Ryan Olson committed
223
224
225
226
227
228
        let mut resources = Resources::new(config)?;
        let block_data_factories = local::LocalBlockDataFactories::new(&mut resources)?;

        let (mut local_block_set, disk_factory, host_factory, device_factory) =
            block_data_factories.dissolve();

229
        let (disk_pool, disk_blocks, disk_offload_filter) = match disk_factory {
Ryan Olson's avatar
Ryan Olson committed
230
            Some(factory) => {
231
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
232
                    create_block_pool::<_, _, Metadata>(factory, &resources, "disk")?;
233
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
234
235
236
            }
            None => {
                tracing::debug!("No disk layout provided; will not allocate disk blocks.");
237
                (None, None, None)
238
239
240
            }
        };

241
        let (host_pool, host_blocks, host_offload_filter) = match host_factory {
Ryan Olson's avatar
Ryan Olson committed
242
            Some(factory) => {
243
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
244
                    create_block_pool::<_, _, Metadata>(factory, &resources, "host")?;
245
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
246
247
            }
            None => {
248
249
                tracing::debug!("No host layout provided; will not allocate host blocks.");
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
250
            }
Ryan Olson's avatar
Ryan Olson committed
251
252
        };

253
        let (device_pool, device_blocks, device_offload_filter) = match device_factory {
Ryan Olson's avatar
Ryan Olson committed
254
            Some(factory) => {
255
                let (pool, blocks, offload_filter) =
Ryan Olson's avatar
Ryan Olson committed
256
                    create_block_pool::<_, _, Metadata>(factory, &resources, "disk")?;
257
                (Some(pool), Some(blocks), offload_filter)
Ryan Olson's avatar
Ryan Olson committed
258
259
            }
            None => {
260
261
                tracing::debug!("No device layout provided; will not allocate device blocks.");
                (None, None, None)
Ryan Olson's avatar
Ryan Olson committed
262
            }
Ryan Olson's avatar
Ryan Olson committed
263
264
265
        };

        // Finalize the local block set by adding NIXL metadata
Ryan Olson's avatar
Ryan Olson committed
266
        if let Some(nixl_agent) = resources.nixl_agent.as_ref() {
Ryan Olson's avatar
Ryan Olson committed
267
268
269
270
            tracing::debug!("Finalize NixlBlockSet: adding NIXL metadata.");
            local_block_set.set_nixl_metadata(nixl_agent.get_local_md()?);
        }

271
272
273
274
275
276
        let offload_filters = OffloadFilters::builder()
            .device(device_offload_filter)
            .host(host_offload_filter)
            .disk(disk_offload_filter)
            .build()?;

277
278
279
280
281
282
283
284
        let offload_config = OffloadManagerConfig {
            nixl_agent: resources.nixl_agent.clone(),
            async_rt_handle: resources.async_rt_handle.clone(),
            metrics: resources.metrics.clone(),
            cancellation_token: resources.cancellation_token.clone(),
            model_config,
        };

285
286
287
288
        let offload_manager = OffloadManager::new(
            disk_pool.clone(),
            host_pool.clone(),
            device_pool.clone(),
289
            offload_filters,
290
            offload_config,
291
        )?;
292

Ryan Olson's avatar
Ryan Olson committed
293
294
        let resources = Arc::new(resources);

Ryan Olson's avatar
Ryan Olson committed
295
        let state = Arc::new(Self {
Ryan Olson's avatar
Ryan Olson committed
296
            resources: resources.clone(),
297
            disk_pool,
Ryan Olson's avatar
Ryan Olson committed
298
299
300
301
            host_pool,
            device_pool,
            local_block_set,
            remote_block_sets: RwLock::new(HashMap::new()),
302
            offload_manager,
Ryan Olson's avatar
Ryan Olson committed
303
304
        });

305
306
307
308
309
        if let Some(mut blocks) = disk_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

Ryan Olson's avatar
Ryan Olson committed
310
            state.disk_pool.as_ref().unwrap().add_blocks(blocks).await?;
311
312
        }

Ryan Olson's avatar
Ryan Olson committed
313
314
315
316
317
        if let Some(mut blocks) = host_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

Ryan Olson's avatar
Ryan Olson committed
318
            state.host_pool.as_ref().unwrap().add_blocks(blocks).await?;
Ryan Olson's avatar
Ryan Olson committed
319
320
321
322
323
324
325
326
327
328
329
        }

        if let Some(mut blocks) = device_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state
                .device_pool
                .as_ref()
                .unwrap()
Ryan Olson's avatar
Ryan Olson committed
330
331
                .add_blocks(blocks)
                .await?;
Ryan Olson's avatar
Ryan Olson committed
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
        }

        Ok(state)
    }

    /// Exports the local blockset configuration as a serialized object.
    pub fn export_local_blockset(&self) -> Result<SerializedNixlBlockSet> {
        SerializedNixlBlockSet::try_from(&self.local_block_set)
            .context("Failed to serialize local blockset")
    }

    /// Imports a remote blockset configuration from a serialized object.
    // TODO: NIXL will validate the every descriptor list against the memory registration list for
    // a given agent; this is can be an expensive operation. To avoid this, NIXL offers the ability
    // to generate "partial pre-validated (PPV)" descriptor lists. However, to support per-block and per-layer
    // PPV lists we will need as many as `num_layers + 1` PPV lists per block:
    // - one for representing the entire block
    // - one for representing each layer individually
    //
    // A deeper dive into the performance impact of PPV lists is required to determine if this is
    // the best approach.
    //
    // If PPV are valuable, it might be beneficial to lazily instantiate PPV lists when they are
    // needed; alternatively, we could generate the entire PPV list for each block at import time.
    pub fn import_remote_blockset(
        &self,
        serialized_blockset: SerializedNixlBlockSet,
    ) -> Result<()> {
        let remote = NixlBlockSet::try_from(serialized_blockset)
            .context("Failed to deserialize remote blockset")?;

        let (block_sets, metadata, worker_id) = remote.dissolve();
        tracing::debug!("Importing remote blockset from worker {}", worker_id);

        assert_ne!(
Ryan Olson's avatar
Ryan Olson committed
367
            worker_id, self.resources.worker_id,
Ryan Olson's avatar
Ryan Olson committed
368
369
370
371
            "Cannot import blockset from self"
        );

        let agent = self
Ryan Olson's avatar
Ryan Olson committed
372
            .resources
Ryan Olson's avatar
Ryan Olson committed
373
374
            .nixl_agent
            .as_ref()
375
            .as_ref()
Ryan Olson's avatar
Ryan Olson committed
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
            .ok_or_else(|| anyhow::anyhow!("NIXL agent not initialized"))?;

        let mut remote_block_sets = self.remote_block_sets.write().unwrap();

        if remote_block_sets.contains_key(&worker_id) {
            anyhow::bail!(
                "Worker ID {} already exists; cannot update remote blockset",
                worker_id
            );
        }

        let mut inner_map = HashMap::new();

        for (block_set_idx, block_set_layout) in block_sets {
            // Deserialize the individual layout and create RemoteBlocks
            let remote_blocks =
                RemoteBlocks::from_serialized(block_set_layout.clone(), block_set_idx, worker_id)?;

            // check the storage type of the remote blocks
            let layout = remote_blocks.layout();
            let storage = layout.storage();

            let storage = storage
                .first()
                .ok_or_else(|| anyhow::anyhow!("No storage found in remote blockset"))?;

            match storage.mem_type() {
                MemType::Dram => {
                    tracing::trace!(block_set_idx, "Detected Host/DRAM remote descriptor");
                }
                MemType::Vram => {
                    tracing::trace!(block_set_idx, "Detected GPU/Device/VRAM remote descriptor");
                }
                _ => {
                    tracing::warn!(
                        block_set_idx,
                        "Detected unknown remote descriptor; skipping blockset..."
                    );
                    continue;
                }
            }

            inner_map.insert(block_set_idx, remote_blocks);
        }

        let agent_id = agent
            .load_remote_md(&metadata)
            .context("Loading remote metadata")?;

        // try to convert the agent_id (String) to a WorkerID (u64)
        let agent_id: WorkerID =
            agent_id // Assuming agent_id is String here
                .parse() // Parse the String into u64 (WorkerID)
                .context("Failed to parse agent ID string into WorkerID (u64)")?;

        assert_eq!(agent_id, worker_id, "Mismatch with remote worker ID");

        remote_block_sets.insert(worker_id, inner_map);

        Ok(())
    }

    /// Get a [`Vec<RemoteBlock<IsImmutable>>`] from a [`BlockDescriptorList`]
    pub fn get_remote_blocks_immutable(
        &self,
        bds: &BlockDescriptorList,
    ) -> Result<Vec<RemoteBlock<IsImmutable>>> {
        // no checks - we can always create an immutable remote block even if the bds is mutable
        self.get_remote_blocks::<IsImmutable>(bds)
    }

    /// Get a [`Vec<RemoteBlock<IsMutable>>`] from a [`BlockDescriptorList`]
    pub fn get_remote_blocks_mutable(
        &self,
        bds: &BlockDescriptorList,
    ) -> Result<Vec<RemoteBlock<IsMutable>>> {
        if bds.mutability() == BlockMutability::Mutable {
            self.get_remote_blocks::<IsMutable>(bds)
        } else {
            anyhow::bail!("Cannot get mutable remote blocks for immutable block descriptor set");
        }
    }

    /// Generate a [`Vec<RemoteBlock>`] from a [`BlockDescriptorList`]
    fn get_remote_blocks<M: MutabilityKind>(
        &self,
        bds: &BlockDescriptorList,
    ) -> Result<Vec<RemoteBlock<M>>> {
        // Get a read lock on the remote block sets
        let remote_block_sets = self.remote_block_sets.read().unwrap();

        // validate we have loaded a remote blockset for the worker and the specific block_set_idx
        let remote_blocks = remote_block_sets
            .get(&bds.worker_id())
            .and_then(|map| map.get(&bds.block_set_idx()))
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "No remote blockset found for worker {} and block_set_idx {}",
                    bds.worker_id(),
                    bds.block_set_idx()
                )
            })?;

        // Iterate through indices, call .block() for each, and collect results.
        // The collect::<Result<...>>() handles potential errors from .block()
        let blocks: Vec<block::nixl::RemoteBlock<M>> = bds
            .block_indices()
            .iter()
            .map(|block_idx| remote_blocks.block(*block_idx))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(blocks)
    }
}

Ryan Olson's avatar
Ryan Olson committed
491
492
493
impl<Locality: LocalityProvider, Metadata: BlockMetadata> std::fmt::Debug
    for KvBlockManagerState<Locality, Metadata>
{
Ryan Olson's avatar
Ryan Olson committed
494
495
496
497
498
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "KvBlockManagerState")
    }
}

Ryan Olson's avatar
Ryan Olson committed
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//     if let Some(storage) = config.storage {
//         let mut layout = layout.create_layout(config.layout_type, storage, false)?;
//         if let Some(nixl_agent) = nixl_agent {
//             layout.nixl_register(nixl_agent, None)?;
//         }
//         return Ok(layout.into());
//     }

//     if let Some(allocator) = config.allocator {
//         let mut layout = layout.allocate_layout(config.layout_type, allocator)?;
//         if let Some(nixl_agent) = nixl_agent {
//             layout.nixl_register(nixl_agent, None)?;
//         }
//         return Ok(layout.into());
//     }

//     anyhow::bail!("failed to create layout");
// }

#[expect(clippy::type_complexity)]
pub(crate) fn create_block_pool<S: Storage, L: LocalityProvider, M: BlockMetadata>(
    factory: impl IntoBlocks<S, L>,
    resources: &Resources,
    pool_name: &str,
523
524
525
526
527
) -> Result<(
    Arc<dyn BlockPool<S, L, M>>,
    Vec<Block<S, L, M>>,
    Option<Arc<dyn OffloadFilter>>,
)> {
Ryan Olson's avatar
Ryan Olson committed
528
529
530
531
532
533
534
    let pool = ManagedBlockPool::<S, L, M>::builder()
        .cancel_token(resources.cancellation_token.clone())
        .global_registry(resources.global_registry.clone())
        .async_runtime(resources.async_rt_handle.clone())
        .event_manager(resources.event_manager.clone())
        .pool_metrics(resources.metrics.pool(pool_name))
        .build()?;
Ryan Olson's avatar
Ryan Olson committed
535

536
    let offload_filter = factory.offload_filter();
Ryan Olson's avatar
Ryan Olson committed
537
    let blocks = factory.into_blocks()?;
Ryan Olson's avatar
Ryan Olson committed
538

539
540
    Ok((Arc::new(pool), blocks, offload_filter))
}