(input: {
readonly core: CoreDb;
readonly pluginId: string;
readonly owner: OwnerBinding;
})
| 1425 | }; |
| 1426 | |
| 1427 | const makePluginStorageFacade = (input: { |
| 1428 | readonly core: CoreDb; |
| 1429 | readonly pluginId: string; |
| 1430 | readonly owner: OwnerBinding; |
| 1431 | }): PluginStorageFacade => { |
| 1432 | // Owner partitions: org always, plus this subject's user partition. |
| 1433 | const readOwners: readonly Owner[] = input.owner.subject == null ? ["org"] : ["user", "org"]; |
| 1434 | |
| 1435 | const ownerSubject = (owner: Owner): { owner: Owner; subject: string } | null => { |
| 1436 | if (owner === "org") return { owner: "org", subject: ORG_SUBJECT }; |
| 1437 | if (input.owner.subject == null) return null; |
| 1438 | return { owner: "user", subject: String(input.owner.subject) }; |
| 1439 | }; |
| 1440 | |
| 1441 | const tenant = String(input.owner.tenant); |
| 1442 | |
| 1443 | const whereFor = |
| 1444 | (collection: string, key?: string): CoreWhere => |
| 1445 | (b: AnyCb) => |
| 1446 | b.and( |
| 1447 | b("plugin_id", "=", input.pluginId), |
| 1448 | b("collection", "=", collection), |
| 1449 | key === undefined ? true : b("key", "=", key), |
| 1450 | ); |
| 1451 | |
| 1452 | const whereOwner = (owner: Owner, collection: string, key: string): CoreWhere => { |
| 1453 | const os = ownerSubject(owner); |
| 1454 | return (b: AnyCb) => |
| 1455 | b.and( |
| 1456 | b("plugin_id", "=", input.pluginId), |
| 1457 | b("collection", "=", collection), |
| 1458 | b("key", "=", key), |
| 1459 | b("owner", "=", owner), |
| 1460 | b("subject", "=", os ? os.subject : ORG_SUBJECT), |
| 1461 | ); |
| 1462 | }; |
| 1463 | |
| 1464 | const ownerRank = (owner: Owner): number => readOwners.indexOf(owner); |
| 1465 | |
| 1466 | const sortByOwnerPrecedence = (rows: readonly CoreRow<"plugin_storage">[]) => |
| 1467 | [...rows].sort((left, right) => { |
| 1468 | const l = ownerRank(left.owner as Owner); |
| 1469 | const r = ownerRank(right.owner as Owner); |
| 1470 | return l - r || left.key.localeCompare(right.key); |
| 1471 | }); |
| 1472 | |
| 1473 | const getVisible = <T>(collection: string, key: string) => |
| 1474 | input.core.findMany("plugin_storage", { where: whereFor(collection, key) }).pipe( |
| 1475 | Effect.map((rows) => sortByOwnerPrecedence(rows)[0] ?? null), |
| 1476 | Effect.map((row) => (row ? pluginStorageEntryFromRow<T>(row) : null)), |
| 1477 | ); |
| 1478 | |
| 1479 | const getForOwnerImpl = <T>(owner: Owner, collection: string, key: string) => |
| 1480 | input.core |
| 1481 | .findFirst("plugin_storage", { |
| 1482 | where: whereOwner(owner, collection, key), |
| 1483 | }) |
| 1484 | .pipe(Effect.map((row) => (row ? pluginStorageEntryFromRow<T>(row) : null))); |
no test coverage detected