@blinkhost/cli 2.7.0 → 2.8.0
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/CHANGELOG.md +4 -0
- package/README.md +514 -2
- package/dist/api.d.ts +2 -2
- package/dist/api.js +57 -8
- package/dist/assistant.js +6 -1
- package/dist/cli.js +157 -9
- package/dist/guidance.d.ts +1 -1
- package/dist/guidance.js +43 -11
- package/dist/javascript-runtime/resource-limits.js +3 -0
- package/dist/javascript-runtime/resource-profiles.js +2 -0
- package/dist/local-dev.d.ts +3 -0
- package/dist/local-dev.js +145 -0
- package/dist/local-development/README.md +410 -0
- package/dist/local-development/artifact-watch.mjs +36 -0
- package/dist/local-development/blinkhost.local.example.json +15 -0
- package/dist/local-development/frontend-proxy.mjs +189 -0
- package/dist/local-development/hello.rs +24 -0
- package/dist/local-development/local-stack.mjs +511 -0
- package/dist/local-development/native-database.mjs +37 -0
- package/dist/local-development/provider-fixtures.example.json +36 -0
- package/dist/local-development/provider-fixtures.mjs +203 -0
- package/dist/local-development/provider-grants.mjs +36 -0
- package/dist/local-development/test-provider-example.mjs +74 -0
- package/dist/local-source-build.d.ts +39 -0
- package/dist/local-source-build.js +225 -0
- package/dist/local-source-watch.d.ts +24 -0
- package/dist/local-source-watch.js +87 -0
- package/dist/local-test-command.d.ts +49 -0
- package/dist/local-test-command.js +128 -0
- package/dist/local-test-config.d.ts +37 -0
- package/dist/local-test-config.js +174 -0
- package/dist/local-test-gates.d.ts +71 -0
- package/dist/local-test-gates.js +247 -0
- package/dist/local-test-go-runner.d.ts +27 -0
- package/dist/local-test-go-runner.js +209 -0
- package/dist/local-test-node-arguments.d.ts +2 -0
- package/dist/local-test-node-arguments.js +14 -0
- package/dist/local-test-node-reporter.d.ts +7 -0
- package/dist/local-test-node-reporter.js +159 -0
- package/dist/local-test-results.d.ts +65 -0
- package/dist/local-test-results.js +163 -0
- package/dist/local-test-rust-runner.d.ts +18 -0
- package/dist/local-test-rust-runner.js +252 -0
- package/dist/local-test-starters.d.ts +3 -0
- package/dist/local-test-starters.js +157 -0
- package/dist/logs.d.ts +43 -0
- package/dist/logs.js +417 -0
- package/dist/module-build-diagnostics.d.ts +10 -0
- package/dist/module-build-diagnostics.js +208 -0
- package/dist/module-build.js +4 -0
- package/dist/release-preparation-diagnostics.d.ts +38 -0
- package/dist/release-preparation-diagnostics.js +204 -0
- package/dist/remote.js +14 -0
- package/dist/templates.d.ts +1 -0
- package/dist/templates.js +4 -1
- package/dist/test-credentials.d.ts +7 -0
- package/dist/test-credentials.js +236 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/workflows.d.ts +39 -2
- package/dist/workflows.js +241 -14
- package/package.json +4 -3
- package/test-runners/python-unittest.py +266 -0
package/dist/logs.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
type Filters = Record<string, string>;
|
|
2
|
+
export type LogEvent = Record<string, unknown> & {
|
|
3
|
+
event_id: string;
|
|
4
|
+
event_time: string;
|
|
5
|
+
};
|
|
6
|
+
export type LogEntry = {
|
|
7
|
+
kind: 'event';
|
|
8
|
+
event: LogEvent;
|
|
9
|
+
} | {
|
|
10
|
+
kind: 'notice';
|
|
11
|
+
code: string;
|
|
12
|
+
message: string;
|
|
13
|
+
} | {
|
|
14
|
+
kind: 'summary';
|
|
15
|
+
events: number;
|
|
16
|
+
duplicates_skipped: number;
|
|
17
|
+
reason: string;
|
|
18
|
+
filters: Filters;
|
|
19
|
+
has_more: boolean;
|
|
20
|
+
next_cursor: string | null;
|
|
21
|
+
};
|
|
22
|
+
export interface LogClient {
|
|
23
|
+
request(path: string, init?: RequestInit, responseLimit?: number): Promise<unknown>;
|
|
24
|
+
}
|
|
25
|
+
export interface LogOptions {
|
|
26
|
+
project?: string;
|
|
27
|
+
filters: Filters;
|
|
28
|
+
follow: boolean;
|
|
29
|
+
maxEvents: number;
|
|
30
|
+
cursor?: string;
|
|
31
|
+
}
|
|
32
|
+
export declare function sinceFilters(value: string, now?: number, aggregate?: boolean): Filters;
|
|
33
|
+
export declare function parseLogOptions(input: string[], now?: number): LogOptions;
|
|
34
|
+
export declare function serializeLogEvent(event: LogEvent): string;
|
|
35
|
+
export declare function renderLogEntry(entry: LogEntry, json: boolean): string;
|
|
36
|
+
/** Stop waiting on a stalled terminal pipe when the user interrupts. */
|
|
37
|
+
export declare function writeLogOutput(output: Pick<NodeJS.WriteStream, 'write'>, value: string, signal: AbortSignal): Promise<boolean>;
|
|
38
|
+
/** Stream one bounded page at a time; every write is awaited by the caller. */
|
|
39
|
+
export declare function readLogs(client: LogClient, options: LogOptions & {
|
|
40
|
+
project: string;
|
|
41
|
+
}, emit: (entry: LogEntry, signal: AbortSignal) => Promise<void>, interruptSignal: AbortSignal, pause?: (ms: number, signal: AbortSignal) => Promise<void>): Promise<void>;
|
|
42
|
+
export declare function runLogCommand(input: string[], profile: string | undefined, emit: (entry: LogEntry, signal: AbortSignal) => Promise<void>, signal: AbortSignal): Promise<void>;
|
|
43
|
+
export {};
|
package/dist/logs.js
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
import { setTimeout as wait } from 'node:timers/promises';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { ApiClient } from './api.js';
|
|
4
|
+
import { CliError, EXIT } from './errors.js';
|
|
5
|
+
import { readProjectLink } from './remote.js';
|
|
6
|
+
import { terminalJson, terminalText } from './terminal.js';
|
|
7
|
+
const PAGE_BYTES = 2 * 1024 * 1024;
|
|
8
|
+
const UUID = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;
|
|
9
|
+
function usage(message) { throw new CliError(message, EXIT.usage, 'invalid_log_options'); }
|
|
10
|
+
function integer(value, min, max, name) {
|
|
11
|
+
if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
|
|
12
|
+
usage(`${name} must be an integer from ${min} to ${max}.`);
|
|
13
|
+
return Number(value);
|
|
14
|
+
}
|
|
15
|
+
function instant(value, now) {
|
|
16
|
+
const match = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
17
|
+
if (!match)
|
|
18
|
+
usage('Use a timezone-aware ISO timestamp with at most millisecond precision.');
|
|
19
|
+
// Date.parse normalizes some invalid calendar dates. Check the local date too.
|
|
20
|
+
const local = Date.parse(`${match[1]}T${match[2]}${match[3] || ''}Z`);
|
|
21
|
+
if (!Number.isFinite(local) || new Date(local).toISOString().slice(0, 19) !== `${match[1]}T${match[2]}`)
|
|
22
|
+
usage('Invalid calendar timestamp.');
|
|
23
|
+
const parsed = Date.parse(value);
|
|
24
|
+
if (!Number.isFinite(parsed) || parsed > now)
|
|
25
|
+
usage('The timestamp must be valid and no later than the current time.');
|
|
26
|
+
return new Date(parsed).toISOString();
|
|
27
|
+
}
|
|
28
|
+
export function sinceFilters(value, now = Date.now(), aggregate = false) {
|
|
29
|
+
const duration = /^(\d+)(s|m|h|d)$/.exec(value);
|
|
30
|
+
if (duration) {
|
|
31
|
+
const units = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
|
|
32
|
+
const milliseconds = Number(duration[1]) * units[duration[2]];
|
|
33
|
+
if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0 || milliseconds > 366 * 86_400_000)
|
|
34
|
+
usage('--since must be a positive duration up to 366d.');
|
|
35
|
+
return aggregate ? { hours: String(Math.ceil(milliseconds / 3_600_000)) }
|
|
36
|
+
: { start_time: new Date(now - milliseconds).toISOString() };
|
|
37
|
+
}
|
|
38
|
+
if (aggregate)
|
|
39
|
+
usage('Metrics and analytics --since use a duration (s, m, h or d), rounded up to whole hours.');
|
|
40
|
+
return { start_time: instant(value, now) };
|
|
41
|
+
}
|
|
42
|
+
function validatePredicates(raw) {
|
|
43
|
+
if (Buffer.byteLength(raw) > 8192)
|
|
44
|
+
usage('Custom filter JSON is limited to 8192 UTF-8 bytes.');
|
|
45
|
+
let input;
|
|
46
|
+
const numberSources = new WeakMap();
|
|
47
|
+
try {
|
|
48
|
+
input = JSON.parse(raw, function (key, value, context) {
|
|
49
|
+
if (typeof value === 'number') {
|
|
50
|
+
if (!Number.isFinite(value) || !context?.source)
|
|
51
|
+
usage('Custom numbers must be finite and use a supported Node.js version.');
|
|
52
|
+
const sources = numberSources.get(this) || new Map();
|
|
53
|
+
sources.set(key, context.source);
|
|
54
|
+
numberSources.set(this, sources);
|
|
55
|
+
}
|
|
56
|
+
return value;
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
usage('Custom filters must be valid finite JSON.');
|
|
61
|
+
}
|
|
62
|
+
if (!Array.isArray(input) || input.length < 1 || input.length > 8)
|
|
63
|
+
usage('Choose one to eight custom filters.');
|
|
64
|
+
for (const item of input) {
|
|
65
|
+
if (!item || typeof item !== 'object' || Array.isArray(item) || !Array.isArray(item.path) || item.path.length < 1 || item.path.length > 4
|
|
66
|
+
|| typeof item.path[0] !== 'string' || !item.path.every((key, index) => typeof key === 'string' ? /^[a-z][a-z0-9_.]{0,79}$/.test(key) : /^\d+$/.test(numberSources.get(item.path)?.get(String(index)) || '') && Number.isInteger(key) && Number(key) >= 0 && Number(key) < 64))
|
|
67
|
+
usage('Every custom filter needs a valid nested field path.');
|
|
68
|
+
const keys = Object.keys(item).sort().join(',');
|
|
69
|
+
if (['exists', 'not_exists'].includes(item.op)) {
|
|
70
|
+
if (keys !== 'op,path')
|
|
71
|
+
usage('Existence filters accept only path and op.');
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (keys !== 'op,path,type,value')
|
|
75
|
+
usage('Comparison filters require path, op, type and value.');
|
|
76
|
+
const numeric = ['eq', 'ne', 'gt', 'gte', 'lt', 'lte'].includes(item.op);
|
|
77
|
+
const numberSource = numberSources.get(item)?.get('value') || '';
|
|
78
|
+
const integerToken = /^-?\d+$/.test(numberSource);
|
|
79
|
+
const valid = item.type === 'string' ? typeof item.value === 'string' && Buffer.byteLength(item.value) <= 1024 && ['eq', 'ne', 'contains', 'prefix'].includes(item.op)
|
|
80
|
+
: item.type === 'integer' ? integerToken && BigInt(numberSource) >= -(BigInt(1) << BigInt(63)) && BigInt(numberSource) < (BigInt(1) << BigInt(64)) && numeric
|
|
81
|
+
: item.type === 'number' ? typeof item.value === 'number' && Number.isFinite(item.value) && (!integerToken || Number.isSafeInteger(item.value)) && numeric
|
|
82
|
+
: item.type === 'boolean' ? typeof item.value === 'boolean' && ['eq', 'ne'].includes(item.op)
|
|
83
|
+
: item.type === 'null' && item.value === null && item.op === 'eq';
|
|
84
|
+
if (!valid)
|
|
85
|
+
usage('Invalid custom field type, operator or value.');
|
|
86
|
+
}
|
|
87
|
+
// Retain the original JSON, including exact 64-bit integer literals. The API
|
|
88
|
+
// parses and validates their signed/unsigned range without JS rounding.
|
|
89
|
+
}
|
|
90
|
+
export function parseLogOptions(input, now = Date.now()) {
|
|
91
|
+
const filters = { hours: '1', limit: '100' };
|
|
92
|
+
const options = {};
|
|
93
|
+
let follow = false;
|
|
94
|
+
const names = new Set(['project', 'since', 'hours', 'limit', 'max-events', 'cursor', 'attribute-filters',
|
|
95
|
+
'severity', 'event-kind', 'environment-id', 'environment-kind', 'preview-session-id', 'deployment-id',
|
|
96
|
+
'release-id', 'region', 'request-id', 'trace-id', 'source', 'operation', 'outcome', 'status-code', 'search', 'start-time', 'end-time']);
|
|
97
|
+
for (let index = 0; index < input.length; index++) {
|
|
98
|
+
const argument = input[index];
|
|
99
|
+
if (argument === '--follow') {
|
|
100
|
+
if (follow)
|
|
101
|
+
usage('Do not repeat --follow.');
|
|
102
|
+
follow = true;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const name = argument.slice(2);
|
|
106
|
+
if (!argument.startsWith('--') || !names.has(name) || Object.hasOwn(options, name))
|
|
107
|
+
usage(`Unknown or repeated log option: ${argument}`);
|
|
108
|
+
const value = input[++index];
|
|
109
|
+
if (!value || value.startsWith('--'))
|
|
110
|
+
usage(`${argument} requires a value.`);
|
|
111
|
+
if (Buffer.byteLength(value) > (name === 'attribute-filters' ? 8192 : name === 'cursor' ? 4096 : 1024))
|
|
112
|
+
usage(`${argument} is too large.`);
|
|
113
|
+
options[name] = value;
|
|
114
|
+
}
|
|
115
|
+
if (options.project && !UUID.test(options.project))
|
|
116
|
+
usage('--project must be a UUID.');
|
|
117
|
+
if (options.since && (options['start-time'] || options.hours))
|
|
118
|
+
usage('Choose --since or --start-time/--hours.');
|
|
119
|
+
if (options.hours)
|
|
120
|
+
filters.hours = String(integer(options.hours, 1, 8784, '--hours'));
|
|
121
|
+
if (options.limit)
|
|
122
|
+
filters.limit = String(integer(options.limit, 1, 200, '--limit'));
|
|
123
|
+
if (options.since)
|
|
124
|
+
Object.assign(filters, sinceFilters(options.since, now));
|
|
125
|
+
for (const name of names) {
|
|
126
|
+
if (['project', 'since', 'hours', 'limit', 'max-events', 'cursor'].includes(name) || !options[name])
|
|
127
|
+
continue;
|
|
128
|
+
filters[name.replaceAll('-', '_')] = options[name];
|
|
129
|
+
}
|
|
130
|
+
for (const key of ['start_time', 'end_time'])
|
|
131
|
+
if (filters[key])
|
|
132
|
+
filters[key] = instant(filters[key], now);
|
|
133
|
+
if (filters.start_time && filters.end_time && filters.start_time >= filters.end_time)
|
|
134
|
+
usage('--start-time must be earlier than --end-time.');
|
|
135
|
+
if (filters.attribute_filters)
|
|
136
|
+
validatePredicates(filters.attribute_filters);
|
|
137
|
+
if (filters.severity && !['debug', 'info', 'warning', 'error', 'critical'].includes(filters.severity))
|
|
138
|
+
usage('Invalid severity.');
|
|
139
|
+
if (filters.outcome && !['success', 'failure', 'denied', 'degraded'].includes(filters.outcome))
|
|
140
|
+
usage('Invalid outcome.');
|
|
141
|
+
if (filters.event_kind && !['request', 'application_log', 'runtime_metric', 'policy_decision', 'database_operation', 'outbound_call'].includes(filters.event_kind))
|
|
142
|
+
usage('Invalid event kind.');
|
|
143
|
+
if (filters.status_code)
|
|
144
|
+
integer(filters.status_code, 0, 599, '--status-code');
|
|
145
|
+
for (const key of ['environment_id', 'deployment_id'])
|
|
146
|
+
if (filters[key]) {
|
|
147
|
+
if (!/^\d+$/.test(filters[key]) || BigInt(filters[key]) >= (BigInt(1) << BigInt(64)))
|
|
148
|
+
usage(`${key} must be an unsigned 64-bit integer.`);
|
|
149
|
+
filters[key] = BigInt(filters[key]).toString();
|
|
150
|
+
}
|
|
151
|
+
if (filters.trace_id) {
|
|
152
|
+
if (!/^[a-f0-9]{32}$/i.test(filters.trace_id))
|
|
153
|
+
usage('--trace-id must have 32 hexadecimal characters.');
|
|
154
|
+
filters.trace_id = filters.trace_id.toLowerCase();
|
|
155
|
+
}
|
|
156
|
+
for (const key of ['release_id', 'region', 'request_id', 'source', 'operation', 'search'])
|
|
157
|
+
if (filters[key] && Array.from(filters[key]).length > 160)
|
|
158
|
+
usage(`${key} is limited to 160 characters.`);
|
|
159
|
+
if (filters.environment_kind && !['deployed', 'preview'].includes(filters.environment_kind))
|
|
160
|
+
usage('--environment-kind must be deployed or preview.');
|
|
161
|
+
if (filters.preview_session_id) {
|
|
162
|
+
if (!UUID.test(filters.preview_session_id))
|
|
163
|
+
usage('--preview-session-id must be a UUID.');
|
|
164
|
+
if (filters.environment_kind === 'deployed')
|
|
165
|
+
usage('Preview sessions require the preview environment kind.');
|
|
166
|
+
filters.environment_kind = 'preview';
|
|
167
|
+
}
|
|
168
|
+
if (filters.environment_kind === 'preview' && (filters.environment_id || filters.deployment_id))
|
|
169
|
+
usage('Preview queries cannot include deployed environment or deployment IDs.');
|
|
170
|
+
if (follow && options.cursor)
|
|
171
|
+
usage('--cursor is for historical reads; start follow from the newest matching records.');
|
|
172
|
+
const maxEvents = options['max-events'] ? integer(options['max-events'], 1, 10_000, '--max-events') : follow ? 10_000 : 200;
|
|
173
|
+
return { filters, follow, maxEvents, ...(options.project ? { project: options.project } : {}), ...(options.cursor ? { cursor: options.cursor } : {}) };
|
|
174
|
+
}
|
|
175
|
+
function page(value) {
|
|
176
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
177
|
+
throw new CliError('Invalid log page.', EXIT.remote, 'invalid_log_response');
|
|
178
|
+
const data = value;
|
|
179
|
+
if (!Array.isArray(data.events) || data.events.length > 200 || typeof data.has_more !== 'boolean'
|
|
180
|
+
|| (data.next_cursor !== null && data.next_cursor !== undefined && (typeof data.next_cursor !== 'string' || data.next_cursor.length > 4096))
|
|
181
|
+
|| (data.has_more && (!data.events.length || !data.next_cursor))
|
|
182
|
+
|| data.events.some(event => !event || typeof event !== 'object' || Array.isArray(event) || typeof event.event_id !== 'string' || event.event_id.length > 128
|
|
183
|
+
|| !event.event_id || typeof event.event_time !== 'string' || event.event_time.length > 64))
|
|
184
|
+
throw new CliError('Invalid log page or cursor.', EXIT.remote, 'invalid_log_response');
|
|
185
|
+
return { events: data.events, has_more: data.has_more, next_cursor: typeof data.next_cursor === 'string' ? data.next_cursor : null };
|
|
186
|
+
}
|
|
187
|
+
function filterJson(filters) {
|
|
188
|
+
const { attribute_filters, ...rest } = filters;
|
|
189
|
+
const serialized = JSON.stringify(rest);
|
|
190
|
+
return attribute_filters ? serialized.slice(0, -1) + ',"attribute_filters":' + attribute_filters + '}' : serialized;
|
|
191
|
+
}
|
|
192
|
+
export function serializeLogEvent(event) {
|
|
193
|
+
const { attributes_json, attributes, ...rest } = event;
|
|
194
|
+
if (typeof attributes_json === 'string' && Buffer.byteLength(attributes_json) <= 131_072) {
|
|
195
|
+
try {
|
|
196
|
+
const parsed = JSON.parse(attributes_json);
|
|
197
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
198
|
+
const pending = [[parsed, 0]];
|
|
199
|
+
let values = 0;
|
|
200
|
+
while (pending.length) {
|
|
201
|
+
const [value, depth] = pending.pop();
|
|
202
|
+
if (++values > 4096 || depth > 16 || (typeof value === 'number' && !Number.isFinite(value)))
|
|
203
|
+
throw new Error('Unbounded attribute JSON');
|
|
204
|
+
if (value && typeof value === 'object')
|
|
205
|
+
for (const child of Object.values(value))
|
|
206
|
+
pending.push([child, depth + 1]);
|
|
207
|
+
}
|
|
208
|
+
// Preserve number tokens and string whitespace, while emitting one NDJSON line.
|
|
209
|
+
const compact = attributes_json.replace(/("(?:\\.|[^"\\])*")|[\t\n\r ]+/g, (_match, quoted) => quoted || '');
|
|
210
|
+
return JSON.stringify(rest).slice(0, -1) + ',"attributes":' + compact + '}';
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
catch { /* Retain the delivered values and explicitly qualify precision. */ }
|
|
214
|
+
}
|
|
215
|
+
return JSON.stringify({ ...rest, attributes, precision_notice: 'Exact stored attribute JSON is unavailable; numeric values reflect the API client representation.' });
|
|
216
|
+
}
|
|
217
|
+
export function renderLogEntry(entry, json) {
|
|
218
|
+
if (json)
|
|
219
|
+
return terminalJson(entry.kind === 'event' ? '{"kind":"event","event":' + serializeLogEvent(entry.event) + '}' : JSON.stringify(entry)) + '\n';
|
|
220
|
+
if (entry.kind === 'event')
|
|
221
|
+
return terminalText(`${JSON.stringify(entry.event.event_time)} ${JSON.stringify(entry.event.severity ?? '')} ${JSON.stringify(entry.event.message ?? '')}`) + '\n';
|
|
222
|
+
if (entry.kind === 'notice')
|
|
223
|
+
return terminalText(`Notice [${entry.code}]: ${entry.message}`) + '\n';
|
|
224
|
+
return terminalText(`${entry.events} events; ${entry.reason}; ${entry.duplicates_skipped} duplicate IDs skipped${entry.has_more ? '; more retained records are available' : ''}.`
|
|
225
|
+
+ (entry.next_cursor ? `\nContinue with --cursor ${JSON.stringify(entry.next_cursor)} and the same filters${entry.filters.start_time ? `, including --start-time ${JSON.stringify(entry.filters.start_time)}` : ''}.` : '')) + '\n';
|
|
226
|
+
}
|
|
227
|
+
/** Stop waiting on a stalled terminal pipe when the user interrupts. */
|
|
228
|
+
export async function writeLogOutput(output, value, signal) {
|
|
229
|
+
if (signal.aborted)
|
|
230
|
+
return false;
|
|
231
|
+
return await new Promise((resolve, reject) => {
|
|
232
|
+
const aborted = () => { signal.removeEventListener('abort', aborted); resolve(false); };
|
|
233
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
234
|
+
try {
|
|
235
|
+
output.write(value, error => {
|
|
236
|
+
signal.removeEventListener('abort', aborted);
|
|
237
|
+
if (error)
|
|
238
|
+
reject(error);
|
|
239
|
+
else
|
|
240
|
+
resolve(true);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
signal.removeEventListener('abort', aborted);
|
|
245
|
+
reject(error);
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
/** Stream one bounded page at a time; every write is awaited by the caller. */
|
|
250
|
+
export async function readLogs(client, options, emit, interruptSignal, pause = async (ms, abort) => { await wait(ms, undefined, { signal: abort }); }) {
|
|
251
|
+
let signal = options.follow ? interruptSignal : AbortSignal.any([interruptSignal, AbortSignal.timeout(120_000)]);
|
|
252
|
+
const stopReason = () => interruptSignal.aborted ? 'interrupted' : options.follow ? 'live-tail ticket expired' : 'time limit reached';
|
|
253
|
+
const base = `/api/sites/${options.project}/observability/`;
|
|
254
|
+
let ticket = '', expires = Infinity, count = 0, duplicates = 0, watermark = '', nextCursor = options.cursor || null, more = false, reason = 'history exhausted';
|
|
255
|
+
const seen = new Set();
|
|
256
|
+
const historicalCursors = new Set();
|
|
257
|
+
let totalPages = 0;
|
|
258
|
+
const remember = (id) => { seen.add(id); if (seen.size > 1000)
|
|
259
|
+
seen.delete(seen.values().next().value); };
|
|
260
|
+
const notice = (code, message) => emit({ kind: 'notice', code, message }, signal);
|
|
261
|
+
const requestPage = async (path) => {
|
|
262
|
+
const queryId = randomUUID();
|
|
263
|
+
try {
|
|
264
|
+
return await client.request(path, { signal, headers: { 'X-Observability-Query-Id': queryId, ...(ticket ? { 'X-Live-Tail-Ticket': ticket } : {}) } }, PAGE_BYTES);
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
if (signal.aborted || (error instanceof CliError && error.exitCode === EXIT.network)) {
|
|
268
|
+
try {
|
|
269
|
+
const closed = await client.request(`/api/observability-query-leases/${queryId}/cancel/`, { method: 'POST', body: '{}', signal: AbortSignal.timeout(5000) }, PAGE_BYTES);
|
|
270
|
+
if (!closed || typeof closed !== 'object' || closed.cancelled !== true)
|
|
271
|
+
throw new Error('Unconfirmed');
|
|
272
|
+
}
|
|
273
|
+
catch (cancelError) {
|
|
274
|
+
// 409 means the owned lease was already released/cancelled. A 404
|
|
275
|
+
// can race admission, so do not falsely claim provider cancellation.
|
|
276
|
+
if (!(cancelError instanceof CliError && cancelError.code === 'api_409'))
|
|
277
|
+
await notice('query_cancel_unconfirmed', 'Provider-query cancellation could not be confirmed; its server deadline still applies.');
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
try {
|
|
284
|
+
if (options.follow) {
|
|
285
|
+
const result = await client.request(base + 'live-tail-tickets/', { method: 'POST', body: '{"filters":' + filterJson(options.filters) + '}', signal }, PAGE_BYTES);
|
|
286
|
+
if (!result || typeof result !== 'object')
|
|
287
|
+
throw new CliError('Invalid live-tail ticket response.', EXIT.remote, 'invalid_log_response');
|
|
288
|
+
const data = result;
|
|
289
|
+
if (typeof data.ticket === 'string' && data.ticket.length <= 256)
|
|
290
|
+
ticket = data.ticket;
|
|
291
|
+
expires = typeof data.expires_at === 'string' ? Date.parse(data.expires_at) : NaN;
|
|
292
|
+
if (!ticket || !Number.isFinite(expires) || expires <= Date.now())
|
|
293
|
+
throw new CliError('Invalid or expired live-tail ticket.', EXIT.remote, 'invalid_log_response');
|
|
294
|
+
signal = AbortSignal.any([interruptSignal, AbortSignal.timeout(Math.max(1, Math.min(expires - Date.now(), 2_147_483_647)))]);
|
|
295
|
+
await notice('best_effort_follow', 'Follow deduplicates up to 1000 recent IDs and reads at most ten pages per poll. Late arrivals, interruptions and full windows can leave gaps; use retained history.');
|
|
296
|
+
}
|
|
297
|
+
let failures = 0;
|
|
298
|
+
while (!signal.aborted && count < options.maxEvents) {
|
|
299
|
+
if (Date.now() >= expires) {
|
|
300
|
+
reason = 'live-tail ticket expired';
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
if (!options.follow && totalPages >= 1000) {
|
|
304
|
+
reason = 'page limit reached';
|
|
305
|
+
break;
|
|
306
|
+
}
|
|
307
|
+
let cursor = options.follow ? null : nextCursor;
|
|
308
|
+
const cursors = options.follow ? new Set() : historicalCursors;
|
|
309
|
+
let newest = '', reachedPrevious = !watermark;
|
|
310
|
+
try {
|
|
311
|
+
for (let pages = 0; pages < 10 && !signal.aborted && count < options.maxEvents && (options.follow || totalPages < 1000); pages++) {
|
|
312
|
+
const requested = Math.min(Number(options.filters.limit), options.maxEvents - count);
|
|
313
|
+
const query = new URLSearchParams(options.follow ? {} : options.filters);
|
|
314
|
+
query.set('limit', String(requested));
|
|
315
|
+
if (cursor)
|
|
316
|
+
query.set('cursor', cursor);
|
|
317
|
+
const batch = page(await requestPage(base + (options.follow ? 'live-tail/' : 'logs/') + '?' + query));
|
|
318
|
+
totalPages++;
|
|
319
|
+
if (batch.events.length > requested)
|
|
320
|
+
throw new CliError('Log page exceeded its requested row bound.', EXIT.remote, 'invalid_log_response');
|
|
321
|
+
more = batch.has_more;
|
|
322
|
+
nextCursor = batch.next_cursor;
|
|
323
|
+
if (!newest)
|
|
324
|
+
newest = batch.events[0]?.event_id || '';
|
|
325
|
+
for (const event of batch.events) {
|
|
326
|
+
if (signal.aborted) {
|
|
327
|
+
if (!options.follow)
|
|
328
|
+
nextCursor = cursor;
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
if (options.follow && event.event_id === watermark) {
|
|
332
|
+
reachedPrevious = true;
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
if (!seen.has(event.event_id)) {
|
|
336
|
+
await emit({ kind: 'event', event }, signal);
|
|
337
|
+
remember(event.event_id);
|
|
338
|
+
count++;
|
|
339
|
+
}
|
|
340
|
+
else
|
|
341
|
+
duplicates++;
|
|
342
|
+
if (count >= options.maxEvents)
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
345
|
+
if (options.follow && watermark && reachedPrevious)
|
|
346
|
+
break;
|
|
347
|
+
if (!more || count >= options.maxEvents)
|
|
348
|
+
break;
|
|
349
|
+
if (!nextCursor || cursors.has(nextCursor) || nextCursor === cursor)
|
|
350
|
+
throw new CliError('Log pagination did not advance.', EXIT.remote, 'invalid_log_response');
|
|
351
|
+
cursors.add(nextCursor);
|
|
352
|
+
cursor = nextCursor;
|
|
353
|
+
if (pages === 9 && options.follow)
|
|
354
|
+
await notice('continuity_unconfirmed', 'The ten-page polling window was full. Some retained records may be absent from this follow view.');
|
|
355
|
+
}
|
|
356
|
+
if (!options.follow) {
|
|
357
|
+
if (!more || count >= options.maxEvents)
|
|
358
|
+
break;
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
if (count >= options.maxEvents)
|
|
362
|
+
break;
|
|
363
|
+
if (watermark && !reachedPrevious)
|
|
364
|
+
await notice('continuity_unconfirmed', 'The previous event was absent from the bounded polling window; continuity cannot be confirmed.');
|
|
365
|
+
if (newest)
|
|
366
|
+
watermark = newest;
|
|
367
|
+
failures = 0;
|
|
368
|
+
await pause(Math.min(2500, Math.max(1, expires - Date.now())), signal);
|
|
369
|
+
}
|
|
370
|
+
catch (error) {
|
|
371
|
+
if (signal.aborted)
|
|
372
|
+
break;
|
|
373
|
+
const retryable = options.follow && error instanceof CliError && (error.exitCode === EXIT.network || ['api_429', 'api_502', 'api_503', 'api_504'].includes(error.code));
|
|
374
|
+
if (!retryable || ++failures > 3)
|
|
375
|
+
throw error;
|
|
376
|
+
await notice('follow_interrupted', 'Log delivery was interrupted. Retrying the scoped ticket; continuity cannot be guaranteed.');
|
|
377
|
+
await pause(Math.min(2500 * 2 ** failures, Math.max(1, expires - Date.now())), signal);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (signal.aborted)
|
|
381
|
+
reason = stopReason();
|
|
382
|
+
else if (count >= options.maxEvents)
|
|
383
|
+
reason = 'event limit reached';
|
|
384
|
+
await emit({ kind: 'summary', events: count, duplicates_skipped: duplicates, reason, filters: options.filters, has_more: more, next_cursor: options.follow ? null : nextCursor }, signal);
|
|
385
|
+
}
|
|
386
|
+
catch (error) {
|
|
387
|
+
if (!signal.aborted)
|
|
388
|
+
throw error;
|
|
389
|
+
await emit({ kind: 'summary', events: count, duplicates_skipped: duplicates, reason: stopReason(), filters: options.filters, has_more: more, next_cursor: options.follow ? null : nextCursor }, signal);
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
if (ticket) {
|
|
393
|
+
try {
|
|
394
|
+
await client.request(base + 'live-tail/', { method: 'DELETE', headers: { 'X-Live-Tail-Ticket': ticket }, signal: AbortSignal.timeout(5000) }, PAGE_BYTES);
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
await notice('ticket_close_unconfirmed', 'Live-tail closure could not be confirmed; its server expiry still applies.');
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
export async function runLogCommand(input, profile, emit, signal) {
|
|
403
|
+
const options = parseLogOptions(input);
|
|
404
|
+
let project = options.project;
|
|
405
|
+
if (!project) {
|
|
406
|
+
try {
|
|
407
|
+
project = (await readProjectLink()).project_id;
|
|
408
|
+
}
|
|
409
|
+
catch { /* Explicit project guidance below. */ }
|
|
410
|
+
}
|
|
411
|
+
if (!project || !UUID.test(project))
|
|
412
|
+
throw new CliError('Provide --project UUID or link this directory with `blinkhost projects link`.', EXIT.usage, 'project_required');
|
|
413
|
+
if (signal.aborted)
|
|
414
|
+
return;
|
|
415
|
+
await readLogs(await ApiClient.create(profile), { ...options, project }, emit, signal);
|
|
416
|
+
}
|
|
417
|
+
//# sourceMappingURL=logs.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare function isModuleBuildPath(path: string): boolean;
|
|
2
|
+
export declare function moduleBuildPortableFailureGuidance(payload: unknown): string | undefined;
|
|
3
|
+
export declare function moduleBuildGuestMemoryFailureGuidance(payload: unknown): string | undefined;
|
|
4
|
+
export declare function moduleBuildPackageFailureGuidance(payload: unknown): string | undefined;
|
|
5
|
+
export declare function moduleBuildFailureGuidance(payload: unknown): string | undefined;
|
|
6
|
+
export declare function moduleBuildSourceGuidance(payload: unknown): string | undefined;
|
|
7
|
+
export declare function moduleBuildQuotaGuidance(payload: unknown): string | undefined;
|
|
8
|
+
export declare function moduleBuildRejectionGuidance(payload: unknown): string | undefined;
|
|
9
|
+
export declare function readModuleBuildRejection(response: Response): Promise<unknown>;
|
|
10
|
+
export declare function moduleBuildRequestId(candidate: string | null, fallback: string): string;
|