@anteros/core 0.0.23 → 0.0.25

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@anteros/core",
3
3
  "module": "index.ts",
4
- "version": "0.0.23",
4
+ "version": "0.0.25",
5
5
  "type": "module",
6
6
  "description": "Anteros Core",
7
7
  "private": false,
@@ -10,7 +10,8 @@
10
10
  "bun": ">=1.3.0"
11
11
  },
12
12
  "devDependencies": {
13
- "@types/bun": "^1.3.14"
13
+ "@types/bun": "^1.3.14",
14
+ "@types/tcp-port-used": "^1.0.4"
14
15
  },
15
16
  "peerDependencies": {
16
17
  "typescript": "6.0.3"
@@ -29,6 +30,7 @@
29
30
  "jose": "6.2.8",
30
31
  "mongodb": "7.5.0",
31
32
  "socket.io": "4.8.3",
33
+ "tcp-port-used": "^1.0.3",
32
34
  "ufo": "1.6.4",
33
35
  "zod": "^4.4.3"
34
36
  }
package/server/boot.ts CHANGED
@@ -22,18 +22,7 @@ import crypto from 'node:crypto';
22
22
  import os from 'node:os';
23
23
  import { registerMetrics, getMetrics, trackRequest } from './metrics';
24
24
  import { startMaster, aggregateMetrics } from './cluster';
25
-
26
- /** Check if a TCP port is already bound */
27
- async function isPortInUse(port: number): Promise<boolean> {
28
- try {
29
- const proc = Bun.spawn(['lsof', '-ti', `:${port}`], { stdout: 'pipe' });
30
- const output = await new Response(proc.stdout).text();
31
- await proc.exited;
32
- return output.trim().length > 0;
33
- } catch {
34
- return false;
35
- }
36
- }
25
+ import tcpPortUsed from 'tcp-port-used';
37
26
 
