Metadata-Version: 2.4
Name: vs-common
Version: 0.1.0
Summary: Core shared library for Viveka Sutra — config, logging, and async cache management
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and derivative works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source code control systems, and issue tracking systems that are managed
              by, or on behalf of, the Licensor for the purpose of discussing and
              improving the Work, but excluding communication that is conspicuously
              marked or designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and incorporated
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by the combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a cross-claim
              or counterclaim in a lawsuit) alleging that the Work or any
              Contribution embodied within the Work constitutes direct or
              contributory patent infringement, then any patent licenses granted to
              You under this License for that Work shall terminate as of the date
              such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" file as part of its distribution,
                  You must include a readable copy of the attribution notices
                  contained within such NOTICE file, in at least one of the
                  following places: within a NOTICE text file distributed as part
                  of the Derivative Works; within the Source form or documentation,
                  if provided along with the Derivative Works; or, within a display
                  generated by the Derivative Works, if and wherever such
                  third-party notices normally appear. The contents of the NOTICE
                  file are for informational purposes only and do not modify the
                  License. You may add Your own attribution notices within
                  Derivative Works that You distribute, alongside or as an addendum
                  to the NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, modify, and distribute
              Your modifications.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any conditions of TITLE,
              NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
              PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or all other
              commercial damages or losses), even if such Contributor has been
              advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2026 VivekaSutra. All rights reserved.
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
           implied. See the License for the specific language governing
           permissions and limitations under the License.
        
Project-URL: Homepage, https://vivekasutra.com/
Project-URL: Source, https://github.com/vivekasutra/viveka-mula
Keywords: config,logging,cache,redis,async,viveka,vs
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == "redis"
Requires-Dist: hiredis>=2.0; extra == "redis"
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Dynamic: license-file

# vs-common

Core shared library for Viveka Sutra — config, logging, and async cache management.

---

## Installation

```bash
pip install vs-common
```

With Redis support:

```bash
pip install vs-common[redis]
```

---

## Application Startup

`vs-common` components are designed to be initialised once at application startup, in this order:

```python
from vs_common.config.vs_ini_config import VsIniConfig
from vs_common.log.vs_log_manager import VsLogManager
from vs_common.cache.vs_cache_manager import VsCacheManager
from vs_common.schema.vs_log_config import VsLogConfig
from vs_common.schema.vs_cache_config import VsCacheConfig

def bootstrap():
    config = VsIniConfig("config.ini")

    VsLogManager.init(VsLogConfig(
        level=config.get("logging.level", default="INFO"),
        file_path=config.get("logging.file_path", default="logs/app.log"),
    ))

    VsCacheManager.init(VsCacheConfig(
        enabled=config.get("cache.enabled", data_type=bool, default=False),
        backend=config.get("cache.backend", default="memory"),
        host=config.get("cache.host", default="localhost"),
        port=config.get("cache.port", data_type=int, default=6379),
        password=config.get("cache.password"),
    ))
```

Call `bootstrap()` once at your application entry point before anything else runs.

**What happens if you skip initialisation:**

| Component | Behaviour without `init()` |
|---|---|
| `VsLogManager` | Auto-inits with `INFO` level, console + file enabled, default log path |
| `VsCacheManager` | Auto-inits with `InMemoryCache` on first use |
| `VsIniConfig` | Reads `config.ini` from current directory; missing file falls back to env vars and defaults |

Skipping is safe for quick scripts and tests, but in production you should always call `bootstrap()` explicitly so configuration is intentional and traceable.

**Re-initialisation behaviour:**

| Component | What happens |
|---|---|
| `VsLogManager.init()` | Updates log level on all existing handlers. Handlers and formatters from first init are kept. Safe to call again. |
| `VsCacheManager.init()` | Replaces the active backend with a new instance. All data in the previous cache is lost — including all in-memory entries if using `InMemoryCache`. |
| `VsIniConfig` | Not a singleton. Each `VsIniConfig(path)` creates a fresh instance and re-reads the file. Use `config.reload()` to refresh an existing instance in-place instead. |

---

## Modules

### Config

`VsIniConfig` reads from a `config.ini` file and supports environment variable overrides.

```python
from vs_common.config.vs_ini_config import VsIniConfig

config = VsIniConfig("config.ini")

config.get("database.url")                        # str
config.get("database.port", data_type=int)        # int
config.get("app.debug", data_type=bool)           # bool
config.get("app.tags", data_type=list)            # list
config.get("app.missing", default="fallback")     # default if not found
config.get_section("database")                    # dict of all keys in section
config.reload()                                   # re-read config.ini from disk
```

Environment variables take priority over `config.ini`. Key `"database.url"` maps to env var `DATABASE_URL`.

**`config.ini` example:**
```ini
[database]
url = postgres://localhost/mydb
port = 5432

[app]
debug = true
tags = a,b,c
```

