feat: use tinymist_std::time for wasm32 targets (#2028)

`std::time` are not implemented for wasm32 targets, so we should use the
time crate made by ourselves.
This commit is contained in:
Myriad-Dreamin 2025-08-12 04:40:04 +08:00 committed by GitHub
parent ce5ab81760
commit f7f2760520
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 37 additions and 30 deletions

1
Cargo.lock generated
View file

@ -3877,6 +3877,7 @@ dependencies = [
"parking_lot", "parking_lot",
"serde", "serde",
"serde_json", "serde_json",
"tinymist-std",
"tokio", "tokio",
"tokio-util", "tokio-util",
] ]

View file

@ -22,6 +22,7 @@ lsp-types = { workspace = true, optional = true }
parking_lot.workspace = true parking_lot.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
tinymist-std.workspace = true
clap = { workspace = true, optional = true } clap = { workspace = true, optional = true }
tokio = { workspace = true, features = ["rt"], optional = true } tokio = { workspace = true, features = ["rt"], optional = true }

View file

@ -12,12 +12,12 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::pin::Pin; use std::pin::Pin;
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
use std::time::Instant;
use futures::future::MaybeDone; use futures::future::MaybeDone;
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::Serialize; use serde::Serialize;
use serde_json::{from_value, Value as JsonValue}; use serde_json::{from_value, Value as JsonValue};
use tinymist_std::time::Instant;
#[cfg(feature = "lsp")] #[cfg(feature = "lsp")]
use crate::lsp::{Notification, Request}; use crate::lsp::{Notification, Request};

View file

@ -110,7 +110,7 @@ where
if is_replay { if is_replay {
let client = self.client.clone(); let client = self.client.clone();
let _ = std::thread::spawn(move || { let _ = std::thread::spawn(move || {
let since = std::time::Instant::now(); let since = tinymist_std::time::Instant::now();
let timeout = std::env::var("REPLAY_TIMEOUT") let timeout = std::env::var("REPLAY_TIMEOUT")
.ok() .ok()
.and_then(|s| s.parse().ok()) .and_then(|s| s.parse().ok())
@ -122,7 +122,7 @@ where
client.begin_panic(); client.begin_panic();
} }
tokio::time::sleep(std::time::Duration::from_millis(10)).await; tokio::time::sleep(tinymist_std::time::Duration::from_millis(10)).await;
} }
}) })
}) })

View file

