laburnum 1.17.1

An LSP framework for building language servers and compilers, powered by an incremental query tree with content-addressed storage, task-based dataflow, and parallel queries.
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
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

use {
  crate::{
    database::{
      RecordKey,
      chunk::Chunk,
      PartitionKey,
      PartitionWriteContextRef,
      Partitions,
    },
    hash::Ident,
    protocol::lsp::LanguageServer,
    scheduler::{lanes::Lane, task::TaskContext},
  },
  globset::{
    Glob,
    GlobSet,
    GlobSetBuilder,
  },
  std::{
    future::Future,
    pin::Pin,
  },
};

#[macro_use]
mod watchers_macro;

pub(crate) fn dispatch_builtin_watcher<P, T, F>(
  pk: Ident,
  updated_sks: Vec<String>,
  deleted_sks: Vec<String>,
  spawn: F,
) where
  P: Partitions,
  T: crate::protocol::lsp::LanguageServer<P>,
  F: Fn(
    Ident,
    Vec<String>,
    Vec<String>,
    for<'a> fn(
      &'a mut TaskContext<P, T>,
      &'a mut PartitionWriteContextRef<'a, P>,
    ) -> Pin<Box<dyn Future<Output = WatcherResult<P, T>> + Send + 'a>>,
  ),
{
  if pk == crate::partitions::Diagnostics::KEY
    && (!updated_sks.is_empty() || !deleted_sks.is_empty())
  {
    spawn(
      pk,
      updated_sks.clone(),
      deleted_sks.clone(),
      crate::builtin_watchers::diagnostic_watcher,
    );
  }

  if pk == crate::partitions::WorkDoneProgress::KEY
    && (!updated_sks.is_empty() || !deleted_sks.is_empty())
  {
    spawn(
      pk,
      updated_sks,
      deleted_sks,
      crate::progress::work_done_progress_watcher,
    );
  }
}

type FollowUpTaskFn<P, T> = Box<
  dyn for<'a> FnOnce(
      &'a mut TaskContext<P, T>,
      &'a mut PartitionWriteContextRef<'a, P>,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>
    + Send,
>;

/// A single follow-up task to be scheduled after a watcher handler completes.
pub struct FollowUpTask<P: Partitions, T: LanguageServer<P>> {
  pub(crate) task_fn: FollowUpTaskFn<P, T>,
  pub(crate) lane:    Lane,
}

/// Result returned by watcher handler functions.
///
/// Contains zero or more follow-up tasks for the scheduler to queue after the
/// handler completes.
pub struct WatcherResult<P: Partitions, T: LanguageServer<P>> {
  pub(crate) follow_ups: Vec<FollowUpTask<P, T>>,
}

impl<P: Partitions, T: LanguageServer<P>> WatcherResult<P, T> {
  /// Create an empty result with no follow-up tasks.
  pub fn empty() -> Self {
    Self {
      follow_ups: Vec::new(),
    }
  }

  /// Create a result with a single follow-up task.
  pub fn with_task<F>(task_fn: F, lane: Lane) -> Self
  where
    F: for<'a> FnOnce(
        &'a mut TaskContext<P, T>,
        &'a mut PartitionWriteContextRef<'a, P>,
      ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>
      + Send
      + 'static,
  {
    Self {
      follow_ups: vec![FollowUpTask {
        task_fn: Box::new(task_fn),
        lane,
      }],
    }
  }

  /// Add a follow-up task to this result.
  pub fn push_task<F>(&mut self, task_fn: F, lane: Lane)
  where
    F: for<'a> FnOnce(
        &'a mut TaskContext<P, T>,
        &'a mut PartitionWriteContextRef<'a, P>,
      ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>
      + Send
      + 'static,
  {
    self.follow_ups.push(FollowUpTask {
      task_fn: Box::new(task_fn),
      lane,
    });
  }
}

impl<P: Partitions, T: LanguageServer<P>> From<()> for WatcherResult<P, T> {
  fn from(_: ()) -> Self {
    Self::empty()
  }
}

