laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
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
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Queued exports and imports: `QueuedWriter`, `ChunkReader`, and the jobs `QueueExport`,
//! `AppendQueryToSheet`, `AppendDataToSheet`, `AppendViewToSheet`, `CloseSheet`,
//! `StoreQueuedExport`, `ReadChunk` and `AfterImportJob`.
//!
//! Between the jobs of a queued export, the workbook is kept as a temporary file in
//! `excel.temporary_files.local_path` (or on `remote_disk`), as Laravel Excel keeps its temporary
//! spreadsheet. A queued import keeps a copy of the file there.

use std::collections::BTreeMap;
use std::path::PathBuf;

use laravel::queue::{self, Attempt, Queueable, job};
use serde::{Deserialize, Serialize};

use crate::config::ExcelConfig;
use crate::error::ExcelError;
use crate::excel::{Queued, Type, detect_strict};
use crate::export::{Export, ExportContext, Source};
use crate::import::{Import, ImportContext, SheetWindow};
use crate::sheets::SheetKey;
use crate::spreadsheet::Spreadsheet;

// ---------------------------------------------------------------------------------------------
// Registration of queueable exports and imports
// ---------------------------------------------------------------------------------------------

/// An export type that queued jobs can rebuild. [`export!`](crate::export) registers it.
#[doc(hidden)]
pub struct QueueableExport {
    pub name: &'static str,
    pub restore: fn(serde_json::Value) -> laravel::Result<Box<dyn Export>>,
}

/// An import type that queued jobs can rebuild. [`import!`](crate::import) registers it.
#[doc(hidden)]
pub struct QueueableImport {
    pub name: &'static str,
    pub restore: fn(serde_json::Value) -> laravel::Result<Box<dyn Import>>,
}

inventory::collect!(QueueableExport);
inventory::collect!(QueueableImport);

fn restore_export(name: &str, payload: serde_json::Value) -> laravel::Result<Box<dyn Export>> {
    let registration = inventory::iter::<QueueableExport>
        .into_iter()
        .find(|registration| registration.name == name)
        .ok_or_else(|| ExcelError::NotRegistered {
            kind: "export",
            name: name.to_owned(),
        })?;
    (registration.restore)(payload)
}

fn restore_import(name: &str, payload: serde_json::Value) -> laravel::Result<Box<dyn Import>> {
    let registration = inventory::iter::<QueueableImport>
        .into_iter()
        .find(|registration| registration.name == name)
        .ok_or_else(|| ExcelError::NotRegistered {
            kind: "import",
            name: name.to_owned(),
        })?;
    (registration.restore)(payload)
}

// ---------------------------------------------------------------------------------------------
// Temporary files
// ---------------------------------------------------------------------------------------------

/// A temporary file shared by a queued export's or import's jobs: `TemporaryFile`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct TemporaryFile {
    name: String,
}

impl TemporaryFile {
    fn make(extension: &str) -> Self {
        Self {
            name: format!("laravel-excel-{}.{extension}", laravel::str::uuid()),
        }
    }

    fn local_path(&self, config: &ExcelConfig) -> PathBuf {
        let directory = &config.temporary_files.local_path;
        let directory = if directory.is_absolute() {
            directory.clone()
        } else {
            laravel::config().app.storage_path(directory)
        };
        directory.join(&self.name)
    }

    fn remote_path(&self, config: &ExcelConfig) -> String {
        match config.temporary_files.remote_prefix.as_deref() {
            Some(prefix) if !prefix.is_empty() => format!("{}/{}", prefix.trim_end_matches('/'), self.name),
            _ => self.name.clone(),
        }
    }

    async fn put(&self, config: &ExcelConfig, contents: Vec<u8>) -> laravel::Result<()> {
        match &config.temporary_files.remote_disk {
            Some(disk) => {
                laravel::storage::disk(disk)?
                    .put(&self.remote_path(config), contents)
                    .await
            }
            None => {
                let path = self.local_path(config);
                if let Some(parent) = path.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                std::fs::write(path, contents)?;
                Ok(())
            }
        }
    }

    async fn get(&self, config: &ExcelConfig) -> laravel::Result<Vec<u8>> {
        match &config.temporary_files.remote_disk {
            Some(disk) => Ok(laravel::storage::disk(disk)?
                .get_with_limit(&self.remote_path(config), u64::MAX)
                .await?
                .to_vec()),
            None => Ok(std::fs::read(self.local_path(config))?),
        }
    }

