@freeweave/core 0.0.0-stage → 0.4.1
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/LICENSE +21 -0
- package/README.md +28 -2
- package/dist/alerts.d.ts +35 -0
- package/dist/alerts.js +72 -0
- package/dist/compliance.d.ts +28 -0
- package/dist/compliance.js +68 -0
- package/dist/executor.d.ts +89 -0
- package/dist/executor.js +192 -0
- package/dist/forecast.d.ts +19 -0
- package/dist/forecast.js +37 -0
- package/dist/http.d.ts +45 -0
- package/dist/http.js +55 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +15 -0
- package/dist/planner.d.ts +76 -0
- package/dist/planner.js +181 -0
- package/dist/relocate-run.d.ts +67 -0
- package/dist/relocate-run.js +171 -0
- package/dist/relocate.d.ts +63 -0
- package/dist/relocate.js +140 -0
- package/dist/stack.d.ts +313 -0
- package/dist/stack.js +93 -0
- package/dist/stub.d.ts +9 -0
- package/dist/stub.js +24 -0
- package/dist/terms.d.ts +80 -0
- package/dist/terms.js +191 -0
- package/dist/topology.d.ts +70 -0
- package/dist/topology.js +77 -0
- package/dist/types.d.ts +168 -0
- package/dist/types.js +2 -0
- package/dist/wiring.d.ts +20 -0
- package/dist/wiring.js +69 -0
- package/package.json +51 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Junho Kim
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,29 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @freeweave/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The engine behind [FreeWeave](https://github.com/xjvmdutl/freeweave): the `stack.yaml` schema, terms-of-service
|
|
4
|
+
guards, planner, wiring and quota forecast.
|
|
5
|
+
|
|
6
|
+
Most people want the CLI instead: `npx freeweave`.
|
|
7
|
+
|
|
8
|
+
## Writing an adapter
|
|
9
|
+
|
|
10
|
+
This package carries the `ProviderAdapter` type that community adapters implement:
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm i -D @freeweave/core
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import type { ProviderAdapter } from "@freeweave/core";
|
|
18
|
+
|
|
19
|
+
const adapter: ProviderAdapter = {
|
|
20
|
+
meta: { id: "turso", displayName: "Turso" /* … */ },
|
|
21
|
+
// verify, quota, deploy, destroy
|
|
22
|
+
};
|
|
23
|
+
export default adapter;
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Publish it as `freeweave-adapter-<id>` and see the
|
|
27
|
+
[adapter guide](https://xjvmdutl.github.io/freeweave/guide/writing-an-adapter) for the rules.
|
|
28
|
+
|
|
29
|
+
Versions follow the `freeweave` CLI.
|
package/dist/alerts.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { QuotaSnapshot } from "./types.js";
|
|
2
|
+
/** One recorded reading of one quota. */
|
|
3
|
+
export interface UsageRecord {
|
|
4
|
+
at: string;
|
|
5
|
+
provider: string;
|
|
6
|
+
key: string;
|
|
7
|
+
used: number;
|
|
8
|
+
limit: number;
|
|
9
|
+
resetsAt?: string;
|
|
10
|
+
}
|
|
11
|
+
export type AlertKind = "over" | "warn" | "forecast" | "note";
|
|
12
|
+
export interface Alert {
|
|
13
|
+
/** Stable id for de-duplication, e.g. "cloudflare:workerRequests:warn". */
|
|
14
|
+
id: string;
|
|
15
|
+
kind: AlertKind;
|
|
16
|
+
provider: string;
|
|
17
|
+
key?: string;
|
|
18
|
+
message: string;
|
|
19
|
+
}
|
|
20
|
+
/** Flatten snapshots into records to append to the usage log. */
|
|
21
|
+
export declare function toRecords(snapshots: Readonly<Record<string, QuotaSnapshot>>): UsageRecord[];
|
|
22
|
+
/**
|
|
23
|
+
* What deserves a heads-up now: a quota at or over the warning line, or one whose
|
|
24
|
+
* trend runs out before it resets. Pure — the caller de-duplicates and sends.
|
|
25
|
+
*/
|
|
26
|
+
export declare function evaluateAlerts(snapshots: Readonly<Record<string, QuotaSnapshot>>, history: readonly UsageRecord[], opts: {
|
|
27
|
+
warnAt: number;
|
|
28
|
+
now: Date;
|
|
29
|
+
displayName?: (provider: string) => string;
|
|
30
|
+
}): Alert[];
|
|
31
|
+
/** Drop alerts sent within `quietHours`; returns what to send and the updated sent-at map. */
|
|
32
|
+
export declare function dedupeAlerts(alerts: readonly Alert[], sent: Readonly<Record<string, string>>, now: Date, quietHours?: number): {
|
|
33
|
+
toSend: Alert[];
|
|
34
|
+
sent: Record<string, string>;
|
|
35
|
+
};
|
package/dist/alerts.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { forecastExhaustion } from "./forecast.js";
|
|
2
|
+
/** Days of history a forecast looks at for quotas that never reset (storage). */
|
|
3
|
+
const NO_RESET_WINDOW_DAYS = 7;
|
|
4
|
+
const pct = (r) => `${Math.round(r * 100)}%`;
|
|
5
|
+
const num = (n) => (Number.isInteger(n) ? n.toLocaleString("en-US") : n.toLocaleString("en-US", { maximumFractionDigits: 2 }));
|
|
6
|
+
const utc = (iso) => `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
|
|
7
|
+
/** Flatten snapshots into records to append to the usage log. */
|
|
8
|
+
export function toRecords(snapshots) {
|
|
9
|
+
return Object.values(snapshots).flatMap((s) => s.usages.map((u) => ({ at: s.takenAt, provider: s.provider, key: u.key, used: u.used, limit: u.limit, ...(u.resetsAt ? { resetsAt: u.resetsAt } : {}) })));
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* What deserves a heads-up now: a quota at or over the warning line, or one whose
|
|
13
|
+
* trend runs out before it resets. Pure — the caller de-duplicates and sends.
|
|
14
|
+
*/
|
|
15
|
+
export function evaluateAlerts(snapshots, history, opts) {
|
|
16
|
+
const name = opts.displayName ?? ((p) => p);
|
|
17
|
+
const alerts = [];
|
|
18
|
+
for (const snap of Object.values(snapshots)) {
|
|
19
|
+
for (const u of snap.usages) {
|
|
20
|
+
if (u.limit <= 0)
|
|
21
|
+
continue;
|
|
22
|
+
const ratio = u.used / u.limit;
|
|
23
|
+
const label = `${name(snap.provider)} · ${u.key}`;
|
|
24
|
+
const base = `${snap.provider}:${u.key}`;
|
|
25
|
+
const amount = `${num(u.used)} / ${num(u.limit)}`;
|
|
26
|
+
if (ratio >= 1) {
|
|
27
|
+
alerts.push({ id: `${base}:over`, kind: "over", provider: snap.provider, key: u.key, message: `${label} is at its free-tier limit (${amount}).` });
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (ratio >= opts.warnAt) {
|
|
31
|
+
alerts.push({ id: `${base}:warn`, kind: "warn", provider: snap.provider, key: u.key, message: `${label} is at ${pct(ratio)} (${amount}).` });
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
// Same period only: samples from before the last reset would bend the trend.
|
|
35
|
+
const windowStart = u.resetsAt ? undefined : opts.now.getTime() - NO_RESET_WINDOW_DAYS * 86_400_000;
|
|
36
|
+
const samples = history
|
|
37
|
+
.filter((h) => h.provider === snap.provider && h.key === u.key)
|
|
38
|
+
.filter((h) => (u.resetsAt ? h.resetsAt === u.resetsAt : Date.parse(h.at) >= windowStart))
|
|
39
|
+
.map((h) => ({ at: h.at, used: h.used }));
|
|
40
|
+
samples.push({ at: snap.takenAt, used: u.used });
|
|
41
|
+
const f = forecastExhaustion(samples, u.limit, u.resetsAt);
|
|
42
|
+
if (f.exhaustsAt && f.exhaustsBeforeReset) {
|
|
43
|
+
const until = u.resetsAt ? `, before the ${utc(u.resetsAt)} reset` : "";
|
|
44
|
+
alerts.push({
|
|
45
|
+
id: `${base}:forecast`,
|
|
46
|
+
kind: "forecast",
|
|
47
|
+
provider: snap.provider,
|
|
48
|
+
key: u.key,
|
|
49
|
+
message: `${label} is at ${pct(ratio)} and on track to run out around ${utc(f.exhaustsAt)}${until}.`,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
for (const w of snap.warnings ?? []) {
|
|
54
|
+
alerts.push({ id: `${snap.provider}:note:${w}`, kind: "note", provider: snap.provider, message: `${name(snap.provider)} · ${w}` });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return alerts;
|
|
58
|
+
}
|
|
59
|
+
/** Drop alerts sent within `quietHours`; returns what to send and the updated sent-at map. */
|
|
60
|
+
export function dedupeAlerts(alerts, sent, now, quietHours = 6) {
|
|
61
|
+
const next = {};
|
|
62
|
+
const cutoff = now.getTime() - quietHours * 3_600_000;
|
|
63
|
+
// Keep only entries still inside the quiet window, so a cleared alert can fire again later.
|
|
64
|
+
for (const [id, at] of Object.entries(sent))
|
|
65
|
+
if (Date.parse(at) >= cutoff)
|
|
66
|
+
next[id] = at;
|
|
67
|
+
const toSend = alerts.filter((a) => !(a.id in next));
|
|
68
|
+
for (const a of toSend)
|
|
69
|
+
next[a.id] = now.toISOString();
|
|
70
|
+
return { toSend, sent: next };
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=alerts.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { AccountIdentity, AdapterMeta, RelocationRecord } from "./types.js";
|
|
2
|
+
/** Days a component may not return to a provider it left. */
|
|
3
|
+
export declare const PING_PONG_DAYS = 30;
|
|
4
|
+
/** Days after which a ToS review is considered stale. */
|
|
5
|
+
export declare const TOS_REVIEW_STALE_DAYS = 90;
|
|
6
|
+
export declare class ComplianceError extends Error {
|
|
7
|
+
readonly code: "one-account" | "commercial" | "ping-pong";
|
|
8
|
+
constructor(code: "one-account" | "commercial" | "ping-pong", message: string);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Hard guard: one account per provider. Registering a key that belongs to a
|
|
12
|
+
* different account on an already-registered provider is refused — FreeWeave
|
|
13
|
+
* never multiplies a provider's free tier across accounts.
|
|
14
|
+
*
|
|
15
|
+
* Returns the updated provider → accountId map.
|
|
16
|
+
*/
|
|
17
|
+
export declare function registerAccount(accounts: Readonly<Record<string, string>>, identity: AccountIdentity): Record<string, string>;
|
|
18
|
+
/** Is this provider allowed for the stack's usage type? */
|
|
19
|
+
export declare function commercialCheck(meta: AdapterMeta, usage: "personal" | "commercial"): string | null;
|
|
20
|
+
/**
|
|
21
|
+
* Ping-pong guard: a component that left a provider cannot go back to it
|
|
22
|
+
* within PING_PONG_DAYS. Returns a reason string when blocked.
|
|
23
|
+
*/
|
|
24
|
+
export declare function pingPongCheck(component: string, provider: string, history: readonly RelocationRecord[], now: Date): string | null;
|
|
25
|
+
/** May the planner move this component off the provider without a human? */
|
|
26
|
+
export declare function autoRelocationAllowed(meta: AdapterMeta, layer: string): boolean;
|
|
27
|
+
/** Problems `freeweave doctor` should report for an adapter's ToS metadata. */
|
|
28
|
+
export declare function tosReviewIssues(meta: AdapterMeta, now: Date): string[];
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** Days a component may not return to a provider it left. */
|
|
2
|
+
export const PING_PONG_DAYS = 30;
|
|
3
|
+
/** Days after which a ToS review is considered stale. */
|
|
4
|
+
export const TOS_REVIEW_STALE_DAYS = 90;
|
|
5
|
+
export class ComplianceError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.name = "ComplianceError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Hard guard: one account per provider. Registering a key that belongs to a
|
|
15
|
+
* different account on an already-registered provider is refused — FreeWeave
|
|
16
|
+
* never multiplies a provider's free tier across accounts.
|
|
17
|
+
*
|
|
18
|
+
* Returns the updated provider → accountId map.
|
|
19
|
+
*/
|
|
20
|
+
export function registerAccount(accounts, identity) {
|
|
21
|
+
const existing = accounts[identity.provider];
|
|
22
|
+
if (existing !== undefined && existing !== identity.accountId) {
|
|
23
|
+
throw new ComplianceError("one-account", `A ${identity.provider} key for account "${existing}" is already registered. ` +
|
|
24
|
+
`FreeWeave allows one account per provider; remove the old key before adding another account.`);
|
|
25
|
+
}
|
|
26
|
+
return { ...accounts, [identity.provider]: identity.accountId };
|
|
27
|
+
}
|
|
28
|
+
/** Is this provider allowed for the stack's usage type? */
|
|
29
|
+
export function commercialCheck(meta, usage) {
|
|
30
|
+
if (usage === "commercial" && !meta.tos.commercialAllowed) {
|
|
31
|
+
return meta.tos.reviewedAt
|
|
32
|
+
? `${meta.displayName}'s free plan does not allow commercial use`
|
|
33
|
+
: `${meta.displayName}'s terms are not reviewed yet; treated as non-commercial`;
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Ping-pong guard: a component that left a provider cannot go back to it
|
|
39
|
+
* within PING_PONG_DAYS. Returns a reason string when blocked.
|
|
40
|
+
*/
|
|
41
|
+
export function pingPongCheck(component, provider, history, now) {
|
|
42
|
+
const windowMs = PING_PONG_DAYS * 24 * 60 * 60 * 1000;
|
|
43
|
+
const left = history.find((h) => h.component === component && h.from === provider && now.getTime() - Date.parse(h.at) < windowMs);
|
|
44
|
+
return left ? `left ${provider} on ${left.at.slice(0, 10)}; cannot return within ${PING_PONG_DAYS} days` : null;
|
|
45
|
+
}
|
|
46
|
+
/** May the planner move this component off the provider without a human? */
|
|
47
|
+
export function autoRelocationAllowed(meta, layer) {
|
|
48
|
+
const stateless = layer === "frontend" || layer === "backend";
|
|
49
|
+
return stateless && !meta.tos.intentClause;
|
|
50
|
+
}
|
|
51
|
+
/** Problems `freeweave doctor` should report for an adapter's ToS metadata. */
|
|
52
|
+
export function tosReviewIssues(meta, now) {
|
|
53
|
+
const issues = [];
|
|
54
|
+
if (!meta.tos.reviewedAt) {
|
|
55
|
+
issues.push(`${meta.displayName}: terms never reviewed (${meta.tos.url})`);
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
const ageDays = (now.getTime() - Date.parse(meta.tos.reviewedAt)) / 86_400_000;
|
|
59
|
+
if (ageDays > TOS_REVIEW_STALE_DAYS) {
|
|
60
|
+
issues.push(`${meta.displayName}: terms last reviewed ${Math.floor(ageDays)} days ago (${meta.tos.url})`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!meta.limitsVerified) {
|
|
64
|
+
issues.push(`${meta.displayName}: free-tier limits are unverified placeholders`);
|
|
65
|
+
}
|
|
66
|
+
return issues;
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=compliance.js.map
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { Placement } from "./planner.js";
|
|
2
|
+
import type { Stack } from "./stack.js";
|
|
3
|
+
import type { Credential, DeployResult, Layer, Outputs, ProviderAdapter } from "./types.js";
|
|
4
|
+
/** What `up` remembers about a deployed component (no secrets). */
|
|
5
|
+
export interface ResourceRecord {
|
|
6
|
+
provider: string;
|
|
7
|
+
layer: Layer;
|
|
8
|
+
resourceId: string;
|
|
9
|
+
outputs: Outputs;
|
|
10
|
+
at: string;
|
|
11
|
+
}
|
|
12
|
+
export type ActionKind = "create" | "update" | "reuse" | "skip-unplaced" | "skip-unsupported" | "skip-dependency" | "blocked-moved";
|
|
13
|
+
export interface Action {
|
|
14
|
+
component: string;
|
|
15
|
+
layer: Layer;
|
|
16
|
+
provider: string | null;
|
|
17
|
+
kind: ActionKind;
|
|
18
|
+
reason?: string;
|
|
19
|
+
}
|
|
20
|
+
/** `<project>-<component>`, lower-case, only [a-z0-9-], at most 63 characters. */
|
|
21
|
+
export declare function resourceNameFor(project: string, component: string): string;
|
|
22
|
+
/** Dry run: what `up` would do for each component, in deploy order. Pure. */
|
|
23
|
+
export declare function previewActions(stack: Stack, placements: readonly Placement[], adapters: readonly ProviderAdapter[], existing: Readonly<Record<string, ResourceRecord>>): Action[];
|
|
24
|
+
export interface ApplyOptions {
|
|
25
|
+
stack: Stack;
|
|
26
|
+
placements: readonly Placement[];
|
|
27
|
+
adapters: readonly ProviderAdapter[];
|
|
28
|
+
/** Credential (token + accountId) for every provider in the plan. */
|
|
29
|
+
credentialFor(provider: string): Credential;
|
|
30
|
+
existing: Readonly<Record<string, ResourceRecord>>;
|
|
31
|
+
/** Secret outputs of an already-deployed component (from the keychain). */
|
|
32
|
+
loadSecrets(component: string): Promise<Outputs>;
|
|
33
|
+
/** Persist one component right after it deploys, so a later failure loses nothing. */
|
|
34
|
+
onDeployed(component: string, record: ResourceRecord, secrets: Outputs): Promise<void>;
|
|
35
|
+
baseDir: string;
|
|
36
|
+
readFile(path: string): Promise<Uint8Array>;
|
|
37
|
+
listFiles(dir: string): Promise<string[]>;
|
|
38
|
+
bundle?(entry: string): Promise<{
|
|
39
|
+
code: Uint8Array;
|
|
40
|
+
nodeBuiltins: boolean;
|
|
41
|
+
}>;
|
|
42
|
+
log(message: string): void;
|
|
43
|
+
now?: () => Date;
|
|
44
|
+
}
|
|
45
|
+
export interface ApplyResult {
|
|
46
|
+
component: string;
|
|
47
|
+
kind: ActionKind;
|
|
48
|
+
status: "done" | "skipped" | "failed";
|
|
49
|
+
detail?: string;
|
|
50
|
+
outputs?: Outputs;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Deploy in dependency order. Stateful resources that already exist are reused,
|
|
54
|
+
* never recreated. Stops at the first failure; everything before it is persisted.
|
|
55
|
+
*/
|
|
56
|
+
export declare function apply(opts: ApplyOptions): Promise<{
|
|
57
|
+
ok: boolean;
|
|
58
|
+
results: ApplyResult[];
|
|
59
|
+
}>;
|
|
60
|
+
/** What deploying one component needs, shared by `up` and `relocate`. */
|
|
61
|
+
export type DeployContext = Pick<ApplyOptions, "stack" | "adapters" | "credentialFor" | "baseDir" | "readFile" | "listFiles" | "bundle" | "log">;
|
|
62
|
+
/**
|
|
63
|
+
* Deploy one component on `provider`, loading what it references from `records`
|
|
64
|
+
* and `loadSecrets`. Used by relocate to create a component elsewhere and to
|
|
65
|
+
* redeploy the components that read it.
|
|
66
|
+
*/
|
|
67
|
+
export declare function deployComponent(ctx: DeployContext, name: string, provider: string, records: Readonly<Record<string, ResourceRecord>>, loadSecrets: (component: string) => Promise<Outputs>): Promise<DeployResult>;
|
|
68
|
+
export interface DestroyTarget {
|
|
69
|
+
component: string;
|
|
70
|
+
record: ResourceRecord;
|
|
71
|
+
/** Holds data: a database or a bucket. Deleting it loses that data. */
|
|
72
|
+
stateful: boolean;
|
|
73
|
+
/** Deployed components that stay and still reference this one. */
|
|
74
|
+
dependents: string[];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* What `down` would delete, dependents before what they depend on.
|
|
78
|
+
* Components no longer in stack.yaml (orphans) go first. Pure.
|
|
79
|
+
*/
|
|
80
|
+
export declare function planDestroy(stack: Stack, resources: Readonly<Record<string, ResourceRecord>>, options?: {
|
|
81
|
+
only?: readonly string[];
|
|
82
|
+
keepData?: boolean;
|
|
83
|
+
}): {
|
|
84
|
+
targets: DestroyTarget[];
|
|
85
|
+
skipped: {
|
|
86
|
+
component: string;
|
|
87
|
+
reason: string;
|
|
88
|
+
}[];
|
|
89
|
+
};
|
package/dist/executor.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { dependencies, deployOrder, referencedOutputs, resolveEnv } from "./wiring.js";
|
|
2
|
+
const STATEFUL = new Set(["database", "storage"]);
|
|
3
|
+
/** `<project>-<component>`, lower-case, only [a-z0-9-], at most 63 characters. */
|
|
4
|
+
export function resourceNameFor(project, component) {
|
|
5
|
+
return `${project}-${component}`
|
|
6
|
+
.toLowerCase()
|
|
7
|
+
.replace(/[^a-z0-9-]/g, "-")
|
|
8
|
+
.replace(/-+/g, "-")
|
|
9
|
+
.replace(/^-|-$/g, "")
|
|
10
|
+
.slice(0, 63)
|
|
11
|
+
.replace(/-$/, "");
|
|
12
|
+
}
|
|
13
|
+
/** Dry run: what `up` would do for each component, in deploy order. Pure. */
|
|
14
|
+
export function previewActions(stack, placements, adapters, existing) {
|
|
15
|
+
const deps = dependencies(stack);
|
|
16
|
+
const byComponent = new Map(placements.map((p) => [p.component, p]));
|
|
17
|
+
const actions = new Map();
|
|
18
|
+
for (const name of deployOrder(stack)) {
|
|
19
|
+
const layer = stack.components[name].layer;
|
|
20
|
+
const placement = byComponent.get(name);
|
|
21
|
+
const provider = placement?.provider ?? null;
|
|
22
|
+
const record = existing[name];
|
|
23
|
+
const blockedDep = (deps[name] ?? []).find((d) => actions.get(d)?.kind.startsWith("skip") || actions.get(d)?.kind === "blocked-moved");
|
|
24
|
+
let action;
|
|
25
|
+
if (!placement) {
|
|
26
|
+
action = { component: name, layer, provider, kind: "skip-unplaced", reason: "no provider fits (see `freeweave plan -v`)" };
|
|
27
|
+
}
|
|
28
|
+
else if (blockedDep) {
|
|
29
|
+
action = { component: name, layer, provider, kind: "skip-dependency", reason: `needs ${blockedDep}` };
|
|
30
|
+
}
|
|
31
|
+
else if (record && record.provider !== placement.provider) {
|
|
32
|
+
action = {
|
|
33
|
+
component: name,
|
|
34
|
+
layer,
|
|
35
|
+
provider,
|
|
36
|
+
kind: "blocked-moved",
|
|
37
|
+
reason: `already on ${record.provider}; to move it: freeweave relocate ${name} --to ${placement.provider}`,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
else if (record && STATEFUL.has(layer)) {
|
|
41
|
+
action = { component: name, layer, provider, kind: "reuse" };
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
const adapter = adapters.find((a) => a.meta.id === placement.provider);
|
|
45
|
+
if (!adapter || !adapter.implemented.deploy.includes(layer)) {
|
|
46
|
+
action = {
|
|
47
|
+
component: name,
|
|
48
|
+
layer,
|
|
49
|
+
provider,
|
|
50
|
+
kind: "skip-unsupported",
|
|
51
|
+
reason: `${adapter?.meta.displayName ?? placement.provider} cannot deploy ${layer} yet`,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
action = { component: name, layer, provider, kind: record ? "update" : "create" };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
actions.set(name, action);
|
|
59
|
+
}
|
|
60
|
+
return [...actions.values()];
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Deploy in dependency order. Stateful resources that already exist are reused,
|
|
64
|
+
* never recreated. Stops at the first failure; everything before it is persisted.
|
|
65
|
+
*/
|
|
66
|
+
export async function apply(opts) {
|
|
67
|
+
const now = opts.now ?? (() => new Date());
|
|
68
|
+
const actions = previewActions(opts.stack, opts.placements, opts.adapters, opts.existing);
|
|
69
|
+
const values = {}; // outputs + secrets, for wiring
|
|
70
|
+
const secretKeys = {};
|
|
71
|
+
const records = { ...opts.existing };
|
|
72
|
+
const results = [];
|
|
73
|
+
let failed = false;
|
|
74
|
+
for (const action of actions) {
|
|
75
|
+
const name = action.component;
|
|
76
|
+
if (failed) {
|
|
77
|
+
results.push({ component: name, kind: action.kind, status: "skipped", detail: "stopped after an earlier failure" });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (action.kind.startsWith("skip") || action.kind === "blocked-moved") {
|
|
81
|
+
results.push({ component: name, kind: action.kind, status: "skipped", detail: action.reason });
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (action.kind === "reuse") {
|
|
85
|
+
const record = opts.existing[name];
|
|
86
|
+
const secrets = await opts.loadSecrets(name);
|
|
87
|
+
values[name] = { ...record.outputs, ...secrets };
|
|
88
|
+
secretKeys[name] = new Set(Object.keys(secrets));
|
|
89
|
+
results.push({ component: name, kind: "reuse", status: "done", outputs: record.outputs });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const spec = opts.stack.components[name];
|
|
93
|
+
const provider = action.provider;
|
|
94
|
+
const adapter = opts.adapters.find((a) => a.meta.id === provider);
|
|
95
|
+
try {
|
|
96
|
+
opts.log(`${action.kind === "create" ? "Creating" : "Updating"} ${name} on ${adapter.meta.displayName}…`);
|
|
97
|
+
const result = await deployWith(opts, name, provider, values, secretKeys, records);
|
|
98
|
+
const record = { provider, layer: spec.layer, resourceId: result.resourceId, outputs: result.outputs, at: now().toISOString() };
|
|
99
|
+
await opts.onDeployed(name, record, result.secrets);
|
|
100
|
+
records[name] = record;
|
|
101
|
+
values[name] = { ...result.outputs, ...result.secrets };
|
|
102
|
+
secretKeys[name] = new Set(Object.keys(result.secrets));
|
|
103
|
+
results.push({ component: name, kind: action.kind, status: "done", outputs: result.outputs });
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
failed = true;
|
|
107
|
+
results.push({ component: name, kind: action.kind, status: "failed", detail: e instanceof Error ? e.message : String(e) });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { ok: !failed, results };
|
|
111
|
+
}
|
|
112
|
+
/** Deploy one component on `provider`, env wired from already-known outputs + secrets. */
|
|
113
|
+
async function deployWith(ctx, name, provider, values, secretKeys, records) {
|
|
114
|
+
const spec = ctx.stack.components[name];
|
|
115
|
+
const adapter = ctx.adapters.find((a) => a.meta.id === provider);
|
|
116
|
+
if (!adapter)
|
|
117
|
+
throw new Error(`no adapter for ${provider}`);
|
|
118
|
+
const env = resolveEnv(spec.env, values);
|
|
119
|
+
const secretEnvKeys = Object.entries(spec.env)
|
|
120
|
+
.filter(([, raw]) => referencedOutputs(raw).some((r) => secretKeys[r.component]?.has(r.output)))
|
|
121
|
+
.map(([k]) => k);
|
|
122
|
+
const wired = (dependencies(ctx.stack)[name] ?? []).map((d) => {
|
|
123
|
+
const r = records[d];
|
|
124
|
+
if (!r)
|
|
125
|
+
throw new Error(`${name} needs ${d}, which is not deployed`);
|
|
126
|
+
const secrets = Object.fromEntries([...(secretKeys[d] ?? [])].flatMap((k) => (values[d]?.[k] === undefined ? [] : [[k, values[d][k]]])));
|
|
127
|
+
return { component: d, layer: r.layer, provider: r.provider, resourceId: r.resourceId, outputs: r.outputs, secrets };
|
|
128
|
+
});
|
|
129
|
+
return adapter.deploy({
|
|
130
|
+
project: ctx.stack.project,
|
|
131
|
+
component: name,
|
|
132
|
+
spec,
|
|
133
|
+
resourceName: resourceNameFor(ctx.stack.project, name),
|
|
134
|
+
env,
|
|
135
|
+
secretEnvKeys,
|
|
136
|
+
dependencies: wired,
|
|
137
|
+
regionHint: ctx.stack.regionHint,
|
|
138
|
+
baseDir: ctx.baseDir,
|
|
139
|
+
readFile: ctx.readFile,
|
|
140
|
+
listFiles: ctx.listFiles,
|
|
141
|
+
bundle: ctx.bundle,
|
|
142
|
+
log: (m) => ctx.log(` ${name}: ${m}`),
|
|
143
|
+
}, ctx.credentialFor(provider));
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Deploy one component on `provider`, loading what it references from `records`
|
|
147
|
+
* and `loadSecrets`. Used by relocate to create a component elsewhere and to
|
|
148
|
+
* redeploy the components that read it.
|
|
149
|
+
*/
|
|
150
|
+
export async function deployComponent(ctx, name, provider, records, loadSecrets) {
|
|
151
|
+
const values = {};
|
|
152
|
+
const secretKeys = {};
|
|
153
|
+
for (const d of dependencies(ctx.stack)[name] ?? []) {
|
|
154
|
+
const r = records[d];
|
|
155
|
+
if (!r)
|
|
156
|
+
throw new Error(`${name} needs ${d}, which is not deployed`);
|
|
157
|
+
const secrets = await loadSecrets(d);
|
|
158
|
+
values[d] = { ...r.outputs, ...secrets };
|
|
159
|
+
secretKeys[d] = new Set(Object.keys(secrets));
|
|
160
|
+
}
|
|
161
|
+
return deployWith(ctx, name, provider, values, secretKeys, records);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* What `down` would delete, dependents before what they depend on.
|
|
165
|
+
* Components no longer in stack.yaml (orphans) go first. Pure.
|
|
166
|
+
*/
|
|
167
|
+
export function planDestroy(stack, resources, options = {}) {
|
|
168
|
+
const skipped = [];
|
|
169
|
+
const wanted = new Set();
|
|
170
|
+
for (const name of options.only ?? Object.keys(resources)) {
|
|
171
|
+
const record = resources[name];
|
|
172
|
+
if (!record)
|
|
173
|
+
skipped.push({ component: name, reason: "not deployed" });
|
|
174
|
+
else if (options.keepData && STATEFUL.has(record.layer))
|
|
175
|
+
skipped.push({ component: name, reason: "kept (--keep-data)" });
|
|
176
|
+
else
|
|
177
|
+
wanted.add(name);
|
|
178
|
+
}
|
|
179
|
+
const inStack = (n) => n in stack.components;
|
|
180
|
+
const deps = dependencies(stack);
|
|
181
|
+
const order = [
|
|
182
|
+
...[...wanted].filter((n) => !inStack(n)).sort(),
|
|
183
|
+
...deployOrder(stack).reverse().filter((n) => wanted.has(n)),
|
|
184
|
+
];
|
|
185
|
+
const targets = order.map((name) => {
|
|
186
|
+
const record = resources[name];
|
|
187
|
+
const dependents = Object.keys(resources).filter((other) => !wanted.has(other) && (deps[other] ?? []).includes(name));
|
|
188
|
+
return { component: name, record, stateful: STATEFUL.has(record.layer), dependents };
|
|
189
|
+
});
|
|
190
|
+
return { targets, skipped };
|
|
191
|
+
}
|
|
192
|
+
//# sourceMappingURL=executor.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface UsageSample {
|
|
2
|
+
at: string;
|
|
3
|
+
used: number;
|
|
4
|
+
}
|
|
5
|
+
export interface Forecast {
|
|
6
|
+
/** Usage now as a share of the limit, 0..1+. */
|
|
7
|
+
ratio: number;
|
|
8
|
+
/** Least-squares growth per day. */
|
|
9
|
+
perDay: number;
|
|
10
|
+
/** When usage reaches the limit at the current trend, or null if it won't before reset. */
|
|
11
|
+
exhaustsAt: string | null;
|
|
12
|
+
/** True when the limit is hit before the period resets. */
|
|
13
|
+
exhaustsBeforeReset: boolean;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Linear trend over recent samples → will this quota run out before it resets?
|
|
17
|
+
* Needs at least two samples at different times to estimate a trend.
|
|
18
|
+
*/
|
|
19
|
+
export declare function forecastExhaustion(samples: readonly UsageSample[], limit: number, resetsAt?: string): Forecast;
|
package/dist/forecast.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Linear trend over recent samples → will this quota run out before it resets?
|
|
3
|
+
* Needs at least two samples at different times to estimate a trend.
|
|
4
|
+
*/
|
|
5
|
+
export function forecastExhaustion(samples, limit, resetsAt) {
|
|
6
|
+
const sorted = [...samples].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
|
|
7
|
+
const last = sorted.at(-1);
|
|
8
|
+
const ratio = last && limit > 0 ? last.used / limit : 0;
|
|
9
|
+
if (!last || sorted.length < 2 || limit <= 0) {
|
|
10
|
+
return { ratio, perDay: 0, exhaustsAt: null, exhaustsBeforeReset: ratio >= 1 };
|
|
11
|
+
}
|
|
12
|
+
const t0 = Date.parse(sorted[0].at);
|
|
13
|
+
const xs = sorted.map((s) => (Date.parse(s.at) - t0) / 86_400_000);
|
|
14
|
+
const ys = sorted.map((s) => s.used);
|
|
15
|
+
const n = xs.length;
|
|
16
|
+
const mx = xs.reduce((a, b) => a + b, 0) / n;
|
|
17
|
+
const my = ys.reduce((a, b) => a + b, 0) / n;
|
|
18
|
+
let num = 0;
|
|
19
|
+
let den = 0;
|
|
20
|
+
for (let i = 0; i < n; i++) {
|
|
21
|
+
num += (xs[i] - mx) * (ys[i] - my);
|
|
22
|
+
den += (xs[i] - mx) ** 2;
|
|
23
|
+
}
|
|
24
|
+
const perDay = den === 0 ? 0 : num / den;
|
|
25
|
+
if (last.used >= limit) {
|
|
26
|
+
return { ratio, perDay, exhaustsAt: last.at, exhaustsBeforeReset: true };
|
|
27
|
+
}
|
|
28
|
+
if (perDay <= 0) {
|
|
29
|
+
return { ratio, perDay, exhaustsAt: null, exhaustsBeforeReset: false };
|
|
30
|
+
}
|
|
31
|
+
const daysLeft = (limit - last.used) / perDay;
|
|
32
|
+
const exhaustsMs = Date.parse(last.at) + daysLeft * 86_400_000;
|
|
33
|
+
const exhaustsAt = new Date(exhaustsMs).toISOString();
|
|
34
|
+
const exhaustsBeforeReset = resetsAt ? exhaustsMs < Date.parse(resetsAt) : true;
|
|
35
|
+
return { ratio, perDay, exhaustsAt, exhaustsBeforeReset };
|
|
36
|
+
}
|
|
37
|
+
//# sourceMappingURL=forecast.js.map
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Tiny fetch abstraction shared by adapters. Inject a fake in tests. */
|
|
2
|
+
export interface HttpResponse {
|
|
3
|
+
ok: boolean;
|
|
4
|
+
status: number;
|
|
5
|
+
json(): Promise<unknown>;
|
|
6
|
+
headers?: {
|
|
7
|
+
get(name: string): string | null;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
export type FetchLike = (url: string, init: {
|
|
11
|
+
method: string;
|
|
12
|
+
headers: Record<string, string>;
|
|
13
|
+
body?: string | FormData | Uint8Array;
|
|
14
|
+
}) => Promise<HttpResponse>;
|
|
15
|
+
export declare class ProviderApiError extends Error {
|
|
16
|
+
readonly provider: string;
|
|
17
|
+
readonly status: number;
|
|
18
|
+
readonly detail: string;
|
|
19
|
+
constructor(provider: string, status: number, detail: string);
|
|
20
|
+
}
|
|
21
|
+
export interface JsonClientOptions {
|
|
22
|
+
provider: string;
|
|
23
|
+
baseUrl: string;
|
|
24
|
+
token: string;
|
|
25
|
+
fetch?: FetchLike;
|
|
26
|
+
}
|
|
27
|
+
/** Bearer-token JSON client. Throws ProviderApiError on non-2xx. */
|
|
28
|
+
export declare function jsonClient(opts: JsonClientOptions): {
|
|
29
|
+
get: <T>(path: string) => Promise<{
|
|
30
|
+
data: T;
|
|
31
|
+
header(name: string): string | null;
|
|
32
|
+
}>;
|
|
33
|
+
post: <T>(path: string, body: unknown) => Promise<{
|
|
34
|
+
data: T;
|
|
35
|
+
header(name: string): string | null;
|
|
36
|
+
}>;
|
|
37
|
+
put: <T>(path: string, body: unknown) => Promise<{
|
|
38
|
+
data: T;
|
|
39
|
+
header(name: string): string | null;
|
|
40
|
+
}>;
|
|
41
|
+
del: <T>(path: string) => Promise<{
|
|
42
|
+
data: T;
|
|
43
|
+
header(name: string): string | null;
|
|
44
|
+
}>;
|
|
45
|
+
};
|