@geastack/core 0.1.44 → 0.1.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/gea_app_entry.cpp CHANGED
@@ -7,6 +7,7 @@
7
7
  #include "gea/embedded.h"
8
8
  #include "host/backends.h"
9
9
  #include "host/worker.h"
10
+ #include "ui/node_features.h"
10
11
  #include "ui/style.h"
11
12
  #include "ui/tree_internal.h" // Tree::mount for the post-mount clean repaint in init()
12
13
 
@@ -29,8 +30,17 @@ namespace gea::framework::app::generated {
29
30
  void drainMicrotasks();
30
31
  } // namespace gea::framework::app::generated
31
32
 
32
- extern "C" void gea_cycle_collection_defer_begin() __attribute__((weak));
33
- extern "C" void gea_cycle_collection_defer_end() __attribute__((weak));
33
+ // Optional hooks a generated program defines weakly. A COFF linker cannot pair
34
+ // a weak reference with a weak definition (each names its own default), so a
35
+ // target that links a default for every such hook (lld-link /alternatename)
36
+ // sets GEA_LINKED_HOOK_DEFAULTS and the references become ordinary ones.
37
+ #if defined(GEA_LINKED_HOOK_DEFAULTS) && GEA_LINKED_HOOK_DEFAULTS
38
+ #define GEA_PROGRAM_HOOK
39
+ #else
40
+ #define GEA_PROGRAM_HOOK __attribute__((weak))
41
+ #endif
42
+ extern "C" void gea_cycle_collection_defer_begin() GEA_PROGRAM_HOOK;
43
+ extern "C" void gea_cycle_collection_defer_end() GEA_PROGRAM_HOOK;
34
44
  extern "C" bool gea_embedded_assets_prepare() __attribute__((weak));
35
45
 
