(input: {
readonly core: CoreDb;
readonly pluginId: string;
readonly owner: OwnerBinding;
})
| 1138 | }; |
| 1139 | |
| 1140 | const makePluginStorageFacade = (input: { |
| 1141 | readonly core: CoreDb; |
| 1142 | readonly pluginId: string; |
| 1143 | readonly owner: OwnerBinding; |
| 1144 | }): PluginStorageFacade => { |
| 1145 | // Owner partitions: org always, plus this subject's user partition. |
| 1146 | const readOwners: readonly Owner[] = input.owner.subject == null ? ["org"] : ["user", "org"]; |
| 1147 | |
| 1148 | const ownerSubject = (owner: Owner): { owner: Owner; subject: string } | null => { |
| 1149 | if (owner === "org") return { owner: "org", subject: ORG_SUBJECT }; |
| 1150 | if (input.owner.subject == null) return null; |
| 1151 | return { owner: "user", subject: String(input.owner.subject) }; |
| 1152 | }; |
| 1153 | |
| 1154 | const tenant = String(input.owner.tenant); |
| 1155 | |
| 1156 | const whereFor = |
| 1157 | (collection: string, key?: string): CoreWhere => |
| 1158 | (b: AnyCb) => |
| 1159 | b.and( |
| 1160 | b("plugin_id", "=", input.pluginId), |
| 1161 | b("collection", "=", collection), |
| 1162 | key === undefined ? true : b("key", "=", key), |
| 1163 | ); |
| 1164 | |
| 1165 | const whereOwner = (owner: Owner, collection: string, key: string): CoreWhere => { |
| 1166 | const os = ownerSubject(owner); |
| 1167 | return (b: AnyCb) => |
| 1168 | b.and( |
| 1169 | b("plugin_id", "=", input.pluginId), |
| 1170 | b("collection", "=", collection), |
| 1171 | b("key", "=", key), |
| 1172 | b("owner", "=", owner), |
| 1173 | b("subject", "=", os ? os.subject : ORG_SUBJECT), |
| 1174 | ); |
| 1175 | }; |
| 1176 | |
| 1177 | const ownerRank = (owner: Owner): number => readOwners.indexOf(owner); |
| 1178 | |
| 1179 | const sortByOwnerPrecedence = (rows: readonly CoreRow<"plugin_storage">[]) => |
| 1180 | [...rows].sort((left, right) => { |
| 1181 | const l = ownerRank(left.owner as Owner); |
| 1182 | const r = ownerRank(right.owner as Owner); |
| 1183 | return l - r || left.key.localeCompare(right.key); |
| 1184 | }); |
| 1185 | |
| 1186 | const getVisible = <T>(collection: string, key: string) => |
| 1187 | input.core.findMany("plugin_storage", { where: whereFor(collection, key) }).pipe( |
| 1188 | Effect.map((rows) => sortByOwnerPrecedence(rows)[0] ?? null), |
| 1189 | Effect.map((row) => (row ? pluginStorageEntryFromRow<T>(row) : null)), |
| 1190 | ); |
| 1191 | |
| 1192 | const getForOwnerImpl = <T>(owner: Owner, collection: string, key: string) => |
| 1193 | input.core |
| 1194 | .findFirst("plugin_storage", { |
| 1195 | where: whereOwner(owner, collection, key), |
| 1196 | }) |
| 1197 | .pipe(Effect.map((row) => (row ? pluginStorageEntryFromRow<T>(row) : null))); |
no test coverage detected