Repository navigation
Expand file tree
/
Copy pathapplication.c
More file actions
3506 lines (3312 loc) · 146 KB
/
Copy pathapplication.c
File metadata and controls
3506 lines (3312 loc) · 146 KB
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* application.c — Daemon-owned CBM application sessions and thin-client wire.
*/
#include "daemon/application.h"
#include "daemon/application_internal.h"
#include "cli/cli.h"
#include "foundation/compat.h"
#include "foundation/compat_fs.h"
#include "foundation/compat_thread.h"
#include "foundation/log.h"
#include "foundation/mem.h"
#include "foundation/platform.h"
#include "foundation/secure_random.h"
#include "foundation/sha256.h"
#include "foundation/subprocess.h"
#include "mcp/index_supervisor.h"
#include "mcp/mcp.h"
#include "mcp/mcp_internal.h"
#include "pipeline/pipeline.h"
#include "ui/config.h"
#include "watcher/watcher.h"
#include <yyjson/yyjson.h>
#include <ctype.h>
#include <limits.h>
#include <stdint.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <io.h>
#include <windows.h>
#define application_close _close
#else
#include <unistd.h>
#define application_close close
#endif
enum {
APPLICATION_CONTEXT_HEADER_SIZE = 19,
APPLICATION_TOOL_HEADER_SIZE = 5,
APPLICATION_UI_CONFIG_REQUEST_SIZE = 7,
APPLICATION_UI_READINESS_REQUEST_SIZE = 1 + CBM_SHA256_DIGEST_LEN,
APPLICATION_PATH_CAP = 4096,
APPLICATION_JOB_THREAD_STACK = 256 * 1024,
APPLICATION_JOB_POLL_US = 10000,
APPLICATION_COORDINATION_CLEANUP_MS = 500,
APPLICATION_DEFAULT_PHYSICAL_JOB_LIMIT = 4,
APPLICATION_DEFAULT_MAX_RESTARTS = 100,
APPLICATION_MARKER_MAX_BYTES = 64 * 1024 * 1024,
APPLICATION_MAX_SUSPECTS = 65536,
APPLICATION_UPDATE_POLL_US = 10000,
APPLICATION_BACKGROUND_REAP_MS = 10000,
APPLICATION_UPDATE_VERSION_CAP = 128,
APPLICATION_UPDATE_NOTICE_CAP = 1024,
};
/* There is deliberately NO production update-check provider. The daemon used to
* spawn `curl` against the GitHub releases API on the first eligible session of
* every run, purely to print "a newer version exists". That put a release URL
* and an outbound request into every shipped binary, and made a developer tool
* phone home from every agent session, to deliver something the install scripts
* and package managers already report.
*
* The SEAM below survives: `update_ops` remains injectable, and the notice,
* ownership, cancellation and generation-replay logic is still exercised by the
* fakes in tests/test_daemon_application.c. With no provider installed the whole
* machinery simply never starts a generation (see
* application_update_subscribe_locked), so a build that ships no provider makes
* no network request by default -- the property, not just the absence of a call.
*/
typedef struct cbm_daemon_application_watch cbm_daemon_application_watch_t;
typedef struct cbm_daemon_application_session cbm_daemon_application_session_t;
typedef struct cbm_daemon_application_job cbm_daemon_application_job_t;
typedef struct cbm_daemon_application_mutation cbm_daemon_application_mutation_t;
typedef struct cbm_daemon_application_watch_job_subscription
cbm_daemon_application_watch_job_subscription_t;
typedef enum {
APPLICATION_JOB_SUBSCRIBE_OK = 0,
APPLICATION_JOB_SUBSCRIBE_OPTIONS_CONFLICT,
APPLICATION_JOB_SUBSCRIBE_BUSY,
APPLICATION_JOB_SUBSCRIBE_CANCELLING,
APPLICATION_JOB_SUBSCRIBE_UNAVAILABLE,
APPLICATION_JOB_SUBSCRIBE_ALLOCATION_FAILED,
} application_job_subscribe_status_t;
struct cbm_daemon_application_watch {
char *project;
char *root;
size_t subscribers;
cbm_daemon_application_watch_t *next;
};
struct cbm_daemon_application_session {
cbm_daemon_application_t *application;
cbm_mcp_server_t *mcp;
cbm_daemon_client_id_t client_id;
uint64_t authenticated_process_id;
bool context_set;
cbm_mcp_tool_profile_t tool_profile;
char *hook_event;
char *hook_dialect;
bool session_cancelled;
bool request_active;
cbm_daemon_runtime_application_token_t active_request_token;
cbm_daemon_runtime_application_token_t request_cancel_token;
cbm_daemon_application_watch_t *watch;
cbm_daemon_application_job_t *active_job;
bool active_job_subscribed;
cbm_daemon_application_job_t *auto_index_job;
bool auto_index_subscribed;
bool auto_index_evaluated;
bool auto_index_retry_pending;
bool background_eligible;
bool update_owner;
bool update_notice_delivered;
bool pending_background_initialize;
bool pending_update_notice;
cbm_daemon_application_session_t *next;
};
struct cbm_daemon_application_job {
cbm_daemon_application_t *application;
char *project_key;
char *root_path;
char *args_json;
char *response;
cbm_daemon_application_worker_t worker;
cbm_thread_t thread;
size_t subscribers;
size_t watcher_waiters;
bool thread_started;
bool thread_done;
bool terminal;
bool successful;
bool cancelled;
bool cancel_requested;
bool supervision_failed;
cbm_daemon_application_job_t *next;
};
/* A watcher-triggered physical job is owned by the exact live sessions that
* currently subscribe to its project/root watch. The callback waiting for the
* job is only a storage waiter; it is deliberately not an ownership
* subscription, so the worker is cancelled when the last matching session
* disconnects even while unrelated daemon sessions remain alive. */
struct cbm_daemon_application_watch_job_subscription {
cbm_daemon_application_session_t *session;
cbm_daemon_application_job_t *job;
cbm_daemon_application_watch_job_subscription_t *next;
};
struct cbm_daemon_application_mutation {
char *project_key;
cbm_project_lock_lease_t *project_lock_lease;
bool releasing;
cbm_daemon_application_mutation_t *next;
};
struct cbm_daemon_application {
cbm_mutex_t mutex;
struct cbm_watcher *watcher;
struct cbm_config *config;
cbm_daemon_application_session_t *sessions;
cbm_daemon_application_watch_t *watches;
cbm_daemon_application_job_t *jobs;
cbm_daemon_application_watch_job_subscription_t *watch_job_subscriptions;
cbm_daemon_application_mutation_t *mutations;
cbm_daemon_application_worker_ops_t worker_ops;
cbm_daemon_application_update_ops_t update_ops;
cbm_project_lock_manager_t *project_locks;
size_t physical_job_limit;
size_t worker_memory_budget_bytes;
size_t active_mutations;
size_t update_owners;
cbm_daemon_application_update_worker_t update_worker;
cbm_thread_t update_thread;
char update_notice[APPLICATION_UPDATE_NOTICE_CAP];
bool update_generation_started;
bool update_cancel_requested;
bool update_thread_started;
bool update_thread_done;
bool update_thread_joining;
bool stopping;
/* See cbm_daemon_application_set_permanent. */
bool permanent;
uint8_t ui_readiness_secret[CBM_SHA256_DIGEST_LEN];
bool ui_readiness_secret_set;
};
static void application_job_unsubscribe_locked(cbm_daemon_application_job_t *job);
static void application_watch_job_unsubscribe_session_locked(
cbm_daemon_application_session_t *session);
static bool application_watch_job_subscribe_late_session_locked(
cbm_daemon_application_session_t *session, cbm_daemon_application_watch_t *watch);
static bool application_unique_recovery_file(char out[APPLICATION_PATH_CAP], const char *kind);
static bool application_update_reap(cbm_daemon_application_t *application, bool wait,
uint32_t timeout_ms);
static void *application_job_thread(void *opaque);
static char *application_auto_index_args(const char *root_path);
static cbm_daemon_application_job_t *application_job_subscribe_locked(
cbm_daemon_application_t *application, const char *project_key, const char *root_path,
const char *args_json, application_job_subscribe_status_t *status_out);
static atomic_bool g_application_fail_next_job_thread_start_for_test = ATOMIC_VAR_INIT(false);
void cbm_daemon_application_fail_next_job_thread_start_for_test(void) {
atomic_store_explicit(&g_application_fail_next_job_thread_start_for_test, true,
memory_order_release);
}
static atomic_bool g_application_hold_job_before_start_for_test = ATOMIC_VAR_INIT(false);
/* Counts completed background-initialize passes (the request-handler tail
* that evaluates auto-index admission). The client can observe its
* initialize RESPONSE before this tail finishes, so a test asserting the
* tail's NEGATIVE outcome ("no job was admitted") needs this positive
* completion signal — a fixed sleep is a lottery in both directions. */
static atomic_int g_application_background_initializes_for_test = ATOMIC_VAR_INIT(0);
int cbm_daemon_application_background_initializes_for_test(void) {
return atomic_load_explicit(&g_application_background_initializes_for_test,
memory_order_acquire);
}
/* Counts iterations of the explicit-index busy-queue wait loop. A test that
* needs "the request is parked behind the physical job limit" waits for a
* DELTA here — the positive signal that queueing (not an error return)
* happened — before releasing the slot. */
static atomic_int g_application_busy_queue_waits_for_test = ATOMIC_VAR_INIT(0);
int cbm_daemon_application_busy_queue_waits_for_test(void) {
return atomic_load_explicit(&g_application_busy_queue_waits_for_test, memory_order_acquire);
}
void cbm_daemon_application_hold_job_before_start_for_test(bool hold) {
atomic_store_explicit(&g_application_hold_job_before_start_for_test, hold,
memory_order_release);
}
static int application_job_thread_create(cbm_thread_t *thread, void *context) {
if (atomic_exchange_explicit(&g_application_fail_next_job_thread_start_for_test, false,
memory_order_acq_rel)) {
return -1;
}
return cbm_thread_create(thread, APPLICATION_JOB_THREAD_STACK, application_job_thread, context);
}
static bool application_request_cancelled_locked(const cbm_daemon_application_session_t *session) {
return session &&
(session->session_cancelled ||
(session->request_active &&
session->active_request_token != CBM_DAEMON_RUNTIME_APPLICATION_TOKEN_INVALID &&
session->request_cancel_token == session->active_request_token));
}
static uint64_t application_deadline_after(uint32_t timeout_ms) {
uint64_t now = cbm_now_ms();
return now > UINT64_MAX - timeout_ms ? UINT64_MAX : now + timeout_ms;
}
static _Noreturn void application_cleanup_force_terminate(const char *component) {
/* In production this module is daemon-owned and the host log sink flushes
* every record synchronously. Continuing would either lose the only retry
* handle or falsely make a project mutation appear released. */
cbm_log_error("daemon.forced_shutdown", "component", component);
(void)fflush(stdout);
(void)fflush(stderr);
#ifdef _WIN32
(void)TerminateProcess(GetCurrentProcess(), EXIT_FAILURE);
abort();
#else
_exit(EXIT_FAILURE);
#endif
}
static void application_project_lock_release_fully(cbm_project_lock_lease_t **lease) {
uint64_t deadline = application_deadline_after(APPLICATION_COORDINATION_CLEANUP_MS);
while (lease && *lease) {
(void)cbm_project_lock_lease_release(lease);
if (!*lease) {
return;
}
if (cbm_now_ms() >= deadline) {
application_cleanup_force_terminate("project_lock_cleanup");
}
cbm_usleep(1000);
}
}
static int application_worker_start_default(void *context, const char *args_json,
size_t memory_budget_bytes, const char *marker_file,
const char *quarantine_file,
cbm_daemon_application_worker_t *worker_out) {
(void)context;
cbm_index_worker_handle_t *worker = NULL;
int result = cbm_index_worker_start(args_json, memory_budget_bytes, false, marker_file,
quarantine_file, &worker);
*worker_out = worker;
return result;
}
static cbm_index_worker_poll_t application_worker_poll_default(
void *context, cbm_daemon_application_worker_t worker,
const cbm_index_worker_result_t **result_out) {
(void)context;
return cbm_index_worker_poll((cbm_index_worker_handle_t *)worker, result_out);
}
static bool application_worker_cancel_default(void *context,
cbm_daemon_application_worker_t worker) {
(void)context;
return cbm_index_worker_request_cancel((cbm_index_worker_handle_t *)worker);
}
static const char *application_worker_log_path_default(void *context,
cbm_daemon_application_worker_t worker) {
(void)context;
return cbm_index_worker_log_path((cbm_index_worker_handle_t *)worker);
}
static void application_worker_destroy_default(void *context,
cbm_daemon_application_worker_t worker) {
(void)context;
cbm_index_worker_destroy((cbm_index_worker_handle_t *)worker);
}
static uint32_t application_get_u32(const uint8_t *bytes) {
return ((uint32_t)bytes[0] << 24) | ((uint32_t)bytes[1] << 16) | ((uint32_t)bytes[2] << 8) |
(uint32_t)bytes[3];
}
static void application_put_u32(uint8_t *bytes, uint32_t value) {
bytes[0] = (uint8_t)(value >> 24);
bytes[1] = (uint8_t)(value >> 16);
bytes[2] = (uint8_t)(value >> 8);
bytes[3] = (uint8_t)value;
}
static char *application_text_copy(const uint8_t *bytes, uint32_t length) {
if (!bytes || length == 0 || memchr(bytes, '\0', length) != NULL) {
return NULL;
}
char *copy = malloc((size_t)length + 1U);
if (copy) {
memcpy(copy, bytes, length);
copy[length] = '\0';
}
return copy;
}
static bool application_regular_db_exists(const char *project) {
const char *cache = cbm_resolve_cache_dir();
if (!cache || !project || !project[0]) {
return false;
}
char path[APPLICATION_PATH_CAP];
int written = snprintf(path, sizeof(path), "%s/%s.db", cache, project);
if (written <= 0 || (size_t)written >= sizeof(path)) {
return false;
}
struct stat status;
return stat(path, &status) == 0 && S_ISREG(status.st_mode);
}
static cbm_daemon_application_watch_t *application_find_watch_locked(
cbm_daemon_application_t *application, const char *project) {
for (cbm_daemon_application_watch_t *watch = application->watches; watch; watch = watch->next) {
if (strcmp(watch->project, project) == 0) {
return watch;
}
}
return NULL;
}
static void application_remove_watch_entry_locked(cbm_daemon_application_t *application,
cbm_daemon_application_watch_t *watch,
bool unregister_physical_watch) {
cbm_daemon_application_watch_t **cursor = &application->watches;
while (*cursor && *cursor != watch) {
cursor = &(*cursor)->next;
}
if (*cursor != watch) {
return;
}
*cursor = watch->next;
for (cbm_daemon_application_session_t *session = application->sessions; session;
session = session->next) {
if (session->watch == watch) {
application_watch_job_unsubscribe_session_locked(session);
session->watch = NULL;
}
}
if (unregister_physical_watch && application->watcher) {
cbm_watcher_unwatch(application->watcher, watch->project);
}
free(watch->project);
free(watch->root);
free(watch);
}
static void application_remove_watch_locked(cbm_daemon_application_t *application,
cbm_daemon_application_watch_t *watch) {
application_remove_watch_entry_locked(application, watch, true);
}
static void application_release_session_watch_locked(cbm_daemon_application_session_t *session) {
cbm_daemon_application_watch_t *watch = session->watch;
if (!watch) {
return;
}
application_watch_job_unsubscribe_session_locked(session);
session->watch = NULL;
if (watch->subscribers > 0) {
watch->subscribers--;
}
if (watch->subscribers == 0) {
application_remove_watch_locked(session->application, watch);
}
}
/* Caller holds application->mutex. */
static void application_refresh_watch_locked(cbm_daemon_application_session_t *session) {
cbm_daemon_application_t *application = session->application;
if (!application->watcher || !session->context_set ||
session->tool_profile != CBM_MCP_TOOL_PROFILE_ALL || session->hook_event ||
session->hook_dialect || session->auto_index_subscribed) {
return;
}
const char *project = cbm_mcp_server_session_project(session->mcp);
const char *root = cbm_mcp_server_session_root(session->mcp);
if (!project || !project[0] || !root || !root[0]) {
return;
}
bool enabled = !application->config ||
cbm_config_get_bool(application->config, CBM_CONFIG_AUTO_WATCH, true);
bool db_exists = application_regular_db_exists(project);
/* Disconnect cancellation is the logical ownership boundary. An
* in-flight request may reach this refresh after cancel returned but
* before runtime can join it and call session_close; it must never
* recreate that session's watch. */
if (application->stopping || application_request_cancelled_locked(session)) {
return;
}
cbm_daemon_application_watch_t *watch = application_find_watch_locked(application, project);
if (!enabled || !db_exists) {
/* A delete/config transition is global for this project. Remove the
* physical watch and clear every logical subscriber in one step. */
if (watch) {
application_remove_watch_locked(application, watch);
}
return;
}
if (session->watch) {
return;
}
if (watch) {
if (strcmp(watch->root, root) == 0) {
if (!application_watch_job_subscribe_late_session_locked(session, watch)) {
cbm_log_warn("daemon.watch.late_owner_allocation_failed", "project", project,
"action", "retry");
return;
}
watch->subscribers++;
session->watch = watch;
} else {
cbm_log_warn("daemon.watch.project_collision", "project", project, "existing_root",
watch->root, "requested_root", root);
}
return;
}
watch = calloc(1, sizeof(*watch));
if (watch) {
watch->project = strdup(project);
watch->root = strdup(root);
}
if (!watch || !watch->project || !watch->root) {
if (watch) {
free(watch->project);
free(watch->root);
free(watch);
}
return;
}
/* Physical registration is the commit point. Never publish a logical
* subscription that the shared watcher failed to install. */
if (!cbm_watcher_watch(application->watcher, project, root)) {
cbm_log_warn("daemon.watch.registration_failed", "project", project, "action", "retry");
free(watch->project);
free(watch->root);
free(watch);
return;
}
watch->subscribers = 1;
watch->next = application->watches;
application->watches = watch;
session->watch = watch;
}
static void application_refresh_watch(cbm_daemon_application_session_t *session) {
if (!session || !session->application) {
return;
}
cbm_mutex_lock(&session->application->mutex);
application_refresh_watch_locked(session);
cbm_mutex_unlock(&session->application->mutex);
}
static void application_job_free(cbm_daemon_application_job_t *job) {
if (!job) {
return;
}
free(job->project_key);
free(job->root_path);
free(job->args_json);
free(job->response);
free(job);
}
/* Reap completed job threads only after every logical demand subscription and
* watcher callback storage waiter has released the job. Exactly one caller
* removes a job under the mutex. */
static void application_jobs_reap_completed(cbm_daemon_application_t *application) {
for (;;) {
cbm_daemon_application_job_t *reap = NULL;
cbm_mutex_lock(&application->mutex);
cbm_daemon_application_job_t **cursor = &application->jobs;
while (*cursor) {
if ((*cursor)->thread_done && (*cursor)->subscribers == 0 &&
(*cursor)->watcher_waiters == 0) {
reap = *cursor;
*cursor = reap->next;
reap->next = NULL;
break;
}
cursor = &(*cursor)->next;
}
cbm_mutex_unlock(&application->mutex);
if (!reap) {
return;
}
if (reap->thread_started) {
(void)cbm_thread_join(&reap->thread);
}
application_job_free(reap);
}
}
typedef enum {
APPLICATION_ATTEMPT_TERMINAL = 0,
APPLICATION_ATTEMPT_START_FAILED,
APPLICATION_ATTEMPT_CANCELLED,
} application_attempt_status_t;
typedef struct {
cbm_index_worker_result_t result;
bool has_result;
char log_path[APPLICATION_PATH_CAP];
} application_attempt_t;
static atomic_flag g_application_tmp_lock = ATOMIC_FLAG_INIT;
static void application_tmp_lock(void) {
while (atomic_flag_test_and_set_explicit(&g_application_tmp_lock, memory_order_acquire)) {
cbm_usleep(1000);
}
}
static void application_tmp_unlock(void) {
atomic_flag_clear_explicit(&g_application_tmp_lock, memory_order_release);
}
static bool application_cache_dir(char out[APPLICATION_PATH_CAP]) {
char configured[APPLICATION_PATH_CAP] = {0};
if (cbm_safe_getenv("CBM_CACHE_DIR", configured, sizeof(configured), NULL) && configured[0]) {
int written = snprintf(out, APPLICATION_PATH_CAP, "%s", configured);
if (written <= 0 || written >= APPLICATION_PATH_CAP) {
return false;
}
cbm_normalize_path_sep(out);
return true;
}
char home[APPLICATION_PATH_CAP] = {0};
if (!cbm_safe_getenv("HOME", home, sizeof(home), NULL) || !home[0]) {
(void)cbm_safe_getenv("USERPROFILE", home, sizeof(home), NULL);
}
if (!home[0]) {
return false;
}
int written = snprintf(out, APPLICATION_PATH_CAP, "%s/.cache/codebase-memory-mcp", home);
if (written <= 0 || written >= APPLICATION_PATH_CAP) {
return false;
}
cbm_normalize_path_sep(out);
return true;
}
static bool application_unique_recovery_file(char out[APPLICATION_PATH_CAP], const char *kind) {
char cache[APPLICATION_PATH_CAP] = {0};
char directory[APPLICATION_PATH_CAP] = {0};
int written;
if (application_cache_dir(cache)) {
written = snprintf(directory, sizeof(directory), "%s/logs", cache);
if (written <= 0 || written >= (int)sizeof(directory) || !cbm_mkdir_p(directory, 0700)) {
return false;
}
} else {
written = snprintf(directory, sizeof(directory), "%s", cbm_tmpdir());
if (written <= 0 || written >= (int)sizeof(directory)) {
return false;
}
}
written = snprintf(out, APPLICATION_PATH_CAP, "%s/.daemon-index-%s-XXXXXX", directory, kind);
if (written <= 0 || written >= APPLICATION_PATH_CAP) {
out[0] = '\0';
return false;
}
application_tmp_lock();
int descriptor = cbm_mkstemp(out);
application_tmp_unlock();
if (descriptor < 0) {
out[0] = '\0';
return false;
}
(void)application_close(descriptor);
return true;
}
static bool application_recovery_files_create(char marker_path[APPLICATION_PATH_CAP],
char quarantine_path[APPLICATION_PATH_CAP]) {
if (!application_unique_recovery_file(marker_path, "marker")) {
return false;
}
if (!application_unique_recovery_file(quarantine_path, "quarantine")) {
(void)cbm_unlink(marker_path);
marker_path[0] = '\0';
return false;
}
return true;
}
static void application_recovery_files_remove(const char *marker_path,
const char *quarantine_path) {
if (marker_path && marker_path[0]) {
(void)cbm_unlink(marker_path);
}
if (quarantine_path && quarantine_path[0]) {
(void)cbm_unlink(quarantine_path);
}
}
static bool application_truncate_file(const char *path) {
FILE *file = cbm_fopen(path, "wb");
return file && fclose(file) == 0;
}
static bool application_job_cancel_requested(cbm_daemon_application_job_t *job);
static char **application_read_suspects(cbm_daemon_application_job_t *job, const char *path,
int *count_out, bool *cancelled_out) {
*count_out = 0;
*cancelled_out = false;
int64_t marker_size = cbm_file_size(path);
if (marker_size < 0 || marker_size > APPLICATION_MARKER_MAX_BYTES) {
return NULL;
}
FILE *file = cbm_fopen(path, "rb");
if (!file) {
return NULL;
}
char **open_paths = NULL;
int open_count = 0;
int open_capacity = 0;
bool allocation_failed = false;
size_t lines_read = 0;
char line[APPLICATION_PATH_CAP];
while (fgets(line, sizeof(line), file)) {
if ((lines_read++ & 255U) == 0U && application_job_cancel_requested(job)) {
*cancelled_out = true;
allocation_failed = true;
break;
}
size_t length = strlen(line);
if (length == 0 || line[length - 1] != '\n') {
break;
}
line[--length] = '\0';
if (length > 0 && line[length - 1] == '\r') {
line[--length] = '\0';
}
if (length < 3 || (line[0] != 'S' && line[0] != 'D') || line[1] != ' ') {
continue;
}
const char *relative = line + 2;
if (line[0] == 'S') {
if (open_count >= APPLICATION_MAX_SUSPECTS) {
allocation_failed = true;
break;
}
bool already_open = false;
for (int i = 0; i < open_count && !already_open; i++) {
already_open = strcmp(open_paths[i], relative) == 0;
}
if (already_open) {
continue;
}
if (open_count == open_capacity) {
int next_capacity = open_capacity ? open_capacity * 2 : 16;
char **next = realloc(open_paths, (size_t)next_capacity * sizeof(*next));
if (!next) {
allocation_failed = true;
break;
}
open_paths = next;
open_capacity = next_capacity;
}
char *copy = cbm_strdup(relative);
if (!copy) {
allocation_failed = true;
break;
}
open_paths[open_count++] = copy;
} else {
for (int i = 0; i < open_count; i++) {
if (strcmp(open_paths[i], relative) == 0) {
free(open_paths[i]);
memmove(&open_paths[i], &open_paths[i + 1],
(size_t)(open_count - i - 1) * sizeof(*open_paths));
open_count--;
break;
}
}
}
}
(void)fclose(file);
if (allocation_failed) {
for (int i = 0; i < open_count; i++) {
free(open_paths[i]);
}
free(open_paths);
return NULL;
}
if (open_count == 0) {
free(open_paths);
return NULL;
}
*count_out = open_count;
return open_paths;
}
static void application_free_suspects(char **suspects, int count) {
if (!suspects) {
return;
}
for (int i = 0; i < count; i++) {
free(suspects[i]);
}
free(suspects);
}
static bool application_suspect_contains(char **suspects, int count, const char *relative) {
for (int i = 0; i < count; i++) {
if (strcmp(suspects[i], relative) == 0) {
return true;
}
}
return false;
}
static bool application_append_quarantine(const char *path, const char *relative,
const char *phase) {
if (!relative || !relative[0] || strpbrk(relative, "\r\n\t")) {
return false;
}
FILE *file = cbm_fopen(path, "ab");
if (!file) {
return false;
}
bool written = fprintf(file, "%s\t%s\n", relative, phase) >= 0;
return fclose(file) == 0 && written;
}
static int application_max_restarts(void) {
char value[32] = {0};
if (!cbm_safe_getenv("CBM_INDEX_MAX_RESTARTS", value, sizeof(value), NULL) || !value[0]) {
return APPLICATION_DEFAULT_MAX_RESTARTS;
}
char *end = NULL;
long parsed = strtol(value, &end, 10);
return end && *end == '\0' && parsed > 0 && parsed <= INT_MAX
? (int)parsed
: APPLICATION_DEFAULT_MAX_RESTARTS;
}
static void application_attempt_init(application_attempt_t *attempt) {
memset(attempt, 0, sizeof(*attempt));
attempt->result.outcome = CBM_PROC_SPAWN_FAILED;
attempt->result.exit_code = -1;
}
static void application_attempt_free(application_attempt_t *attempt) {
free(attempt->result.response);
attempt->result.response = NULL;
}
static bool application_job_cancel_requested(cbm_daemon_application_job_t *job) {
cbm_daemon_application_t *application = job->application;
cbm_mutex_lock(&application->mutex);
bool cancelled = job->cancel_requested || application->stopping;
cbm_mutex_unlock(&application->mutex);
return cancelled;
}
static bool application_project_keys_conflict(const char *left, const char *right) {
return left && right &&
(strcmp(left, right) == 0 || strcmp(left, "*") == 0 || strcmp(right, "*") == 0);
}
static bool application_mutation_conflicts_locked(cbm_daemon_application_t *application,
const char *project_key) {
for (cbm_daemon_application_mutation_t *mutation = application->mutations; mutation;
mutation = mutation->next) {
if (application_project_keys_conflict(mutation->project_key, project_key)) {
return true;
}
}
return false;
}
static bool application_job_reserves_project_locked(cbm_daemon_application_t *application,
const char *project_key) {
for (cbm_daemon_application_job_t *job = application->jobs; job; job = job->next) {
if (!job->terminal && application_project_keys_conflict(job->project_key, project_key)) {
return true;
}
}
return false;
}
static bool application_mutation_begin_internal(cbm_daemon_application_t *application,
cbm_daemon_application_session_t *session,
const char *project_key, bool wait) {
if (!application || !project_key || !project_key[0]) {
return false;
}
cbm_daemon_application_mutation_t *reserved = NULL;
for (;;) {
cbm_mutex_lock(&application->mutex);
bool cancelled =
application->stopping || (session && application_request_cancelled_locked(session));
bool busy = application_mutation_conflicts_locked(application, project_key) ||
application_job_reserves_project_locked(application, project_key);
if (!cancelled && !busy) {
cbm_daemon_application_mutation_t *mutation = calloc(1, sizeof(*mutation));
if (mutation) {
mutation->project_key = cbm_strdup(project_key);
}
if (!mutation || !mutation->project_key) {
if (mutation) {
free(mutation->project_key);
free(mutation);
}
cbm_mutex_unlock(&application->mutex);
return false;
}
mutation->next = application->mutations;
application->mutations = mutation;
application->active_mutations++;
cbm_mutex_unlock(&application->mutex);
reserved = mutation;
break;
}
cbm_mutex_unlock(&application->mutex);
if (cancelled || !wait) {
return false;
}
cbm_usleep(APPLICATION_JOB_POLL_US);
}
if (!application->project_locks) {
return true;
}
for (;;) {
uint64_t now = cbm_now_ms();
uint64_t deadline = now > UINT64_MAX - 100U ? UINT64_MAX : now + 100U;
cbm_project_lock_lease_t *lease = NULL;
cbm_private_file_lock_status_t status =
wait ? cbm_project_lock_acquire(application->project_locks, project_key, deadline, NULL,
&lease)
: cbm_project_lock_try_acquire(application->project_locks, project_key, &lease);
if (status == CBM_PRIVATE_FILE_LOCK_OK && lease) {
cbm_mutex_lock(&application->mutex);
bool cancelled =
application->stopping || (session && application_request_cancelled_locked(session));
cbm_mutex_unlock(&application->mutex);
if (cancelled) {
application_project_lock_release_fully(&lease);
status = CBM_PRIVATE_FILE_LOCK_BUSY;
} else {
reserved->project_lock_lease = lease;
return true;
}
}
application_project_lock_release_fully(&lease);
cbm_mutex_lock(&application->mutex);
bool cancelled =
application->stopping || (session && application_request_cancelled_locked(session));
if (status != CBM_PRIVATE_FILE_LOCK_BUSY || cancelled || !wait) {
cbm_daemon_application_mutation_t **cursor = &application->mutations;
while (*cursor && *cursor != reserved) {
cursor = &(*cursor)->next;
}
if (*cursor == reserved) {
*cursor = reserved->next;
if (application->active_mutations > 0) {
application->active_mutations--;
}
}
cbm_mutex_unlock(&application->mutex);
free(reserved->project_key);
free(reserved);
if (status != CBM_PRIVATE_FILE_LOCK_BUSY) {
cbm_log_error("daemon.project_lock_failed", "project", project_key, "action",
"refuse_mutation");
}
return false;
}
cbm_mutex_unlock(&application->mutex);
}
}
bool cbm_daemon_application_project_mutation_try_begin(cbm_daemon_application_t *application,
const char *project) {
return application_mutation_begin_internal(application, NULL, project, false);
}
void cbm_daemon_application_project_mutation_end(cbm_daemon_application_t *application,
const char *project) {
if (!application || !project || !project[0]) {
return;
}
cbm_mutex_lock(&application->mutex);
cbm_daemon_application_mutation_t *mutation = application->mutations;
while (mutation && strcmp(mutation->project_key, project) != 0) {
mutation = mutation->next;
}
if (!mutation || mutation->releasing) {
cbm_mutex_unlock(&application->mutex);
return;
}
mutation->releasing = true;
cbm_mutex_unlock(&application->mutex);
/* Keep the logical reservation visible until the native lease is gone.
* Otherwise another in-daemon operation can observe an apparently free
* project and enter the OS-lock wait during the release handoff. */
application_project_lock_release_fully(&mutation->project_lock_lease);
cbm_mutex_lock(&application->mutex);
cbm_daemon_application_mutation_t **cursor = &application->mutations;
while (*cursor && *cursor != mutation) {
cursor = &(*cursor)->next;
}
if (*cursor == mutation) {
*cursor = mutation->next;
if (application->active_mutations > 0) {
application->active_mutations--;
}
}
cbm_mutex_unlock(&application->mutex);
free(mutation->project_key);
free(mutation);
}
static bool application_watcher_mutation_begin(void *context, const char *project) {
return cbm_daemon_application_project_mutation_try_begin(context, project);
}
static void application_watcher_mutation_end(void *context, const char *project) {
cbm_daemon_application_project_mutation_end(context, project);
}
static void application_watcher_project_pruned(void *context, const char *project) {
cbm_daemon_application_t *application = context;
if (!application || !project) {
return;
}