36
46
  namespace gea::framework::app {
@@ -316,10 +326,12 @@ void Application::frame(int timestampMs)
316
326
  #else
317
327
  gea::host::workers::Context::runMainPending();
318
328
  #endif
329
+ #if !defined(GEA_UI_VIDEO_NODES) || GEA_UI_VIDEO_NODES
319
330
  applicationFramePhaseSet(ApplicationFramePhase::VideoPresentation);
320
331
  startUs = phaseClockUs();
321
332
  gea::host::video::presentFrames();
322
333
  recordFramePhase(ApplicationFramePhase::VideoPresentation, phaseClockUs() - startUs);
334
+ #endif
323
335
  #if !defined(GEA_EMBEDDED_NETWORK_SERVICES_DISABLED) || !GEA_EMBEDDED_NETWORK_SERVICES_DISABLED
324
336
  applicationFramePhaseSet(ApplicationFramePhase::HttpRequests);
325
337
  startUs = phaseClockUs();
@@ -1,7 +1,23 @@
1
1
  #pragma once
2
+ #include <algorithm>
3
+ #include <atomic>
4
+ #include <cstddef>
5
+ #include <cstdint>
2
6
  #include <memory>
3
7
  #include <mutex>
4
- #include <unordered_map>
8
+ #include <utility>
9
+ #include <vector>
10
+ #if defined(ESP_PLATFORM)
11
+ #include "freertos/FreeRTOS.h"
12
+ #endif
13
+
14
+ // Node creation and removal are cold; keeping them out of line also keeps
15
+ // their growth path from widening callers' value ranges.
16
+ #if defined(__GNUC__)
17
+ #define GEA_IDENTITY_COLD __attribute__((noinline, cold))
18
+ #else
19
+ #define GEA_IDENTITY_COLD
20
+ #endif
5
21
 
6
22
  namespace gea::framework::identity {
7
23
  struct Token {};
@@ -24,42 +40,134 @@ public:
24
40
  private:
25
41
  mutable Owner owner_;
26
42
  };
43
+
27
44
  // Tree ids are reused. Registry entries cover only the current allocation;
28
45
  // the tree retains live-node tokens until removal/clear. Retained handles
29
46
  // own retired tokens independently; weak collections never extend that life.
30
47
  struct NodeRegistry {
48
+ #if defined(ESP_PLATFORM)
49
+ // Every node handle reads this. A FreeRTOS mutex costs a take and a give
50
+ // with priority inheritance, so ESP-IDF guards the few instructions with a
51
+ // spinlock critical section. Nothing allocates or frees inside it.
52
+ portMUX_TYPE lock = portMUX_INITIALIZER_UNLOCKED;
53
+ void enter() { portENTER_CRITICAL(&lock); }
54
+ void exit() { portEXIT_CRITICAL(&lock); }
55
+ #else
31
56
  std::mutex mutex;
32
- std::unordered_map<int, Owner> nodes;
57
+ void enter() { mutex.lock(); }
58
+ void exit() { mutex.unlock(); }
59
+ #endif
60
+ // Indexed by tree id; ids are small and dense. Changed under the lock.
61
+ std::vector<Owner> nodes;
62
+ // The address of each live token, published for lock-free `current`
63
+ // checks. A handle's own owner keeps its token alive, so an equal address
64
+ // is the same allocation. Pages are never freed, so readers never race a
65
+ // reallocation; ids beyond the directory fall back to the locked path.
66
+ static constexpr std::size_t kPageSize = 64;
67
+ static constexpr std::size_t kPages = 64;
68
+ using Page = std::atomic<const Token *>;
69
+ std::atomic<Page *> pages[kPages] = {};
70
+ Page *page(std::size_t index) const {
71
+ return index / kPageSize < kPages ? pages[index / kPageSize].load(std::memory_order_acquire) : nullptr;
72
+ }
73
+ // Allocates outside any lock; a racing writer's spare page is discarded.
74
+ void ensurePage(std::size_t index) {
75
+ if (index / kPageSize >= kPages || page(index)) return;
76
+ Page *fresh = new Page[kPageSize];
77
+ for (std::size_t i = 0; i < kPageSize; ++i) fresh[i].store(nullptr, std::memory_order_relaxed);
78
+ Page *expected = nullptr;
79
+ if (!pages[index / kPageSize].compare_exchange_strong(expected, fresh, std::memory_order_acq_rel))
80
+ delete[] fresh;
81
+ }
82
+ // Under the lock.
83
+ void publish(std::size_t index, const Token *token) {
84
+ if (Page *slots = page(index)) slots[index % kPageSize].store(token, std::memory_order_release);
85
+ }
33
86
  };
34
- inline NodeRegistry &registry() { static NodeRegistry value; return value; }
87
+ class RegistryLock {
88
+ public:
89
+ explicit RegistryLock(NodeRegistry &registry) : registry_(registry) { registry_.enter(); }
90
+ ~RegistryLock() { registry_.exit(); }
91
+ RegistryLock(const RegistryLock &) = delete;
92
+ RegistryLock &operator=(const RegistryLock &) = delete;
93
+ private:
94
+ NodeRegistry &registry_;
95
+ };
96
+ inline NodeRegistry &registry() {
97
+ // Without hardware atomics (ESP32-S3) a guarded function-local static takes
98
+ // an RTOS mutex on every access; later calls take this plain load.
99
+ static std::atomic<NodeRegistry *> ready{nullptr};
100
+ if (auto *value = ready.load(std::memory_order_acquire)) return *value;
101
+ static NodeRegistry value;
102
+ ready.store(&value, std::memory_order_release);
103
+ return value;
104
+ }
35
105
  inline Owner node(int id) {
36
106
  if (id < 0) return {};
107
+ const auto index = static_cast<std::size_t>(id);
37
108
  auto &r = registry();
38
- std::lock_guard<std::mutex> lock(r.mutex);
39
- const auto found = r.nodes.find(id);
40
- return found == r.nodes.end() ? Owner{} : found->second;
109
+ RegistryLock lock(r);
110
+ return index < r.nodes.size() ? r.nodes[index] : Owner{};
41
111
  }
42
- inline bool current(int id, const Owner &owner) {
43
- if (id < 0 || !owner) return false;
112
+ // `token` must be kept alive by the caller (a handle's owner), so an equal
113
+ // address is the same allocation.
114
+ inline bool current(int id, const Token *token) {
115
+ if (id < 0 || !token) return false;
116
+ const auto index = static_cast<std::size_t>(id);
44
117
  auto &r = registry();
45
- std::lock_guard<std::mutex> lock(r.mutex);
46
- const auto found = r.nodes.find(id);
47
- return found != r.nodes.end() && found->second == owner;
118
+ // The slot is only compared, never dereferenced, so it needs no barrier;
119
+ // the page itself is acquired because its slots are read.
120
+ if (const auto *slots = r.page(index))
121
+ return slots[index % NodeRegistry::kPageSize].load(std::memory_order_relaxed) == token;
122
+ RegistryLock lock(r);
123
+ return index < r.nodes.size() && r.nodes[index].get() == token;
48
124
  }
49
- inline void activate(int id) {
125
+ inline bool current(int id, const Owner &owner) { return current(id, owner.get()); }
126
+ GEA_IDENTITY_COLD inline void activate(int id) {
50
127
  if (id < 0) return;
128
+ const auto index = static_cast<std::size_t>(id);
129
+ // Declared before the lock: the replaced token and any outgrown storage
130
+ // are released after it.
131
+ Owner token = std::make_shared<Token>();
132
+ const Token *published = token.get();
133
+ std::vector<Owner> spare;
51
134
  auto &r = registry();
52
- std::lock_guard<std::mutex> lock(r.mutex);
53
- r.nodes[id] = std::make_shared<Token>();
135
+ r.ensurePage(index);
136
+ for (;;) {
137
+ std::size_t size;
138
+ {
139
+ RegistryLock lock(r);
140
+ if (index < r.nodes.size()) {
141
+ std::swap(r.nodes[index], token);
142
+ r.publish(index, published);
143
+ return;
144
+ }
145
+ if (index < spare.size() && r.nodes.size() <= spare.size()) {
146
+ std::swap_ranges(r.nodes.begin(), r.nodes.end(), spare.begin());
147
+ r.nodes.swap(spare);
148
+ std::swap(r.nodes[index], token);
149
+ r.publish(index, published);
150
+ return;
151
+ }
152
+ size = r.nodes.size();
153
+ }
154
+ spare.assign(std::max(index + 1, size * 2), Owner{});
155
+ }
54
156
  }
55
- inline void retire(int id) {
157
+ GEA_IDENTITY_COLD inline void retire(int id) {
158
+ if (id < 0) return;
159
+ const auto index = static_cast<std::size_t>(id);
160
+ Owner released;
56
161
  auto &r = registry();
57
- std::lock_guard<std::mutex> lock(r.mutex);
58
- r.nodes.erase(id);
162
+ RegistryLock lock(r);
163
+ if (index < r.nodes.size()) std::swap(r.nodes[index], released);
164
+ r.publish(index, nullptr);
59
165
  }
60
- inline void clear() {
166
+ GEA_IDENTITY_COLD inline void clear() {
167
+ std::vector<Owner> released;
61
168
  auto &r = registry();
62
- std::lock_guard<std::mutex> lock(r.mutex);
63
- r.nodes.clear();
169
+ RegistryLock lock(r);
170
+ for (std::size_t index = 0; index < r.nodes.size(); ++index) r.publish(index, nullptr);
171
+ released.swap(r.nodes);
64
172
  }
65
173
  } // namespace gea::framework::identity
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/core",
3
- "version": "0.1.44",
3
+ "version": "0.1.46",
4
4
  "description": "GeaStack app API, reactivity headers, runtime sources, and type declarations.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "@geajs/core": "1.5.1",
67
67
  "@geajs/vite-plugin": "1.5.0",
68
68
  "@geastack/compiler": "^1.0.29",
69
- "@geastack/geatsc-plugin-gea": "0.1.24",
69
+ "@geastack/geatsc-plugin-gea": "0.1.25",
70
70
  "opentype.js": "^2.0.0",
71
71
  "vite": "^8.0.0"
72
72
  },
@@ -110,6 +110,12 @@ function readAllOptions(name) {
110
110
  return values.filter(Boolean)
111
111
  }
112
112
 
113
+ // The app's own Vite config: any of the names Vite itself looks for.
114
+ function appViteConfig(dir) {
115
+ const names = ['vite.config.ts', 'vite.config.mts', 'vite.config.mjs', 'vite.config.js']
116
+ return names.map((name) => path.join(dir, name)).find((file) => fs.existsSync(file)) ?? path.join(dir, names[0])
117
+ }
118
+
113
119
  function fail(message) {
114
120
  process.stderr.write(`${message}\n`)
115
121
  process.exit(1)
@@ -4479,7 +4485,7 @@ const moduleGraphOutDir = moduleGraphOutOption
4479
4485
  : ''
4480
4486
  let viteConfig = geaEmbeddedCompat
4481
4487
  ? path.join(outDir, 'gea-embedded-compat.vite.config.mjs')
4482
- : path.resolve(readOption('--vite-config') ?? path.join(appDir, 'vite.config.ts'))
4488
+ : path.resolve(readOption('--vite-config') ?? appViteConfig(appDir))
4483
4489
  const appleNativePluginSpecifier = path.resolve(readOption('--geatsc-apple-native-plugin') ?? tryResolve('@geastack/geatsc-plugin-apple-native'))
4484
4490
 
4485
4491
  if (!geaEmbeddedCompat && !fs.existsSync(viteConfig)) fail(`missing Vite config: ${viteConfig}`)
@@ -4675,6 +4681,15 @@ const geatscArgs = [
4675
4681
  `gea.native-signature-host-root=${process.env.GEA_HOST_DIR || path.resolve(coreRoot, '..', 'host')}`,
4676
4682
  ]
4677
4683
  if (!moduleGraphCompile) geatscArgs.push('--target', 'cpp')
4684
+ // --project <tsconfig.json>: the TypeScript project the program means. Without
4685
+ // it the compiler reads modules under the project nearest its input, which for
4686
+ // an app whose sources live outside its package can be another package's
4687
+ // (resolving a type-only import to a different copy of a library).
4688
+ const projectOption = readOption('--project')
4689
+ if (projectOption) {
4690
+ if (!fs.existsSync(projectOption)) fail(`--project names a missing TypeScript project: ${projectOption}`)
4691
+ geatscArgs.push('--project', path.resolve(projectOption))
4692
+ }
4678
4693
  if (moduleGraphCompile) {
4679
4694
  geatscArgs.push('--entry', stagedEntryFile ?? path.join(appDir, entry), '--module-graph-stage', 'hybrid')
4680
4695
  }
@@ -4704,16 +4719,26 @@ geatscArgs.push('--plugin-option', `gea.store-relowering=${compilerSettings.stor
4704
4719
  if (hasFlag('--gea-ir-backend') || hasFlag('--gea-replace-renderers')) {
4705
4720
  geatscArgs.push('--plugin-option', 'gea.replace-renderers=true')
4706
4721
  }
4707
- // The whole-program analysis of a three.js app (a 284-module graph)
4708
- // peaks well above node's default heap cap: on 2026-09-14 this exact spawn
4709
- // died with `Ineffective mark-compacts near heap limit` after five minutes,
4710
- // and the build reported "C++ generation failed". The compiler's own
4711
- // measurement scripts are always run with this
4712
- // limit; the build has to state the same one, not depend on the caller's
4713
- // NODE_OPTIONS.
4722
+ // The whole-program analysis of a large app peaks above node's default heap
4723
+ // cap, so the build states its own limit rather than depending on the caller's
4724
+ // NODE_OPTIONS. 4 GiB leaves several times the measured peak (a 48K-line app
4725
+ // compiles in under 1 GiB of live heap) while stopping V8 from growing the heap
4726
+ // freely: under a 32 GiB cap the same compile held ~1.8 GB resident, mostly
4727
+ // uncollected garbage.
4728
+ // GEA_GEATSC_MAX_OLD_SPACE_SIZE (MiB) lowers or raises that limit for a
4729
+ // machine with less memory to spare; a heap the analysis outgrows then fails
4730
+ // the build instead of exhausting the machine.
4714
4731
  // Native interface call graphs can exceed V8's default ~1 MiB stack during
4715
4732
  // closure analysis; keep the compiler stack below the host's 8 MiB limit.
4716
- run('node', ['--stack_size=8192', '--max-old-space-size=32768', ...geatscArgs])
4733
+ const geatscHeapMiB = (() => {
4734
+ const stated = process.env.GEA_GEATSC_MAX_OLD_SPACE_SIZE
4735
+ if (stated === undefined || stated === '') return 4096
4736
+ const value = Number(stated)
4737
+ if (!Number.isInteger(value) || value < 512) fail(`GEA_GEATSC_MAX_OLD_SPACE_SIZE must be a whole number of MiB (at least 512): ${stated}`)
4738
+ return value
4739
+ })()
4740
+ const geatscNodeArgs = ['--stack_size=8192', `--max-old-space-size=${geatscHeapMiB}`]
4741
+ run('node', [...geatscNodeArgs, ...geatscArgs])
4717
4742
 
4718
4743
  if (nativeModules.size) {
4719
4744
  const nativeSources = []
@@ -4736,7 +4761,7 @@ if (nativeModules.size) {
4736
4761
  ]
4737
4762
  if (cppBoard) moduleArgs.push('--cpp-board', cppBoard)
4738
4763
  if (cxxStandard) moduleArgs.push('--cxx-standard', cxxStandard)
4739
- run('node', ['--stack_size=8192', '--max-old-space-size=32768', ...moduleArgs])
4764
+ run('node', [...geatscNodeArgs, ...moduleArgs])
4740
4765
  const list = fs.readFileSync(path.join(moduleOut, 'geatsc-sources.txt'), 'utf8').split(/\r?\n/).filter(Boolean)
4741
4766
  nativeSources.push(...list.filter((source) => path.basename(source) !== 'gea_runtime_builtins.cpp'))
4742
4767
  }
@@ -91,7 +91,10 @@ export function geaThreeModuleAliases(options = {}) {
91
91
  }
92
92
 
93
93
  export function geaModuleGraphPlugins(options = {}) {
94
- const outDir = options.outDir || process.env.GEA_VITE_MODULE_GRAPH_OUT || ''
94
+ // A build driver (build-gea-vite-geatsc.mjs) states where it reads the graph
95
+ // through GEA_VITE_MODULE_GRAPH_OUT; that wins over the location an app's own
96
+ // Vite config names for its standalone runs.
97
+ const outDir = process.env.GEA_VITE_MODULE_GRAPH_OUT || options.outDir || ''
95
98
  if (!outDir) return []
96
99
 
97
100
  const state = {