Repository navigation
Expand file tree
/
Copy pathrelease-check.ts
More file actions
213 lines (198 loc) · 6.36 KB
/
Copy pathrelease-check.ts
File metadata and controls
213 lines (198 loc) · 6.36 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
import { randomUUID } from "node:crypto";
import type { DB } from "@db/index.js";
import { fail } from "@core/shared/errors.js";
import { comparePluginVersions } from "@smartdoca/plugin-contracts";
import { z } from "zod";
import { HOST_VERSION } from "../app/version.js";
import { OFFICIAL_PLUGIN_STORE_ORIGIN, readBounded } from "../plugins/store.js";
const settingsId = "software-release-check";
const intervalMs = 60 * 60 * 1000;
const numericVersion = /^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})/;
const stableVersion = z.string().regex(new RegExp(numericVersion.source + "$"));
const hostVersion = z
.string()
.max(80)
.regex(
new RegExp(
numericVersion.source +
"(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$",
),
);
const officialResponse = z.strictObject({
protocolVersion: z.literal(1),
latestVersion: stableVersion,
});
const stateSchema = z.strictObject({
enabled: z.boolean(),
deploymentId: z.uuidv4(),
lastAttemptAt: z.number().int().nonnegative().nullable(),
result: z.union([stableVersion, z.literal("unavailable"), z.null()]),
});
type State = z.infer<typeof stateSchema>;
type StoredState = { revision: number; config: State };
export type ReleaseCheckStatus = {
currentVersion: string;
enabled: boolean;
status: "disabled" | "waiting" | "unavailable" | "current" | "update";
update: { version: string; image: string; releaseUrl: string } | null;
};
export type ReleaseCheckOptions = {
fetch?: typeof fetch;
now?: () => number;
};
async function requestRelease(
fetcher: typeof fetch,
deploymentId: string,
signal: AbortSignal,
) {
const response = await fetcher(
new URL("/api/v1/doca/releases/check", OFFICIAL_PLUGIN_STORE_ORIGIN),
{
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
protocolVersion: 1,
currentVersion: hostVersion.parse(HOST_VERSION),
deploymentId,
}),
redirect: "error",
credentials: "omit",
signal: AbortSignal.any([signal, AbortSignal.timeout(5_000)]),
},
);
const contentType = response.headers
.get("content-type")
?.split(";")[0]
?.trim()
.toLowerCase();
if (response.status !== 200 || contentType !== "application/json") {
await response.body?.cancel();
throw new Error("Invalid Doca release check response");
}
const data = JSON.parse(
(await readBounded(response, 4 * 1024)).toString("utf8"),
);
return officialResponse.parse(data).latestVersion;
}
function status(config?: State): ReleaseCheckStatus {
const base = {
currentVersion: HOST_VERSION,
enabled: config?.enabled ?? true,
update: null,
};
if (!base.enabled) return { ...base, status: "disabled" };
const version = config?.result;
if (!version) return { ...base, status: "waiting" };
if (version === "unavailable") return { ...base, status: "unavailable" };
if (comparePluginVersions(version, HOST_VERSION) <= 0)
return { ...base, status: "current" };
return {
...base,
status: "update",
update: {
version,
image: `docker.io/smartdoca/doca:${version}`,
releaseUrl: `https://github.com/workhold/doca/releases/tag/v${version}`,
},
};
}
export function createReleaseChecker(
db: DB,
{ fetch: fetcher = fetch, now = Date.now }: ReleaseCheckOptions = {},
) {
let active: AbortController | undefined;
async function read(): Promise<StoredState | undefined> {
const row = await db
.selectFrom("account_settings")
.select(["config", "revision"])
.where("id", "=", settingsId)
.executeTakeFirst();
if (row)
return {
revision: row.revision,
config: stateSchema.parse(JSON.parse(row.config)),
};
}
async function initialize(): Promise<StoredState> {
const row = await read();
if (row) return row;
const config: State = {
enabled: true,
deploymentId: randomUUID(),
lastAttemptAt: null,
result: null,
};
await db
.insertInto("account_settings")
.values({ id: settingsId, config: JSON.stringify(config), revision: 1 })
.onConflict((oc) => oc.column("id").doNothing())
.execute();
const saved = await read();
if (!saved)
throw new Error("Doca release check settings could not be initialized");
return saved;
}
async function replace(revision: number, config: State) {
const changed = await db
.updateTable("account_settings")
.set({ config: JSON.stringify(config), revision: revision + 1 })
.where("id", "=", settingsId)
.where("revision", "=", revision)
.executeTakeFirst();
return Boolean(changed.numUpdatedRows);
}
return {
async status() {
return status((await read())?.config);
},
async setEnabled(enabled: boolean) {
for (let attempt = 0; attempt < 5; attempt++) {
const { revision, config } = await initialize();
const next =
config.enabled === enabled
? config
: { ...config, enabled, result: null };
if (next !== config && !(await replace(revision, next))) continue;
if (!enabled) active?.abort();
return status(next);
}
fail(409, "release_check_settings_changed");
},
async check() {
if (active) return;
const controller = new AbortController();
active = controller;
try {
const { revision, config } = await initialize();
const time = now();
if (
!config.enabled ||
controller.signal.aborted ||
(config.lastAttemptAt !== null &&
time - config.lastAttemptAt < intervalMs)
)
return;
// Claim the hourly slot before sending. This revision also guards the
// result against a later settings change on any server replica.
const claimed = { ...config, lastAttemptAt: time };
if (!(await replace(revision, claimed)) || controller.signal.aborted)
return;
const result = await requestRelease(
fetcher,
config.deploymentId,
controller.signal,
).catch(() => "unavailable" as const);
if (!controller.signal.aborted)
await replace(revision + 1, { ...claimed, result });
} finally {
active = undefined;
}
},
cancel() {
active?.abort();
},
};
}