---

### Logging

`VsLogManager` is a singleton that configures the root logger once at startup.

```python
from vs_common.log.vs_log_manager import VsLogManager
from vs_common.schema.vs_log_config import VsLogConfig

VsLogManager.init(VsLogConfig(
    level="DEBUG",
    console_enabled=True,
    file_enabled=True,
    file_path="logs/app.log",
))

logger = VsLogManager.get_instance("my-service")

logger.debug("debug message")
logger.info("info message")
logger.warn("warning message")
logger.error("error message", exc_info=True)
logger.exception("exception with traceback")
```

`VsLogConfig` defaults:

| Field | Default |
|---|---|
| `level` | `INFO` |
| `console_enabled` | `True` |
| `file_enabled` | `True` |
| `file_path` | `logs/viveka.log` |
| `file_max_bytes` | `10 MB` |
| `file_backup_count` | `5` |

If `VsLogManager.get_instance()` is called before `init()`, it auto-initialises with defaults.

---

### Cache

`VsCacheManager` is a static facade over a pluggable cache backend.

**In-memory (default):**
```python
from vs_common.cache.vs_cache_manager import VsCacheManager

await VsCacheManager.set("key", {"data": 1}, ttl=60)
value = await VsCacheManager.get("key")
await VsCacheManager.delete("key")
await VsCacheManager.delete_pattern("user:*")
alive = await VsCacheManager.ping()
```

**Redis:**
```python
from vs_common.cache.vs_cache_manager import VsCacheManager
from vs_common.schema.vs_cache_config import VsCacheConfig

VsCacheManager.init(VsCacheConfig(
    enabled=True,
    backend="redis",
    host="localhost",
    port=6379,
    db=0,
    password="secret",
    default_ttl=3600,
))
```

`VsCacheConfig` defaults:

| Field | Default |
|---|---|
| `enabled` | `False` |
| `backend` | `memory` |
| `host` | `localhost` |
| `port` | `6379` |
| `db` | `0` |
| `password` | `None` |
| `default_ttl` | `3600` |

---

## Customization

### Extending the Config

Implement `VsBaseConfig` to load configuration from any source — YAML, AWS SSM, environment-only, Vault, etc.

```python
from typing import Any, Dict, Type
from vs_common.config.vs_base_config import VsBaseConfig

class YamlConfig(VsBaseConfig):

    def __init__(self, path: str):
        import yaml
        with open(path) as f:
            self._data = yaml.safe_load(f)

    def get(self, key: str, default: Any = None, data_type: Type = str) -> Any:
        section, config_key = key.split(".", 1)
        value = self._data.get(section, {}).get(config_key)
        if value is None:
            return default
        return data_type(value)

    def get_section(self, section: str) -> Dict[str, str]:
        return self._data.get(section, {})
```

Use it directly wherever a `VsBaseConfig` is expected:

```python
config = YamlConfig("config.yaml")
config.get("database.url")
config.get("database.port", data_type=int)
```

`get_section()` is optional — if your backend does not support sections, the base class returns `{}` by default.

---

### Extending the Cache

Implement `VsBaseCache` to plug in any cache backend — DynamoDB, Memcached, a custom store, etc.

```python
from typing import Any, Optional
from vs_common.cache.vs_base_cache import VsBaseCache

class MyCustomCache(VsBaseCache):

    async def get(self, key: str) -> Optional[Any]:
        ...

    async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:
        ...

    async def delete(self, key: str) -> bool:
        ...

    async def delete_pattern(self, pattern: str) -> int:
        ...

    async def ping(self) -> bool:
        ...
```

Register it with the manager:

```python
from vs_common.cache.vs_cache_manager import VsCacheManager

VsCacheManager.register(MyCustomCache())
```

All subsequent calls to `VsCacheManager.get/set/delete` will use your implementation.

### RedisCache reference implementation

`RedisCache` ships with the library and serves as a reference for how to implement `VsBaseCache` against an async client:

```python
from typing import Any, Optional
import redis.asyncio as aioredis
from vs_common.cache.vs_base_cache import VsBaseCache
from vs_common.schema.vs_cache_config import VsCacheConfig

class RedisCache(VsBaseCache):

    def __init__(self, config: VsCacheConfig):
        self._default_ttl = config.default_ttl
        self._client = aioredis.Redis(
            host=config.host,
            port=config.port,
            db=config.db,
            password=config.password,
            decode_responses=False,
        )

    async def get(self, key: str) -> Optional[Any]:
        import pickle
        value = await self._client.get(key)
        return pickle.loads(value) if value is not None else None

    async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:
        import pickle
        ex = ttl if ttl is not None else self._default_ttl
        return await self._client.set(key, pickle.dumps(value), ex=ex)

    async def delete(self, key: str) -> bool:
        return await self._client.delete(key) > 0

    async def delete_pattern(self, pattern: str) -> int:
        keys = await self._client.keys(pattern)
        if not keys:
            return 0
        return await self._client.delete(*keys)

    async def ping(self) -> bool:
        try:
            return await self._client.ping()
        except Exception:
            return False

    async def close(self) -> None:
        await self._client.aclose()
```

