Struct tauri::api::http::ClientBuilder

source ·
pub struct ClientBuilder {
    pub max_redirections: Option<usize>,
    pub connect_timeout: Option<Duration>,
}
Available on crate feature http-api only.
Expand description

The builder of Client.

Fields§

§max_redirections: Option<usize>

Max number of redirections to follow.

§connect_timeout: Option<Duration>

Connect timeout for the request.

Implementations§

Creates a new client builder with the default options.

Examples found in repository?
src/updater/core.rs (line 381)
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
  pub async fn build(mut self) -> Result<Update<R>> {
    let mut remote_release: Option<RemoteRelease> = None;

    // make sure we have at least one url
    if self.urls.is_empty() {
      return Err(Error::Builder(
        "Unable to check update, `url` is required.".into(),
      ));
    };

    // If no executable path provided, we use current_exe from tauri_utils
    let executable_path = self.executable_path.unwrap_or(current_exe()?);

    let arch = get_updater_arch().ok_or(Error::UnsupportedArch)?;
    // `target` is the `{{target}}` variable we replace in the endpoint
    // `json_target` is the value we search if the updater server returns a JSON with the `platforms` object
    let (target, json_target) = if let Some(target) = self.target {
      (target.clone(), target)
    } else {
      let target = get_updater_target().ok_or(Error::UnsupportedOs)?;
      (target.to_string(), format!("{}-{}", target, arch))
    };

    // Get the extract_path from the provided executable_path
    let extract_path = extract_path_from_executable(&self.app.state::<Env>(), &executable_path);

    // Set SSL certs for linux if they aren't available.
    // We do not require to recheck in the download_and_install as we use
    // ENV variables, we can expect them to be set for the second call.
    #[cfg(target_os = "linux")]
    {
      if env::var_os("SSL_CERT_FILE").is_none() {
        env::set_var("SSL_CERT_FILE", "/etc/ssl/certs/ca-certificates.crt");
      }
      if env::var_os("SSL_CERT_DIR").is_none() {
        env::set_var("SSL_CERT_DIR", "/etc/ssl/certs");
      }
    }

    // we want JSON only
    let mut headers = self.headers;
    headers.insert("Accept", HeaderValue::from_str("application/json").unwrap());

    // Allow fallback if more than 1 urls is provided
    let mut last_error: Option<Error> = None;
    for url in &self.urls {
      // replace {{current_version}}, {{target}} and {{arch}} in the provided URL
      // this is useful if we need to query example
      // https://releases.myapp.com/update/{{target}}/{{arch}}/{{current_version}}
      // will be translated into ->
      // https://releases.myapp.com/update/darwin/aarch64/1.0.0
      // The main objective is if the update URL is defined via the Cargo.toml
      // the URL will be generated dynamically
      let fixed_link = url
        .replace("{{current_version}}", &self.current_version.to_string())
        .replace("{{target}}", &target)
        .replace("{{arch}}", arch);

      let mut request = HttpRequestBuilder::new("GET", &fixed_link)?.headers(headers.clone());
      if let Some(timeout) = self.timeout {
        request = request.timeout(timeout);
      }
      let resp = ClientBuilder::new().build()?.send(request).await;

      // If we got a success, we stop the loop
      // and we set our remote_release variable
      if let Ok(res) = resp {
        let res = res.read().await?;
        // got status code 2XX
        if StatusCode::from_u16(res.status)
          .map_err(|e| Error::Builder(e.to_string()))?
          .is_success()
        {
          // if we got 204
          if StatusCode::NO_CONTENT.as_u16() == res.status {
            // return with `UpToDate` error
            // we should catch on the client
            return Err(Error::UpToDate);
          };
          // Convert the remote result to our local struct
          let built_release = serde_json::from_value(res.data).map_err(Into::into);
          // make sure all went well and the remote data is compatible
          // with what we need locally
          match built_release {
            Ok(release) => {
              last_error = None;
              remote_release = Some(release);
              break;
            }
            Err(err) => last_error = Some(err),
          }
        } // if status code is not 2XX we keep loopin' our urls
      }
    }

    // Last error is cleaned on success -- shouldn't be triggered if
    // we have a successful call
    if let Some(error) = last_error {
      return Err(error);
    }

    // Extracted remote metadata
    let final_release = remote_release.ok_or(Error::ReleaseNotFound)?;

    // is the announced version greater than our current one?
    let should_update = if let Some(comparator) = self.should_install.take() {
      comparator(&self.current_version, &final_release)
    } else {
      final_release.version() > &self.current_version
    };

    headers.remove("Accept");

    // create our new updater
    Ok(Update {
      app: self.app,
      target,
      extract_path,
      should_update,
      version: final_release.version().to_string(),
      date: final_release.pub_date().cloned(),
      current_version: self.current_version,
      download_url: final_release.download_url(&json_target)?.to_owned(),
      body: final_release.notes().cloned(),
      signature: final_release.signature(&json_target)?.to_owned(),
      #[cfg(target_os = "windows")]
      with_elevated_task: final_release.with_elevated_task(&json_target)?,
      timeout: self.timeout,
      headers,
    })
  }
}

