Merge origin/main into local-fonts
This commit is contained in:
commit
cde9424ce3
47 changed files with 2005 additions and 234 deletions
|
|
@ -15,7 +15,7 @@ export function parseArgs(argv: string[], booleans: string[] = []): Args {
|
|||
const repeated = new Map<string, string[]>();
|
||||
const set = (k: string, v: string) => { flags.set(k, v); repeated.set(k, [...(repeated.get(k) ?? []), v]); };
|
||||
const _: string[] = [];
|
||||
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'include-drafts', ...booleans]);
|
||||
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'force-unlock', 'include-drafts', ...booleans]);
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i]!;
|
||||
if (!a.startsWith('--')) { _.push(a); continue; }
|
||||
|
|
|
|||
|
|
@ -129,7 +129,9 @@ export function normalizeKeywords(text: string, o: { name?: string; subtitle?: s
|
|||
return { text: kept.join(','), dropped };
|
||||
}
|
||||
|
||||
export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; limit: number; problems: string[] }
|
||||
/** `chars` is what the store counts: characters, except App Store keywords, which App Store Connect limits in UTF-8 bytes
|
||||
* (`unit` says which). */
|
||||
export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; unit: 'chars' | 'bytes'; limit: number; problems: string[] }
|
||||
|
||||
/** Limits and rules of one translated section. `source` = the source language's fields (identical text is flagged). */
|
||||
export function checkFields(store: 'apple' | 'play', f: Record<string, string | undefined>, source: Record<string, string | undefined> = {}, status?: TStatus): FieldCheck[] {
|
||||
|
|
@ -139,10 +141,11 @@ export function checkFields(store: 'apple' | 'play', f: Record<string, string |
|
|||
const v = f[k];
|
||||
if (v === undefined) continue;
|
||||
const limit = (FIELD_LIMITS[store] as Record<string, number>)[k]!;
|
||||
const c: FieldCheck = { store, field: k, chars: len(v), limit, problems: [] };
|
||||
if (len(v) > limit) c.problems.push(`${len(v)} > ${limit} characters`);
|
||||
if (store === 'apple' && k === 'keywords') {
|
||||
if (Buffer.byteLength(v) > limit) c.problems.push(`${Buffer.byteLength(v)} bytes > ${limit}`);
|
||||
const bytes = store === 'apple' && k === 'keywords';
|
||||
const n = bytes ? Buffer.byteLength(v, 'utf8') : len(v);
|
||||
const c: FieldCheck = { store, field: k, chars: n, unit: bytes ? 'bytes' : 'chars', limit, problems: [] };
|
||||
if (n > limit) c.problems.push(`${n} > ${limit} ${bytes ? 'bytes' : 'characters'}`);
|
||||
if (bytes) {
|
||||
if (/,\s|\s,/.test(v)) c.problems.push('spaces around commas');
|
||||
const words = v.split(',').map(w => w.trim().toLocaleLowerCase()).filter(Boolean);
|
||||
const dup = words.filter((w, i) => words.indexOf(w) !== i);
|
||||
|
|
|
|||
90
cli/lib/lock.ts
Normal file
90
cli/lib/lock.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
// One writer per app and store: a write command takes .storebound/locks/<store>-<app>.lock before it changes
|
||||
// anything, so two storebound runs (two terminals, an agent and a CI job, a flow and a hand run) never write to the
|
||||
// same app at once and race each other into duplicates. Dry runs and reads take no lock.
|
||||
// A lock whose process is gone (same machine) is taken over; a live one stops the run with who holds it. A lock
|
||||
// left by a crash on another machine (shared folder) stays until --force-unlock or 12 hours.
|
||||
import { hostname } from 'node:os';
|
||||
import { mkdirSync, openSync, readFileSync, rmSync, writeSync, closeSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { ShipConfig } from './config';
|
||||
import type { Args } from './args';
|
||||
|
||||
export interface LockInfo { pid: number; host: string; command: string; startedAt: string }
|
||||
const STALE_MS = 12 * 3600_000;
|
||||
|
||||
export const lockPath = (root: string, key: string): string => join(root, '.storebound', 'locks', `${key.replace(/[^A-Za-z0-9._-]+/g, '_')}.lock`);
|
||||
|
||||
function alive(pid: number): boolean {
|
||||
try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }
|
||||
}
|
||||
|
||||
/** Whether a lock may be taken over: its process is gone (same host) or it is older than 12 hours. Pure apart from
|
||||
* the process check. */
|
||||
export function staleLock(l: LockInfo | null, now = Date.now(), host = hostname(), isAlive = alive): boolean {
|
||||
if (!l) return true;
|
||||
if (now - Date.parse(l.startedAt) > STALE_MS) return true;
|
||||
return l.host === host && !isAlive(l.pid);
|
||||
}
|
||||
|
||||
const held = new Set<string>();
|
||||
let hooked = false;
|
||||
|
||||
/** Takes the lock `key` for `command` (`apple iap`); throws with the holder when another run has it. Released when the
|
||||
* process exits. `force` removes a lock first (--force-unlock). */
|
||||
export function acquireLock(root: string, key: string, command: string, o: { force?: boolean } = {}): () => void {
|
||||
const path = lockPath(root, key);
|
||||
mkdirSync(join(root, '.storebound', 'locks'), { recursive: true });
|
||||
if (o.force) rmSync(path, { force: true });
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
const fd = openSync(path, 'wx', 0o600);
|
||||
const info: LockInfo = { pid: process.pid, host: hostname(), command, startedAt: new Date().toISOString() };
|
||||
writeSync(fd, JSON.stringify(info) + '\n');
|
||||
closeSync(fd);
|
||||
break;
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== 'EEXIST' || attempt > 2) throw e;
|
||||
let cur: LockInfo | null = null;
|
||||
try { cur = JSON.parse(readFileSync(path, 'utf8')) as LockInfo; } catch { /* half written or unreadable: treat as stale */ }
|
||||
if (!staleLock(cur)) {
|
||||
throw new Error(`another storebound run is writing to ${key.replace(/^(\w+)-/, '$1 ')}: \`storebound ${cur!.command}\` (pid ${cur!.pid} on ${cur!.host}, since ${cur!.startedAt.slice(0, 16).replace('T', ' ')} UTC). `
|
||||
+ `Two writers at once can create duplicates, so this run stops. Wait for it to finish; if it is no longer running, re-run with --force-unlock (removes ${join('.storebound', 'locks', path.split('/').pop()!)}).`);
|
||||
}
|
||||
rmSync(path, { force: true });
|
||||
}
|
||||
}
|
||||
held.add(path);
|
||||
if (!hooked) { hooked = true; process.on('exit', () => { for (const p of held) rmSync(p, { force: true }); }); }
|
||||
return () => { rmSync(path, { force: true }); held.delete(path); };
|
||||
}
|
||||
|
||||
/** Read-only subcommands and flags: no lock. */
|
||||
const READ_SUBS = new Set(['status', 'list', 'devices', 'diff', 'export', 'pull', 'wait', 'options', 'coverage', 'report', 'campaigns', 'check', 'help']);
|
||||
|
||||
/**
|
||||
* The lock keys a command run needs: none for dry runs and reads, `apple-<bundle id>` / `play-<package>` for store
|
||||
* writes, both for `prices import`, `revenuecat-<project>` for revenuecat sync. Pure.
|
||||
*/
|
||||
export function lockKeys(command: string, args: Args, config: ShipConfig): string[] {
|
||||
// a dry run never writes, so it never waits for (or blocks) a writer
|
||||
const readOnly = args.has('dry');
|
||||
if (readOnly) return [];
|
||||
const sub = args._[0];
|
||||
const apple = config.apple?.bundleId ? [`apple-${config.apple.bundleId}`] : [];
|
||||
const play = config.play?.packageName ? [`play-${config.play.packageName}`] : [];
|
||||
if (command.startsWith('apple ')) {
|
||||
if (['apple status', 'apple next-build', 'apple build'].includes(command)) return [];
|
||||
if (command === 'apple listing' && sub === 'pull') return [];
|
||||
if (sub && READ_SUBS.has(sub)) return [];
|
||||
if (command === 'apple adhoc' && ['options', 'export'].includes(sub ?? '')) return [];
|
||||
return apple;
|
||||
}
|
||||
if (command.startsWith('play ')) {
|
||||
if (['play status', 'play next-version-code', 'play build'].includes(command)) return [];
|
||||
if (command === 'play listing' && sub === 'pull') return [];
|
||||
return play;
|
||||
}
|
||||
if (command === 'prices') return sub === 'import' && !args.has('json') ? [...apple, ...play] : [];
|
||||
if (command === 'revenuecat') return sub === 'sync' ? [`revenuecat-${config.apple?.bundleId ?? config.play?.packageName ?? 'project'}`] : [];
|
||||
return [];
|
||||
}
|
||||
152
cli/lib/upsert.ts
Normal file
152
cli/lib/upsert.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// Idempotent writes against the stores. Every create in storebound goes through here or follows the same rules
|
||||
// (docs/idempotency.md):
|
||||
// 1. Look the thing up by its stable key first (product id, locale, version string, display type, name) and update or
|
||||
// leave it instead of creating it again.
|
||||
// 2. Right before a create, look again with a fresh GET (findOrCreate), and ask a journal of recent creates
|
||||
// (.storebound/created.json) for an id the store's list may not show yet: a direct GET by id is not subject to the
|
||||
// minute of list lag right after a create.
|
||||
// 3. A create answered with 409 / ALREADY_EXISTS is "found": look it up and use it, never create again (createOnce).
|
||||
// 4. A create whose outcome is unknown (timeout, connection reset, 5xx on a POST) is never sent blindly again: look
|
||||
// first; only when the store itself refuses duplicates of that key (unique) is a second attempt safe (its 409
|
||||
// then finds the first one). Otherwise stop with a message: re-running reads the store and converges.
|
||||
// Retries of 429 / 5xx in the API clients are only for requests that end the same when sent twice (retrySafe).
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { log, warn } from './log';
|
||||
|
||||
/** A write whose outcome is unknown: it may or may not have been applied (timeout, connection reset, 5xx answer to a
|
||||
* POST). The API clients throw this instead of retrying such a request. */
|
||||
export class AmbiguousWriteError extends Error {
|
||||
readonly ambiguous = true;
|
||||
constructor(message: string, readonly status: number | null = null) { super(message); this.name = 'AmbiguousWriteError'; }
|
||||
}
|
||||
|
||||
export const isAmbiguous = (e: unknown): boolean => e instanceof AmbiguousWriteError || (e as { ambiguous?: boolean } | null)?.ambiguous === true;
|
||||
|
||||
/**
|
||||
* The store refused a create because the thing already exists: Google ALREADY_EXISTS / 409, App Store Connect 409 with
|
||||
* a "duplicate / already / unique / in use / taken" detail (Apple also answers 409 for plain validation errors, which
|
||||
* are not conflicts), RevenueCat 409. Pure.
|
||||
*/
|
||||
export function isConflict(e: unknown): boolean {
|
||||
const s = String((e as Error)?.message ?? e);
|
||||
if (/ALREADY_EXISTS/.test(s)) return true;
|
||||
if (!/(-> |: )409\b/.test(s)) return false;
|
||||
return /duplicate|already|unique|in use|taken|exists/i.test(s.replace(/^.*?409/, ''));
|
||||
}
|
||||
|
||||
/** POSTs that end the same when sent twice: relationship adds, Google custom actions that set a state, and the App
|
||||
* Store "create or replace" singletons (price schedules, availability). */
|
||||
const IDEMPOTENT_POST: RegExp[] = [
|
||||
/\/relationships\//,
|
||||
/:(validate|convertRegionPrices|batchUpdateStates|activate|deactivate|query|batchGet|reply)(\?|$)/,
|
||||
/\/edits(\?|$)/, // a new edit; an unused one expires on its own and changes nothing
|
||||
/\/dataSafety(\?|$)/,
|
||||
/^\/v1\/(inAppPurchasePriceSchedules|appPriceSchedules|inAppPurchaseAvailabilities|subscriptionAvailabilities)(\?|$)/,
|
||||
/^\/v2\/appAvailabilities(\?|$)/,
|
||||
];
|
||||
|
||||
/** Whether a request may be sent again after a 5xx or a network error. GET, HEAD, PUT, PATCH and DELETE set a state;
|
||||
* a POST creates unless its path is a known idempotent action. `path` may be a full URL. Pure. */
|
||||
export function retrySafe(method: string, path: string): boolean {
|
||||
const m = method.toUpperCase();
|
||||
if (m !== 'POST') return true;
|
||||
const p = path.replace(/^https:\/\/[^/]+/, '').replace(/^\/(androidpublisher|upload\/androidpublisher)\/v3\/applications\/[^/]+/, '');
|
||||
return IDEMPOTENT_POST.some(re => re.test(p));
|
||||
}
|
||||
|
||||
/** Waits between re-checks (STOREBOUND_UPSERT_WAIT_MS; the test preload sets 0). */
|
||||
export const upsertTiming = { waitMs: Number(process.env.STOREBOUND_UPSERT_WAIT_MS ?? 3000), tries: 4, sleep: (ms: number): Promise<void> => (ms > 0 ? Bun.sleep(ms) : Promise.resolve()) };
|
||||
|
||||
export interface CreateOnce<T> {
|
||||
/** what is being created, for log lines and errors: `in-app purchase com.example.gems` */
|
||||
what: string;
|
||||
/** the create request; returns the created thing */
|
||||
create: () => Promise<T>;
|
||||
/** a fresh lookup by the stable key (GET with a filter, or the list), null when it is not there */
|
||||
find: () => Promise<T | null | undefined>;
|
||||
/** the store refuses a second one with this key (409): a create may then be tried again after an unknown outcome */
|
||||
unique?: boolean;
|
||||
/** log tag */
|
||||
tag?: string;
|
||||
}
|
||||
|
||||
async function recheck<T>(o: CreateOnce<T>): Promise<T | null> {
|
||||
for (let i = 0; i < upsertTiming.tries; i++) {
|
||||
const v = await o.find();
|
||||
if (v) return v;
|
||||
if (i < upsertTiming.tries - 1) await upsertTiming.sleep(upsertTiming.waitMs * (i + 1));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** One create, never two: a conflict finds the existing one, an unknown outcome looks before (maybe) trying again. */
|
||||
export async function createOnce<T>(o: CreateOnce<T>, attempt = 1): Promise<{ value: T; created: boolean }> {
|
||||
try {
|
||||
return { value: await o.create(), created: true };
|
||||
} catch (e) {
|
||||
const msg = (e as Error).message;
|
||||
if (isConflict(e)) {
|
||||
const v = await recheck(o);
|
||||
if (v) { log(o.tag ?? 'upsert', `${o.what}: already exists, using it (not created again)`); return { value: v, created: false }; }
|
||||
throw new Error(`${o.what}: the store says it already exists but does not list it yet (its lists lag right after a create). Nothing was created twice; run the command again in a minute.\n${msg}`);
|
||||
}
|
||||
if (!isAmbiguous(e)) throw e;
|
||||
warn(o.tag ?? 'upsert', `${o.what}: no clear answer to the create (${msg.slice(0, 160)}); checking whether it exists before anything else`);
|
||||
const v = await recheck(o);
|
||||
if (v) { log(o.tag ?? 'upsert', `${o.what}: the create went through`); return { value: v, created: true }; }
|
||||
if (o.unique && attempt < 2) return createOnce(o, attempt + 1);
|
||||
throw new Error(`${o.what}: the create got no clear answer and the store does not list it (yet). It was not sent again, so nothing is created twice: run the command again in a minute (it reads the store first).\n${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- journal of creates
|
||||
|
||||
/** Creates of the last day, keyed by store + kind + stable key: { id, at }. Lives in .storebound/created.json. */
|
||||
type Journal = Record<string, { id: string; at: string }>;
|
||||
const JOURNAL_MS = 24 * 3600_000;
|
||||
const journalPath = (root: string): string => join(root, '.storebound', 'created.json');
|
||||
|
||||
export function readJournal(root: string, now = Date.now()): Journal {
|
||||
try {
|
||||
const j = JSON.parse(readFileSync(journalPath(root), 'utf8')) as Journal;
|
||||
return Object.fromEntries(Object.entries(j).filter(([, v]) => v && now - Date.parse(v.at) < JOURNAL_MS));
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
export function remember(root: string, key: string, id: string, now = new Date()): void {
|
||||
try {
|
||||
const j = readJournal(root, now.getTime());
|
||||
j[key] = { id, at: now.toISOString() };
|
||||
mkdirSync(join(root, '.storebound'), { recursive: true });
|
||||
const tmp = journalPath(root) + `.${process.pid}.tmp`;
|
||||
writeFileSync(tmp, JSON.stringify(j, null, 2) + '\n');
|
||||
renameSync(tmp, journalPath(root));
|
||||
} catch (e) { warn('upsert', `could not note the create in .storebound/created.json: ${(e as Error).message}`); }
|
||||
}
|
||||
|
||||
export interface FindOrCreate<T> extends CreateOnce<T> {
|
||||
/** journal of recent creates: guards against the list lag right after a create of an earlier run */
|
||||
journal?: { root: string; key: string; byId: (id: string) => Promise<T | null | undefined>; idOf: (v: T) => string };
|
||||
}
|
||||
|
||||
/** Looks with a fresh GET, then in the journal (direct GET by id), and only then creates (createOnce). */
|
||||
export async function findOrCreate<T>(o: FindOrCreate<T>): Promise<{ value: T; created: boolean }> {
|
||||
const found = await o.find();
|
||||
if (found) return { value: found, created: false };
|
||||
if (o.journal && existsSync(join(o.journal.root, '.storebound'))) {
|
||||
const hit = readJournal(o.journal.root)[o.journal.key];
|
||||
if (hit) {
|
||||
const v = await o.journal.byId(hit.id).catch(() => null);
|
||||
if (v) { log(o.tag ?? 'upsert', `${o.what}: created ${hit.at.slice(11, 16)} UTC by an earlier run (${hit.id}); the store's list does not show it yet, using it`); return { value: v, created: false }; }
|
||||
}
|
||||
}
|
||||
const r = await createOnce(o);
|
||||
if (o.journal && r.created) remember(o.journal.root, o.journal.key, o.journal.idOf(r.value));
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Apple: GET of one resource by id, null on 404. For FindOrCreate.journal.byId. */
|
||||
export async function getById(asc: (m: string, p: string) => Promise<{ data?: unknown }>, path: string): Promise<unknown | null> {
|
||||
try { return (await asc('GET', path)).data ?? null; } catch (e) { if (/-> 404/.test(String(e))) return null; throw e; }
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue