|
| 1 | +/** |
| 2 | + * NeoFS-specific utility helpers. |
| 3 | + */ |
| 4 | + |
| 5 | +import { ContainerID, ObjectAttribute } from '../types'; |
| 6 | +import { hexToBytes } from './buffer'; |
| 7 | +import { base58Decode } from './base58'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Parse a container ID from a hex string (with optional `0x` prefix) or |
| 11 | + * a Base58-encoded string into a {@link ContainerID}. |
| 12 | + * |
| 13 | + * @example |
| 14 | + * ```ts |
| 15 | + * const cid = toContainerId('CYzn4HPHXRmGW5cwvrqHtosd79kjBtVYAP3ykH6RCCAa'); |
| 16 | + * const cid2 = toContainerId('0xabcdef...'); |
| 17 | + * ``` |
| 18 | + * |
| 19 | + * @throws Error if the string is not valid hex or Base58 |
| 20 | + */ |
| 21 | +export function toContainerId(containerId: string): ContainerID { |
| 22 | + const raw = containerId.trim(); |
| 23 | + const hex = raw.toLowerCase().replace(/^0x/, ''); |
| 24 | + if (/^[0-9a-f]+$/i.test(hex) && hex.length > 0 && hex.length % 2 === 0) { |
| 25 | + return { value: hexToBytes(hex) }; |
| 26 | + } |
| 27 | + try { |
| 28 | + const bytes = base58Decode(raw); |
| 29 | + return { value: bytes }; |
| 30 | + } catch { |
| 31 | + throw new Error( |
| 32 | + `Invalid container ID: expected hex (even length, optional 0x prefix) or Base58. Got: "${raw}"`, |
| 33 | + ); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Convert an array of `{ key, value }` object attributes (as returned by the |
| 39 | + * NeoFS API) into a plain `Record<string, string>` for easier lookup. |
| 40 | + * |
| 41 | + * @example |
| 42 | + * ```ts |
| 43 | + * const head = await objectClient.head({ address, raw: false }); |
| 44 | + * const attrs = decodeAttributes(head.attributes); |
| 45 | + * console.log(attrs['FileName']); |
| 46 | + * ``` |
| 47 | + */ |
| 48 | +export function decodeAttributes( |
| 49 | + attrs?: ObjectAttribute[] | Array<{ key: string; value: string }>, |
| 50 | +): Record<string, string> { |
| 51 | + const out: Record<string, string> = {}; |
| 52 | + if (attrs) { |
| 53 | + for (const a of attrs) out[a.key] = a.value; |
| 54 | + } |
| 55 | + return out; |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Classify a NeoFS gRPC / SDK error as retryable. |
| 60 | + * |
| 61 | + * Returns `true` for transient failures such as expired sessions, |
| 62 | + * authentication issues that may self-resolve after session renewal, |
| 63 | + * and timeout / deadline errors. |
| 64 | + */ |
| 65 | +export function isRetryableNeoFSError(err: unknown): boolean { |
| 66 | + const msg = String((err as any)?.message || (err as any)?.details || ''); |
| 67 | + return ( |
| 68 | + msg.includes('session') || |
| 69 | + msg.includes('expired') || |
| 70 | + msg.includes('UNAUTHENTICATED') || |
| 71 | + msg.includes('permission') || |
| 72 | + msg.includes('deadline') || |
| 73 | + msg.includes('timeout') |
| 74 | + ); |
| 75 | +} |
0 commit comments