@ -180,7 +180,7 @@ where
if is_replay { if is_replay {
let client = self.client.clone(); let client = self.client.clone();
let _ = std::thread::spawn(move || { let _ = std::thread::spawn(move || {
let since = std::time::Instant::now(); let since = tinymist_std::time::Instant::now();
let timeout = std::env::var("REPLAY_TIMEOUT") let timeout = std::env::var("REPLAY_TIMEOUT")
.ok() .ok()
.and_then(|s| s.parse().ok()) .and_then(|s| s.parse().ok())

View file

@ -462,7 +462,12 @@ impl LsHook for TypstLsHook {
} }
} }
fn stop_request(&self, req_id: &RequestId, method: &str, received_at: std::time::Instant) { fn stop_request(
&self,
req_id: &RequestId,
method: &str,
received_at: tinymist_std::time::Instant,
) {
().stop_request(req_id, method, received_at); ().stop_request(req_id, method, received_at);
if let Some(scope) = self.0.lock().remove(req_id) { if let Some(scope) = self.0.lock().remove(req_id) {
@ -477,7 +482,7 @@ impl LsHook for TypstLsHook {
fn stop_notification( fn stop_notification(
&self, &self,
method: &str, method: &str,
received_at: std::time::Instant, received_at: tinymist_std::time::Instant,
result: LspResult<()>, result: LspResult<()>,
) { ) {
().stop_notification(method, received_at, result); ().stop_notification(method, received_at, result);

View file

@ -180,7 +180,7 @@ pub async fn test_main(args: TestArgs) -> Result<()> {
} = start_project(verse, None, move |c, mut i, next| { } = start_project(verse, None, move |c, mut i, next| {
if let Interrupt::Compiled(artifact) = &mut i { if let Interrupt::Compiled(artifact) = &mut i {
let mut config = ctx.lock(); let mut config = ctx.lock();
let instant = std::time::Instant::now(); let instant = tinymist_std::time::Instant::now();
// todo: well term support // todo: well term support
// Clear the screen and then move the cursor to the top left corner. // Clear the screen and then move the cursor to the top left corner.
eprintln!("\x1B[2J\x1B[1;1H"); eprintln!("\x1B[2J\x1B[1;1H");

View file

@ -825,7 +825,7 @@ impl<F: CompilerFeat, Ext: 'static> ProjectInsState<F, Ext> {
graph: Arc<WorldComputeGraph<F>>, graph: Arc<WorldComputeGraph<F>>,
export_target: ExportTarget, export_target: ExportTarget,
) -> impl FnOnce() -> CompiledArtifact<F> { ) -> impl FnOnce() -> CompiledArtifact<F> {
let start = tinymist_std::time::now(); let start = tinymist_std::time::Instant::now();
// todo unwrap main id // todo unwrap main id
let id = graph.world().main_id().unwrap(); let id = graph.world().main_id().unwrap();
@ -846,7 +846,7 @@ impl<F: CompilerFeat, Ext: 'static> ProjectInsState<F, Ext> {
let res = CompileStatusResult { let res = CompileStatusResult {
diag: (compiled.warning_cnt() + compiled.error_cnt()) as u32, diag: (compiled.warning_cnt() + compiled.error_cnt()) as u32,
elapsed: start.elapsed().unwrap_or_default(), elapsed: start.elapsed(),
}; };
let rep = CompileReport { let rep = CompileReport {
id: compiled.id().clone(), id: compiled.id().clone(),
@ -898,7 +898,7 @@ impl<F: CompilerFeat, Ext: 'static> ProjectInsState<F, Ext> {
// Trigger an evict task. // Trigger an evict task.
rayon::spawn(move || { rayon::spawn(move || {
let evict_start = std::time::Instant::now(); let evict_start = tinymist_std::time::Instant::now();
if is_primary { if is_primary {
comemo::evict(10); comemo::evict(10);

View file

@ -460,11 +460,11 @@ impl<F: FnMut(FilesystemEvent) + Send + Sync> NotifyActor<F> {
// The async scheduler is not accurate, so we need to ensure a window here // The async scheduler is not accurate, so we need to ensure a window here
let reserved = now - event.at_realtime; let reserved = now - event.at_realtime;
if reserved < std::time::Duration::from_millis(50) { if reserved < tinymist_std::time::Duration::from_millis(50) {
let send = self.undetermined_send.clone(); let send = self.undetermined_send.clone();
tokio::spawn(async move { tokio::spawn(async move {
// todo: sleep in browser // todo: sleep in browser
tokio::time::sleep(std::time::Duration::from_millis(50) - reserved).await; tokio::time::sleep(tinymist_std::time::Duration::from_millis(50) - reserved).await;
log_send_error("reschedule", send.send(event)); log_send_error("reschedule", send.send(event));
}); });
return None; return None;

View file

@ -1089,7 +1089,7 @@ impl SharedContext {
let entry = entry.entry(query).or_default(); let entry = entry.entry(query).or_default();
QueryStatGuard { QueryStatGuard {
bucket: entry.clone(), bucket: entry.clone(),
since: std::time::SystemTime::now(), since: tinymist_std::time::Instant::now(),
} }
} }

View file

@ -1,9 +1,10 @@
//! Statistics about the analyzers //! Statistics about the analyzers
use std::{sync::Arc, time::Duration}; use std::sync::Arc;
use parking_lot::Mutex; use parking_lot::Mutex;
use tinymist_std::hash::FxDashMap; use tinymist_std::hash::FxDashMap;
use tinymist_std::time::Duration;
use typst::syntax::FileId; use typst::syntax::FileId;
#[derive(Clone)] #[derive(Clone)]
@ -35,12 +36,12 @@ pub(crate) struct QueryStatBucket {
pub(crate) struct QueryStatGuard { pub(crate) struct QueryStatGuard {
pub bucket: QueryStatBucket, pub bucket: QueryStatBucket,
pub since: std::time::SystemTime, pub since: tinymist_std::time::Instant,
} }
impl Drop for QueryStatGuard { impl Drop for QueryStatGuard {
fn drop(&mut self) { fn drop(&mut self) {
let elapsed = self.since.elapsed().unwrap_or_default(); let elapsed = self.since.elapsed();
let mut data = self.bucket.data.lock(); let mut data = self.bucket.data.lock();
data.query += 1; data.query += 1;
data.total += elapsed; data.total += elapsed;

View file

@ -54,7 +54,7 @@ pub(crate) fn type_check(
module_exports: Default::default(), module_exports: Default::default(),
}; };
let type_check_start = std::time::Instant::now(); let type_check_start = tinymist_std::time::Instant::now();
checker.check(&root); checker.check(&root);

View file

@ -16,7 +16,7 @@ pub(crate) fn get_lexical_hierarchy(
source: &Source, source: &Source,
scope_kind: LexicalScopeKind, scope_kind: LexicalScopeKind,
) -> Option<EcoVec<LexicalHierarchy>> { ) -> Option<EcoVec<LexicalHierarchy>> {
let start = std::time::Instant::now(); let start = tinymist_std::time::Instant::now();
let root = LinkedNode::new(source.root()); let root = LinkedNode::new(source.root());
let mut worker = LexicalHierarchyWorker { let mut worker = LexicalHierarchyWorker {

View file

@ -81,7 +81,7 @@ impl FontProfileItem {
pub fn mtime(&self) -> Option<SystemTime> { pub fn mtime(&self) -> Option<SystemTime> {
self.meta.get("mtime").and_then(|v| { self.meta.get("mtime").and_then(|v| {
let v = v.parse::<u64>().ok(); let v = v.parse::<u64>().ok();
v.map(|v| SystemTime::UNIX_EPOCH + std::time::Duration::from_micros(v)) v.map(|v| SystemTime::UNIX_EPOCH + tinymist_std::time::Duration::from_micros(v))
}) })
} }

View file

@ -565,7 +565,7 @@ impl CompileHandler<LspCompilerFeat, ProjectInsStateExt> for CompileHandlerImpl
== 0; == 0;
if check_stalled { if check_stalled {
let since = (tinymist_std::time::Time::now().duration_since(*compiling_since)) let since = (tinymist_std::time::now().duration_since(*compiling_since))
.unwrap_or_default(); .unwrap_or_default();
if since.as_secs() > 60 { if since.as_secs() > 60 {
@ -630,7 +630,7 @@ impl CompileHandler<LspCompilerFeat, ProjectInsStateExt> for CompileHandlerImpl
let Some(compile_fn) = s.may_compile(&c.handler) else { let Some(compile_fn) = s.may_compile(&c.handler) else {
continue; continue;
}; };
s.ext.compiling_since = Some(tinymist_std::time::Time::now()); s.ext.compiling_since = Some(tinymist_std::time::now());
rayon::spawn(move || { rayon::spawn(move || {
compile_fn(); compile_fn();
}); });

View file

@ -345,7 +345,7 @@ impl ServerState {
mut state: ServiceState<T, T::S>, mut state: ServiceState<T, T::S>,
params: LspInterrupt, params: LspInterrupt,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let _start = std::time::Instant::now(); let _start = tinymist_std::time::Instant::now();
// log::info!("incoming interrupt: {params:?}"); // log::info!("incoming interrupt: {params:?}");
let Some(ready) = state.ready() else { let Some(ready) = state.ready() else {
log::info!("interrupted on not ready server"); log::info!("interrupted on not ready server");
@ -362,7 +362,7 @@ impl ServerState {
mut state: ServiceState<T, T::S>, mut state: ServiceState<T, T::S>,
params: ServerEvent, params: ServerEvent,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let _start = std::time::Instant::now(); let _start = tinymist_std::time::Instant::now();
// log::info!("incoming interrupt: {params:?}"); // log::info!("incoming interrupt: {params:?}");
let Some(ready) = state.ready() else { let Some(ready) = state.ready() else {
log::info!("server event sent to not ready server"); log::info!("server event sent to not ready server");

View file

@ -2,7 +2,7 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock}; use std::sync::{Arc, OnceLock};
use std::time::Duration; use tinymist_std::time::Duration;
use parking_lot::Mutex; use parking_lot::Mutex;
use reflexo::{hash::FxDashMap, path::unix_slash}; use reflexo::{hash::FxDashMap, path::unix_slash};
@ -36,13 +36,13 @@ pub struct QueryStatBucket {
pub struct QueryStatGuard { pub struct QueryStatGuard {
pub bucket: QueryStatBucket, pub bucket: QueryStatBucket,
pub since: std::time::SystemTime, pub since: tinymist_std::time::Instant,
pub snap_since: OnceLock<std::time::Duration>, pub snap_since: OnceLock<tinymist_std::time::Duration>,
} }
impl Drop for QueryStatGuard { impl Drop for QueryStatGuard {
fn drop(&mut self) { fn drop(&mut self) {
let elapsed = self.since.elapsed().unwrap_or_default(); let elapsed = self.since.elapsed();
let mut data = self.bucket.data.lock(); let mut data = self.bucket.data.lock();
data.query += 1; data.query += 1;
data.total += elapsed; data.total += elapsed;
@ -54,8 +54,7 @@ impl Drop for QueryStatGuard {
impl QueryStatGuard { impl QueryStatGuard {
pub(crate) fn snap(&self) { pub(crate) fn snap(&self) {
self.snap_since self.snap_since.get_or_init(|| self.since.elapsed());
.get_or_init(|| self.since.elapsed().unwrap_or_default());
} }
} }
@ -76,7 +75,7 @@ impl CompilerQueryStats {
let refs2 = refs.entry(name).or_default(); let refs2 = refs.entry(name).or_default();
QueryStatGuard { QueryStatGuard {
bucket: refs2.clone(), bucket: refs2.clone(),
since: std::time::SystemTime::now(), since: tinymist_std::time::Instant::now(),
snap_since: OnceLock::new(), snap_since: OnceLock::new(),
} }
} }