harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0105harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0105Enhancement: Harder, concurrent, and memory-conscious implementation of socotra_marketplace_helpers
Overview
You must implement a Python package at /app/socotra_marketplace_helpers with a stricter, more production-like surface and constraints. The package should still expose the same public API used by the tests, but should be implemented with performance, correctness under edge cases, and concurrency in mind. The solution must be importable as socotra_marketplace_helpers and expose a submodule socotra_marketplace_helpers.jwt with a deterministic sign() function.
What to implement (harder version)
- Package layout
- /app/socotra_marketplace_helpers/
- __init__.py
- jwt.py
- Module-level sentinels and utilities (robust and thread-safe considerations)
- _default_key: a sentinel value used as a default for find_key
- _default_test: a secondary sentinel used when default_value is None
- find_key(headers: dict, default_value: object = _default_key) -> object
- Behavior (with extended robustness):
- If headers is not a mapping, treat as an empty dict
- If the key 'x-smp-key' exists in headers (at any depth? stay simple: direct key in mapping):
- Return headers['x-smp-key']
- If default_value is None:
- Return _default_test
- If default_value is the _default_key sentinel:
- Return that sentinel
- Otherwise:
- Return default_value
- Concurrency note: this function should be side-effect free and thread-safe (no mutation of global state).
- Data container for config data (SAC)
- SAC class with:
- __init__(self, tenant: tuple, mappings=None, settings=None)
- to_json(self) -> dict
- Top-level keys exactly as:
- 'socotraApiUrl' -> tenant[0]
- 'tenantHostName' -> tenant[1]
- 'token' -> tenant[2]
- 'mappings' -> mappings (default to {} if None)
- 'settings' -> settings (default to {} if None)
- Thread-safety: SAC instances are immutable from external mutation after construction (or at least changes to internal state are carefully controlled). If you expose mapping/settings, consider defensive copies.
- Core helpers
- read_config_from(file_name: str) -> SAC
- Reads the JSON file named file_name and reconstructs an SAC instance using logic mirroring the tests’ _parse, but with robustness and performance in mind:
- product_name = file_name
- mappings = {} initially
- contents = parsed JSON from the file
- config_fields = contents.get('config', {}).get('fields', [])
- For each field in config_fields:
- name = field.get('name', '')
- ftype = field.get('type', '')
- values = field.get('values', [{'value': product_name}])
- first = values[0].get('value') if values else None
- If name == '':
- Emit a UserWarning about missing field name (as tests expect a warning in such scenarios)
- elif ftype == 'mapped':
- mappings[name] = f"{product_name}-mapped-{name}"
- elif ftype == 'select':
- settings[name] = first
- else:
- settings[name] = f"{product_name}-vendor-{name}"
- Build a synthetic JWT:
- claims = {'aud': [hostname]}
- hostname and base_url derived from environment similar to tests:
- domain = os.getenv('TEST_DOMAIN', 'sandbox.socotra.com')
- tenant = os.getenv('TEST_DOMAIN', 'marketplace-partner')
- base_url = os.getenv('TEST_SANDBOX_BASE_URL', f'https://api.{domain}')
- hostname = os.getenv('TEST_TENANT_HOSTNAME', f'{tenant}.co.{domain}')
- jwt = os.getenv('JWT', sign(claims=claims))
- tenant = (base_url, hostname, jwt)
- Return SAC(tenant, mappings=[(file_name, mappings)], settings=settings)
- Implement a small, thread-safe cache to avoid re-parsing the same file concurrently (e.g., using threading.Lock or a threading.RLock). The cache should be transparent to callers and should not leak memory unboundedly (consider an optional eviction policy or a max size hint).
- Time/space complexity guidance: aim for O(n) time over the file content and O(m) extra space where m is the number of fields, with a bounded extra memory footprint for the cache.
- load(key: str, url: str | None = None) -> SAC
- Return an SAC representing a minimal, plausible config derived from the given URL (used by tests to verify presence of top-level keys).
- Behavior:
- If url is provided:
- Parse socotraApiUrl as url
- Extract tenantHostName robustly from the URL (handle http(s) schemes, IPv6, and port if present)
- Generate or fetch a token by signing claims with audience hostname as in tests:
- token = os.getenv('JWT', sign({'aud': [tenantHostName]}))
- tenant = (socotraApiUrl, tenantHostName, token)
- If url is not provided:
- Construct a reasonable default URL using the key (e.g., f'https://api.{key}.example')
- Derive a corresponding hostname from the URL for the token's audience
- The returned SAC must have:
- tenant = (socotraApiUrl, tenantHostName, token)
- mappings = {}
- settings = {}
- The to_json() output must include: 'socotraApiUrl', 'tenantHostName', 'token', 'mappings', 'settings'
- Performance and correctness: ensure this function is safe to call from multiple threads; it should not perform network I/O. It should consistently produce deterministic tokens for the same URL and environment.
- JWT helper (socotra_marketplace_helpers.jwt)
- sign(claims: dict, secret: str = '') -> str
- Implement a deterministic, simple signing function (not necessarily a real JWT) that is stable across runs with the same inputs.
- Requirements:
- Use a deterministic algorithm to produce a token based on the provided claims.
- If secret is provided, incorporate it via a deterministic HMAC-like approach.
- A practical approach: serialize claims with json.dumps(claims, sort_keys=True), then derive a digest (e.g., SHA-256) over the serialized string, and compose a compact token.
- Return a token string that is stable for the same input claims (and secret).
- The exact token format is not part of the external contract, but tests will rely on consistency and determinism.
- The function must be importable as:
- from socotra_marketplace_helpers.jwt import sign
- Exposed API surface and exports
- __init__.py should expose:
- _default_key, _default_test
- find_key
- SAC class
- read_config_from
- load
- socotra_marketplace_helpers.jwt should expose sign
- Provide a well-defined __all__ in __init__.py and explicit export surface in jwt.py for clarity.
- Implementation constraints and quality
- Place the package at /app/, preserving the exact directory name.
- Emphasize robust input handling: empty inputs, None values, non-dict headers, missing fields, and unicode content.
- Thread-safety: any shared caches or global state must be guarded (threading.Lock / threading.RLock).
- Efficiency:
- read_config_from should process large config files efficiently; avoid unnecessary copies.
- Maintain O(n) time with respect to file content and O(m) extra space where m is the number of fields; the optional cache should be bounded.
- Documentation: include concise docstrings explaining behavior, edge cases, and thread-safety notes.
Notes for testing
- Tests will import from socotra_marketplace_helpers and socotra_marketplace_helpers.jwt:
- You must ensure proper importability and a deterministic sign() implementation.
- The test expectations described above (top-level to_json keys, default behaviors, warning emission for missing field names, and URL-derived tokens) should be satisfied even under edge cases and concurrent usage.
What you’ll deliver
- A robust, concurrent-capable Python package at /app/socotra_marketplace_helpers with:
- __init__.py and jwt.py
- A thread-safe, memory-conscious read_config_from and load
- A deterministic sign function for token generation
- Proper handling of edge cases and large inputs
- Clear, maintainable code with appropriate docstrings and comments to explain decisions and edge-case handling.