/// Type alias for watcher handler function signature.
pub type WatcherHandlerFn<P, T> =
  for<'a> fn(
    &'a mut TaskContext<P, T>,
    &'a mut PartitionWriteContextRef<'a, P>,
  ) -> Pin<Box<dyn Future<Output = WatcherResult<P, T>> + Send + 'a>>;

/// Metadata for a single watcher handler function with optional glob filtering.
pub struct WatcherHandler<P, T>
where
  P: Partitions,
  T: LanguageServer<P>,
{
  pub handler_fn: WatcherHandlerFn<P, T>,
  pub glob_set:   Option<GlobSet>,
}

pub trait KeyWatcher<P, T>: Send + Sync + 'static
where
  P: crate::database::storage::Partitions,
  T: crate::protocol::lsp::LanguageServer<P>,
{
  fn dispatch_watcher<F>(
    pk: Ident,
    updated_sks: Vec<String>,
    deleted_sks: Vec<String>,
    spawn: F,
  ) where
    F: Fn(
      Ident,
      Vec<String>,
      Vec<String>,
      for<'a> fn(
        &'a mut TaskContext<P, T>,
        &'a mut PartitionWriteContextRef<'a, P>,
      ) -> Pin<Box<dyn Future<Output = WatcherResult<P, T>> + Send + 'a>>,
    );
}

/// Configuration for database key watching and reactive task spawning.
///
/// Manages a collection of watch rules that monitor database key changes and
/// trigger handler functions when matching keys are created, modified, or
/// deleted.
///
/// Generic over `H` which is the handler enum type (user-defined via
/// `watchers!` macro).
///
/// # Example
///
/// ```ignore
/// let mut config = WatcherConfig::empty();
/// config.add_matcher_enum(
///   vec![PatternSpec::PkAndSk(Ident::new("diagnostics"), "*.rs".to_string())],
///   WatcherHandler::DiagnosticWatcher
/// )?;
/// ```
pub struct WatcherConfig<P: Partitions, H = ()> {
  pub(crate) rules: Vec<WatchRule<P, H>>,
}

impl<P: Partitions, H: Clone> WatcherConfig<P, H> {
  /// Creates an empty watcher configuration.
  pub fn empty() -> Self {
    Self { rules: Vec::new() }
  }

  /// Registers watch patterns with a handler enum variant.
  ///
  /// Creates one [`WatchRule`] for each pattern. When database keys matching
  /// any pattern are created, modified, or deleted, the handler is invoked
  /// with the matched keys available via [`TaskContext`].
  pub fn add_matcher_enum(
    &mut self,
    patterns: Vec<PatternSpec>,
    handler: H,
  ) -> Result<(), globset::Error> {
    for pattern in patterns {
      let (pk_ident, sk_globset, task_id) = match pattern {
        | PatternSpec::PkOnly(pk_ident) => {
          let task_id = Ident::new(&format!("watcher:{}", pk_ident));
          (pk_ident, None, task_id)
        },
        | PatternSpec::PkAndSk(pk_ident, sk_pattern) => {
          let mut builder = GlobSetBuilder::new();
          builder.add(Glob::new(&sk_pattern)?);
          let sk_globset = Some(builder.build()?);
          let task_id =
            Ident::new(&format!("watcher:{}:{}", pk_ident, sk_pattern));
          (pk_ident, sk_globset, task_id)
        },
      };

      let rule = WatchRule {
        pk_ident,
        sk_globset,
        handler: handler.clone(),
        task_id,
        _phantom: std::marker::PhantomData,
      };

      self.rules.push(rule);
    }

    Ok(())
  }
}