pub fn builder<R: Runtime>(app: AppHandle<R>) -> UpdateBuilder<R> {
  UpdateBuilder::new(app)
}

#[derive(Debug)]
pub struct Update<R: Runtime> {
  /// Application handle.
  pub app: AppHandle<R>,
  /// Update description
  pub body: Option<String>,
  /// Should we update or not
  pub should_update: bool,
  /// Version announced
  pub version: String,
  /// Running version
  pub current_version: Version,
  /// Update publish date
  pub date: Option<OffsetDateTime>,
  /// Target
  #[allow(dead_code)]
  target: String,
  /// Extract path
  extract_path: PathBuf,
  /// Download URL announced
  download_url: Url,
  /// Signature announced
  signature: String,
  #[cfg(target_os = "windows")]
  /// Optional: Windows only try to use elevated task
  /// Default to false
  with_elevated_task: bool,
  /// Request timeout
  timeout: Option<Duration>,
  /// Request headers
  headers: HeaderMap,
}

impl<R: Runtime> Clone for Update<R> {
  fn clone(&self) -> Self {
    Self {
      app: self.app.clone(),
      body: self.body.clone(),
      should_update: self.should_update,
      version: self.version.clone(),
      current_version: self.current_version.clone(),
      date: self.date,
      target: self.target.clone(),
      extract_path: self.extract_path.clone(),
      download_url: self.download_url.clone(),
      signature: self.signature.clone(),
      #[cfg(target_os = "windows")]
      with_elevated_task: self.with_elevated_task,
      timeout: self.timeout,
      headers: self.headers.clone(),
    }
  }
}

impl<R: Runtime> Update<R> {
  // Download and install our update
  // @todo(lemarier): Split into download and install (two step) but need to be thread safe
  pub(crate) async fn download_and_install<C: Fn(usize, Option<u64>), D: FnOnce()>(
    &self,
    pub_key: String,
    on_chunk: C,
    on_download_finish: D,
  ) -> Result {
    // make sure we can install the update on linux
    // We fail here because later we can add more linux support
    // actually if we use APPIMAGE, our extract path should already
    // be set with our APPIMAGE env variable, we don't need to do
    // anything with it yet
    #[cfg(target_os = "linux")]
    if self.app.state::<Env>().appimage.is_none() {
      return Err(Error::UnsupportedLinuxPackage);
    }

    // set our headers
    let mut headers = self.headers.clone();
    headers.insert(
      "Accept",
      HeaderValue::from_str("application/octet-stream").unwrap(),
    );
    headers.insert(
      "User-Agent",
      HeaderValue::from_str("tauri/updater").unwrap(),
    );

    let client = ClientBuilder::new().build()?;
    // Create our request
    let mut req = HttpRequestBuilder::new("GET", self.download_url.as_str())?.headers(headers);
    if let Some(timeout) = self.timeout {
      req = req.timeout(timeout);
    }

    let response = client.send(req).await?;

    // make sure it's success
    if !response.status().is_success() {
      return Err(Error::Network(format!(
        "Download request failed with status: {}",
        response.status()
      )));
    }

    let content_length: Option<u64> = response
      .headers()
      .get("Content-Length")
      .and_then(|value| value.to_str().ok())
      .and_then(|value| value.parse().ok());

    let mut buffer = Vec::new();
    #[cfg(feature = "reqwest-client")]
    {
      use futures_util::StreamExt;
      let mut stream = response.bytes_stream();
      while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        let bytes = chunk.as_ref().to_vec();
        on_chunk(bytes.len(), content_length);
        buffer.extend(bytes);
      }
    }
    #[cfg(not(feature = "reqwest-client"))]
    {
      let mut reader = response.reader();
      let mut buf = [0; 16384];
      loop {
        match reader.read(&mut buf) {
          Ok(b) => {
            if b == 0 {
              break;
            } else {
              let bytes = buf[0..b].to_vec();
              on_chunk(bytes.len(), content_length);
              buffer.extend(bytes);
            }
          }
          Err(e) => return Err(e.into()),
        }
      }
    }

    on_download_finish();

    // create memory buffer from our archive (Seek + Read)
    let mut archive_buffer = Cursor::new(buffer);

    // We need an announced signature by the server
    // if there is no signature, bail out.
    verify_signature(&mut archive_buffer, &self.signature, &pub_key)?;

    // TODO: implement updater in mobile
    #[cfg(desktop)]
    {
      // we copy the files depending of the operating system
      // we run the setup, appimage re-install or overwrite the
      // macos .app
      #[cfg(target_os = "windows")]
      copy_files_and_run(
        archive_buffer,
        &self.extract_path,
        self.with_elevated_task,
        self
          .app
          .config()
          .tauri
          .updater
          .windows
          .install_mode
          .clone()
          .msiexec_args(),
      )?;
      #[cfg(not(target_os = "windows"))]
      copy_files_and_run(archive_buffer, &self.extract_path)?;
    }

    // We are done!
    Ok(())
  }

Sets the maximum number of redirections.

Sets the connection timeout.

Builds the Client.

Examples found in repository?
src/endpoints/http.rs (line 65)
61
62
63
64
65
66
67
68
69
70
  async fn create_client<R: Runtime>(
    _context: InvokeContext<R>,
    options: Option<ClientBuilder>,
  ) -> super::Result<ClientId> {
    let client = options.unwrap_or_default().build()?;
    let mut store = clients().lock().unwrap();
    let id = rand::random::<ClientId>();
    store.insert(id, client);
    Ok(id)
  }