    async fn exists(&self, config: &ExcelConfig) -> laravel::Result<bool> {
        match &config.temporary_files.remote_disk {
            Some(disk) => laravel::storage::disk(disk)?.exists(&self.remote_path(config)).await,
            None => Ok(self.local_path(config).exists()),
        }
    }

    async fn delete(&self, config: &ExcelConfig) -> laravel::Result<()> {
        match &config.temporary_files.remote_disk {
            Some(disk) => laravel::storage::disk(disk)?.delete(&self.remote_path(config)).await,
            None => {
                let path = self.local_path(config);
                if path.exists() {
                    std::fs::remove_file(path)?;
                }
                Ok(())
            }
        }
    }

    async fn save(&self, config: &ExcelConfig, spreadsheet: &Spreadsheet) -> laravel::Result<()> {
        self.put(config, serde_json::to_vec(spreadsheet)?).await
    }

    async fn load(&self, config: &ExcelConfig) -> laravel::Result<Spreadsheet> {
        Ok(serde_json::from_slice(&self.get(config).await?)?)
    }
}

// ---------------------------------------------------------------------------------------------
// Exports
// ---------------------------------------------------------------------------------------------

/// The sheets of an export: its own sheet, or each `WithMultipleSheets` sheet.
enum SheetExports<'a> {
    Single(&'a dyn Export),
    Multiple(Vec<Box<dyn Export>>),
}

impl<'a> SheetExports<'a> {
    fn of(export: &'a dyn Export) -> Self {
        match export.__concerns().multiple_sheets {
            Some(multiple) => Self::Multiple(multiple.sheets().exports()),
            None => Self::Single(export),
        }
    }

