mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 01:24:30 +01:00
Fix first-agent skill setup racing an uncommitted installation (#23308)
## Thinking Path > - Paperclip manages AI agents and the skills they need for work. > - First-agent setup assigns the bundled operating and onboarding skills. > - An environment plugin can initialize those skills inside a transaction. > - Another request could share that transaction's refresh promise and read before its commit. > - The hire then rejected valid default skills as unknown references. > - This pull request scopes shared refresh work to each database handle and makes concurrent bundled creation idempotent. ## Linked Issues or Issue Description **What happened?** First-agent onboarding on a fresh hosted stack failed with `Invalid company skill selection (unknown references: ...)` after the user entered a Claude API key. The failure occurred during skill assignment, before a provider connection could be verified. The environment plugin initialized the bundled library inside its skill-install transaction. The hire request awaited the same company-wide refresh promise. That promise settled before the outer transaction committed. The hire's separate connection then read an empty library and returned HTTP 422. **Expected behavior** A hire resolves committed bundled skills even when another installer is active. A failed competing transaction must not leave the hire dependent on rolled-back work. Concurrent callers must retain one installed skill per key. **Steps to reproduce** 1. Create a company with no initialized skill library. 2. Start bundled inventory initialization inside a transaction and hold its commit. 3. Resolve first-agent skill selections through the ordinary database handle while initialization is active. 4. Let initialization finish, while the outer transaction is still open. 5. Observe the unknown-reference error from the separate connection. The added real-PostgreSQL regression controls these boundaries without real-clock sleeps. **Paperclip version or commit** Observed on `79dadd86551e4deb254163dd1f952f2908f1d351`. Reproduced locally on `79ef76757879`. **Deployment mode** Hosted Docker deployment. The underlying transaction race also applies to other deployments. Related: #22477 repaired a different first-agent skill upload failure. Searches of open and closed skill/onboarding and skill/transaction changes found no duplicate of this repair. ## What Changed - Store in-flight inventory refreshes by database handle and company. Service instances on the same handle still share work. Other connections and transactions refresh through their own visibility boundary. - Take the existing skill publication advisory lock before the bundled-create recheck. Reuse a concurrent installation once it is visible. Keep normal user-created skill conflict handling intact. - Recheck a shipped release under the skill-row lock before inserting its version. Reuse a matching release and reject a concurrent snapshot with different contents. - Keep the fix in the existing inventory and import owner. No schema, provider, UI, or public API changes are required. - Add commit and rollback regressions that hold the installer open until the competing caller attempts publication. Preseed the folder metadata and use inline packages for this specific creation race so unrelated folder and object-store locks do not settle the race first. - Add concurrent release-seeding cases for matching and corrupted snapshots. Existing tests cover shared refreshes, separate actor visibility, and revoked project access. ## Verification - The original commit/rollback regressions reproduced the unknown-reference HTTP 422 before the repair. - Review regression, red: both concurrent release-seeding cases reproduced PostgreSQL `23505` on `company_skill_versions_skill_release_idx` before the release recheck was added. - Creation-race test: removing the bundled-create recheck makes the tightened commit case fail with HTTP 409. The protected code passes. This proves the test reaches the concurrent-creation boundary. - Green: all six inventory-concurrency cases pass, including commit, rollback, matching release reuse, corrupt release refusal, same-handle coalescing, and separate actor visibility. - Final revision: `5ac8f4d7acc1a2fe5111935d892c5d57ef54b5a6`. All 277 tests passed across nine focused files: company skill service, runtime concurrency, runtime selection, environment skills, plugin-managed skills, managed content, agent skill routes, package upload, and bundled release validation. - `pnpm --filter @paperclipai/server typecheck` passed, including source and test layers, on the final source. - Test command: `pnpm exec vitest run server/src/__tests__/{company-skills-runtime-concurrency,company-skills-service,company-skills-runtime-selection,environment-skills,plugin-managed-skills,managed-skill-content,agent-skills-routes,skill-package-upload}.test.ts server/src/services/bundled-skill-release-validation.test.ts`. - `node scripts/check-test-budget.mjs --files server/src/__tests__/company-skills-runtime-concurrency.test.ts` and `git diff --check` passed. - Environment: local macOS arm64 with real embedded PostgreSQL. Tests use controlled gates rather than real-clock sleeps. - The previous head, `088b8f8822d5bc218f4e5e7cfcf61c510de0776d`, passed all 270 focused tests, server source/test typechecks, and [CI](https://github.com/paperclipai/paperclip/actions/runs/46488494810). The 4/5 review identified the release race and the test gap addressed here. The final revision has now passed fresh CI and review; the results are recorded below. - `pnpm verify --explain` selected 1,981 tests, with 1,978 retained conservatively. Focused local checks cover this repair; required CI supplies the broader typecheck, build, test, Runner, and browser coverage. - Staging diagnosis used the served Core SHA, bounded request logs, and read-only database queries. The logs and row timestamps match the reproduced transaction race. - Test code and service behavior document this internal invariant; no user-facing command or API contract changed. - A deployed onboarding retry with the fixed revision has not been run. This PR does not deploy the repair or validate the user's provider credential. - Current-head [Greptile review](https://github.com/paperclipai/paperclip/pull/23308#issuecomment-7288511940) is 5/5 on `5ac8f4d7acc1a2fe5111935d892c5d57ef54b5a6`. Both prior review threads are resolved. - Final [CI run, attempt 2](https://github.com/paperclipai/paperclip/actions/runs/46491251884/attempts/2) completed successfully on `5ac8f4d7acc1a2fe5111935d892c5d57ef54b5a6`. Scope: typecheck/release registry, build, native Runner checks, general tests, serialized server suites, and all 16 browser shards. GitHub reports the branch as clean and mergeable. - Attempt 1 lost the runners for [browser shard 5](https://github.com/paperclipai/paperclip/actions/runs/46491251884/job/142104554848) and [browser shard 12](https://github.com/paperclipai/paperclip/actions/runs/46491251884/job/142104554842). Those interrupted attempts are not passes. GitHub initially rejected targeted retries while the parent workflow was running. Both shards passed in attempt 2. ## Risks Different database handles now perform their own inventory refresh. The bundled-create lock prevents duplicate publication when these refreshes overlap. Same-handle coalescing and the existing access checks remain effective. The change does not relax unknown-skill validation or normal edit/create conflicts. No migration is needed. ## Model Used OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through the Codex harness, with xhigh reasoning effort and tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
79ef767578
commit
5f1178b966
2 files changed
+199
-30
No files matched your search
@@ -1,13 +1,15 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import { promises as fs } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, companyMemberships, companySkills, companySkillSources, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,
|
||||
import { agents, companies, companyMemberships, companySkills, companySkillSources, companySkillVersions, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,
|
||||
projectAccessMembers, projects, projectSkillSources } from "@paperclipai/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, isNotNull } from "drizzle-orm";
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
import { PAPERCLIP_FEEDBACK_SKILL_KEYS, PAPERCLIP_OPERATIONAL_SKILL_KEY } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { companySkillService } from "../services/company-skills.js";
|
||||
import { companySkillService, ONBOARDING_FIRST_TASK_SKILL_KEY, PAPERCLIP_CORE_SKILL_KEYS } from "../services/company-skills.js";
|
||||
import { withSkillActor } from "../services/skill-access.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
@@ -35,6 +37,21 @@ describeDatabase("concurrent runtime skill preparation", () => {
|
||||
if (home) await fs.rm(home, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function observeTransactionStatements(observe: (query: { sql: string; params: unknown[] }) => void) {
|
||||
const transaction = db.transaction.bind(db);
|
||||
const dialect = new PgDialect();
|
||||
return vi.spyOn(db, "transaction").mockImplementation((action, config) => transaction(async tx => {
|
||||
const execute = tx.execute.bind(tx);
|
||||
const spy = vi.spyOn(tx, "execute").mockImplementation(query => {
|
||||
const result = execute(query);
|
||||
observe(typeof query === "string" ? { sql: query, params: [] } : dialect.sqlToQuery(query.getSQL()));
|
||||
return result;
|
||||
});
|
||||
try { return await action(tx); }
|
||||
finally { spy.mockRestore(); }
|
||||
}, config));
|
||||
}
|
||||
|
||||
it("shares an in-flight inventory refresh across service instances before snapshot locking", async () => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Concurrent skill readers", issuePrefix: `SC${companyId.slice(0, 6)}` });
|
||||
@@ -77,4 +94,133 @@ describeDatabase("concurrent runtime skill preparation", () => {
|
||||
await db.delete(projectAccessMembers).where(and(eq(projectAccessMembers.projectId, project!.id), eq(projectAccessMembers.subjectId, readers[0]!.id)));
|
||||
expect(await read(readers[0]!.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["commit", "rollback"] as const)("resolves first-agent skills while a competing installer will %s", async outcome => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "First-agent skill race", issuePrefix: `ST${companyId.slice(0, 6)}` });
|
||||
await companySkillService(db).listFull(companyId);
|
||||
await db.delete(companySkills).where(eq(companySkills.companyId, companyId));
|
||||
const previousStorage = process.env.PAPERCLIP_SKILL_PACKAGE_STORAGE_ENABLED;
|
||||
process.env.PAPERCLIP_SKILL_PACKAGE_STORAGE_ENABLED = "false";
|
||||
const operation = new AsyncLocalStorage<"install" | "assign">();
|
||||
const installing = Promise.withResolvers<void>();
|
||||
const continueInstall = Promise.withResolvers<void>();
|
||||
const installerReady = Promise.withResolvers<void>();
|
||||
const publicationAttempt = Promise.withResolvers<void>();
|
||||
const finishTransaction = Promise.withResolvers<void>();
|
||||
const rollback = new Error("Roll back the competing installation");
|
||||
const readFile = fs.readFile.bind(fs);
|
||||
let paused = false;
|
||||
let publicationAttempted = false;
|
||||
const transaction = observeTransactionStatements(query => {
|
||||
if (operation.getStore() === "assign" && query.sql.includes("pg_advisory_xact_lock")
|
||||
&& query.params.includes(`${companyId}:agentmail`)) {
|
||||
publicationAttempted = true;
|
||||
publicationAttempt.resolve();
|
||||
}
|
||||
});
|
||||
const read = vi.spyOn(fs, "readFile").mockImplementation(async (file, options) => {
|
||||
if (String(file).endsWith("/first-task/SKILL.md")) {
|
||||
if (operation.getStore() === "assign") await installerReady.promise;
|
||||
if (operation.getStore() === "install" && !paused) {
|
||||
paused = true;
|
||||
installing.resolve();
|
||||
await continueInstall.promise;
|
||||
}
|
||||
}
|
||||
return readFile(file, options);
|
||||
});
|
||||
const installation = operation.run("install", () => db.transaction(async tx => {
|
||||
await companySkillService(tx as unknown as typeof db).listFull(companyId);
|
||||
installerReady.resolve();
|
||||
await finishTransaction.promise;
|
||||
if (outcome === "rollback") throw rollback;
|
||||
})).catch(error => {
|
||||
if (error !== rollback) throw error;
|
||||
});
|
||||
let assignment: Promise<unknown> | undefined;
|
||||
try {
|
||||
await installing.promise;
|
||||
const requested = [...PAPERCLIP_CORE_SKILL_KEYS, ONBOARDING_FIRST_TASK_SKILL_KEY];
|
||||
assignment = operation.run("assign", () => companySkillService(db).resolveRequestedSkillEntries(companyId, requested))
|
||||
.then(value => ({ value }), error => ({ error }));
|
||||
continueInstall.resolve();
|
||||
await Promise.race([assignment, publicationAttempt.promise]);
|
||||
finishTransaction.resolve();
|
||||
await installation;
|
||||
expect(await assignment).toEqual({ value: {
|
||||
resolved: requested.map(key => ({ key, versionId: null })), unresolved: [],
|
||||
} });
|
||||
expect(publicationAttempted).toBe(true);
|
||||
const installed = await db.select({ key: companySkills.key }).from(companySkills).where(eq(companySkills.companyId, companyId));
|
||||
for (const key of requested) expect(installed.filter(skill => skill.key === key)).toHaveLength(1);
|
||||
} finally {
|
||||
continueInstall.resolve();
|
||||
finishTransaction.resolve();
|
||||
await Promise.allSettled([installation, assignment]);
|
||||
read.mockRestore();
|
||||
transaction.mockRestore();
|
||||
if (previousStorage === undefined) delete process.env.PAPERCLIP_SKILL_PACKAGE_STORAGE_ENABLED;
|
||||
else process.env.PAPERCLIP_SKILL_PACKAGE_STORAGE_ENABLED = previousStorage;
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it.each([false, true])("rechecks a missing release after its competing installer commits (corrupt=%s)", async corrupt => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Concurrent release setup", issuePrefix: `SR${companyId.slice(0, 6)}` });
|
||||
const initial = await companySkillService(db).listFull(companyId);
|
||||
const skill = initial.find(entry => entry.key === PAPERCLIP_OPERATIONAL_SKILL_KEY)!;
|
||||
const [release] = await db.select().from(companySkillVersions).where(and(
|
||||
eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.companySkillId, skill.id),
|
||||
isNotNull(companySkillVersions.releaseId))).limit(1);
|
||||
expect(release?.releaseId).toBeTruthy();
|
||||
await db.delete(companySkillVersions).where(eq(companySkillVersions.id, release!.id));
|
||||
const installerReady = Promise.withResolvers<void>();
|
||||
const finishTransaction = Promise.withResolvers<void>();
|
||||
const publicationAttempt = Promise.withResolvers<void>();
|
||||
const operation = new AsyncLocalStorage<"install" | "read">();
|
||||
let publicationAttempted = false;
|
||||
const transaction = observeTransactionStatements(query => {
|
||||
if (operation.getStore() === "read" && query.sql.includes("for update") && query.params.includes(skill.id)) {
|
||||
publicationAttempted = true;
|
||||
publicationAttempt.resolve();
|
||||
}
|
||||
});
|
||||
const installation = operation.run("install", () => db.transaction(async tx => {
|
||||
await companySkillService(tx as unknown as typeof db).listFull(companyId);
|
||||
if (corrupt) await tx.update(companySkillVersions).set({ fileInventory: [{
|
||||
path: "SKILL.md", kind: "skill", content: "Corrupted release snapshot",
|
||||
}] }).where(and(eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.releaseId, release!.releaseId!)));
|
||||
installerReady.resolve();
|
||||
await finishTransaction.promise;
|
||||
}));
|
||||
let reading: Promise<{ value?: typeof initial; error?: unknown }> | undefined;
|
||||
try {
|
||||
await installerReady.promise;
|
||||
reading = operation.run("read", () => companySkillService(db).listFull(companyId))
|
||||
.then(value => ({ value }), error => ({ error }));
|
||||
await Promise.race([reading, publicationAttempt.promise]);
|
||||
finishTransaction.resolve();
|
||||
await installation;
|
||||
const result = await reading;
|
||||
if (corrupt) expect(result).toMatchObject({ error: {
|
||||
message: `Bundled skill release ${release!.releaseId} does not match its seeded snapshot.`,
|
||||
} });
|
||||
else {
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.value?.map(entry => ({ key: entry.key, currentVersionId: entry.currentVersionId })))
|
||||
.toEqual(initial.map(entry => ({ key: entry.key, currentVersionId: entry.currentVersionId })));
|
||||
}
|
||||
expect(publicationAttempted).toBe(true);
|
||||
const versions = await db.select().from(companySkillVersions).where(and(
|
||||
eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.releaseId, release!.releaseId!)));
|
||||
expect(versions).toHaveLength(1);
|
||||
expect(versions[0]!.fileInventory).toEqual(corrupt
|
||||
? [{ path: "SKILL.md", kind: "skill", content: "Corrupted release snapshot" }] : release!.fileInventory);
|
||||
} finally {
|
||||
finishTransaction.resolve();
|
||||
await Promise.allSettled([installation, reading]);
|
||||
transaction.mockRestore();
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -464,7 +464,7 @@ type RuntimeSkillSourceResolution =
|
||||
| { status: "available"; source: string }
|
||||
| { status: "missing"; source: string; detail: string };
|
||||
|
||||
const skillInventoryRefreshPromises = new Map<string, Promise<void>>();
|
||||
const skillInventoryRefreshPromises = new WeakMap<Db, Map<string, Promise<void>>>();
|
||||
|
||||
function selectCompanySkillColumns() {
|
||||
return {
|
||||
@@ -617,6 +617,16 @@ function buildInventoryContentHash(entries: Array<{ path: string; sha256: string
|
||||
return `sha256:${sha256Buffer(Buffer.from(JSON.stringify(hashInput)))}`;
|
||||
}
|
||||
|
||||
function bundledSkillReleaseInventoryHash(inventory: CompanySkillVersionFileInventoryEntry[]) {
|
||||
return buildInventoryContentHash(inventory.map(entry => ({ path: entry.path, sha256: sha256Buffer(entry.content) })));
|
||||
}
|
||||
|
||||
function assertBundledSkillReleaseInventory(releaseId: string, expectedHash: string, existing: CompanySkillVersionRow) {
|
||||
if (bundledSkillReleaseInventoryHash(toCompanySkillVersion(existing).fileInventory) !== expectedHash) {
|
||||
throw new Error(`Bundled skill release ${releaseId} does not match its seeded snapshot.`);
|
||||
}
|
||||
}
|
||||
|
||||
function uniqueSkillSlug(baseSlug: string, usedSlugs: Set<string>) {
|
||||
if (!usedSlugs.has(baseSlug)) return baseSlug;
|
||||
let attempt = 2;
|
||||
@@ -3153,21 +3163,10 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo
|
||||
const fileInventory = serializeVersionFileInventory(
|
||||
await collectVersionFileInventoryFromDirectory(release.releaseDir),
|
||||
);
|
||||
const registryHash = buildInventoryContentHash(fileInventory.map((entry) => ({
|
||||
path: entry.path,
|
||||
sha256: sha256Buffer(entry.content),
|
||||
})));
|
||||
const registryHash = bundledSkillReleaseInventoryHash(fileInventory);
|
||||
if (await verifyExistingBundledSkillRelease({ db, companyId, skillId: paperclipSkill.id, releaseId: release.id,
|
||||
expectedInventoryHash: registryHash, validateInventory: existing => {
|
||||
const existingInventory = toCompanySkillVersion(existing).fileInventory;
|
||||
const existingHash = buildInventoryContentHash(existingInventory.map((entry) => ({
|
||||
path: entry.path,
|
||||
sha256: sha256Buffer(entry.content),
|
||||
})));
|
||||
if (existingHash !== registryHash) {
|
||||
throw new Error(`Bundled skill release ${release.id} does not match its seeded snapshot.`);
|
||||
}
|
||||
},
|
||||
expectedInventoryHash: registryHash,
|
||||
validateInventory: existing => assertBundledSkillReleaseInventory(release.id, registryHash, existing),
|
||||
})) continue;
|
||||
const releasedAt = new Date(release.releasedAt);
|
||||
if (Number.isNaN(releasedAt.getTime())) {
|
||||
@@ -3299,7 +3298,12 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo
|
||||
async function ensureSkillInventoryCurrent(companyId: string) {
|
||||
// Denied reads must not perform the lazy bundled-skill reconciliation.
|
||||
if (!visibility().canReadCompany(companyId)) return;
|
||||
const existingRefresh = skillInventoryRefreshPromises.get(companyId);
|
||||
let refreshes = skillInventoryRefreshPromises.get(db);
|
||||
if (!refreshes) {
|
||||
refreshes = new Map();
|
||||
skillInventoryRefreshPromises.set(db, refreshes);
|
||||
}
|
||||
const existingRefresh = refreshes.get(companyId);
|
||||
if (existingRefresh) {
|
||||
await measureRunPhase("skills.inventory.wait", () => existingRefresh);
|
||||
return;
|
||||
@@ -3320,12 +3324,12 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo
|
||||
await measureRunPhase("skills.inventory.local_sources", () => reconcileLocalPathSkillSources(companyId));
|
||||
})();
|
||||
|
||||
skillInventoryRefreshPromises.set(companyId, refreshPromise);
|
||||
refreshes.set(companyId, refreshPromise);
|
||||
try {
|
||||
await refreshPromise;
|
||||
} finally {
|
||||
if (skillInventoryRefreshPromises.get(companyId) === refreshPromise) {
|
||||
skillInventoryRefreshPromises.delete(companyId);
|
||||
if (refreshes.get(companyId) === refreshPromise) {
|
||||
refreshes.delete(companyId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3864,6 +3868,15 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo
|
||||
and ${companySkills.companyId} = ${companyId}
|
||||
for update
|
||||
`);
|
||||
if (options.release) {
|
||||
const [existing] = await tx.select().from(companySkillVersions).where(and(
|
||||
eq(companySkillVersions.companyId, companyId), eq(companySkillVersions.companySkillId, skillId),
|
||||
eq(companySkillVersions.releaseId, options.release.id))).limit(1);
|
||||
if (existing) {
|
||||
assertBundledSkillReleaseInventory(options.release.id, bundledSkillReleaseInventoryHash(fileInventory), existing);
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
// File edits already own the skill lock when a dedicated connection saves
|
||||
// their package. Never hold a package lock while waiting for that skill.
|
||||
if (packageSnapshotId) {
|
||||
@@ -6519,15 +6532,25 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo
|
||||
? await collectVersionFileInventoryFromDirectory(normalizeSourceLocatorDirectory(skill.sourceLocator)!) : undefined);
|
||||
if (files) {
|
||||
const candidate = await managedContent.prepare(companyId, files);
|
||||
const saved = existing
|
||||
? await managedContent.publish(existing, candidate, values, { type: "system" }, {
|
||||
...options.publication, reuseCurrentVersion: true, validate: async tx => {
|
||||
await visibility(tx).assertSkill(companyId, existing.id);
|
||||
await options.publication?.validate?.(tx);
|
||||
},
|
||||
const publish = (database: DbOrTransaction, base: CompanySkill | null) => {
|
||||
const content = database === db ? managedContent : managedSkillContent(database as Db, packageDb);
|
||||
return base
|
||||
? content.publish(base, candidate, values, { type: "system" }, {
|
||||
...options.publication, reuseCurrentVersion: true, validate: async tx => {
|
||||
await visibility(tx).assertSkill(companyId, base.id);
|
||||
await options.publication?.validate?.(tx);
|
||||
},
|
||||
})
|
||||
: content.create(values, candidate, { type: "system" }, options.publication);
|
||||
};
|
||||
const saved = !existing && incomingKind === "paperclip_bundled"
|
||||
? await database.transaction(async tx => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`${companyId}:${skill.slug}`}, 0))`);
|
||||
const concurrent = await getByKey(companyId, skill.key, tx, options);
|
||||
return concurrent?.currentVersionId ? concurrent : toCompanySkill((await publish(tx, concurrent)).skill);
|
||||
})
|
||||
: await managedContent.create(values, candidate, { type: "system" }, options.publication);
|
||||
out.push(toCompanySkill(saved.skill));
|
||||
: toCompanySkill((await publish(database, existing)).skill);
|
||||
out.push(saved);
|
||||
continue;
|
||||
}
|
||||
if (existing && importedSkillPersistValuesMatchExisting(existing, values)) {
|
||||
|
||||
Reference in new issue
Block a user