More examples
Hide additional examples
src/updater/core.rs (line 381)
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
  pub async fn build(mut self) -> Result<Update<R>> {
    let mut remote_release: Option<RemoteRelease> = None;

    // make sure we have at least one url
    if self.urls.is_empty() {
      return Err(Error::Builder(
        "Unable to check update, `url` is required.".into(),
      ));
    };

    // If no executable path provided, we use current_exe from tauri_utils
    let executable_path = self.executable_path.unwrap_or(current_exe()?);

    let arch = get_updater_arch().ok_or(Error::UnsupportedArch)?;
    // `target` is the `{{target}}` variable we replace in the endpoint
    // `json_target` is the value we search if the updater server returns a JSON with the `platforms` object
    let (target, json_target) = if let Some(target) = self.target {
      (target.clone(), target)
    } else {
      let target = get_updater_target().ok_or(Error::UnsupportedOs)?;
      (target.to_string(), format!("{}-{}", target, arch))
    };

    // Get the extract_path from the provided executable_path
    let extract_path = extract_path_from_executable(&self.app.state::<Env>(), &executable_path);

    // Set SSL certs for linux if they aren't available.
    // We do not require to recheck in the download_and_install as we use
    // ENV variables, we can expect them to be set for the second call.
    #[cfg(target_os = "linux")]
    {
      if env::var_os("SSL_CERT_FILE").is_none() {
        env::set_var("SSL_CERT_FILE", "/etc/ssl/certs/ca-certificates.crt");
      }
      if env::var_os("SSL_CERT_DIR").is_none() {
        env::set_var("SSL_CERT_DIR", "/etc/ssl/certs");
      }
    }

    // we want JSON only
    let mut headers = self.headers;
    headers.insert("Accept", HeaderValue::from_str("application/json").unwrap());

    // Allow fallback if more than 1 urls is provided
    let mut last_error: Option<Error> = None;
    for url in &self.urls {
      // replace {{current_version}}, {{target}} and {{arch}} in the provided URL
      // this is useful if we need to query example
      // https://releases.myapp.com/update/{{target}}/{{arch}}/{{current_version}}
      // will be translated into ->
      // https://releases.myapp.com/update/darwin/aarch64/1.0.0
      // The main objective is if the update URL is defined via the Cargo.toml
      // the URL will be generated dynamically
      let fixed_link = url
        .replace("{{current_version}}", &self.current_version.to_string())
        .replace("{{target}}", &target)
        .replace("{{arch}}", arch);

      let mut request = HttpRequestBuilder::new("GET", &fixed_link)?.headers(headers.clone());
      if let Some(timeout) = self.timeout {
        request = request.timeout(timeout);
      }
      let resp = ClientBuilder::new().build()?.send(request).await;

      // If we got a success, we stop the loop
      // and we set our remote_release variable
      if let Ok(res) = resp {
        let res = res.read().await?;
        // got status code 2XX
        if StatusCode::from_u16(res.status)
          .map_err(|e| Error::Builder(e.to_string()))?
          .is_success()
        {
          // if we got 204
          if StatusCode::NO_CONTENT.as_u16() == res.status {
            // return with `UpToDate` error
            // we should catch on the client
            return Err(Error::UpToDate);
          };
          // Convert the remote result to our local struct
          let built_release = serde_json::from_value(res.data).map_err(Into::into);
          // make sure all went well and the remote data is compatible
          // with what we need locally
          match built_release {
            Ok(release) => {
              last_error = None;
              remote_release = Some(release);
              break;
            }
            Err(err) => last_error = Some(err),
          }
        } // if status code is not 2XX we keep loopin' our urls
      }
    }

    // Last error is cleaned on success -- shouldn't be triggered if
    // we have a successful call
    if let Some(error) = last_error {
      return Err(error);
    }

    // Extracted remote metadata
    let final_release = remote_release.ok_or(Error::ReleaseNotFound)?;

    // is the announced version greater than our current one?
    let should_update = if let Some(comparator) = self.should_install.take() {
      comparator(&self.current_version, &final_release)
    } else {
      final_release.version() > &self.current_version
    };

    headers.remove("Accept");

    // create our new updater
    Ok(Update {
      app: self.app,
      target,
      extract_path,
      should_update,
      version: final_release.version().to_string(),
      date: final_release.pub_date().cloned(),
      current_version: self.current_version,
      download_url: final_release.download_url(&json_target)?.to_owned(),
      body: final_release.notes().cloned(),
      signature: final_release.signature(&json_target)?.to_owned(),
      #[cfg(target_os = "windows")]
      with_elevated_task: final_release.with_elevated_task(&json_target)?,
      timeout: self.timeout,
      headers,
    })
  }
}

pub fn builder<R: Runtime>(app: AppHandle<R>) -> UpdateBuilder<R> {
  UpdateBuilder::new(app)
}

#[derive(Debug)]
pub struct Update<R: Runtime> {
  /// Application handle.
  pub app: AppHandle<R>,
  /// Update description
  pub body: Option<String>,
  /// Should we update or not
  pub should_update: bool,
  /// Version announced
  pub version: String,
  /// Running version
  pub current_version: Version,
  /// Update publish date
  pub date: Option<OffsetDateTime>,
  /// Target
  #[allow(dead_code)]
  target: String,
  /// Extract path
  extract_path: PathBuf,
  /// Download URL announced
  download_url: Url,
  /// Signature announced
  signature: String,
  #[cfg(target_os = "windows")]
  /// Optional: Windows only try to use elevated task
  /// Default to false
  with_elevated_task: bool,
  /// Request timeout
  timeout: Option<Duration>,
  /// Request headers
  headers: HeaderMap,
}