38
27
  type BootAppOptions = ServerConfig & {
39
28
 
@@ -117,14 +106,38 @@ async function bootApp(options: BootAppOptions = {} as BootAppOptions) {
117
106
 
118
107
  console.log(`[cluster] Aggregated /health → http://localhost:${metricsPort}/health`.gray);
119
108
 
109
+ // Graceful shutdown: stop workers + metrics server so a restart
110
+ // (e.g. bun --watch) never leaves the port occupied
111
+ const shutdownCluster = (signal: string) => {
112
+ console.log(`\n${signal} received — shutting down workers…`.gray);
113
+ try { master.shutdown(); } catch {}
114
+ try { metricsServer.stop(true); } catch {}
115
+ for (const tenant of cfg.tenants ?? []) {
116
+ try { tenant.database?.client?.close(); } catch {}
117
+ }
118
+ process.exit(0);
119
+ };
120
+ process.once('SIGINT', () => shutdownCluster('SIGINT'));
121
+ process.once('SIGTERM', () => shutdownCluster('SIGTERM'));
122
+
120
123
  // Keep the master alive
121
124
  return { master, metricsServer } as any;
122
125
  }
123
126
 
124
- // Detect zombie: check if port is already in use when NOT sharing the port
127
+ // Detect zombie: check if port is already in use when NOT sharing the port.
128
+ // tcp-port-used probes with a real TCP connection — only a listening server
129
+ // counts (a connected client never triggers a false positive) and it works
130
+ // on any platform (no lsof dependency). Grace period: after a restart the
131
+ // previous process may still be releasing the port (Mongo / Socket.IO
132
+ // shutdown) — wait before declaring a zombie.
125
133
  if (!reusePort && env === 'dev') {
126
- const occupied = await isPortInUse(PORT);
127
- if (occupied) {
134
+ if (await tcpPortUsed.check(PORT)) {
135
+ console.log(`⏳ Port ${PORT} is still held, waiting for the previous process to release it (~2.5s)…`.gray);
136
+ }
137
+ try {
138
+ // ~2.5s grace (5 × 500ms); rejects if the port stays occupied
139
+ await tcpPortUsed.waitUntilFree(PORT, 500, 2500);
140
+ } catch {
128
141
  console.error(`\n⚠ Port ${PORT} is already in use. Possible zombie server.\n → Kill it: lsof -ti :${PORT} | xargs kill -9\n`.red.bold);
129
142
  process.exit(1);
130
143
  }
@@ -158,6 +171,19 @@ async function bootApp(options: BootAppOptions = {} as BootAppOptions) {
158
171
  // Register server for built-in metrics (GET /health)
159
172
  registerMetrics(server);
160
173
 
174
+ // Graceful shutdown: release the port & DB connections so restarts
175
+ // (e.g. bun --watch) never hit a zombie / EADDRINUSE
176
+ const shutdownServer = (signal: string) => {
177
+ console.log(`\n${signal} received — shutting down…`.gray);
178
+ try { server.stop(true); } catch {}
179
+ for (const tenant of cfg.tenants ?? []) {
180
+ try { tenant.database?.client?.close(); } catch {}
181
+ }
182
+ process.exit(0);
183
+ };
184
+ process.once('SIGINT', () => shutdownServer('SIGINT'));
185
+ process.once('SIGTERM', () => shutdownServer('SIGTERM'));
186
+
161
187
  // ── WORKER (cluster): report metrics to the master via IPC ──
162
188
  if (isWorker && typeof process.send === 'function') {
163
189
  setInterval(() => {
package/tests/api.test.ts CHANGED
@@ -73,6 +73,56 @@ describe("find", () => {
73
73
  });
74
74
  });
75
75
 
76
+ describe("$limit", () => {
77
+ it("$limit: 0 means no limit (returns all matching docs)", async () => {
78
+ const marker = `limit-zero-${crypto.randomUUID()}`;
79
+ await rest.bulkWrite("items", Array.from({ length: 101 }, (_, i) => ({
80
+ insertOne: { document: { title: marker, count: i } },
81
+ })) as any);
82
+
83
+ const all = await rest.find("items", { $match: { title: marker }, $limit: 0 });
84
+ expect(all.length).toBe(101); // the old 100 cap would have returned 100
85
+
86
+ await rest.db.collection("items").deleteMany({ title: marker });
87
+ });
88
+
89
+ it("accepts $limit above 1000", async () => {
90
+ const marker = `limit-big-${crypto.randomUUID()}`;
91
+ await rest.insertMany("items", [
92
+ { title: marker, count: 1 },
93
+ { title: marker, count: 2 },
94
+ { title: marker, count: 3 },
95
+ ]);
96
+
97
+ const docs = await rest.find("items", { $match: { title: marker }, $limit: 5000 });
98
+ expect(docs.length).toBe(3);
99
+
100
+ await rest.db.collection("items").deleteMany({ title: marker });
101
+ });
102
+
103
+ it("defaults to $limit 100", async () => {
104
+ const marker = `limit-default-${crypto.randomUUID()}`;
105
+ await rest.bulkWrite("items", Array.from({ length: 120 }, (_, i) => ({
106
+ insertOne: { document: { title: marker, count: i } },
107
+ })) as any);
108
+
109
+ const docs = await rest.find("items", { $match: { title: marker } });
110
+ expect(docs.length).toBe(100);
111
+
112
+ await rest.db.collection("items").deleteMany({ title: marker });
113
+ });
114
+
115
+ it("rejects negative $limit with INVALID_LIMIT", async () => {
116
+ const err: any = await rest.find("items", { $limit: -1 }).then(() => null, (e) => e);
117
+ expect(err?.code).toBe("INVALID_LIMIT");
118
+ });
119
+
120
+ it("rejects non-integer $limit with INVALID_LIMIT", async () => {
121
+ const err: any = await rest.find("items", { $limit: 1.5 }).then(() => null, (e) => e);
122
+ expect(err?.code).toBe("INVALID_LIMIT");
123
+ });
124
+ });
125
+
76
126
  describe("findOne", () => {
77
127
  it("returns single doc by _id", async () => {
78
128
  const doc = await rest.insertOne("items", { title: "single" });
package/utils/func.ts CHANGED
@@ -748,18 +748,20 @@ function buildPipeline(p: FindOptions, options?: {
748
748
  })
749
749
  }
750
750
 
751
- // $limit — Faille 14: must be a safe integer in (0, MAX_LIMIT]; 0 would mean "no limit"
752
- const MAX_LIMIT = 1000;
751
+ // $limit — 0 means "no limit" (the $limit stage is omitted);
752
+ // any positive safe integer is allowed (no 1000 cap)
753
753
  p.$limit = p?.$limit ?? 100
754
- if (!Number.isSafeInteger(p.$limit) || p.$limit <= 0 || p.$limit > MAX_LIMIT) {
755
- throw new AppError(`Invalid $limit (expected an integer between 1 and ${MAX_LIMIT})`, {
754
+ if (!Number.isSafeInteger(p.$limit) || p.$limit < 0) {
755
+ throw new AppError(`Invalid $limit (expected a non-negative integer; 0 = no limit)`, {
756
756
  code: 'INVALID_LIMIT',
757
757
  status: 400
758
758
  });
759
759
  }
760
- pipeline.push({
761
- $limit: p.$limit
762
- })
760
+ if (p.$limit > 0) {
761
+ pipeline.push({
762
+ $limit: p.$limit
763
+ })
764
+ }
763
765
 
764
766
  // $include
765
767
  if (p?.$include && Array.isArray(p?.$include)) {