    fn list(&self) -> Vec<&dyn Export> {
        match self {
            Self::Single(export) => vec![*export],
            Self::Multiple(sheets) => sheets.iter().map(AsRef::as_ref).collect(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
enum ExportStep {
    /// `QueueExport`: creates the workbook and opens each sheet.
    Open,
    /// `AppendQueryToSheet` (with a window), or `AppendDataToSheet`/`AppendViewToSheet`.
    Append { sheet: usize, window: Option<(u64, u64)> },
    /// `CloseSheet`.
    Close { sheet: usize },
    /// `StoreQueuedExport`.
    Store,
}

/// One step of a queued export.
#[derive(Queueable)]
pub struct QueuedExportJob {
    step: ExportStep,
    export_type: String,
    export: serde_json::Value,
    temporary: TemporaryFile,
    writer_type: Type,
    file_path: String,
    disk: Option<String>,
}

#[job(name = "laravel-excel.export")]
impl QueuedExportJob {
    async fn handle(self) -> laravel::Result<()> {
        let export = restore_export(&self.export_type, self.export.clone())?;
        let export = export.as_ref();
        let context = ExportContext::current().await;
        let config = &context.config;
        let parent_binder = export.__concerns().value_binder;
        let sheets = SheetExports::of(export);
        let sheets = sheets.list();
        match self.step {
            ExportStep::Open => {
                if sheets.is_empty() {
                    return Err(ExcelError::NoSheetsFound.into());
                }
                let mut spreadsheet = crate::export::open(export, &context)?;
                let has_template = export.__concerns().template.is_some();
                for (position, sheet) in sheets.iter().enumerate() {
                    let index = crate::export::sheet_for_export(&mut spreadsheet, position, has_template);
                    crate::export::open_sheet(&mut spreadsheet, index, *sheet, parent_binder, &context)?;
                }
                self.temporary.save(config, &spreadsheet).await
            }
            ExportStep::Append { sheet, window } => {
                let mut spreadsheet = self.temporary.load(config).await?;
                let sheet_export = sheets.get(sheet).copied().ok_or(ExcelError::NoSheetsFound)?;
                crate::export::write_sheet(&mut spreadsheet, sheet, sheet_export, parent_binder, &context, window)
                    .await?;
                self.temporary.save(config, &spreadsheet).await
            }
            ExportStep::Close { sheet } => {
                let mut spreadsheet = self.temporary.load(config).await?;
                let sheet_export = sheets.get(sheet).copied().ok_or(ExcelError::NoSheetsFound)?;
                crate::export::close_sheet(&mut spreadsheet, sheet, sheet_export, &context)?;
                self.temporary.save(config, &spreadsheet).await
            }
            ExportStep::Store => {
                let mut spreadsheet = self.temporary.load(config).await?;
                let bytes = crate::excel::write_spreadsheet(
                    export,
                    &mut spreadsheet,
                    self.writer_type,
                    Some(&self.file_path),
                    &context,
                )?;
                let disk = match &self.disk {
                    Some(name) => laravel::storage::disk(name)?,
                    None => laravel::storage::default_disk()?,
                };
                disk.put(&self.file_path, bytes).await?;
                self.temporary.delete(config).await
            }
        }
    }

    async fn failed(self, _error: &laravel::Error) -> laravel::Result<()> {
        let config = crate::config::current();
        self.temporary.delete(&config).await
    }
}

/// `QueuedWriter::store()`: dispatches the jobs of a queued export.
pub(crate) async fn queue_export(
    export: &dyn Export,
    file_path: &str,
    disk: Option<&str>,
    writer_type: Option<Type>,
) -> laravel::Result<Queued> {
    if let Some(fake) = crate::excel::fake().await {
        fake.record_queue(disk, file_path, export);
        return Ok(Queued::Faked);
    }
    let config = crate::config::current();
    let writer_type = detect_strict(file_path, writer_type, &config)?;
    let (export_type, payload) = export.__queue_payload().ok_or_else(|| ExcelError::NotRegistered {
        kind: "export",
        name: export.__type_name().to_owned(),
    })??;

    let temporary = TemporaryFile::make("json");
    let job = |step| QueuedExportJob {
        step,
        export_type: export_type.to_owned(),
        export: payload.clone(),
        temporary: temporary.clone(),
        writer_type,
        file_path: file_path.to_owned(),
        disk: disk.map(str::to_owned),
    };

    let mut jobs = vec![job(ExportStep::Open)];
    let sheets = SheetExports::of(export);
    for (index, sheet) in sheets.list().into_iter().enumerate() {
        let concerns = sheet.__concerns();
        if concerns.source == Source::Query {
            let chunk = concerns
                .chunk_size
                .map_or(config.chunk_size, |chunk| chunk.chunk_size())
                .max(1);
            drop(concerns);
            let count = sheet.__count().await?.unwrap_or(0);
            let mut offset = 0;
            while offset < count {
                jobs.push(job(ExportStep::Append {
                    sheet: index,
                    window: Some((offset, chunk)),
                }));
                offset += chunk;
            }
        } else {
            drop(concerns);
            jobs.push(job(ExportStep::Append {
                sheet: index,
                window: None,
            }));
        }
        jobs.push(job(ExportStep::Close { sheet: index }));
    }
    jobs.push(job(ExportStep::Store));

    let concerns = export.__concerns();
    let connection = concerns.should_queue.and_then(|queue| queue.on_connection());
    let queue_name = concerns.should_queue.and_then(|queue| queue.on_queue());
    let batched = concerns.should_batch;
    drop(concerns);
    dispatch_chain(jobs, connection, queue_name, batched).await
}

async fn dispatch_chain<J: laravel::queue::Job>(
    jobs: Vec<J>,
    connection: Option<String>,
    queue_name: Option<String>,
    batched: bool,
) -> laravel::Result<Queued> {
    let mut chain = queue::chain(jobs);
    if batched {
        let mut batch = queue::batch([chain]);
        if let Some(connection) = connection {
            batch = batch.on_connection(connection);
        }
        if let Some(queue_name) = queue_name {
            batch = batch.on_queue(queue_name);
        }
        return Ok(Queued::Batch(batch.await?));
    }
    if let Some(connection) = connection {
        chain = chain.on_connection(connection);
    }
    if let Some(queue_name) = queue_name {
        chain = chain.on_queue(queue_name);
    }
    Ok(Queued::Chain(chain.await?))
}

// ---------------------------------------------------------------------------------------------
// Imports
// ---------------------------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Chunk {
    /// The sheet's position in the file.
    sheet: usize,
    /// The `WithMultipleSheets` sheet import, by position in `sheets()`, or the import itself.
    sheet_import: Option<usize>,
    start_row: u32,
    chunk_size: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
enum ImportStep {
    /// `ReadChunk`.
    ReadChunk {
        chunk: Chunk,
        marker: Option<TemporaryFile>,
    },
    /// `AfterImportJob`.
    AfterImport { markers: Vec<TemporaryFile>, interval: u64 },
}

/// One step of a queued import.
#[derive(Queueable)]
pub struct QueuedImportJob {
    step: ImportStep,
    import_type: String,
    import: serde_json::Value,
    temporary: TemporaryFile,
    file_name: String,
    reader_type: Type,
    total_rows: BTreeMap<String, u32>,
}

#[job(name = "laravel-excel.import")]
impl QueuedImportJob {
    async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
        let import = restore_import(&self.import_type, self.import.clone())?;
        let import = import.as_ref();
        let context = ImportContext::current().await;
        match &self.step {
            ImportStep::ReadChunk { chunk, marker } => {
                let bytes = self.temporary.get(&context.config).await?;
                run_chunk(import, &bytes, &self.file_name, Some(self.reader_type), chunk, &context).await?;
                if let Some(marker) = marker {
                    marker.delete(&context.config).await?;
                }
                Ok(())
            }
            ImportStep::AfterImport { markers, interval } => {
                for marker in markers {
                    if marker.exists(&context.config).await? {
                        attempt.release(laravel::time::SignedDuration::from_secs(*interval as i64));
                        return Ok(());
                    }
                }
                crate::import::after_import(import, &self.total_rows, &context.listeners)?;
                self.temporary.delete(&context.config).await
            }
        }
    }

    async fn failed(self, error: &laravel::Error) -> laravel::Result<()> {
        let context = ImportContext::current().await;
        let _ = self.temporary.delete(&context.config).await;
        if let Ok(import) = restore_import(&self.import_type, self.import.clone()) {
            crate::import::import_failed(import.as_ref(), error, &context.listeners);
        }
        Ok(())
    }
}

/// Imports one chunk: `ReadChunk::handle()`.
async fn run_chunk(
    import: &dyn Import,
    bytes: &[u8],
    file_name: &str,
    reader_type: Option<Type>,
    chunk: &Chunk,
    context: &ImportContext,
) -> laravel::Result<()> {
    let (_, mut sheets) = crate::excel::load(import, bytes, file_name, reader_type, &context.config).await?;
    let owned = match import.__concerns().multiple_sheets {
        Some(multiple) => multiple.sheets().imports(),
        None => Vec::new(),
    };
    let sheet_import: &dyn Import = match chunk.sheet_import {
        Some(index) => owned
            .get(index)
            .map(|(_, sheet_import)| sheet_import.as_ref())
            .ok_or(ExcelError::NoSheetsFound)?,
        None => import,
    };
    let Some(sheet) = sheets.get_mut(chunk.sheet) else {
        return Ok(());
    };
    if sheet.highest_row() < chunk.start_row {
        return Ok(());
    }
    let window = SheetWindow {
        start_row: chunk.start_row,
        end_row: Some(chunk.start_row + chunk.chunk_size - 1),
        chunk_offset: Some(chunk.start_row),
    };
    crate::import::transaction(&context.config, async || {
        crate::import::import_sheet(sheet_import, sheet, window, context).await
    })
    .await
}

/// `ChunkReader::read()`: reads an import in chunks, now or as queued jobs.
pub(crate) async fn read_in_chunks(
    import: &dyn Import,
    bytes: Vec<u8>,
    file_name: &str,
    reader_type: Option<Type>,
    context: &ImportContext,
) -> laravel::Result<Option<Queued>> {
    let (kind, sheets) = crate::excel::load(import, &bytes, file_name, reader_type, &context.config).await?;
    let total_rows = crate::import::total_rows(&sheets);
    crate::import::before_import(import, &total_rows, &context.listeners)?;

    let concerns = import.__concerns();
    let progress = concerns.progress_bar;
    if let Some(progress) = progress {
        progress.progress_start(total_rows.values().map(|rows| u64::from(*rows)).sum());
    }
    let chunk_size = concerns.chunk_reading.map_or(1, |chunk| chunk.chunk_size().max(1));
    let owned = match concerns.multiple_sheets {
        Some(multiple) => multiple.sheets().imports(),
        None => Vec::new(),
    };
    let mut worksheets: Vec<(SheetKey, Option<usize>, &dyn Import)> = Vec::new();
    if concerns.multiple_sheets.is_some() {
        for (index, (key, sheet_import)) in owned.iter().enumerate() {
            worksheets.push((key.clone(), Some(index), sheet_import.as_ref()));
        }
    } else {
        for sheet in &sheets {
            worksheets.push((SheetKey::Name(sheet.name().to_owned()), None, import));
        }
    }

    let mut chunks = Vec::new();
    for (key, sheet_import_index, sheet_import) in worksheets {
        let position = match &key {
            SheetKey::Index(index) => (*index < sheets.len()).then_some(*index),
            SheetKey::Name(name) => sheets.iter().position(|sheet| sheet.name() == name),
        };
        let Some(position) = position else {
            if let Some(skips) = concerns.skips_unknown_sheets {
                skips.on_unknown_sheet(&key);
                continue;
            }
            if let Some(skips) = sheet_import.__concerns().skips_unknown_sheets {
                skips.on_unknown_sheet(&key);
                continue;
            }
            return Err(match key {
                SheetKey::Index(index) => ExcelError::SheetNotFoundByIndex {
                    index,
                    count: sheets.len(),
                },
                SheetKey::Name(name) => ExcelError::SheetNotFoundByName(name),
            }
            .into());
        };
        let total = sheets[position].highest_row();
        let sheet_concerns = sheet_import.__concerns();
        let start = sheet_concerns.start_row_number();
        let end = sheet_concerns.end_row(start, total).unwrap_or(total);
        let mut current = start;
        while current <= end {
            chunks.push(Chunk {
                sheet: position,
                sheet_import: sheet_import_index,
                start_row: current,
                chunk_size,
            });
            current += chunk_size;
        }
    }

    let queued = concerns.should_queue;
    let connection = queued.and_then(|queue| queue.on_connection());
    let queue_name = queued.and_then(|queue| queue.on_queue());
    let batched = concerns.should_batch;
    let without_chain = concerns.without_chain.map(|without| without.cleanup_interval());
    let is_queued = queued.is_some();
    drop(concerns);
    drop(owned);
    drop(sheets);

    if !is_queued {
        for chunk in &chunks {
            if let Err(error) = run_chunk(import, &bytes, file_name, Some(kind), chunk, context).await {
                crate::import::import_failed(import, &error, &context.listeners);
                return Err(error);
            }
        }
        crate::import::after_import(import, &total_rows, &context.listeners)?;
        if let Some(progress) = import.__concerns().progress_bar {
            progress.progress_finish();
        }
        return Ok(None);
    }

    let (import_type, payload) = import.__queue_payload().ok_or_else(|| ExcelError::NotRegistered {
        kind: "import",
        name: import.__type_name().to_owned(),
    })??;
    let config = &context.config;
    let extension = std::path::Path::new(file_name).extension().map_or_else(
        || "tmp".to_owned(),
        |extension| extension.to_string_lossy().to_lowercase(),
    );
    let temporary = TemporaryFile::make(&extension);
    temporary.put(config, bytes).await?;

    let job = |step| QueuedImportJob {
        step,
        import_type: import_type.to_owned(),
        import: payload.clone(),
        temporary: temporary.clone(),
        file_name: file_name.to_owned(),
        reader_type: kind,
        total_rows: total_rows.clone(),
    };

    if let Some(interval) = without_chain {
        let mut markers = Vec::new();
        let mut jobs = Vec::new();
        for chunk in chunks {
            let marker = TemporaryFile::make("chunk");
            marker.put(config, Vec::new()).await?;
            markers.push(marker.clone());
            jobs.push(job(ImportStep::ReadChunk {
                chunk,
                marker: Some(marker),
            }));
        }
        let count = jobs.len() + 1;
        let mut bulk = queue::bulk(jobs);
        if let Some(connection) = &connection {
            bulk = bulk.on_connection(connection.clone());
        }
        if let Some(queue_name) = &queue_name {
            bulk = bulk.on_queue(queue_name.clone());
        }
        bulk.await?;
        let mut after = job(ImportStep::AfterImport { markers, interval })
            .dispatch()
            .delay(laravel::time::SignedDuration::from_secs(interval as i64));
        if let Some(connection) = connection {
            after = after.on_connection(connection);
        }
        if let Some(queue_name) = queue_name {
            after = after.on_queue(queue_name);
        }
        after.await?;
        if let Some(progress) = import.__concerns().progress_bar {
            progress.progress_finish();
        }
        return Ok(Some(Queued::Jobs(count)));
    }

    let mut jobs: Vec<QueuedImportJob> = chunks
        .into_iter()
        .map(|chunk| job(ImportStep::ReadChunk { chunk, marker: None }))
        .collect();
    jobs.push(job(ImportStep::AfterImport {
        markers: Vec::new(),
        interval: 60,
    }));
    let dispatched = dispatch_chain(jobs, connection, queue_name, batched).await.map(Some);
    if let Some(progress) = import.__concerns().progress_bar {
        progress.progress_finish();
    }
    dispatched
}