impl<R: Runtime> Clone for Update<R> {
  fn clone(&self) -> Self {
    Self {
      app: self.app.clone(),
      body: self.body.clone(),
      should_update: self.should_update,
      version: self.version.clone(),
      current_version: self.current_version.clone(),
      date: self.date,
      target: self.target.clone(),
      extract_path: self.extract_path.clone(),
      download_url: self.download_url.clone(),
      signature: self.signature.clone(),
      #[cfg(target_os = "windows")]
      with_elevated_task: self.with_elevated_task,
      timeout: self.timeout,
      headers: self.headers.clone(),
    }
  }
}

impl<R: Runtime> Update<R> {
  // Download and install our update
  // @todo(lemarier): Split into download and install (two step) but need to be thread safe
  pub(crate) async fn download_and_install<C: Fn(usize, Option<u64>), D: FnOnce()>(
    &self,
    pub_key: String,
    on_chunk: C,
    on_download_finish: D,
  ) -> Result {
    // make sure we can install the update on linux
    // We fail here because later we can add more linux support
    // actually if we use APPIMAGE, our extract path should already
    // be set with our APPIMAGE env variable, we don't need to do
    // anything with it yet
    #[cfg(target_os = "linux")]
    if self.app.state::<Env>().appimage.is_none() {
      return Err(Error::UnsupportedLinuxPackage);
    }

    // set our headers
    let mut headers = self.headers.clone();
    headers.insert(
      "Accept",
      HeaderValue::from_str("application/octet-stream").unwrap(),
    );
    headers.insert(
      "User-Agent",
      HeaderValue::from_str("tauri/updater").unwrap(),
    );

    let client = ClientBuilder::new().build()?;
    // Create our request
    let mut req = HttpRequestBuilder::new("GET", self.download_url.as_str())?.headers(headers);
    if let Some(timeout) = self.timeout {
      req = req.timeout(timeout);
    }

    let response = client.send(req).await?;

    // make sure it's success
    if !response.status().is_success() {
      return Err(Error::Network(format!(
        "Download request failed with status: {}",
        response.status()
      )));
    }

    let content_length: Option<u64> = response
      .headers()
      .get("Content-Length")
      .and_then(|value| value.to_str().ok())
      .and_then(|value| value.parse().ok());

    let mut buffer = Vec::new();
    #[cfg(feature = "reqwest-client")]
    {
      use futures_util::StreamExt;
      let mut stream = response.bytes_stream();
      while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        let bytes = chunk.as_ref().to_vec();
        on_chunk(bytes.len(), content_length);
        buffer.extend(bytes);
      }
    }
    #[cfg(not(feature = "reqwest-client"))]
    {
      let mut reader = response.reader();
      let mut buf = [0; 16384];
      loop {
        match reader.read(&mut buf) {
          Ok(b) => {
            if b == 0 {
              break;
            } else {
              let bytes = buf[0..b].to_vec();
              on_chunk(bytes.len(), content_length);
              buffer.extend(bytes);
            }
          }
          Err(e) => return Err(e.into()),
        }
      }
    }

    on_download_finish();

    // create memory buffer from our archive (Seek + Read)
    let mut archive_buffer = Cursor::new(buffer);

    // We need an announced signature by the server
    // if there is no signature, bail out.
    verify_signature(&mut archive_buffer, &self.signature, &pub_key)?;

    // TODO: implement updater in mobile
    #[cfg(desktop)]
    {
      // we copy the files depending of the operating system
      // we run the setup, appimage re-install or overwrite the
      // macos .app
      #[cfg(target_os = "windows")]
      copy_files_and_run(
        archive_buffer,
        &self.extract_path,
        self.with_elevated_task,
        self
          .app
          .config()
          .tauri
          .updater
          .windows
          .install_mode
          .clone()
          .msiexec_args(),
      )?;
      #[cfg(not(target_os = "windows"))]
      copy_files_and_run(archive_buffer, &self.extract_path)?;
    }

    // We are done!
    Ok(())
  }

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
Deserialize this value from the given Serde deserializer. 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
Derives an instance of Self from the CommandItem. Read more

Returns the argument unchanged.

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.

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