/// A pattern-based watch rule that triggers a handler when matching keys
/// change.
///
/// Represents a single database trigger rule. Matches keys based on a partition
/// key (PK) and optional sort key (SK) glob pattern, then invokes a handler
/// when matching keys are created, modified, or deleted.
///
/// Generic over `H` which is the handler enum type (user-defined via
/// `watchers!` macro).
///
/// # Pattern Matching
///
/// * **Partition Key**: Exact match using pre-hashed [`Ident`] (no wildcards)
/// * **Sort Key**: Optional glob pattern match using pre-compiled [`GlobSet`]
pub struct WatchRule<P: Partitions, H = ()> {
  pub(crate) pk_ident:   Ident,
  pub(crate) sk_globset: Option<GlobSet>,
  /// User-supplied handler kept for future dispatch wiring (see
  /// `laburnum-p25`). Currently dispatch goes through
  /// `dispatch_builtin_watcher` to hard-coded built-ins; this field is
  /// stored but not yet invoked.
  #[allow(dead_code)]
  pub(crate) handler:    H,
  pub(crate) task_id:    Ident,
  _phantom:              std::marker::PhantomData<P>,
}

impl<P: Partitions, H> WatchRule<P, H> {
  /// Filters keys to those matching this rule's patterns.
  ///
  /// A key matches if the partition key equals `pk_ident` and the sort key
  /// matches `sk_globset` (or rule has no SK filter).
  pub fn match_keys(&self, keys: &[RecordKey]) -> Vec<RecordKey> {
    let mut matched = Vec::new();

    for key in keys {
      if key.partition_key() != self.pk_ident {
        continue;
      }

      let sk_matches = if let Some(ref globset) = self.sk_globset {
        globset.is_match(key.sort_key())
      } else {
        true
      };

      if sk_matches {
        matched.push(key.clone());
      }
    }

    matched
  }

  /// Returns the pre-computed task identifier for this rule.
  ///
  /// The task ID is used by the scheduler to track and deduplicate watcher
  /// tasks.
  pub fn task_id(&self) -> Ident {
    self.task_id
  }
}

/// Specification for database key patterns to watch.
///
/// Each spec creates one [`WatchRule`] when registered with
/// [`WatcherConfig::add_matcher`].
///
/// # Examples
///
/// ```ignore
/// // Watch all keys under "diagnostics" partition
/// PatternSpec::PkOnly(Ident::new("diagnostics"))
///
/// // Watch only Rust files under "ast" partition
/// PatternSpec::PkAndSk(Ident::new("ast"), "**/*.rs".to_string())
/// ```
pub enum PatternSpec {
  PkOnly(Ident),
  PkAndSk(Ident, String),
}

/// Extracts all record keys from a database chunk.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn extract_chunk_keys<P: Partitions>(
  chunk: &Chunk<P>,
) -> Vec<RecordKey> {
  let mut keys = Vec::new();

  for (partition_key, sort_map) in chunk.records() {
    for sort_key in sort_map.keys() {
      keys.push(RecordKey::new(*partition_key, sort_key.clone()));
    }
  }

  keys
}

/// Computes which keys were updated (created/modified) and deleted.
///
/// Returns (updated, deleted) where updated contains keys in `new_keys` but not
/// in `old_keys`, and deleted contains keys in `old_keys` but not in
/// `new_keys`.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn compute_key_changes(
  new_keys: &[RecordKey],
  old_keys: &[RecordKey],
) -> (Vec<RecordKey>, Vec<RecordKey>) {
  use std::collections::HashSet;

  let new_set: HashSet<_> = new_keys.iter().collect();
  let old_set: HashSet<_> = old_keys.iter().collect();

  let updated: Vec<_> =
    new_set.difference(&old_set).map(|k| (*k).clone()).collect();

  let deleted: Vec<_> =
    old_set.difference(&new_set).map(|k| (*k).clone()).collect();

  (updated, deleted)
}

#[cfg(test)]
mod tests {
  use {
    super::*,
    crate::database::chunk::RecordWriter,
  };

  fn rk(pk: &str, sk: &str) -> RecordKey {
    RecordKey::new(Ident::new(pk), sk.to_string())
  }

