summaryrefslogtreecommitdiff
path: root/cli/tools/serve.rs
blob: e3f9e94f8e00b80a0d8f01b8887edb1c59b833af (plain)
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
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use std::sync::Arc;

use deno_core::error::AnyError;
use deno_core::futures::TryFutureExt;
use deno_core::ModuleSpecifier;

use super::run::check_permission_before_script;
use super::run::maybe_npm_install;
use crate::args::Flags;
use crate::args::ServeFlags;
use crate::args::WatchFlagsWithPaths;
use crate::factory::CliFactory;
use crate::util::file_watcher::WatcherRestartMode;
use crate::worker::CliMainWorkerFactory;

pub async fn serve(
  flags: Arc<Flags>,
  serve_flags: ServeFlags,
) -> Result<i32, AnyError> {
  check_permission_before_script(&flags);

  if let Some(watch_flags) = serve_flags.watch {
    return serve_with_watch(flags, watch_flags, serve_flags.worker_count)
      .await;
  }

  let factory = CliFactory::from_flags(flags);
  let cli_options = factory.cli_options()?;
  let deno_dir = factory.deno_dir()?;
  let http_client = factory.http_client_provider();

  // Run a background task that checks for available upgrades or output
  // if an earlier run of this background task found a new version of Deno.
  #[cfg(feature = "upgrade")]
  super::upgrade::check_for_upgrades(
    http_client.clone(),
    deno_dir.upgrade_check_file_path(),
  );

  let main_module = cli_options.resolve_main_module()?;

  maybe_npm_install(&factory).await?;

  let worker_factory = factory.create_cli_main_worker_factory().await?;
  let hmr = serve_flags
    .watch
    .map(|watch_flags| watch_flags.hmr)
    .unwrap_or(false);
  do_serve(
    worker_factory,
    main_module.clone(),
    serve_flags.worker_count,
    hmr,
  )
  .await
}

async fn do_serve(
  worker_factory: CliMainWorkerFactory,
  main_module: ModuleSpecifier,
  worker_count: Option<usize>,
  hmr: bool,
) -> Result<i32, AnyError> {
  let mut worker = worker_factory
    .create_main_worker(
      deno_runtime::WorkerExecutionMode::Serve {
        is_main: true,
        worker_count,
      },
      main_module.clone(),
    )
    .await?;
  let worker_count = match worker_count {
    None | Some(1) => return worker.run().await,
    Some(c) => c,
  };

  let main = deno_core::unsync::spawn(async move { worker.run().await });

  let extra_workers = worker_count.saturating_sub(1);

  let mut channels = Vec::with_capacity(extra_workers);
  for i in 0..extra_workers {
    let worker_factory = worker_factory.clone();
    let main_module = main_module.clone();
    let (tx, rx) = tokio::sync::oneshot::channel();
    channels.push(rx);
    std::thread::Builder::new()
      .name(format!("serve-worker-{i}"))
      .spawn(move || {
        deno_runtime::tokio_util::create_and_run_current_thread(async move {
          let result = run_worker(i, worker_factory, main_module, hmr).await;
          let _ = tx.send(result);
        });
      })?;
  }

  let (main_result, worker_results) = tokio::try_join!(
    main.map_err(AnyError::from),
    deno_core::futures::future::try_join_all(
      channels.into_iter().map(|r| r.map_err(AnyError::from))
    )
  )?;

  let mut exit_code = main_result?;
  for res in worker_results {
    let ret = res?;
    if ret != 0 && exit_code == 0 {
      exit_code = ret;
    }
  }
  Ok(exit_code)
}

async fn run_worker(
  worker_count: usize,
  worker_factory: CliMainWorkerFactory,
  main_module: ModuleSpecifier,
  hmr: bool,
) -> Result<i32, AnyError> {
  let mut worker: crate::worker::CliMainWorker = worker_factory
    .create_main_worker(
      deno_runtime::WorkerExecutionMode::Serve {
        is_main: false,
        worker_count: Some(worker_count),
      },
      main_module,
    )
    .await?;
  if hmr {
    worker.run_for_watcher().await?;
    Ok(0)
  } else {
    worker.run().await
  }
}

async fn serve_with_watch(
  flags: Arc<Flags>,
  watch_flags: WatchFlagsWithPaths,
  worker_count: Option<usize>,
) -> Result<i32, AnyError> {
  let hmr = watch_flags.hmr;
  crate::util::file_watcher::watch_recv(
    flags,
    crate::util::file_watcher::PrintConfig::new_with_banner(
      if watch_flags.hmr { "HMR" } else { "Watcher" },
      "Process",
      !watch_flags.no_clear_screen,
    ),
    WatcherRestartMode::Automatic,
    move |flags, watcher_communicator, _changed_paths| {
      Ok(async move {
        let factory = CliFactory::from_flags_for_watcher(
          flags,
          watcher_communicator.clone(),
        );
        let cli_options = factory.cli_options()?;
        let main_module = cli_options.resolve_main_module()?;

        maybe_npm_install(&factory).await?;

        let _ = watcher_communicator.watch_paths(cli_options.watch_paths());
        let worker_factory = factory.create_cli_main_worker_factory().await?;

        do_serve(worker_factory, main_module.clone(), worker_count, hmr)
          .await?;

        Ok(())
      })
    },
  )
  .await?;
  Ok(0)
}