---

## Decorators

### `@vs_logger`

Injects a `VsLogger` instance as a class attribute, giving any class structured logging without manual setup.

```python
from vs_common.decorator.vs_logger_decorator import vs_logger

@vs_logger("OrderService")
class OrderService:

    def place_order(self, order_id: str):
        self.vs_logger.info(f"Placing order {order_id}")
        try:
            ...
        except Exception as e:
            self.vs_logger.error(f"Order {order_id} failed", exc_info=True)
```

The string passed to `@vs_logger` becomes the logger name — it appears in every log line and lets you filter logs by service/component.

**Use cases:**

| Scenario | Example name |
|---|---|
| Service class | `@vs_logger("PaymentService")` |
| Repository / DAO | `@vs_logger("UserRepository")` |
| Background worker | `@vs_logger("IngestWorker")` |
| Cache manager | `@vs_logger("VsCacheManager")` |

**Available log methods:**

```python
self.vs_logger.debug("low-level detail")
self.vs_logger.info("normal operations")
self.vs_logger.warn("something unexpected but recoverable")
self.vs_logger.error("failure that needs attention")
self.vs_logger.exception("error with full traceback — use inside except blocks")
```

`exception()` automatically captures and appends the current exception traceback, making it ideal inside `except` blocks:

```python
try:
    result = call_external_api()
except Exception:
    self.vs_logger.exception("External API call failed")
```

**Passing structured context:**

All methods accept an optional `extra` dict that gets merged into the log record. Useful for attaching request IDs, user IDs, or trace context:

```python
self.vs_logger.info("User logged in", extra={"user_id": user.id, "ip": request.ip})
```

---

### `@cacheable`

Caches the return value of an async method. On the first call, the method executes and the result is stored. On subsequent calls with the same arguments, the cached value is returned immediately — the method body never runs.

```python
from vs_common.decorator.vs_cache_decorator import cacheable

class ProductService:

    @cacheable(key_prefix="product", ttl=300)
    async def get_product(self, product_id: str):
        return await db.fetch_product(product_id)
```

How the cache key is built:

| Call | Cache key |
|---|---|
| `get_product("abc")` | `product:abc` |
| `get_product("abc", locale="en")` | `product:abc:locale=en` |
| `get_product()` | `product:default` |

**Why it makes life easy:**

Without `@cacheable` you write the same boilerplate on every method — check cache, return if hit, call db, store result, return. With it, the entire pattern collapses to one line above the method signature. TTL is declared where the method is, so the caching intent is always visible alongside the logic it protects.

```python
# without @cacheable — repeated everywhere
async def get_product(self, product_id: str):
    cached = await VsCacheManager.get(f"product:{product_id}")
    if cached:
        return cached
    result = await db.fetch_product(product_id)
    await VsCacheManager.set(f"product:{product_id}", result, ttl=300)
    return result

# with @cacheable — all of the above, in one line
@cacheable(key_prefix="product", ttl=300)
async def get_product(self, product_id: str):
    return await db.fetch_product(product_id)
```

---

### `@cache_evict`

After a write/update/delete method runs, deletes all cache keys matching `key_prefix:*`. Keeps the cache consistent without manual invalidation calls.

```python
from vs_common.decorator.vs_cache_decorator import cacheable, cache_evict

class ProductService:

    @cacheable(key_prefix="product", ttl=300)
    async def get_product(self, product_id: str):
        return await db.fetch_product(product_id)

    @cache_evict(key_prefix="product")
    async def update_product(self, product_id: str, data: dict):
        return await db.update_product(product_id, data)

    @cache_evict(key_prefix="product")
    async def delete_product(self, product_id: str):
        return await db.delete_product(product_id)
```

When `update_product` or `delete_product` is called, all `product:*` keys are wiped — so the next `get_product` call fetches fresh data from the database.

**Why it makes life easy:**

Cache invalidation is one of the hardest problems in software. `@cache_evict` makes it declarative — you say *what* to invalidate, not *how*. No risk of forgetting to clear cache after a write, no scattered `VsCacheManager.delete_pattern()` calls across your codebase.

**Typical pairing pattern:**

```python
@cacheable(key_prefix="user", ttl=600)
async def get_user(self, user_id: str): ...

@cache_evict(key_prefix="user")
async def update_user(self, user_id: str, data: dict): ...

@cache_evict(key_prefix="user")
async def delete_user(self, user_id: str): ...
```

Every read is cached. Every write auto-invalidates. Zero manual cache management.

---

## Running Tests

```bash
./run_tests.sh
```