  #[test]
  fn test_extract_keys_from_empty_chunk() {
    use crate::database::tests::storage::TestPartitions;

    let writer: RecordWriter<TestPartitions> =
      RecordWriter::new(Ident::new("test"));
    let chunk = writer.build();

    let keys = extract_chunk_keys(&chunk);
    assert_eq!(keys.len(), 0);
  }

  #[test]
  fn test_extract_keys_from_chunk_with_records() {
    use crate::{
      database::tests::storage::{
        Test1Partition,
        Test2Partition,
        TestPartitions,
        TestRecordData,
      },
      record::LaburnumRecord,
    };

    let mut writer: RecordWriter<TestPartitions> =
      RecordWriter::new(Ident::new("test"));

    let test_record =
      TestRecordData::Laburnum(LaburnumRecord::WorkspaceConfig {
        value: "test".to_string(),
      });
    writer.insert::<Test1Partition, _>("sk1".to_string(), test_record.clone());
    writer.insert::<Test1Partition, _>("sk2".to_string(), test_record.clone());
    writer.insert::<Test2Partition, _>("sk3".to_string(), test_record);

    let chunk = writer.build();
    let keys = extract_chunk_keys(&chunk);

    assert_eq!(keys.len(), 3);
    assert!(keys.contains(&rk("pk1", "sk1")));
    assert!(keys.contains(&rk("pk1", "sk2")));
    assert!(keys.contains(&rk("pk2", "sk3")));
  }

  #[test]
  fn test_no_previous_chunk_all_created() {
    let new_keys = vec![rk("pk", "sk1")];
    let old_keys = vec![];

    let (updated, deleted) = compute_key_changes(&new_keys, &old_keys);

    assert_eq!(updated.len(), 1);
    assert_eq!(deleted.len(), 0);
  }

  #[test]
  fn test_all_keys_deleted() {
    let new_keys = vec![];
    let old_keys = vec![rk("pk", "sk1")];

    let (updated, deleted) = compute_key_changes(&new_keys, &old_keys);

    assert_eq!(updated.len(), 0);
    assert_eq!(deleted.len(), 1);
  }

  #[test]
  fn test_partial_overlap() {
    let new_keys = vec![rk("pk", "sk2"), rk("pk", "sk3")];
    let old_keys = vec![rk("pk", "sk1"), rk("pk", "sk2")];

    let (updated, deleted) = compute_key_changes(&new_keys, &old_keys);

    // sk3 is new, sk2 exists in both (not updated), sk1 was deleted
    assert_eq!(updated.len(), 1);
    assert!(updated.contains(&rk("pk", "sk3")));
    assert_eq!(deleted.len(), 1);
    assert!(deleted.contains(&rk("pk", "sk1")));
  }

  #[test]
  fn test_no_changes() {
    let keys = vec![rk("pk", "sk1"), rk("pk", "sk2")];

    let (updated, deleted) = compute_key_changes(&keys, &keys);

    // Same keys: nothing updated, nothing deleted
    assert_eq!(updated.len(), 0);
    assert_eq!(deleted.len(), 0);
  }

  #[test]
  fn test_unchanged_keys_not_reported_as_updated() {
    // When old and new keys are identical, nothing should be reported as
    // updated
    let keys = vec![rk("pk", "sk1"), rk("pk", "sk2")];

    let (updated, deleted) = compute_key_changes(&keys, &keys);

    assert_eq!(
      updated.len(),
      0,
      "unchanged keys should not be reported as updated"
    );
    assert_eq!(deleted.len(), 0);
  }

  #[test]
  fn test_only_new_keys_reported_as_updated() {
    // When adding one new key to existing keys, only the new key should be
    // updated
    let old_keys = vec![rk("pk", "sk1")];
    let new_keys = vec![rk("pk", "sk1"), rk("pk", "sk2")];

    let (updated, deleted) = compute_key_changes(&new_keys, &old_keys);

    assert_eq!(
      updated.len(),
      1,
      "only the new key should be reported as updated"
    );
    assert!(updated.contains(&rk("pk", "sk2")));
    assert_eq!(deleted.len(), 0);
  }
}